d3-force/src/simulation.js

90 lines
2.3 KiB
JavaScript
Raw Normal View History

2016-04-06 04:50:36 +08:00
import {dispatch as newDispatch} from "d3-dispatch";
import {map as newMap} from "d3-collection";
import {timer as newTimer} from "d3-timer";
2016-04-06 04:50:36 +08:00
export default function(nodes) {
var simulation,
iteration = 0,
alpha = 1,
2016-04-07 04:51:59 +08:00
alphaMin = 0.0001,
alphaDecay = -0.02,
velocityDecay = 0.5,
force = newMap(),
2016-04-06 04:50:36 +08:00
timer = newTimer(tick),
dispatch = newDispatch("start", "tick", "end");
2016-04-06 04:50:36 +08:00
2016-04-07 04:21:23 +08:00
function start() {
2016-04-07 04:51:59 +08:00
if (iteration < Infinity) {
iteration = 0, alpha = 1;
} else {
iteration = 0, alpha = 1;
dispatch.call("start", simulation);
2016-04-07 04:21:23 +08:00
timer.restart(tick);
}
return simulation;
2016-04-07 04:21:23 +08:00
}
function stop() {
2016-04-07 04:51:59 +08:00
if (iteration < Infinity) {
iteration = Infinity, alpha = 0;
dispatch.call("end", simulation);
2016-04-07 04:21:23 +08:00
timer.stop();
2016-04-06 04:50:36 +08:00
}
return simulation;
2016-04-06 04:50:36 +08:00
}
function tick() {
alpha = Math.exp(++iteration * alphaDecay);
2016-04-07 04:51:59 +08:00
if (!(alpha > alphaMin)) return stop();
force.each(apply);
2016-04-06 04:50:36 +08:00
for (var i = 0, n = nodes.length, node; i < n; ++i) {
node = nodes[i];
2016-04-07 04:21:23 +08:00
node.x += node.vx *= velocityDecay;
node.y += node.vy *= velocityDecay;
2016-04-06 04:50:36 +08:00
}
dispatch.call("tick", simulation);
2016-04-06 04:50:36 +08:00
}
function index() {
for (var i = 0, n = nodes.length; i < n; ++i) {
nodes[i].index = i;
}
}
function initialize(force) {
2016-04-21 00:53:56 +08:00
if (force.nodes) force.nodes(nodes);
}
function apply(force) {
force(alpha);
}
index();
return simulation = {
start: start,
stop: stop,
tick: tick,
2016-04-06 04:50:36 +08:00
nodes: function(_) {
return arguments.length ? (nodes = _, index(), force.each(initialize), simulation) : nodes;
2016-04-06 04:50:36 +08:00
},
2016-04-07 04:51:59 +08:00
alphaMin: function(_) {
return arguments.length ? (alphaMin = _, simulation) : alphaMin;
2016-04-06 04:50:36 +08:00
},
alphaDecay: function(_) {
return arguments.length ? (alphaDecay = -_, iteration = Math.round(Math.log(alpha) / alphaDecay), simulation) : -alphaDecay;
2016-04-06 04:50:36 +08:00
},
2016-04-07 04:21:23 +08:00
friction: function(_) {
return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay;
},
force: function(name, _) {
return arguments.length > 1 ? (initialize(_), force.set(name, _), simulation) : force.get(name);
2016-04-06 04:50:36 +08:00
},
on: function(name, _) {
return arguments.length > 1 ? (dispatch.on(name, _), simulation) : dispatch.on(name);
2016-04-06 04:50:36 +08:00
}
};
}