source: node_modules/d3-force/src/collide.js@ e4c61dd

Last change on this file since e4c61dd was e4c61dd, checked in by istevanoska <ilinastevanoska@…>, 6 months ago

Prototype 1.1

  • Property mode set to 100644
File size: 2.5 KB
Line 
1import {quadtree} from "d3-quadtree";
2import constant from "./constant.js";
3import jiggle from "./jiggle.js";
4
5function x(d) {
6 return d.x + d.vx;
7}
8
9function y(d) {
10 return d.y + d.vy;
11}
12
13export default function(radius) {
14 var nodes,
15 radii,
16 random,
17 strength = 1,
18 iterations = 1;
19
20 if (typeof radius !== "function") radius = constant(radius == null ? 1 : +radius);
21
22 function force() {
23 var i, n = nodes.length,
24 tree,
25 node,
26 xi,
27 yi,
28 ri,
29 ri2;
30
31 for (var k = 0; k < iterations; ++k) {
32 tree = quadtree(nodes, x, y).visitAfter(prepare);
33 for (i = 0; i < n; ++i) {
34 node = nodes[i];
35 ri = radii[node.index], ri2 = ri * ri;
36 xi = node.x + node.vx;
37 yi = node.y + node.vy;
38 tree.visit(apply);
39 }
40 }
41
42 function apply(quad, x0, y0, x1, y1) {
43 var data = quad.data, rj = quad.r, r = ri + rj;
44 if (data) {
45 if (data.index > node.index) {
46 var x = xi - data.x - data.vx,
47 y = yi - data.y - data.vy,
48 l = x * x + y * y;
49 if (l < r * r) {
50 if (x === 0) x = jiggle(random), l += x * x;
51 if (y === 0) y = jiggle(random), l += y * y;
52 l = (r - (l = Math.sqrt(l))) / l * strength;
53 node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj));
54 node.vy += (y *= l) * r;
55 data.vx -= x * (r = 1 - r);
56 data.vy -= y * r;
57 }
58 }
59 return;
60 }
61 return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;
62 }
63 }
64
65 function prepare(quad) {
66 if (quad.data) return quad.r = radii[quad.data.index];
67 for (var i = quad.r = 0; i < 4; ++i) {
68 if (quad[i] && quad[i].r > quad.r) {
69 quad.r = quad[i].r;
70 }
71 }
72 }
73
74 function initialize() {
75 if (!nodes) return;
76 var i, n = nodes.length, node;
77 radii = new Array(n);
78 for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes);
79 }
80
81 force.initialize = function(_nodes, _random) {
82 nodes = _nodes;
83 random = _random;
84 initialize();
85 };
86
87 force.iterations = function(_) {
88 return arguments.length ? (iterations = +_, force) : iterations;
89 };
90
91 force.strength = function(_) {
92 return arguments.length ? (strength = +_, force) : strength;
93 };
94
95 force.radius = function(_) {
96 return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
97 };
98
99 return force;
100}
Note: See TracBrowser for help on using the repository browser.