-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathPhysicsEngine.js
461 lines (406 loc) · 14.2 KB
/
PhysicsEngine.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* @license MPL 2.0
* @copyright Famous Industries, Inc. 2014
*/
define(function(require, exports, module) {
var EventHandler = require('famous/core/EventHandler');
/**
* The Physics Engine is responsible for mediating Bodies and their
* interaction with forces and constraints. The Physics Engine handles the
* logic of adding and removing bodies, updating their state of the over
* time.
*
* @class PhysicsEngine
* @constructor
* @param options {Object} options
*/
function PhysicsEngine(options) {
this.options = Object.create(PhysicsEngine.DEFAULT_OPTIONS);
if (options) this.setOptions(options);
this._particles = []; //list of managed particles
this._bodies = []; //list of managed bodies
this._agents = {}; //hash of managed agents
this._forces = []; //list of IDs of agents that are forces
this._constraints = []; //list of IDs of agents that are constraints
this._buffer = 0.0;
this._prevTime = now();
this._isSleeping = false;
this._eventHandler = null;
this._currAgentId = 0;
this._hasBodies = false;
}
var TIMESTEP = 17;
var MIN_TIME_STEP = 1000 / 120;
var MAX_TIME_STEP = 17;
/**
* @property PhysicsEngine.DEFAULT_OPTIONS
* @type Object
* @protected
* @static
*/
PhysicsEngine.DEFAULT_OPTIONS = {
/**
* The number of iterations the engine takes to resolve constraints
* @attribute constraintSteps
* @type Number
*/
constraintSteps : 1,
/**
* The energy threshold before the Engine stops updating
* @attribute sleepTolerance
* @type Number
*/
sleepTolerance : 1e-7
};
var now = (function() {
return Date.now;
})();
/**
* Options setter
* @method setOptions
* @param options {Object}
*/
PhysicsEngine.prototype.setOptions = function setOptions(opts) {
for (var key in opts) if (this.options[key]) this.options[key] = opts[key];
};
/**
* Method to add a physics body to the engine. Necessary to update the
* body over time.
*
* @method addBody
* @param body {Body}
* @return body {Body}
*/
PhysicsEngine.prototype.addBody = function addBody(body) {
body._engine = this;
if (body.isBody) {
this._bodies.push(body);
this._hasBodies = true;
}
else this._particles.push(body);
return body;
};
/**
* Remove a body from the engine. Detaches body from all forces and
* constraints.
*
* @method removeBody
* @param body {Body}
*/
PhysicsEngine.prototype.removeBody = function removeBody(body) {
var array = (body.isBody) ? this._bodies : this._particles;
var index = array.indexOf(body);
if (index > -1) {
for (var i = 0; i < Object.keys(this._agents).length; i++) this.detachFrom(i, body);
array.splice(index,1);
}
if (this.getBodies().length === 0) this._hasBodies = false;
};
function _mapAgentArray(agent) {
if (agent.applyForce) return this._forces;
if (agent.applyConstraint) return this._constraints;
}
function _attachOne(agent, targets, source) {
if (targets === undefined) targets = this.getParticlesAndBodies();
if (!(targets instanceof Array)) targets = [targets];
this._agents[this._currAgentId] = {
agent : agent,
targets : targets,
source : source
};
_mapAgentArray.call(this, agent).push(this._currAgentId);
return this._currAgentId++;
}
/**
* Attaches a force or constraint to a Body. Returns an AgentId of the
* attached agent which can be used to detach the agent.
*
* @method attach
* @param agent {Agent|Array.Agent} A force, constraint, or array of them.
* @param [targets=All] {Body|Array.Body} The Body or Bodies affected by the agent
* @param [source] {Body} The source of the agent
* @return AgentId {Number}
*/
PhysicsEngine.prototype.attach = function attach(agents, targets, source) {
if (agents instanceof Array) {
var agentIDs = [];
for (var i = 0; i < agents.length; i++)
agentIDs[i] = _attachOne.call(this, agents[i], targets, source);
return agentIDs;
}
else return _attachOne.call(this, agents, targets, source);
};
/**
* Append a body to the targets of a previously defined physics agent.
*
* @method attachTo
* @param agentID {AgentId} The agentId of a previously defined agent
* @param target {Body} The Body affected by the agent
*/
PhysicsEngine.prototype.attachTo = function attachTo(agentID, target) {
_getBoundAgent.call(this, agentID).targets.push(target);
};
/**
* Undoes PhysicsEngine.attach. Removes an agent and its associated
* effect on its affected Bodies.
*
* @method detach
* @param agentID {AgentId} The agentId of a previously defined agent
*/
PhysicsEngine.prototype.detach = function detach(id) {
// detach from forces/constraints array
var agent = this.getAgent(id);
var agentArray = _mapAgentArray.call(this, agent);
var index = agentArray.indexOf(id);
agentArray.splice(index,1);
// detach agents array
delete this._agents[id];
};
/**
* Remove a single Body from a previously defined agent.
*
* @method detach
* @param agentID {AgentId} The agentId of a previously defined agent
* @param target {Body} The body to remove from the agent
*/
PhysicsEngine.prototype.detachFrom = function detachFrom(id, target) {
var boundAgent = _getBoundAgent.call(this, id);
if (boundAgent.source === target) this.detach(id);
else {
var targets = boundAgent.targets;
var index = targets.indexOf(target);
if (index > -1) targets.splice(index,1);
}
};
/**
* A convenience method to give the Physics Engine a clean slate of
* agents. Preserves all added Body objects.
*
* @method detachAll
*/
PhysicsEngine.prototype.detachAll = function detachAll() {
this._agents = {};
this._forces = [];
this._constraints = [];
this._currAgentId = 0;
};
function _getBoundAgent(id) {
return this._agents[id];
}
/**
* Returns the corresponding agent given its agentId.
*
* @method getAgent
* @param id {AgentId}
*/
PhysicsEngine.prototype.getAgent = function getAgent(id) {
return _getBoundAgent.call(this, id).agent;
};
/**
* Returns all particles that are currently managed by the Physics Engine.
*
* @method getParticles
* @return particles {Array.Particles}
*/
PhysicsEngine.prototype.getParticles = function getParticles() {
return this._particles;
};
/**
* Returns all bodies, except particles, that are currently managed by the Physics Engine.
*
* @method getBodies
* @return bodies {Array.Bodies}
*/
PhysicsEngine.prototype.getBodies = function getBodies() {
return this._bodies;
};
/**
* Returns all bodies that are currently managed by the Physics Engine.
*
* @method getBodies
* @return bodies {Array.Bodies}
*/
PhysicsEngine.prototype.getParticlesAndBodies = function getParticlesAndBodies() {
return this.getParticles().concat(this.getBodies());
};
/**
* Iterates over every Particle and applies a function whose first
* argument is the Particle
*
* @method forEachParticle
* @param fn {Function} Function to iterate over
* @param [dt] {Number} Delta time
*/
PhysicsEngine.prototype.forEachParticle = function forEachParticle(fn, dt) {
var particles = this.getParticles();
for (var index = 0, len = particles.length; index < len; index++)
fn.call(this, particles[index], dt);
};
/**
* Iterates over every Body that isn't a Particle and applies
* a function whose first argument is the Body
*
* @method forEachBody
* @param fn {Function} Function to iterate over
* @param [dt] {Number} Delta time
*/
PhysicsEngine.prototype.forEachBody = function forEachBody(fn, dt) {
if (!this._hasBodies) return;
var bodies = this.getBodies();
for (var index = 0, len = bodies.length; index < len; index++)
fn.call(this, bodies[index], dt);
};
/**
* Iterates over every Body and applies a function whose first
* argument is the Body
*
* @method forEach
* @param fn {Function} Function to iterate over
* @param [dt] {Number} Delta time
*/
PhysicsEngine.prototype.forEach = function forEach(fn, dt) {
this.forEachParticle(fn, dt);
this.forEachBody(fn, dt);
};
function _updateForce(index) {
var boundAgent = _getBoundAgent.call(this, this._forces[index]);
boundAgent.agent.applyForce(boundAgent.targets, boundAgent.source);
}
function _updateForces() {
for (var index = this._forces.length - 1; index > -1; index--)
_updateForce.call(this, index);
}
function _updateConstraint(index, dt) {
var boundAgent = this._agents[this._constraints[index]];
return boundAgent.agent.applyConstraint(boundAgent.targets, boundAgent.source, dt);
}
function _updateConstraints(dt) {
var iteration = 0;
while (iteration < this.options.constraintSteps) {
for (var index = this._constraints.length - 1; index > -1; index--)
_updateConstraint.call(this, index, dt);
iteration++;
}
}
function _updateVelocities(particle, dt) {
particle.integrateVelocity(dt);
}
function _updateAngularVelocities(body, dt) {
body.integrateAngularMomentum(dt);
body.updateAngularVelocity();
}
function _updateOrientations(body, dt) {
body.integrateOrientation(dt);
}
function _updatePositions(particle, dt) {
particle.integratePosition(dt);
particle.emit('update', particle);
}
function _integrate(dt) {
_updateForces.call(this, dt);
this.forEach(_updateVelocities, dt);
this.forEachBody(_updateAngularVelocities, dt);
_updateConstraints.call(this, dt);
this.forEachBody(_updateOrientations, dt);
this.forEach(_updatePositions, dt);
}
function _getEnergyParticles() {
var energy = 0.0;
var particleEnergy = 0.0;
this.forEach(function(particle) {
particleEnergy = particle.getEnergy();
energy += particleEnergy;
if (particleEnergy < particle.sleepTolerance) particle.sleep();
});
return energy;
}
function _getEnergyForces() {
var energy = 0;
for (var index = this._forces.length - 1; index > -1; index--)
energy += this._forces[index].getEnergy() || 0.0;
return energy;
}
function _getEnergyConstraints() {
var energy = 0;
for (var index = this._constraints.length - 1; index > -1; index--)
energy += this._constraints[index].getEnergy() || 0.0;
return energy;
}
/**
* Calculates the kinetic energy of all Body objects and potential energy
* of all attached agents.
*
* TODO: implement.
* @method getEnergy
* @return energy {Number}
*/
PhysicsEngine.prototype.getEnergy = function getEnergy() {
return _getEnergyParticles.call(this) + _getEnergyForces.call(this) + _getEnergyConstraints.call(this);
};
/**
* Updates all Body objects managed by the physics engine over the
* time duration since the last time step was called.
*
* @method step
*/
PhysicsEngine.prototype.step = function step() {
// if (this.getEnergy() < this.options.sleepTolerance) {
// this.sleep();
// return;
// };
//set current frame's time
var currTime = now();
//milliseconds elapsed since last frame
var dtFrame = currTime - this._prevTime;
this._prevTime = currTime;
if (dtFrame < MIN_TIME_STEP) return;
if (dtFrame > MAX_TIME_STEP) dtFrame = MAX_TIME_STEP;
//robust integration
// this._buffer += dtFrame;
// while (this._buffer > this._timestep){
// _integrate.call(this, this._timestep);
// this._buffer -= this._timestep;
// };
// _integrate.call(this, this._buffer);
// this._buffer = 0.0;
_integrate.call(this, TIMESTEP);
// this.emit('update', this);
};
/**
* Tells whether the Physics Engine is sleeping or awake.
* @method isSleeping
* @return {Boolean}
*/
PhysicsEngine.prototype.isSleeping = function isSleeping() {
return this._isSleeping;
};
/**
* Stops the Physics Engine from updating. Emits an 'end' event.
* @method sleep
*/
PhysicsEngine.prototype.sleep = function sleep() {
this.emit('end', this);
this._isSleeping = true;
};
/**
* Starts the Physics Engine from updating. Emits an 'start' event.
* @method wake
*/
PhysicsEngine.prototype.wake = function wake() {
this._prevTime = now();
this.emit('start', this);
this._isSleeping = false;
};
PhysicsEngine.prototype.emit = function emit(type, data) {
if (this._eventHandler === null) return;
this._eventHandler.emit(type, data);
};
PhysicsEngine.prototype.on = function on(event, fn) {
if (this._eventHandler === null) this._eventHandler = new EventHandler();
this._eventHandler.on(event, fn);
};
module.exports = PhysicsEngine;
});