ngraph.forcelayout3d
Version:
Force directed graph layout in 3d
52 lines (41 loc) • 1.36 kB
JavaScript
/**
* Performs 3d forces integration, using given timestep. Uses Euler method to solve
* differential equation (http://en.wikipedia.org/wiki/Euler_method ).
*
* @returns {Number} squared distance of total position updates.
*/
module.exports = integrate;
function integrate(bodies, timeStep, adaptiveTimeStepWeight) {
var dx = 0, tx = 0,
dy = 0, ty = 0,
dz = 0, tz = 0,
i,
max = bodies.length;
for (i = 0; i < max; ++i) {
var body = bodies[i];
if (adaptiveTimeStepWeight && body.springCount) {
timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);
}
var coeff = timeStep / body.mass;
body.velocity.x += coeff * body.force.x;
body.velocity.y += coeff * body.force.y;
body.velocity.z += coeff * body.force.z;
var vx = body.velocity.x,
vy = body.velocity.y,
vz = body.velocity.z,
v = Math.sqrt(vx * vx + vy * vy + vz * vz);
if (v > 1) {
body.velocity.x = vx / v;
body.velocity.y = vy / v;
body.velocity.z = vz / v;
}
dx = timeStep * body.velocity.x;
dy = timeStep * body.velocity.y;
dz = timeStep * body.velocity.z;
body.pos.x += dx;
body.pos.y += dy;
body.pos.z += dz;
tx += Math.abs(dx); ty += Math.abs(dy); tz += Math.abs(dz);
}
return (tx * tx + ty * ty + tz * tz)/bodies.length;
}