-
Notifications
You must be signed in to change notification settings - Fork 0
/
physics.js
executable file
·836 lines (633 loc) · 17.9 KB
/
physics.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
// Generated by CoffeeScript 1.3.3
/* Allows safe, dyamic creation of namespaces.
*/
var Attraction, Behaviour, Collision, ConstantForce, EdgeBounce, EdgeWrap, Euler, ImprovedEuler, Integrator, Particle, Physics, Random, Spring, Vector, Verlet, Wander, namespace,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
namespace = function(id) {
var path, root, _i, _len, _ref, _ref1, _results;
root = self;
_ref = id.split('.');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
path = _ref[_i];
_results.push(root = (_ref1 = root[path]) != null ? _ref1 : root[path] = {});
}
return _results;
};
/* RequestAnimationFrame shim.
*/
(function() {
var time, vendor, vendors, _i, _len;
time = 0;
vendors = ['ms', 'moz', 'webkit', 'o'];
for (_i = 0, _len = vendors.length; _i < _len; _i++) {
vendor = vendors[_i];
if (!(!window.requestAnimationFrame)) {
continue;
}
window.requestAnimationFrame = window[vendor + 'RequestAnimationFrame'];
window.cancelRequestAnimationFrame = window[vendor + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var delta, now, old;
now = new Date().getTime();
delta = Math.max(0, 16 - (now - old));
setTimeout((function() {
return callback(time + delta);
}), delta);
return old = now + delta;
};
}
if (!window.cancelAnimationFrame) {
return window.cancelAnimationFrame = function(id) {
return clearTimeout(id);
};
}
})();
/* Random
*/
Random = function(min, max) {
if (!(max != null)) {
max = min;
min = 0;
}
return min + Math.random() * (max - min);
};
Random.int = function(min, max) {
if (!(max != null)) {
max = min;
min = 0;
}
return Math.floor(min + Math.random() * (max - min));
};
Random.sign = function(prob) {
if (prob == null) {
prob = 0.5;
}
if (Math.random() < prob) {
return 1;
} else {
return -1;
}
};
Random.bool = function(prob) {
if (prob == null) {
prob = 0.5;
}
return Math.random() < prob;
};
Random.item = function(list) {
return list[Math.floor(Math.random() * list.length)];
};
/* 2D Vector
*/
Vector = (function() {
/* Adds two vectors and returns the product.
*/
Vector.add = function(v1, v2) {
return new Vector(v1.x + v2.x, v1.y + v2.y);
};
/* Subtracts v2 from v1 and returns the product.
*/
Vector.sub = function(v1, v2) {
return new Vector(v1.x - v2.x, v1.y - v2.y);
};
/* Projects one vector (v1) onto another (v2)
*/
Vector.project = function(v1, v2) {
return v1.clone().scale((v1.dot(v2)) / v1.magSq());
};
/* Creates a new Vector instance.
*/
function Vector(x, y) {
this.x = x != null ? x : 0.0;
this.y = y != null ? y : 0.0;
}
/* Sets the components of this vector.
*/
Vector.prototype.set = function(x, y) {
this.x = x;
this.y = y;
return this;
};
/* Add a vector to this one.
*/
Vector.prototype.add = function(v) {
this.x += v.x;
this.y += v.y;
return this;
};
/* Subtracts a vector from this one.
*/
Vector.prototype.sub = function(v) {
this.x -= v.x;
this.y -= v.y;
return this;
};
/* Scales this vector by a value.
*/
Vector.prototype.scale = function(f) {
this.x *= f;
this.y *= f;
return this;
};
/* Computes the dot product between vectors.
*/
Vector.prototype.dot = function(v) {
return this.x * v.x + this.y * v.y;
};
/* Computes the cross product between vectors.
*/
Vector.prototype.cross = function(v) {
return (this.x * v.y) - (this.y * v.x);
};
/* Computes the magnitude (length).
*/
Vector.prototype.mag = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/* Computes the squared magnitude (length).
*/
Vector.prototype.magSq = function() {
return this.x * this.x + this.y * this.y;
};
/* Computes the distance to another vector.
*/
Vector.prototype.dist = function(v) {
var dx, dy;
dx = v.x - this.x;
dy = v.y - this.y;
return Math.sqrt(dx * dx + dy * dy);
};
/* Computes the squared distance to another vector.
*/
Vector.prototype.distSq = function(v) {
var dx, dy;
dx = v.x - this.x;
dy = v.y - this.y;
return dx * dx + dy * dy;
};
/* Normalises the vector, making it a unit vector (of length 1).
*/
Vector.prototype.norm = function() {
var m;
m = Math.sqrt(this.x * this.x + this.y * this.y);
this.x /= m;
this.y /= m;
return this;
};
/* Limits the vector length to a given amount.
*/
Vector.prototype.limit = function(l) {
var m, mSq;
mSq = this.x * this.x + this.y * this.y;
if (mSq > l * l) {
m = Math.sqrt(mSq);
this.x /= m;
this.y /= m;
this.x *= l;
this.y *= l;
return this;
}
};
/* Copies components from another vector.
*/
Vector.prototype.copy = function(v) {
this.x = v.x;
this.y = v.y;
return this;
};
/* Clones this vector to a new itentical one.
*/
Vector.prototype.clone = function() {
return new Vector(this.x, this.y);
};
/* Resets the vector to zero.
*/
Vector.prototype.clear = function() {
this.x = 0.0;
this.y = 0.0;
return this;
};
return Vector;
})();
/* Particle
*/
Particle = (function() {
Particle.GUID = 0;
function Particle(mass) {
this.mass = mass != null ? mass : 1.0;
this.id = 'p' + Particle.GUID++;
this.setMass(this.mass);
this.setRadius(1.0);
this.fixed = false;
this.behaviours = [];
this.pos = new Vector();
this.vel = new Vector();
this.acc = new Vector();
this.old = {
pos: new Vector(),
vel: new Vector(),
acc: new Vector()
};
}
/* Moves the particle to a given location vector.
*/
Particle.prototype.moveTo = function(pos) {
this.pos.copy(pos);
return this.old.pos.copy(pos);
};
/* Sets the mass of the particle.
*/
Particle.prototype.setMass = function(mass) {
this.mass = mass != null ? mass : 1.0;
return this.massInv = 1.0 / this.mass;
};
/* Sets the radius of the particle.
*/
Particle.prototype.setRadius = function(radius) {
this.radius = radius != null ? radius : 1.0;
return this.radiusSq = this.radius * this.radius;
};
/* Applies all behaviours to derive new force.
*/
Particle.prototype.update = function(dt, index) {
var behaviour, _i, _len, _ref, _results;
if (!this.fixed) {
_ref = this.behaviours;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
behaviour = _ref[_i];
_results.push(behaviour.apply(this, dt, index));
}
return _results;
}
};
return Particle;
})();
/* Spring
*/
Spring = (function() {
function Spring(p1, p2, restLength, stiffness) {
this.p1 = p1;
this.p2 = p2;
this.restLength = restLength != null ? restLength : 100;
this.stiffness = stiffness != null ? stiffness : 1.0;
this._delta = new Vector();
}
Spring.prototype.apply = function() {
var dist, force;
(this._delta.copy(this.p2.pos)).sub(this.p1.pos);
dist = this._delta.mag() + 0.000001;
force = (dist - this.restLength) / (dist * (this.p1.massInv + this.p2.massInv)) * this.stiffness;
if (!this.p1.fixed) {
this.p1.pos.add(this._delta.clone().scale(force * this.p1.massInv));
}
if (!this.p2.fixed) {
return this.p2.pos.add(this._delta.scale(-force * this.p2.massInv));
}
};
return Spring;
})();
/* Physics Engine
*/
Physics = (function() {
function Physics(integrator) {
this.integrator = integrator != null ? integrator : new Euler();
this.timestep = 1.0 / 60;
this.viscosity = 0.005;
this.behaviours = [];
this._time = 0.0;
this._step = 0.0;
this._clock = null;
this._buffer = 0.0;
this._maxSteps = 4;
this.particles = [];
this.springs = [];
}
/* Performs a numerical integration step.
*/
Physics.prototype.integrate = function(dt) {
var behaviour, drag, index, particle, spring, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results;
drag = 1.0 - this.viscosity;
_ref = this.particles;
for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
particle = _ref[index];
_ref1 = this.behaviours;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
behaviour = _ref1[_j];
behaviour.apply(particle, dt, index);
}
particle.update(dt, index);
}
this.integrator.integrate(this.particles, dt, drag);
_ref2 = this.springs;
_results = [];
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
spring = _ref2[_k];
_results.push(spring.apply());
}
return _results;
};
/* Steps the system.
*/
Physics.prototype.step = function() {
var delta, i, time, _ref;
if ((_ref = this._clock) == null) {
this._clock = new Date().getTime();
}
time = new Date().getTime();
delta = time - this._clock;
if (delta <= 0.0) {
return;
}
delta *= 0.001;
this._clock = time;
this._buffer += delta;
i = 0;
while (this._buffer >= this.timestep && ++i < this._maxSteps) {
this.integrate(this.timestep);
this._buffer -= this.timestep;
this._time += this.timestep;
}
return this._step = new Date().getTime() - time;
};
/* Clean up after yourself.
*/
Physics.prototype.destroy = function() {
this.integrator = null;
this.particles = null;
return this.springs = null;
};
return Physics;
})();
/* Integrator
*/
Integrator = (function() {
function Integrator() {}
Integrator.prototype.integrate = function(particles, dt) {};
return Integrator;
})();
/* Euler Integrator
*/
Euler = (function(_super) {
__extends(Euler, _super);
function Euler() {
return Euler.__super__.constructor.apply(this, arguments);
}
Euler.prototype.integrate = function(particles, dt, drag) {
var p, vel, _i, _len, _results;
vel = new Vector();
_results = [];
for (_i = 0, _len = particles.length; _i < _len; _i++) {
p = particles[_i];
if (!(!p.fixed)) {
continue;
}
p.old.pos.copy(p.pos);
p.acc.scale(p.massInv);
vel.copy(p.vel);
p.vel.add(p.acc.scale(dt));
p.pos.add(vel.scale(dt));
if (drag) {
p.vel.scale(drag);
}
_results.push(p.acc.clear());
}
return _results;
};
return Euler;
})(Integrator);
/* Improved Euler Integrator
*/
ImprovedEuler = (function(_super) {
__extends(ImprovedEuler, _super);
function ImprovedEuler() {
return ImprovedEuler.__super__.constructor.apply(this, arguments);
}
ImprovedEuler.prototype.integrate = function(particles, dt, drag) {
var acc, dtSq, p, vel, _i, _len, _results;
acc = new Vector();
vel = new Vector();
dtSq = dt * dt;
_results = [];
for (_i = 0, _len = particles.length; _i < _len; _i++) {
p = particles[_i];
if (!(!p.fixed)) {
continue;
}
p.old.pos.copy(p.pos);
p.acc.scale(p.massInv);
vel.copy(p.vel);
acc.copy(p.acc);
p.pos.add((vel.scale(dt)).add(acc.scale(0.5 * dtSq)));
p.vel.add(p.acc.scale(dt));
if (drag) {
p.vel.scale(drag);
}
_results.push(p.acc.clear());
}
return _results;
};
return ImprovedEuler;
})(Integrator);
/* Velocity Verlet Integrator
*/
Verlet = (function(_super) {
__extends(Verlet, _super);
function Verlet() {
return Verlet.__super__.constructor.apply(this, arguments);
}
Verlet.prototype.integrate = function(particles, dt, drag) {
var dtSq, p, pos, _i, _len, _results;
pos = new Vector();
dtSq = dt * dt;
_results = [];
for (_i = 0, _len = particles.length; _i < _len; _i++) {
p = particles[_i];
if (!(!p.fixed)) {
continue;
}
p.acc.scale(p.massInv);
(p.vel.copy(p.pos)).sub(p.old.pos);
if (drag) {
p.vel.scale(drag);
}
(pos.copy(p.pos)).add(p.vel.add(p.acc.scale(dtSq)));
p.old.pos.copy(p.pos);
p.pos.copy(pos);
_results.push(p.acc.clear());
}
return _results;
};
return Verlet;
})(Integrator);
/* Behaviour
*/
Behaviour = (function() {
Behaviour.GUID = 0;
function Behaviour() {
this.GUID = Behaviour.GUID++;
this.interval = 1;
}
Behaviour.prototype.apply = function(p, dt, index) {
var _name, _ref;
return ((_ref = p[_name = '__behaviour' + this.GUID]) != null ? _ref : p[_name] = {
counter: 0
}).counter++;
};
return Behaviour;
})();
/* Attraction Behaviour
*/
Attraction = (function(_super) {
__extends(Attraction, _super);
function Attraction(target, radius, strength) {
this.target = target != null ? target : new Vector();
this.radius = radius != null ? radius : 1000;
this.strength = strength != null ? strength : 100.0;
this._delta = new Vector();
this.setRadius(this.radius);
Attraction.__super__.constructor.apply(this, arguments);
}
/* Sets the effective radius of the bahavious.
*/
Attraction.prototype.setRadius = function(radius) {
this.radius = radius;
return this.radiusSq = radius * radius;
};
Attraction.prototype.apply = function(p, dt, index) {
var distSq;
(this._delta.copy(this.target)).sub(p.pos);
distSq = this._delta.magSq();
if (distSq < this.radiusSq && distSq > 0.000001) {
this._delta.norm().scale(1.0 - distSq / this.radiusSq);
return p.acc.add(this._delta.scale(this.strength));
}
};
return Attraction;
})(Behaviour);
/* Collision Behaviour
*/
Collision = (function(_super) {
__extends(Collision, _super);
function Collision(useMass, callback) {
this.useMass = useMass != null ? useMass : true;
this.callback = callback != null ? callback : null;
this.pool = [];
this._delta = new Vector();
Collision.__super__.constructor.apply(this, arguments);
}
Collision.prototype.apply = function(p, dt, index) {
var dist, distSq, i, mt, o, overlap, r1, r2, radii, _i, _ref, _results;
_results = [];
for (i = _i = index, _ref = this.pool.length - 1; index <= _ref ? _i <= _ref : _i >= _ref; i = index <= _ref ? ++_i : --_i) {
o = this.pool[i];
if (o !== p) {
(this._delta.copy(o.pos)).sub(p.pos);
distSq = this._delta.magSq();
radii = p.radius + o.radius;
if (distSq <= radii * radii) {
dist = Math.sqrt(distSq);
overlap = (p.radius + o.radius) - dist;
overlap += 0.5;
mt = p.mass + o.mass;
r1 = this.useMass ? o.mass / mt : 0.5;
r2 = this.useMass ? p.mass / mt : 0.5;
p.pos.add(this._delta.clone().norm().scale(overlap * -r1));
o.pos.add(this._delta.norm().scale(overlap * r2));
_results.push(typeof this.callback === "function" ? this.callback(p, o, overlap) : void 0);
} else {
_results.push(void 0);
}
} else {
_results.push(void 0);
}
}
return _results;
};
return Collision;
})(Behaviour);
/* Constant Force Behaviour
*/
ConstantForce = (function(_super) {
__extends(ConstantForce, _super);
function ConstantForce(force) {
this.force = force != null ? force : new Vector();
ConstantForce.__super__.constructor.apply(this, arguments);
}
ConstantForce.prototype.apply = function(p, dt, index) {
return p.acc.add(this.force);
};
return ConstantForce;
})(Behaviour);
/* Edge Bounce Behaviour
*/
EdgeBounce = (function(_super) {
__extends(EdgeBounce, _super);
function EdgeBounce(min, max) {
this.min = min != null ? min : new Vector();
this.max = max != null ? max : new Vector();
EdgeBounce.__super__.constructor.apply(this, arguments);
}
EdgeBounce.prototype.apply = function(p, dt, index) {
if (p.pos.x - p.radius < this.min.x) {
p.pos.x = this.min.x + p.radius;
} else if (p.pos.x + p.radius > this.max.x) {
p.pos.x = this.max.x - p.radius;
}
if (p.pos.y - p.radius < this.min.y) {
return p.pos.y = this.min.y + p.radius;
} else if (p.pos.y + p.radius > this.max.y) {
return p.pos.y = this.max.y - p.radius;
}
};
return EdgeBounce;
})(Behaviour);
/* Edge Wrap Behaviour
*/
EdgeWrap = (function(_super) {
__extends(EdgeWrap, _super);
function EdgeWrap(min, max) {
this.min = min != null ? min : new Vector();
this.max = max != null ? max : new Vector();
EdgeWrap.__super__.constructor.apply(this, arguments);
}
EdgeWrap.prototype.apply = function(p, dt, index) {
if (p.pos.x + p.radius < this.min.x) {
p.pos.x = this.max.x + p.radius;
p.old.pos.x = p.pos.x;
} else if (p.pos.x - p.radius > this.max.x) {
p.pos.x = this.min.x - p.radius;
p.old.pos.x = p.pos.x;
}
if (p.pos.y + p.radius < this.min.y) {
p.pos.y = this.max.y + p.radius;
return p.old.pos.y = p.pos.y;
} else if (p.pos.y - p.radius > this.max.y) {
p.pos.y = this.min.y - p.radius;
return p.old.pos.y = p.pos.y;
}
};
return EdgeWrap;
})(Behaviour);
/* Wander Behaviour
*/
Wander = (function(_super) {
__extends(Wander, _super);
function Wander(jitter, radius, strength) {
this.jitter = jitter != null ? jitter : 0.5;
this.radius = radius != null ? radius : 100;
this.strength = strength != null ? strength : 1.0;
this.theta = Math.random() * Math.PI * 2;
Wander.__super__.constructor.apply(this, arguments);
}
Wander.prototype.apply = function(p, dt, index) {
this.theta += (Math.random() - 0.5) * this.jitter * Math.PI * 2;
p.acc.x += Math.cos(this.theta) * this.radius * this.strength;
return p.acc.y += Math.sin(this.theta) * this.radius * this.strength;
};
return Wander;
})(Behaviour);