-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathcp.js
6195 lines (5089 loc) · 170 KB
/
cp.js
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
(function(){
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
Object.create = Object.create || function(o) {
function F() {}
F.prototype = o;
return new F();
};
//var VERSION = CP_VERSION_MAJOR + "." + CP_VERSION_MINOR + "." + CP_VERSION_RELEASE;
var cp;
if(typeof exports === 'undefined'){
cp = {};
if(typeof window === 'object'){
window.cp = cp;
}
} else {
cp = exports;
}
var assert = function(value, message)
{
if (!value) {
throw new Error('Assertion failed: ' + message);
}
};
var assertSoft = function(value, message)
{
if(!value && console && console.warn) {
console.warn("ASSERTION FAILED: " + message);
if(console.trace) {
console.trace();
}
}
};
var mymin = function(a, b)
{
return a < b ? a : b;
};
var mymax = function(a, b)
{
return a > b ? a : b;
};
var min, max;
if (typeof window === 'object' && window.navigator.userAgent.indexOf('Firefox') > -1){
// On firefox, Math.min and Math.max are really fast:
// http://jsperf.com/math-vs-greater-than/8
min = Math.min;
max = Math.max;
} else {
// On chrome and safari, Math.min / max are slooow. The ternery operator above is faster
// than the builtins because we only have to deal with 2 arguments that are always numbers.
min = mymin;
max = mymax;
}
/* The hashpair function takes two numbers and returns a hash code for them.
* Required that hashPair(a, b) === hashPair(b, a).
* Chipmunk's hashPair function is defined as:
* #define CP_HASH_COEF (3344921057ul)
* #define CP_HASH_PAIR(A, B) ((cpHashValue)(A)*CP_HASH_COEF ^ (cpHashValue)(B)*CP_HASH_COEF)
* But thats not suitable in javascript because multiplying by a large number will make the number
* a large float.
*
* The result of hashPair is used as the key in objects, so it returns a string.
*/
var hashPair = function(a, b)
{
//assert(typeof(a) === 'number', "HashPair used on something not a number");
return a < b ? a + ' ' + b : b + ' ' + a;
};
var deleteObjFromList = function(arr, obj)
{
for(var i=0; i<arr.length; i++){
if(arr[i] === obj){
arr[i] = arr[arr.length - 1];
arr.length--;
return;
}
}
};
var closestPointOnSegment = function(p, a, b)
{
var delta = vsub(a, b);
var t = clamp01(vdot(delta, vsub(p, b))/vlengthsq(delta));
return vadd(b, vmult(delta, t));
};
var closestPointOnSegment2 = function(px, py, ax, ay, bx, by)
{
var deltax = ax - bx;
var deltay = ay - by;
var t = clamp01(vdot2(deltax, deltay, px - bx, py - by)/vlengthsq2(deltax, deltay));
return new Vect(bx + deltax * t, by + deltay * t);
};
cp.momentForCircle = function(m, r1, r2, offset)
{
return m*(0.5*(r1*r1 + r2*r2) + vlengthsq(offset));
};
cp.areaForCircle = function(r1, r2)
{
return Math.PI*Math.abs(r1*r1 - r2*r2);
};
cp.momentForSegment = function(m, a, b)
{
var offset = vmult(vadd(a, b), 0.5);
return m*(vdistsq(b, a)/12 + vlengthsq(offset));
};
cp.areaForSegment = function(a, b, r)
{
return r*(Math.PI*r + 2*vdist(a, b));
};
cp.momentForPoly = function(m, verts, offset)
{
var sum1 = 0;
var sum2 = 0;
var len = verts.length;
for(var i=0; i<len; i+=2){
var v1x = verts[i] + offset.x;
var v1y = verts[i+1] + offset.y;
var v2x = verts[(i+2)%len] + offset.x;
var v2y = verts[(i+3)%len] + offset.y;
var a = vcross2(v2x, v2y, v1x, v1y);
var b = vdot2(v1x, v1y, v1x, v1y) + vdot2(v1x, v1y, v2x, v2y) + vdot2(v2x, v2y, v2x, v2y);
sum1 += a*b;
sum2 += a;
}
return (m*sum1)/(6*sum2);
};
cp.areaForPoly = function(verts)
{
var area = 0;
for(var i=0, len=verts.length; i<len; i+=2){
area += vcross(new Vect(verts[i], verts[i+1]), new Vect(verts[(i+2)%len], verts[(i+3)%len]));
}
return -area/2;
};
cp.centroidForPoly = function(verts)
{
var sum = 0;
var vsum = new Vect(0,0);
for(var i=0, len=verts.length; i<len; i+=2){
var v1 = new Vect(verts[i], verts[i+1]);
var v2 = new Vect(verts[(i+2)%len], verts[(i+3)%len]);
var cross = vcross(v1, v2);
sum += cross;
vsum = vadd(vsum, vmult(vadd(v1, v2), cross));
}
return vmult(vsum, 1/(3*sum));
};
cp.recenterPoly = function(verts)
{
var centroid = cp.centroidForPoly(verts);
for(var i=0; i<verts.length; i+=2){
verts[i] -= centroid.x;
verts[i+1] -= centroid.y;
}
};
cp.momentForBox = function(m, width, height)
{
return m*(width*width + height*height)/12;
};
cp.momentForBox2 = function(m, box)
{
var width = box.r - box.l;
var height = box.t - box.b;
var offset = vmult([box.l + box.r, box.b + box.t], 0.5);
// TODO NaN when offset is 0 and m is INFINITY
return cp.momentForBox(m, width, height) + m*vlengthsq(offset);
};
// Quick hull
var loopIndexes = cp.loopIndexes = function(verts)
{
var start = 0, end = 0;
var minx, miny, maxx, maxy;
minx = maxx = verts[0];
miny = maxy = verts[1];
var count = verts.length >> 1;
for(var i=1; i<count; i++){
var x = verts[i*2];
var y = verts[i*2 + 1];
if(x < minx || (x == minx && y < miny)){
minx = x;
miny = y;
start = i;
} else if(x > maxx || (x == maxx && y > maxy)){
maxx = x;
maxy = y;
end = i;
}
}
return [start, end];
};
var SWAP = function(arr, idx1, idx2)
{
var tmp = arr[idx1*2];
arr[idx1*2] = arr[idx2*2];
arr[idx2*2] = tmp;
tmp = arr[idx1*2+1];
arr[idx1*2+1] = arr[idx2*2+1];
arr[idx2*2+1] = tmp;
};
var QHullPartition = function(verts, offs, count, a, b, tol)
{
if(count === 0) return 0;
var max = 0;
var pivot = offs;
var delta = vsub(b, a);
var valueTol = tol * vlength(delta);
var head = offs;
for(var tail = offs+count-1; head <= tail;){
var v = new Vect(verts[head * 2], verts[head * 2 + 1]);
var value = vcross(delta, vsub(v, a));
if(value > valueTol){
if(value > max){
max = value;
pivot = head;
}
head++;
} else {
SWAP(verts, head, tail);
tail--;
}
}
// move the new pivot to the front if it's not already there.
if(pivot != offs) SWAP(verts, offs, pivot);
return head - offs;
};
var QHullReduce = function(tol, verts, offs, count, a, pivot, b, resultPos)
{
if(count < 0){
return 0;
} else if(count == 0) {
verts[resultPos*2] = pivot.x;
verts[resultPos*2+1] = pivot.y;
return 1;
} else {
var left_count = QHullPartition(verts, offs, count, a, pivot, tol);
var left = new Vect(verts[offs*2], verts[offs*2+1]);
var index = QHullReduce(tol, verts, offs + 1, left_count - 1, a, left, pivot, resultPos);
var pivotPos = resultPos + index++;
verts[pivotPos*2] = pivot.x;
verts[pivotPos*2+1] = pivot.y;
var right_count = QHullPartition(verts, offs + left_count, count - left_count, pivot, b, tol);
var right = new Vect(verts[(offs+left_count)*2], verts[(offs+left_count)*2+1]);
return index + QHullReduce(tol, verts, offs + left_count + 1, right_count - 1, pivot, right, b, resultPos + index);
}
};
// QuickHull seemed like a neat algorithm, and efficient-ish for large input sets.
// My implementation performs an in place reduction using the result array as scratch space.
//
// Pass an Array into result to put the result of the calculation there. Otherwise, pass null
// and the verts list will be edited in-place.
//
// Expects the verts to be described in the same way as cpPolyShape - which is to say, it should
// be a list of [x1,y1,x2,y2,x3,y3,...].
//
// tolerance is in world coordinates. Eg, 2.
cp.convexHull = function(verts, result, tolerance)
{
if(result){
// Copy the line vertexes into the empty part of the result polyline to use as a scratch buffer.
for (var i = 0; i < verts.length; i++){
result[i] = verts[i];
}
} else {
// If a result array was not specified, reduce the input instead.
result = verts;
}
// Degenerate case, all points are the same.
var indexes = loopIndexes(verts);
var start = indexes[0], end = indexes[1];
if(start == end){
//if(first) (*first) = 0;
result.length = 2;
return result;
}
SWAP(result, 0, start);
SWAP(result, 1, end == 0 ? start : end);
var a = new Vect(result[0], result[1]);
var b = new Vect(result[2], result[3]);
var count = verts.length >> 1;
//if(first) (*first) = start;
var resultCount = QHullReduce(tolerance, result, 2, count - 2, a, b, a, 1) + 1;
result.length = resultCount*2;
assertSoft(polyValidate(result),
"Internal error: cpConvexHull() and cpPolyValidate() did not agree." +
"Please report this error with as much info as you can.");
return result;
};
/// Clamp @c f to be between @c min and @c max.
var clamp = function(f, minv, maxv)
{
return min(max(f, minv), maxv);
};
/// Clamp @c f to be between 0 and 1.
var clamp01 = function(f)
{
return max(0, min(f, 1));
};
/// Linearly interpolate (or extrapolate) between @c f1 and @c f2 by @c t percent.
var lerp = function(f1, f2, t)
{
return f1*(1 - t) + f2*t;
};
/// Linearly interpolate from @c f1 to @c f2 by no more than @c d.
var lerpconst = function(f1, f2, d)
{
return f1 + clamp(f2 - f1, -d, d);
};
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// I'm using an array tuple here because (at time of writing) its about 3x faster
// than an object on firefox, and the same speed on chrome.
//var numVects = 0;
var Vect = cp.Vect = function(x, y)
{
this.x = x;
this.y = y;
//numVects++;
// var s = new Error().stack;
// traces[s] = traces[s] ? traces[s]+1 : 1;
};
cp.v = function (x,y) { return new Vect(x, y) };
var vzero = cp.vzero = new Vect(0,0);
// The functions below *could* be rewritten to be instance methods on Vect. I don't
// know how that would effect performance. For now, I'm keeping the JS similar to
// the original C code.
/// Vector dot product.
var vdot = cp.v.dot = function(v1, v2)
{
return v1.x*v2.x + v1.y*v2.y;
};
var vdot2 = function(x1, y1, x2, y2)
{
return x1*x2 + y1*y2;
};
/// Returns the length of v.
var vlength = cp.v.len = function(v)
{
return Math.sqrt(vdot(v, v));
};
var vlength2 = cp.v.len2 = function(x, y)
{
return Math.sqrt(x*x + y*y);
};
/// Check if two vectors are equal. (Be careful when comparing floating point numbers!)
var veql = cp.v.eql = function(v1, v2)
{
return (v1.x === v2.x && v1.y === v2.y);
};
/// Add two vectors
var vadd = cp.v.add = function(v1, v2)
{
return new Vect(v1.x + v2.x, v1.y + v2.y);
};
Vect.prototype.add = function(v2)
{
this.x += v2.x;
this.y += v2.y;
return this;
};
/// Subtract two vectors.
var vsub = cp.v.sub = function(v1, v2)
{
return new Vect(v1.x - v2.x, v1.y - v2.y);
};
Vect.prototype.sub = function(v2)
{
this.x -= v2.x;
this.y -= v2.y;
return this;
};
/// Negate a vector.
var vneg = cp.v.neg = function(v)
{
return new Vect(-v.x, -v.y);
};
Vect.prototype.neg = function()
{
this.x = -this.x;
this.y = -this.y;
return this;
};
/// Scalar multiplication.
var vmult = cp.v.mult = function(v, s)
{
return new Vect(v.x*s, v.y*s);
};
Vect.prototype.mult = function(s)
{
this.x *= s;
this.y *= s;
return this;
};
/// 2D vector cross product analog.
/// The cross product of 2D vectors results in a 3D vector with only a z component.
/// This function returns the magnitude of the z value.
var vcross = cp.v.cross = function(v1, v2)
{
return v1.x*v2.y - v1.y*v2.x;
};
var vcross2 = function(x1, y1, x2, y2)
{
return x1*y2 - y1*x2;
};
/// Returns a perpendicular vector. (90 degree rotation)
var vperp = cp.v.perp = function(v)
{
return new Vect(-v.y, v.x);
};
/// Returns a perpendicular vector. (-90 degree rotation)
var vpvrperp = cp.v.pvrperp = function(v)
{
return new Vect(v.y, -v.x);
};
/// Returns the vector projection of v1 onto v2.
var vproject = cp.v.project = function(v1, v2)
{
return vmult(v2, vdot(v1, v2)/vlengthsq(v2));
};
Vect.prototype.project = function(v2)
{
this.mult(vdot(this, v2) / vlengthsq(v2));
return this;
};
/// Uses complex number multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector.
var vrotate = cp.v.rotate = function(v1, v2)
{
return new Vect(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x);
};
Vect.prototype.rotate = function(v2)
{
this.x = this.x * v2.x - this.y * v2.y;
this.y = this.x * v2.y + this.y * v2.x;
return this;
};
/// Inverse of vrotate().
var vunrotate = cp.v.unrotate = function(v1, v2)
{
return new Vect(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y);
};
/// Returns the squared length of v. Faster than vlength() when you only need to compare lengths.
var vlengthsq = cp.v.lengthsq = function(v)
{
return vdot(v, v);
};
var vlengthsq2 = cp.v.lengthsq2 = function(x, y)
{
return x*x + y*y;
};
/// Linearly interpolate between v1 and v2.
var vlerp = cp.v.lerp = function(v1, v2, t)
{
return vadd(vmult(v1, 1 - t), vmult(v2, t));
};
/// Returns a normalized copy of v.
var vnormalize = cp.v.normalize = function(v)
{
return vmult(v, 1/vlength(v));
};
/// Returns a normalized copy of v or vzero if v was already vzero. Protects against divide by zero errors.
var vnormalize_safe = cp.v.normalize_safe = function(v)
{
return (v.x === 0 && v.y === 0 ? vzero : vnormalize(v));
};
/// Clamp v to length len.
var vclamp = cp.v.clamp = function(v, len)
{
return (vdot(v,v) > len*len) ? vmult(vnormalize(v), len) : v;
};
/// Linearly interpolate between v1 towards v2 by distance d.
var vlerpconst = cp.v.lerpconst = function(v1, v2, d)
{
return vadd(v1, vclamp(vsub(v2, v1), d));
};
/// Returns the distance between v1 and v2.
var vdist = cp.v.dist = function(v1, v2)
{
return vlength(vsub(v1, v2));
};
/// Returns the squared distance between v1 and v2. Faster than vdist() when you only need to compare distances.
var vdistsq = cp.v.distsq = function(v1, v2)
{
return vlengthsq(vsub(v1, v2));
};
/// Returns true if the distance between v1 and v2 is less than dist.
var vnear = cp.v.near = function(v1, v2, dist)
{
return vdistsq(v1, v2) < dist*dist;
};
/// Spherical linearly interpolate between v1 and v2.
var vslerp = cp.v.slerp = function(v1, v2, t)
{
var omega = Math.acos(vdot(v1, v2));
if(omega) {
var denom = 1/Math.sin(omega);
return vadd(vmult(v1, Math.sin((1 - t)*omega)*denom), vmult(v2, Math.sin(t*omega)*denom));
} else {
return v1;
}
};
/// Spherical linearly interpolate between v1 towards v2 by no more than angle a radians
var vslerpconst = cp.v.slerpconst = function(v1, v2, a)
{
var angle = Math.acos(vdot(v1, v2));
return vslerp(v1, v2, min(a, angle)/angle);
};
/// Returns the unit length vector for the given angle (in radians).
var vforangle = cp.v.forangle = function(a)
{
return new Vect(Math.cos(a), Math.sin(a));
};
/// Returns the angular direction v is pointing in (in radians).
var vtoangle = cp.v.toangle = function(v)
{
return Math.atan2(v.y, v.x);
};
/// Returns a string representation of v. Intended mostly for debugging purposes and not production use.
var vstr = cp.v.str = function(v)
{
return "(" + v.x.toFixed(3) + ", " + v.y.toFixed(3) + ")";
};
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/// Chipmunk's axis-aligned 2D bounding box type along with a few handy routines.
var numBB = 0;
// Bounding boxes are JS objects with {l, b, r, t} = left, bottom, right, top, respectively.
var BB = cp.BB = function(l, b, r, t)
{
this.l = l;
this.b = b;
this.r = r;
this.t = t;
numBB++;
};
cp.bb = function(l, b, r, t) { return new BB(l, b, r, t); };
var bbNewForCircle = function(p, r)
{
return new BB(
p.x - r,
p.y - r,
p.x + r,
p.y + r
);
};
/// Returns true if @c a and @c b intersect.
var bbIntersects = function(a, b)
{
return (a.l <= b.r && b.l <= a.r && a.b <= b.t && b.b <= a.t);
};
var bbIntersects2 = function(bb, l, b, r, t)
{
return (bb.l <= r && l <= bb.r && bb.b <= t && b <= bb.t);
};
/// Returns true if @c other lies completely within @c bb.
var bbContainsBB = function(bb, other)
{
return (bb.l <= other.l && bb.r >= other.r && bb.b <= other.b && bb.t >= other.t);
};
/// Returns true if @c bb contains @c v.
var bbContainsVect = function(bb, v)
{
return (bb.l <= v.x && bb.r >= v.x && bb.b <= v.y && bb.t >= v.y);
};
var bbContainsVect2 = function(l, b, r, t, v)
{
return (l <= v.x && r >= v.x && b <= v.y && t >= v.y);
};
/// Returns a bounding box that holds both bounding boxes.
var bbMerge = function(a, b){
return new BB(
min(a.l, b.l),
min(a.b, b.b),
max(a.r, b.r),
max(a.t, b.t)
);
};
/// Returns a bounding box that holds both @c bb and @c v.
var bbExpand = function(bb, v){
return new BB(
min(bb.l, v.x),
min(bb.b, v.y),
max(bb.r, v.x),
max(bb.t, v.y)
);
};
/// Returns the area of the bounding box.
var bbArea = function(bb)
{
return (bb.r - bb.l)*(bb.t - bb.b);
};
/// Merges @c a and @c b and returns the area of the merged bounding box.
var bbMergedArea = function(a, b)
{
return (max(a.r, b.r) - min(a.l, b.l))*(max(a.t, b.t) - min(a.b, b.b));
};
var bbMergedArea2 = function(bb, l, b, r, t)
{
return (max(bb.r, r) - min(bb.l, l))*(max(bb.t, t) - min(bb.b, b));
};
/// Return true if the bounding box intersects the line segment with ends @c a and @c b.
var bbIntersectsSegment = function(bb, a, b)
{
return (bbSegmentQuery(bb, a, b) != Infinity);
};
/// Clamp a vector to a bounding box.
var bbClampVect = function(bb, v)
{
var x = min(max(bb.l, v.x), bb.r);
var y = min(max(bb.b, v.y), bb.t);
return new Vect(x, y);
};
// TODO edge case issue
/// Wrap a vector to a bounding box.
var bbWrapVect = function(bb, v)
{
var ix = Math.abs(bb.r - bb.l);
var modx = (v.x - bb.l) % ix;
var x = (modx > 0) ? modx : modx + ix;
var iy = Math.abs(bb.t - bb.b);
var mody = (v.y - bb.b) % iy;
var y = (mody > 0) ? mody : mody + iy;
return new Vect(x + bb.l, y + bb.b);
};
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/// Segment query info struct.
/* These are created using literals where needed.
typedef struct cpSegmentQueryInfo {
/// The shape that was hit, null if no collision occured.
cpShape *shape;
/// The normalized distance along the query segment in the range [0, 1].
cpFloat t;
/// The normal of the surface hit.
cpVect n;
} cpSegmentQueryInfo;
*/
var shapeIDCounter = 0;
var CP_NO_GROUP = cp.NO_GROUP = 0;
var CP_ALL_LAYERS = cp.ALL_LAYERS = ~0;
cp.resetShapeIdCounter = function()
{
shapeIDCounter = 0;
};
/// The cpShape struct defines the shape of a rigid body.
//
/// Opaque collision shape struct. Do not create directly - instead use
/// PolyShape, CircleShape and SegmentShape.
var Shape = cp.Shape = function(body) {
/// The rigid body this collision shape is attached to.
this.body = body;
/// The current bounding box of the shape.
this.bb_l = this.bb_b = this.bb_r = this.bb_t = 0;
this.hashid = shapeIDCounter++;
/// Sensor flag.
/// Sensor shapes call collision callbacks but don't produce collisions.
this.sensor = false;
/// Coefficient of restitution. (elasticity)
this.e = 0;
/// Coefficient of friction.
this.u = 0;
/// Surface velocity used when solving for friction.
this.surface_v = vzero;
/// Collision type of this shape used when picking collision handlers.
this.collision_type = 0;
/// Group of this shape. Shapes in the same group don't collide.
this.group = 0;
// Layer bitmask for this shape. Shapes only collide if the bitwise and of their layers is non-zero.
this.layers = CP_ALL_LAYERS;
this.space = null;
// Copy the collision code from the prototype into the actual object. This makes collision
// function lookups slightly faster.
this.collisionCode = this.collisionCode;
};
Shape.prototype.setElasticity = function(e) { this.e = e; };
Shape.prototype.setFriction = function(u) { this.body.activate(); this.u = u; };
Shape.prototype.setLayers = function(layers) { this.body.activate(); this.layers = layers; };
Shape.prototype.setSensor = function(sensor) { this.body.activate(); this.sensor = sensor; };
Shape.prototype.setCollisionType = function(collision_type) { this.body.activate(); this.collision_type = collision_type; };
Shape.prototype.getBody = function() { return this.body; };
Shape.prototype.active = function()
{
// return shape->prev || (shape->body && shape->body->shapeList == shape);
return this.body && this.body.shapeList.indexOf(this) !== -1;
};
Shape.prototype.setBody = function(body)
{
assert(!this.active(), "You cannot change the body on an active shape. You must remove the shape from the space before changing the body.");
this.body = body;
};
Shape.prototype.cacheBB = function()
{
return this.update(this.body.p, this.body.rot);
};
Shape.prototype.update = function(pos, rot)
{
assert(!isNaN(rot.x), 'Rotation is NaN');
assert(!isNaN(pos.x), 'Position is NaN');
this.cacheData(pos, rot);
};
Shape.prototype.pointQuery = function(p)
{
var info = this.nearestPointQuery(p);
if (info.d < 0) return info;
};
Shape.prototype.getBB = function()
{
return new BB(this.bb_l, this.bb_b, this.bb_r, this.bb_t);
};
/* Not implemented - all these getters and setters. Just edit the object directly.
CP_DefineShapeStructGetter(cpBody*, body, Body);
void cpShapeSetBody(cpShape *shape, cpBody *body);
CP_DefineShapeStructGetter(cpBB, bb, BB);
CP_DefineShapeStructProperty(cpBool, sensor, Sensor, cpTrue);
CP_DefineShapeStructProperty(cpFloat, e, Elasticity, cpFalse);
CP_DefineShapeStructProperty(cpFloat, u, Friction, cpTrue);
CP_DefineShapeStructProperty(cpVect, surface_v, SurfaceVelocity, cpTrue);
CP_DefineShapeStructProperty(cpDataPointer, data, UserData, cpFalse);
CP_DefineShapeStructProperty(cpCollisionType, collision_type, CollisionType, cpTrue);
CP_DefineShapeStructProperty(cpGroup, group, Group, cpTrue);
CP_DefineShapeStructProperty(cpLayers, layers, Layers, cpTrue);
*/
/// Extended point query info struct. Returned from calling pointQuery on a shape.
var PointQueryExtendedInfo = function(shape)
{
/// Shape that was hit, NULL if no collision occurred.
this.shape = shape;
/// Depth of the point inside the shape.
this.d = Infinity;
/// Direction of minimum norm to the shape's surface.
this.n = vzero;
};
var NearestPointQueryInfo = function(shape, p, d)
{
/// The nearest shape, NULL if no shape was within range.
this.shape = shape;
/// The closest point on the shape's surface. (in world space coordinates)
this.p = p;
/// The distance to the point. The distance is negative if the point is inside the shape.
this.d = d;
};
var SegmentQueryInfo = function(shape, t, n)
{
/// The shape that was hit, NULL if no collision occured.
this.shape = shape;
/// The normalized distance along the query segment in the range [0, 1].
this.t = t;
/// The normal of the surface hit.
this.n = n;
};
/// Get the hit point for a segment query.
SegmentQueryInfo.prototype.hitPoint = function(start, end)
{
return vlerp(start, end, this.t);
};
/// Get the hit distance for a segment query.
SegmentQueryInfo.prototype.hitDist = function(start, end)
{
return vdist(start, end) * this.t;
};
// Circles.
var CircleShape = cp.CircleShape = function(body, radius, offset)
{
this.c = this.tc = offset;
this.r = radius;
this.type = 'circle';
Shape.call(this, body);
};
CircleShape.prototype = Object.create(Shape.prototype);
CircleShape.prototype.cacheData = function(p, rot)
{
//var c = this.tc = vadd(p, vrotate(this.c, rot));
var c = this.tc = vrotate(this.c, rot).add(p);
//this.bb = bbNewForCircle(c, this.r);
var r = this.r;
this.bb_l = c.x - r;