Link force add end condition
This commit is contained in:
34
src/link.js
34
src/link.js
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user