Link force add end condition

This commit is contained in:
Pitchaya Boonsarngsuk
2018-02-06 13:19:39 +00:00
parent 3bbd39f04d
commit 4243cc0f9c
2 changed files with 36 additions and 2 deletions

View File

@@ -14,7 +14,9 @@ function startLinkSimulation() {
force = d3.forceLinkFullyConnected()
.distance(function (n, m) {
return distanceFunction(n, m, props, norm);
});
})
.stableVelocity(0.000001) //TODO
.onStableVelo(ended);
}
else {
for (i = nodes.length-1; i >= 1; i--) {

View File

@@ -13,11 +13,22 @@ export default function() {
distance = constant(30),
distances = [],
nodes,
stableVelocity = 0,
stableVeloHandler = null,
iterations = 1;
function force(alpha) {
let n = nodes.length;
// Cache old velocity for comparison later
if (stableVeloHandler!==null && stableVelocity>=0) {
for (let i = n-1, node; i>=0; i--) {
node = nodes[i];
node.oldvx = node.vx;
node.oldvy = node.vy;
}
}
// Each iteration in a tick
for (var k = 0, n = nodes.length, source, target, i, j, x, y, l; k < iterations; ++k) {
for (var k = 0, source, target, i, j, x, y, l; k < iterations; ++k) {
// For each link
for (i = 1; i < n; i++) for (j = 0; j < i; j++) {
// jiggle so l won't be zero and divide by zero error after this
@@ -34,6 +45,20 @@ export default function() {
source.vy += y;
}
}
// Calculate velocity changes, aka force applied.
if (stableVeloHandler!==null && stableVelocity>=0) {
let velocityDiff = 0;
for (let i = n-1, node; i>=0; i--) {
node = nodes[i];
velocityDiff += Math.abs(Math.hypot(node.vx-node.oldvx, node.vy-node.oldvy));
}
velocityDiff /= n*(n-1);
if(velocityDiff<stableVelocity){
stableVeloHandler();
}
}
}
function initialize() {
@@ -65,5 +90,12 @@ export default function() {
return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance;
};
force.onStableVelo = function (_) {
return arguments.length ? (stableVeloHandler = _, force) : stableVeloHandler;
};
force.stableVelocity = function (_) {
return arguments.length ? (stableVelocity = _, force) : stableVelocity;
};
return force;
}