-
Notifications
You must be signed in to change notification settings - Fork 7
/
Car.html
1393 lines (1171 loc) · 38.7 KB
/
Car.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Physics simulation</title>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-3425939-7', 'auto');
ga('send', 'pageview');
</script>
<style type="text/css">
body { background-color:#ededed; font:nor2mal 12px/18px Arial, Helvetica, sans-serif; }
h1 { display:block; width:800px; margin:20px auto; paddVing-bottom:20px; font:norm2al 24px/30px Georgia, "Times New Roman", Times, serif; color:#333; text-shadow: 1px 2px 3px #ccc; border-bottom:1px solid #cbcbcb; }
#container { width:800px; margin:0 auto; }
#myCanvas { background:#fff; border:1px solid #cbcbcb; }
#myCanvas
{
display: block;
margin: 0 auto;
}
</style>
<script type="text/javascript">
'use strict';
var PI = 3.14159265359;
function DegToRad(a) {return a*PI/180.0 }
function max(a,b) { return a>b?a:b; }
function min(a,b) { return a<b?a:b; }
function clamp(a,l) { l=Math.abs(l); if (a>=l) a=l; if (a<=-l) a=-l; return a; }
//Vector class + math
function Vector(x,y) { this.x = x; this.y = y; }
function addV(a,b) { return new Vector(a.x+b.x, a.y+b.y); }
function subV(a,b) { return new Vector(a.x-b.x, a.y-b.y); }
function mulV(a,k) { return new Vector(a.x*k, a.y *k); }
function dotV(a,b) { return a.x*b.x+a.y*b.y; }
function RotV(a, v) { return new Vector(Math.cos(a)*v.x - Math.sin(a)*v.y, Math.sin(a)*v.x + Math.cos(a)*v.y); }
function ortoV(a) { return new Vector( -a.y, a.x); }
function crossKV(k,v) { return new Vector(-v.y*k, v.x *k); }
function crossVV(a,b) { return a.x*b.y-a.y*b.x; }
function lengthV(a) { return Math.sqrt(dotV(a,a)); }
function normV(a) { return mulV(a, 1.0/lengthV(a)); }
// Frame of reference
function Frame(x, y, r) { this.x = x; this.y = y; this.r = r; }
function FrameV(v, r) { this.x = v.x; this.y = v.y; this.r = r; }
function addF(a,b) { return new Frame(a.x+b.x, a.y+b.y, a.r+b.r); }
function subF(a,b) { return new Frame(a.x-b.x, a.y-b.y, a.r-b.r); }
function mulFK(a,k) { return new Frame(a.x*k, a.y*k, a.r*k); }
function maxF(a) { return new Frame(max(a.x,0), max(a.y,0), max(a.r,0)); }
function clampF(a,b) { return new Frame(clamp(a.x, b.x), clamp(a.y, b.y), clamp(a.r, b.r)); }
function dotF(a,b) { return a.x*b.x+a.y*b.y+a.r*b.r; }
function TransFV(f,p) { return addV(f, RotV(f.r, p) ); }
function InvTransFV(f,p) { return RotV(-f.r, subV(p, f) ); }
function ApplyForceF(f, point, force)
{
f.v.x += force.x;
f.v.y += force.y;
f.v.r += crossVV(subV(point, f.p), force);
}
// velocities, positions and radius
function State(pos, vel) { this.p = pos; this.v = vel; }
function Body(state, body, invMass, invI) { this.state = state; this.b = body; this.rb = []; this.M=invMass; this.I = invI; }
function getVelS(f, p) { return addV( f.v, crossKV( f.v.r, subV(p,f.p) ) ); }
function getPosS(f, p) { return TransFV( f.p, p ); }
function Link(b1, p1, b2, p2)
{
this.b1 = b1; this.p1 = p1;
this.b2 = b2; this.p2 = p2;
}
function Contact(b1, b2, p1, n1, p2)
{
this.b1 = b1; this.p1 = p1;
this.b2 = b2; this.p2 = p2;
this.n1 = n1;
}
var Contacts = []
var Links = [];
var States = [];
var Bodies = [];
var constraintIterations = 4;
var intergrationStep = 1.0/55.0;
var CoefficientOfRestitution = .1;
var RestitutionCoefficient = 1;
var frictionCoefficient = 0;
var frictionWheelCoefficient = .03;
var showNormals = null;
var mousePosition = new Vector(0,0);
var context;
var myCanvas = null;
var pickedPoint = new Vector(0,0);
var pickedObject = -1;
var oldTime = new Date
function CreateState(px, py, rot, geom, invMass, invI)
{
var p = new Frame(px,py, rot);
var v = new Frame( 0, 0, 0);
var state = new State(p, v)
var body = new Body(state, geom, invMass, invI )
States.push(state);
Bodies.push(body);
return body;
}
function CreateStateStatic(geom)
{
var cm = new Vector(0,0)
for(var i=0;i<geom.length;i++)
{
cm = addV(cm, geom[i])
}
cm = mulV(cm, 1.0/geom.length)
var g=[]
for(var i=0;i<geom.length;i++)
{
g.push(subV(geom[i], cm))
}
CreateState(cm.x, cm.y, 0, g, 0, 0);
}
function serializeState(state)
{
var out = '"px":'+state.p.x+","+'"py":'+state.p.y+","+'"pr":'+state.p.r+","+
'"vx":'+state.v.x+","+'"vy":'+state.v.y+","+'"vr":'+state.v.r;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Drawing helpers
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var canvasScale = 1;
function scaleCanvas(canvas, context, width, height)
{
canvasScale = height/30
// assume the device pixel ratio is 1 if the browser doesn't specify it
const devicePixelRatio = window.devicePixelRatio || 1;
// determine the 'backing store ratio' of the canvas context
const backingStoreRatio = (
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1
);
// determine the actual ratio we want to draw at
const ratio = devicePixelRatio / backingStoreRatio;
if (devicePixelRatio !== backingStoreRatio) {
// set the 'real' canvas size to the higher width/height
canvas.width = width * ratio;
canvas.height = height * ratio;
// ...then scale it back down with CSS
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
}
else {
// this is a normal 1:1 device; just scale it simply
canvas.width = width;
canvas.height = height;
canvas.style.width = '';
canvas.style.height = '';
}
// scale the drawing context so everything will work at the higher ratio
context.scale(ratio, ratio);
}
function moveTo(p) { context.moveTo(p.x*canvasScale,p.y*canvasScale); }
function lineTo(p) { context.lineTo(p.x*canvasScale,p.y*canvasScale); }
function circle(p) { context.arc(p.x*canvasScale,p.y*canvasScale, canvasScale, 0, 2*Math.PI, false); }
function drawLine( p1,p2, color)
{
context.beginPath();
context.strokeStyle=(color==null)?"#000000":color;
context.lineWidth = 1;
moveTo(p1)
lineTo(p2)
context.stroke();
}
function drawCross(p, radius, color)
{
drawLine( addV(p, new Vector(-1/5,0)), addV(p, new Vector(1/5,0)));
drawLine( addV(p, new Vector(0,-1/5)), addV(p, new Vector(0,1/5)));
}
function drawPoly(state, color)
{
context.beginPath();
context.strokeStyle=(color==null)?"#000000":color;
context.lineWidth = 1;
moveTo(state.rb[0])
for(var i=1;i<state.b.length;i++)
lineTo(state.rb[i])
context.closePath();
context.stroke();
}
function drawDisc(state, color)
{
context.beginPath();
context.strokeStyle=(color==null)?"#000000":color;
circle(state.rb[0]);
moveTo(state.p)
lineTo(addV(state.p, new Vector(Math.cos(state.p.r),Math.sin(state.p.r))))
context.closePath();
context.stroke();
}
function drawNormal( p1,p2, col, r)
{
var n = subV(p2,p1);
var l = lengthV(n);
var n = mulV(n,1/l)
if (r!=undefined)
{
l=r
p2 = addV(p1,mulV(n, r))
}
drawLine( p1,p2, col);
var nn = mulV(n,l*.8);
var nf = mulV(n,l*.08);
drawLine( addV(p1, addV(nn, ortoV(nf))) ,p2, col)
drawLine( addV(p1, addV(nn, mulV(ortoV(nf),-1))) ,p2, col)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Matrix math
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//multiply 2 matrices made out of vectors
//
function MulMatFF(m1, m2)
{
var O = [];
for(var j=0;j<m1.length;j++)
{
O[j]=[];
for(var i=0;i<m2[0].length;i++)
{
var tmp=0;
for(var k=0;k<m1[i].length;k++)
{
tmp += dotF(m1[j][k], m2[k][i]);
}
O[j][i] = tmp;
}
}
return O;
}
//
//multiply 2 matrices made out of vectors
//
function MulMatSF(s, f)
{
var O = [];
for(var j=0;j<f.length;j++)
{
O[j]=[];
for(var i=0;i<f[0].length;i++)
{
O[j][i] = new FrameV( mulV(f[j][i], s[j].M), f[j][i].r*s[j].I);
}
}
return O;
}
//
// multiply 2 matrices made out of scalars
//
function MulMatKK(m1, m2)
{
var O = [];
for(var j=0;j<m1.length;j++)
{
O[j]=[];
for(var i=0;i<m2[0].length;i++)
{
var tmp=0;
for(var k=0;k<m1[i].length;k++)
{
tmp += (m1[j][k] * m2[k][i]);
}
O[j][i] = tmp;
}
}
return O;
}
//
// multiply 2 matrices, one made out of vectors and the other made out of scalars
//
function MulMatFK(m1, m2)
{
var O = [];
for(var j=0;j<m1.length;j++)
{
O[j]=[];
for(var i=0;i<m2[0].length;i++)
{
var tmp = new Frame(0,0,0);
for(var k=0;k<m1[i].length;k++)
{
tmp = addF(mulFK(m1[j][k], m2[k][i]), tmp);
}
O[j][i] = tmp;
}
}
return O;
}
//
// addV 2 matrices made out of scalars
//
function addVMatKK(m1, m2)
{
var O = [];
for(var j=0;j<m1.length;j++)
{
O[j]=[];
for(var i=0;i<m1[0].length;i++)
{
O[j][i] = m1[j][i] + m2[j][i];
}
}
return O;
}
//
// Transpose matrix
//
function TransposeMat(m)
{
var O = [];
for(var j=0;j<m[0].length;j++)
{
O[j]=[];
for(var i=0;i<m.length;i++)
{
O[j][i] = m[i][j];
}
}
return O;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Constraints solver
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Inverts a matrix (taken from http://blog.acipo.com/matrix-inversion-in-javascript/)
//
function invertMat(M){
// I use Guassian Elimination to calculate the inverse:
// (1) 'augment' the matrix (left) by the identity (on the right)
// (2) Turn the matrix on the left into the identity by elemetry row ops
// (3) The matrix on the right is the inverse (was the identity matrix)
// There are 3 elemtary row ops: (I combine b and c in my code)
// (a) Swap 2 rows
// (b) Multiply a row by a scalar
// (c) addV 2 rows
//if the matrix isn't square: exit (error)
if(M.length !== M[0].length){return;}
//create the identity matrix (I), and a copy (C) of the original
var i=0, ii=0, j=0, dim=M.length, e=0, t=0;
var I = [], C = [];
for(i=0; i<dim; i+=1){
// Create the row
I[I.length]=[];
C[C.length]=[];
for(j=0; j<dim; j+=1){
//if we're on the diagonal, put a 1 (for identity)
if(i==j){ I[i][j] = 1; }
else{ I[i][j] = 0; }
// Also, make the copy of the original
C[i][j] = M[i][j];
}
}
// Perform elementary row operations
for(i=0; i<dim; i+=1){
// get the element e on the diagonal
e = C[i][i];
// if we have a 0 on the diagonal (we'll need to swap with a lower row)
if(e==0){
//look through every row below the i'th row
for(ii=i+1; ii<dim; ii+=1){
//if the ii'th row has a non-0 in the i'th col
if(C[ii][i] != 0){
//it would make the diagonal have a non-0 so swap it
for(j=0; j<dim; j++){
e = C[i][j]; //temp store i'th row
C[i][j] = C[ii][j];//replace i'th row by ii'th
C[ii][j] = e; //repace ii'th by temp
e = I[i][j]; //temp store i'th row
I[i][j] = I[ii][j];//replace i'th row by ii'th
I[ii][j] = e; //repace ii'th by temp
}
//don't bother checking other rows since we've swapped
break;
}
}
//get the new diagonal
e = C[i][i];
//if it's still 0, not invertable (error)
if(e==0){return}
}
// Scale this row down by e (so we have a 1 on the diagonal)
for(j=0; j<dim; j++){
C[i][j] = C[i][j]/e; //apply to original matrix
I[i][j] = I[i][j]/e; //apply to identity
}
// substract this row (scaled appropriately for each row) from ALL of
// the other rows so that there will be 0's in this column in the
// rows above and below this one
for(ii=0; ii<dim; ii++){
// Only apply to other rows (we want a 1 on the diagonal)
if(ii==i){continue;}
// We want to change this element to 0
e = C[ii][i];
// substract (the row above(or below) scaled by e) from (the
// current row) but start at the i'th column and assume all the
// stuff left of diagonal is 0 (which it should be if we made this
// algorithm correctly)
for(j=0; j<dim; j++){
C[ii][j] -= e*C[i][j]; //apply to original matrix
I[ii][j] -= e*I[i][j]; //apply to identity
}
}
}
//we've done all operations, C should be the identity
//matrix I should be the inverse:
return I;
}
function GetLambda(J, invM, velT, bias)
{
var J_velT = MulMatFF(J, velT);
if (bias!=undefined)
J_velT = addVMatKK(J_velT, bias);
var Jt = TransposeMat(J);
var invM_Jt = MulMatSF(invM, Jt);
var J_invM_Jt = MulMatFF(J, invM_Jt );
var invJJt = invertMat( J_invM_Jt );
var lambda = MulMatKK( invJJt, J_velT);
return [[-lambda[0][0]]];
}
function GetMinvJtlambda(invM, J, lambda)
{
var Jt = TransposeMat(J);
var Jt_lambda = MulMatFK( Jt, lambda);
var invM_Jt_lambda = MulMatSF(invM, Jt_lambda);
return invM_Jt_lambda;
}
//
// Compute velocity corrections to satisfy a distance constraint
//
function DistanceConstraint(link)
{
var Pa = getPosS( link.b1, link.p1);
var Pb = getPosS( link.b2, link.p2);
var PaPb = subV(Pb, Pa);
var PbPa = subV(Pa, Pb);
// compute bias---------------
var betaoverh = .5/intergrationStep;
var C = dotV(PaPb, PaPb);
// if the constraint is zero (is met) then bail out, the jacobian is zero and
// obviously it wont have an inverse
if (C<= 1e-15)
return;
var bias = [[betaoverh * C]];
// compute jacobian---------
var J = []
var Ca = link.b1.p;
var Cb = link.b2.p;
var CaPa = subV(Pa, Ca);
var CbPb = subV(Pb, Cb);
var Wa = -crossVV(CaPa, PaPb);
var Wb = crossVV(CbPb, PaPb);
J[0] = [ new FrameV(mulV(mulV(PaPb,-1),2), 2*Wa), new FrameV(mulV(PaPb,2), 2*Wb) ];
// compute vels--------------
var vel = [[ link.b1.v, link.b2.v ]];
var velT = TransposeMat(vel);
//just the diagonal matrix -----
var invM = [ link.b1, link.b2 ];
// solver-----------------------
var lambda = GetLambda(J, invM, velT, bias);
var invMJtlambda = GetMinvJtlambda(invM, J, lambda);
// update speeds-----------------
link.b1.v = addF(link.b1.v, invMJtlambda[0][0]);
link.b2.v = addF(link.b2.v, invMJtlambda[1][0]);
}
//
// Compute velocity corrections to satisfy a contact constraint
//
function InequalityConstraints(pair)
{
var normal = mulV(pair.n1, 1/lengthV(pair.n1));
// compute bias---------------
var betaoverh = (.5/intergrationStep);
var C = dotV(subV(pair.p1, pair.p2), normal );
var Cdot = dotV( subV(getVelS(pair.b1.state, pair.p1), getVelS(pair.b2.state, pair.p2)), normal);
var bias = [[betaoverh * C + Cdot*CoefficientOfRestitution]];
// compute jacobian---------
var J = []
var CaPa = subV(pair.p1, pair.b1.state.p);
var CbPb = subV(pair.p2, pair.b2.state.p);
J[0] = [ new Frame( normal.x, normal.y, crossVV(CaPa, normal)),
new Frame(-normal.x, -normal.y, -crossVV(CbPb, normal))];
// compute vels--------------
var vel = [[ pair.b1.state.v, pair.b2.state.v ]];
var velT = TransposeMat(vel);
//just the diagonal matrix -----
var invM = [ pair.b1, pair.b2 ];
// solver-----------------------
var lambda = GetLambda(J, invM, velT, bias);
if (pair.lambdaAcc != undefined)
{
lambda = [[pair.lambdaAcc[0][0] + lambda[0][0]]];
var lambdaPositive = [[ Math.max(lambda[0][0], 0) ]];
lambda = [[lambdaPositive[0][0] - pair.lambdaAcc[0][0] ]];
pair.lambda = lambda;
pair.lambdaAcc = lambdaPositive;
}
else
{
pair.lambdaAcc = lambda;
}
var invMJtlambda = GetMinvJtlambda(invM, J, lambda);
// update speeds-----------------
pair.b1.state.v = addF(pair.b1.state.v, invMJtlambda[0][0]);
pair.b2.state.v = addF(pair.b2.state.v, invMJtlambda[1][0]);
//return lambda for friction
return [invMJtlambda[0][0], invMJtlambda[1][0]];
}
//
// Friction solver
//
function FrictionConstraints(pair, lambdaNormal)
{
var normal = mulV(pair.n1, 1/lengthV(pair.n1));
var tangent = mulV(ortoV(normal),1);
// compute bias---------------
var betaoverh = (.1/intergrationStep);
var tangent = mulV(ortoV(pair.n1),1);
var C = dotV(subV(pair.p1, pair.p2), tangent );
var vrel = subV(getVelS(pair.b1.state, pair.p1), getVelS(pair.b2.state, pair.p2))
var Cdot = dotV( vrel, tangent);
var bias = [[betaoverh * C + Cdot*RestitutionCoefficient]];
// compute jacobian---------
var J = []
var CaPa = subV(pair.p1, pair.b1.state.p);
var CbPb = subV(pair.p2, pair.b2.state.p);
J[0] = [ new Frame( tangent.x, tangent.y, crossVV(CaPa, tangent)),
new Frame(-tangent.x, -tangent.y, -crossVV(CbPb, tangent))];
// compute vels--------------
var vel = [[ pair.b1.state.v, pair.b2.state.v ]];
var velT = TransposeMat(vel);
//just the diagonal matrix -----
var invM = [ pair.b1, pair.b2 ];
// solver-----------------------
var lambda = GetLambda(J, invM, velT, bias);
lambda = [[ clamp(lambda[0][0], pair.lambda[0][0] * frictionCoefficient) ]]
var invMJtlambda = GetMinvJtlambda(invM, J, lambda);
// update speeds-----------------
pair.b1.state.v = addF(pair.b1.state.v, invMJtlambda[0][0]);
pair.b2.state.v = addF(pair.b2.state.v, invMJtlambda[1][0]);
}
function WheelConstraints(body, pos, axis)
{
// compute bias---------------
var bias = [[ 0 ]];
// compute jacobian---------
var J = []
J[0] = [ new Frame( axis.x, axis.y, crossVV(pos, axis) )];
// compute vels--------------
var vel = [[ body.state.v ]];
var velT = TransposeMat(vel);
//just the diagonal matrix -----
var invM = [ body ];
// solver-----------------------
var lambda = GetLambda(J, invM, velT, bias);
var clampedLambda = clamp(lambda[0][0], lambda[0][0] * frictionWheelCoefficient);
var invMJtlambda = GetMinvJtlambda(invM, J, [[ clampedLambda ]]);
// update speeds-----------------
body.state.v = addF(body.state.v, invMJtlambda[0][0]);
return invMJtlambda[0][0]
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// vehicle
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function drawTrail(trails)
{
if (trails.length<1)
return;
context.beginPath();
context.strokeStyle = "#808080";
context.lineWidth = 0.2*canvasScale;
moveTo(trails[0])
for(var i=0;i<trails.length;i+=1)
{
lineTo(trails[i])
}
context.stroke();
}
class Vehicle
{
constructor()
{
this.trailList = []
this.trail = []
for(var i=0;i<4;i++)
this.trail.push([])
this.back = false;
this.wheelAngle = 0
this.accelCar = 0;
this.rearWheelVelCorr = new Frame(0, 0, 0);
this.frontWheelVelCorr = new Frame(0, 0, 0);
}
Create(pos, angle)
{
var r = 1;
var boxVerts = [ new Vector(-r, -r/2), new Vector(r, -r/2), new Vector(r, r/2), new Vector(-r, r/2)];
this.body = CreateState(pos.x ,pos.y, angle,boxVerts,1,1);
return this.body;
}
ApplyForcesBasedOnControl(forward, backward, left, right)
{
this.accelCar = 0;
//car.wheelAngle *= 0.9;
this.back = false;
if (forward) { this.accelCar = .1; this.back = false; }
else if (backward) { this.accelCar = -.1; this.back = true; }
if (right) this.wheelAngle += .03;
else if (left) this.wheelAngle -= .03;
else this.wheelAngle *= 0.9;
this.wheelAngle = clamp(this.wheelAngle, 0.5)
this.accelCar = clamp(this.accelCar, .1)
this.ApplyForce();
}
ApplyForce()
{
var p = this.body.state.p;
var p1 = RotV(p.r, new Vector(-.7,0))
var f = RotV(p.r, new Vector(this.accelCar,0))
ApplyForceF(this.body.state, addV(p, p1), f);
//drawNormal( addV(body.p,p1), addV(body.p,addV(p1,f)), "#ff0000",1);
}
DrawWheel(wheelPos, wheelAngle, vertexBuffer, color)
{
//wheelPos = TransFV(this.body.state.p, wheelPos);
//wheelAngle = this.body.state.p.r + wheelAngle;
context.beginPath();
context.strokeStyle = color;
context.lineWidth = 1;
moveTo(addV(wheelPos, RotV(wheelAngle, vertexBuffer[0])))
for(var i=1;i<vertexBuffer.length;i++)
{
lineTo(addV(wheelPos, RotV(wheelAngle, vertexBuffer[i])))
}
context.closePath();
context.stroke();
}
ComputeTrails()
{
}
Draw()
{
var p = this.body.state.p;
var wheelPos = [new Vector( .7, .4), new Vector( .7,-.4), new Vector(-.7, .4), new Vector(-.7,-.4)]
var wheelAngle = [this.wheelAngle, this.wheelAngle, 0, 0]
var wheelVerts = [new Vector(-.2, -.1), new Vector(.2, -.1), new Vector(.2, .1), new Vector(-.2, .1)];
var windShieldVerts = [new Vector(-.2, -.1), new Vector(.2, -.1), new Vector(.35, .2), new Vector(-.35, .2)];
var backLightsVerts = [ new Vector(0, -.1), new Vector(0, .1) ];
// compute wheel trails
//
for(var i=0;i<4;i++)
{
var wheelPosWS = TransFV(p, wheelPos[i]);
var wheelAngleWS = this.body.state.p.r + wheelAngle[i];
// calc trails
var wheelVelWS = getVelS(this.body.state, wheelPosWS);
var wheelDirWS = RotV(wheelAngleWS, new Vector(0,1))
var vt = dotV(wheelVelWS,wheelDirWS);
if (Math.abs(vt)>2)
{
this.trail[i].push(wheelPosWS)
}
else
{
if (this.trail[i].length>0)
{
this.trailList.push(this.trail[i])
if (this.trailList.length>15)
this.trailList.shift()
this.trail[i] = []
}
}
// Draw wheel axis
//drawNormal( wheelPosWS, addV(wheelPosWS, wheelDirWS), "#ff0000",2);
//drawNormal( wheelPosWS, addV(wheelPosWS, wheelVelWS), "#00ff00",2);
//context.fillText("Hello World " + vt , 10, 50+i*20);
}
// draw trails
for(var i=0;i<this.trailList.length;i++)
drawTrail(this.trailList[i])
for(var i=0;i<4;i++)
drawTrail(this.trail[i])
// draw wheels
for(var i=0;i<4;i++)
{
var wheelPosWS = TransFV(p, wheelPos[i]);
var wheelAngleWS = this.body.state.p.r + wheelAngle[i];
// draw wheel
this.DrawWheel(wheelPosWS, wheelAngleWS, wheelVerts, "#000000");
}
// draw wind shield
this.DrawWheel(TransFV(p, new Vector(.25,0)), this.body.state.p.r + DegToRad(90), windShieldVerts, "#000000" );
if (this.back)
{
this.DrawWheel(TransFV(p, new Vector(-1.1, 0.4)), this.body.state.p.r, backLightsVerts, "#FF0000" );
this.DrawWheel(TransFV(p, new Vector(-1.1,-0.4)), this.body.state.p.r, backLightsVerts, "#FF0000" );
}
}
ApplyWheelConstraints()
{
var p = this.body.state.p;
// rear wheel
{
var p1 = RotV(p.r, new Vector(-.7,0))
var p2 = RotV(p.r, new Vector(0,-1))
WheelConstraints(this.body, p1, p2)
//drawNormal( addV(p,p1), addV(p,addV(p1,ortoV(p2))), "#ff0000",2);
}
// front wheel
{
var p1 = RotV(p.r, new Vector(.7,0))
var p2 = RotV(p.r, RotV(this.wheelAngle, new Vector(0,-1)))
WheelConstraints(this.body, p1, p2)
//drawNormal( addV(p,p1), addV(p,addV(p1,ortoV(p2))), "#ff0000",2);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Collision detection
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Determine whether 2 segments intersect
//
function SegmentIntersection( a, b, c, d)
{
var ab = subV(b,a); var cd = subV(d,c);
var ca = subV(a,c); var db = subV(b,d);
var s = crossVV(ca, ab) / crossVV(cd, ab);
if (s>=0 && s<=1)
{
var t = -crossVV(ca, cd) / crossVV(ab, cd);
if (t>=0 && t<=1)
return true;
}
return false;
}
//
// Determine if a point is inside of a convex poligon
//
function PointInPoly(point, lines)
{
if (lines.length==1)
{
//it is a disc
return lengthV(subV(point,lines[0]))<=1;
}
var outer = null;
var dist = 10000000;
for (var i = 0; i < lines.length; i++)
{
var p1 = lines[i]
var p2 = lines[i+1==lines.length?0:i+1];
var dir = subV(p2,p1);
var l = lengthV(dir)
var dirn = mulV(dir, 1/l);
var n = ortoV(dirn);
var p1p = subV(point, p1);
var projP = dotV(p1p, n);
if (projP<0)
return false;
}
return true;
}
//
// Project a point onto a line
//
function ProjectPointToLine(p, a,b)
{
var ab = subV(b, a);
var abn = mulV(ab,1/lengthV(ab));
var ap = subV(p, a);
var pr = dotV(abn, ap)
var pt = addV( a, mulV(abn,pr))
return pt;
}
function ClosesPointToSegment(p, a,b)
{
var ab = subV(b, a);
var l = lengthV(ab)
var abn = mulV(ab,1/l);
var ap = subV(p, a);
var pr = dotV(abn, ap)
if (pr<0) return a;
if (pr>l) return b;
return addV(mulV(abn,pr),a);
}
function ComputeBoxBoxContacts(s1,s2)
{
// box box collision
for (var r=0;r<2;r++)
{
// onw way collision
for (var i = 0; i < s1.rb.length; i++)
{
if (PointInPoly(s1.rb[i], s2.rb))
{
for (var j = 0; j < s2.rb.length; j++)
{
var jj = j+1; if (jj >= s2.rb.length) jj = 0;
if (SegmentIntersection(s1.state.p, s1.rb[i], s2.rb[j], s2.rb[jj]))
{
var pt = ProjectPointToLine(s1.rb[i], s2.rb[j], s2.rb[jj]);
var normal = ortoV(subV(s2.rb[j], s2.rb[jj]));
Contacts.push(new Contact(s1,s2, s1.rb[i], normal, pt));
}
}
}
}
// swap objects
var ss = s1;
s1=s2;
s2=ss;
}
}
function ComputeDiscBoxContacts(d,s)
{