@ac-kit/math-graph 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/LICENSE +28 -0
  3. package/README.md +118 -2
  4. package/dist/index.d.ts +12 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +11 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/layout/_force-forces.d.ts +227 -0
  9. package/dist/layout/_force-forces.d.ts.map +1 -0
  10. package/dist/layout/_force-forces.js +1572 -0
  11. package/dist/layout/_force-forces.js.map +1 -0
  12. package/dist/layout/_hierarchy-table.d.ts +34 -0
  13. package/dist/layout/_hierarchy-table.d.ts.map +1 -0
  14. package/dist/layout/_hierarchy-table.js +131 -0
  15. package/dist/layout/_hierarchy-table.js.map +1 -0
  16. package/dist/layout/_index-graph.d.ts +32 -0
  17. package/dist/layout/_index-graph.d.ts.map +1 -0
  18. package/dist/layout/_index-graph.js +51 -0
  19. package/dist/layout/_index-graph.js.map +1 -0
  20. package/dist/layout/_layer-order.d.ts +138 -0
  21. package/dist/layout/_layer-order.d.ts.map +1 -0
  22. package/dist/layout/_layer-order.js +954 -0
  23. package/dist/layout/_layer-order.js.map +1 -0
  24. package/dist/layout/_layered-acyclic.d.ts +28 -0
  25. package/dist/layout/_layered-acyclic.d.ts.map +1 -0
  26. package/dist/layout/_layered-acyclic.js +179 -0
  27. package/dist/layout/_layered-acyclic.js.map +1 -0
  28. package/dist/layout/_layered-position.d.ts +56 -0
  29. package/dist/layout/_layered-position.d.ts.map +1 -0
  30. package/dist/layout/_layered-position.js +369 -0
  31. package/dist/layout/_layered-position.js.map +1 -0
  32. package/dist/layout/_layered-rank.d.ts +58 -0
  33. package/dist/layout/_layered-rank.d.ts.map +1 -0
  34. package/dist/layout/_layered-rank.js +529 -0
  35. package/dist/layout/_layered-rank.js.map +1 -0
  36. package/dist/layout/_tree-common.d.ts +38 -0
  37. package/dist/layout/_tree-common.d.ts.map +1 -0
  38. package/dist/layout/_tree-common.js +73 -0
  39. package/dist/layout/_tree-common.js.map +1 -0
  40. package/dist/layout/_treemap-tiling.d.ts +73 -0
  41. package/dist/layout/_treemap-tiling.d.ts.map +1 -0
  42. package/dist/layout/_treemap-tiling.js +247 -0
  43. package/dist/layout/_treemap-tiling.js.map +1 -0
  44. package/dist/layout/circular-layout.d.ts +27 -0
  45. package/dist/layout/circular-layout.d.ts.map +1 -0
  46. package/dist/layout/circular-layout.js +35 -0
  47. package/dist/layout/circular-layout.js.map +1 -0
  48. package/dist/layout/create-force-step.d.ts +127 -0
  49. package/dist/layout/create-force-step.d.ts.map +1 -0
  50. package/dist/layout/create-force-step.js +167 -0
  51. package/dist/layout/create-force-step.js.map +1 -0
  52. package/dist/layout/dendrogram-layout.d.ts +32 -0
  53. package/dist/layout/dendrogram-layout.d.ts.map +1 -0
  54. package/dist/layout/dendrogram-layout.js +110 -0
  55. package/dist/layout/dendrogram-layout.js.map +1 -0
  56. package/dist/layout/force-directed-layout.d.ts +42 -0
  57. package/dist/layout/force-directed-layout.d.ts.map +1 -0
  58. package/dist/layout/force-directed-layout.js +112 -0
  59. package/dist/layout/force-directed-layout.js.map +1 -0
  60. package/dist/layout/layered-layout.d.ts +109 -0
  61. package/dist/layout/layered-layout.d.ts.map +1 -0
  62. package/dist/layout/layered-layout.js +124 -0
  63. package/dist/layout/layered-layout.js.map +1 -0
  64. package/dist/layout/partition-layout.d.ts +31 -0
  65. package/dist/layout/partition-layout.d.ts.map +1 -0
  66. package/dist/layout/partition-layout.js +78 -0
  67. package/dist/layout/partition-layout.js.map +1 -0
  68. package/dist/layout/phyllotaxis-layout.d.ts +17 -0
  69. package/dist/layout/phyllotaxis-layout.d.ts.map +1 -0
  70. package/dist/layout/phyllotaxis-layout.js +32 -0
  71. package/dist/layout/phyllotaxis-layout.js.map +1 -0
  72. package/dist/layout/sankey-layout.d.ts +113 -0
  73. package/dist/layout/sankey-layout.d.ts.map +1 -0
  74. package/dist/layout/sankey-layout.js +641 -0
  75. package/dist/layout/sankey-layout.js.map +1 -0
  76. package/dist/layout/tidy-tree-layout.d.ts +25 -0
  77. package/dist/layout/tidy-tree-layout.d.ts.map +1 -0
  78. package/dist/layout/tidy-tree-layout.js +197 -0
  79. package/dist/layout/tidy-tree-layout.js.map +1 -0
  80. package/dist/layout/treemap-layout.d.ts +63 -0
  81. package/dist/layout/treemap-layout.d.ts.map +1 -0
  82. package/dist/layout/treemap-layout.js +126 -0
  83. package/dist/layout/treemap-layout.js.map +1 -0
  84. package/dist/layout/types.d.ts +90 -0
  85. package/dist/layout/types.d.ts.map +1 -0
  86. package/dist/layout/types.js +2 -0
  87. package/dist/layout/types.js.map +1 -0
  88. package/package.json +68 -3
@@ -0,0 +1,1572 @@
1
+ import { binaryExponent, scaleByPowerOfTwoInPlace } from "@ac-kit/core";
2
+ import { Quadtree } from "@ac-kit/math-geometry";
3
+ /**
4
+ * Where {@link drawJiggle} leaves its offset. Callers read it from here instead
5
+ * of taking a return value: merging a call's result with a computed double
6
+ * forces V8 to box that double, once per link or pair.
7
+ */
8
+ const JIGGLE = new Float64Array(1);
9
+ /**
10
+ * Offset separating two coincident points that one call moves apart (a link or
11
+ * a collision applies it to both ends, with opposite signs): a seeded value in
12
+ * [−5e-7, 5e-7], as d3-force draws it. A draw that is 0, NaN or outside that
13
+ * range (a generator returning 0.5 or anything outside [0, 1)) takes ±5e-7 by
14
+ * node order, positive when `to > from`.
15
+ */
16
+ function drawJiggle(random, from, to) {
17
+ const value = (random() - 0.5) * 1e-6;
18
+ JIGGLE[0] =
19
+ value !== 0 && Math.abs(value) <= 5e-7 ? value : to > from ? 5e-7 : -5e-7;
20
+ }
21
+ /**
22
+ * {@link drawJiggle} for one end of a coincident pair whose two ends draw
23
+ * separately (the charge): they part only if their offsets differ. The draw is
24
+ * kept, as d3-force's, unless it is 0, NaN, not inside (−5e-7, 5e-7), or equal
25
+ * to the previous draw (left in `scratch[slot]`), as a constant generator gives
26
+ * both ends; then the offset is ±5e-7 by node order, positive when `to > from`,
27
+ * which no kept draw equals, and opposite at the two ends.
28
+ */
29
+ function drawPairJiggle(random, from, to, scratch, slot) {
30
+ const value = (random() - 0.5) * 1e-6;
31
+ const previous = scratch[slot];
32
+ scratch[slot] = value;
33
+ JIGGLE[0] =
34
+ value !== 0 && Math.abs(value) < 5e-7 && value !== previous
35
+ ? value
36
+ : to > from
37
+ ? 5e-7
38
+ : -5e-7;
39
+ }
40
+ function grown(array, length) {
41
+ return array.length >= length
42
+ ? array
43
+ : new Float64Array(Math.max(length, array.length * 2));
44
+ }
45
+ /**
46
+ * The contract where a position or velocity would leave the doubles: it
47
+ * saturates at ±`Number.MAX_VALUE`. Replaces an infinite `values[index]` by the
48
+ * largest double of its sign; anything else is left.
49
+ */
50
+ function saturate_(values, index) {
51
+ const value = values[index];
52
+ if (value === Infinity) {
53
+ values[index] = Number.MAX_VALUE;
54
+ }
55
+ else if (value === -Infinity) {
56
+ values[index] = -Number.MAX_VALUE;
57
+ }
58
+ }
59
+ /**
60
+ * Writes `(p[to] + v[to]) − (p[from] + v[from])`, x then y, into `out[slot]`
61
+ * and `out[slot + 1]` (`p` the positions, `v` the velocities, `to` and `from`
62
+ * indices of x), and returns the power of two they are to be multiplied by: 0
63
+ * as d3-force rounds it, or 2 with every term quartered first where a sum or
64
+ * the difference would leave the doubles (a quarter of each is exact but for
65
+ * the bits below the smallest double, which the others then dwarf).
66
+ */
67
+ function predictedDelta_(out, slot, positions, velocities, to, from) {
68
+ const dx = positions[to] + velocities[to] - positions[from] - velocities[from];
69
+ const dy = positions[to + 1] +
70
+ velocities[to + 1] -
71
+ positions[from + 1] -
72
+ velocities[from + 1];
73
+ if (dx - dx + (dy - dy) === 0) {
74
+ out[slot] = dx;
75
+ out[slot + 1] = dy;
76
+ return 0;
77
+ }
78
+ out[slot] =
79
+ positions[to] * 0.25 +
80
+ velocities[to] * 0.25 -
81
+ (positions[from] * 0.25 + velocities[from] * 0.25);
82
+ out[slot + 1] =
83
+ positions[to + 1] * 0.25 +
84
+ velocities[to + 1] * 0.25 -
85
+ (positions[from + 1] * 0.25 + velocities[from + 1] * 0.25);
86
+ return 2;
87
+ }
88
+ /**
89
+ * Coordinates a quadtree takes beyond which the forces index scaled copies: the
90
+ * tree holds points within ±1e150 (about 2^498).
91
+ */
92
+ const TREE_LIMIT_ = 2 ** 480;
93
+ /**
94
+ * The exponent `s` such that coordinates up to `largest`, scaled by `2^−s`,
95
+ * stay within {@link TREE_LIMIT_}: 0 while they already do.
96
+ */
97
+ function treeShift_(largest) {
98
+ return largest <= TREE_LIMIT_ ? 0 : binaryExponent(largest) - 479;
99
+ }
100
+ /**
101
+ * Springs between linked nodes, on positions advanced by their velocities (the
102
+ * velocity-Verlet predictor); the correction goes to the velocities. A link
103
+ * whose squared length, ratio `(l − d) / l` or move would leave the doubles is
104
+ * settled on lengths scaled by a power of two, each end's share applied before
105
+ * scaling back, so that it pulls or pushes wherever its share of the move is
106
+ * finite (a rest length of `Number.MAX_VALUE` included).
107
+ */
108
+ export function applyLinkForce(positions, velocities, alpha, data, random) {
109
+ const { sources, targets, distances, strengths, biases, iterations } = data;
110
+ for (let iteration = 0; iteration < iterations; iteration++) {
111
+ for (let link = 0; link < sources.length; link++) {
112
+ const source = sources[link] * 2;
113
+ const target = targets[link] * 2;
114
+ const pair = FORCE_;
115
+ const prescale = predictedDelta_(pair, FORCE_DX_, positions, velocities, target, source);
116
+ let dx = pair[FORCE_DX_];
117
+ if (dx === 0) {
118
+ drawJiggle(random, sources[link], targets[link]);
119
+ dx = JIGGLE[0];
120
+ }
121
+ let dy = pair[FORCE_DY_];
122
+ if (dy === 0) {
123
+ drawJiggle(random, sources[link], targets[link]);
124
+ dy = JIGGLE[0];
125
+ }
126
+ const squared = dx * dx + dy * dy;
127
+ const length = Math.sqrt(squared);
128
+ const scale = ((length - distances[link]) / length) * alpha * strengths[link];
129
+ if (prescale === 0 &&
130
+ squared >= NORMAL_SQUARE_ &&
131
+ squared < Infinity &&
132
+ dx * scale - dx * scale === 0 &&
133
+ dy * scale - dy * scale === 0) {
134
+ dx *= scale;
135
+ dy *= scale;
136
+ let share = biases[link];
137
+ velocities[target] -= dx * share;
138
+ velocities[target + 1] -= dy * share;
139
+ saturate_(velocities, target);
140
+ saturate_(velocities, target + 1);
141
+ share = 1 - share;
142
+ velocities[source] += dx * share;
143
+ velocities[source + 1] += dy * share;
144
+ saturate_(velocities, source);
145
+ saturate_(velocities, source + 1);
146
+ continue;
147
+ }
148
+ // A difference, a square, the ratio (l − d) / l or the move left the
149
+ // doubles: the move (l − d) / l · (dx, dy) = −u · (d − l), u the unit
150
+ // direction, each end's share taken in scaled lengths.
151
+ pair[FORCE_DX_] = dx;
152
+ pair[FORCE_DY_] = dy;
153
+ pair[FORCE_PRESCALE_] = prescale;
154
+ pair[FORCE_REACH_] = distances[link];
155
+ pair[FORCE_REACH_OTHER_] = 0;
156
+ pair[FORCE_FACTOR_] = alpha;
157
+ pair[FORCE_SECOND_FACTOR_] = strengths[link];
158
+ // A self-link's two ends are one node: its moves net out first.
159
+ pair[FORCE_SHARE_] =
160
+ source === target ? biases[link] - (1 - biases[link]) : biases[link];
161
+ pair[FORCE_SHARE_OTHER_] = source === target ? 0 : 1 - biases[link];
162
+ scaledMove_();
163
+ velocities[target] += pair[FORCE_MOVE_X_];
164
+ velocities[target + 1] += pair[FORCE_MOVE_Y_];
165
+ saturate_(velocities, target);
166
+ saturate_(velocities, target + 1);
167
+ velocities[source] -= pair[FORCE_MOVE_OTHER_X_];
168
+ velocities[source + 1] -= pair[FORCE_MOVE_OTHER_Y_];
169
+ saturate_(velocities, source);
170
+ saturate_(velocities, source + 1);
171
+ }
172
+ }
173
+ }
174
+ // Slots of the scratch buffers the visitors read: a visitor cannot take the
175
+ // current node as an argument, and a captured `let` would box every double.
176
+ const NODE_X = 0;
177
+ const NODE_Y = 1;
178
+ const ALPHA = 2;
179
+ const SELF = 3;
180
+ const PREVIOUS_DRAW = 4;
181
+ /**
182
+ * Share of a cell's width by which the box a target must lie outside, for the
183
+ * cell to be summarised, extends on each side: GADGET-2's 20 % enlargement.
184
+ */
185
+ const CONTAINMENT_MARGIN = 0.1;
186
+ /** The least normal double: a square at least this large lost no digits. */
187
+ const NORMAL_SQUARE_ = 2 ** -1022;
188
+ /**
189
+ * Operands of {@link compareDistance_} and {@link addPull_}, passed here rather
190
+ * than as arguments: a double passed to a call the engine does not inline is
191
+ * boxed, once per pair.
192
+ */
193
+ const PAIR_ = new Float64Array(9);
194
+ const PAIR_DX_ = 0;
195
+ const PAIR_DY_ = 1;
196
+ const PAIR_LIMIT_ = 2;
197
+ const PAIR_LIMIT_SQUARED_ = 3;
198
+ const PAIR_STRENGTH_ = 4;
199
+ const PAIR_DISTANCE_MIN_ = 5;
200
+ const PAIR_DISTANCE_MIN_SQUARED_ = 6;
201
+ /** The power of two the strength was scaled down by: 1, or a monopole's. */
202
+ const PAIR_STRENGTH_SCALE_ = 7;
203
+ /**
204
+ * The power of two `(dx, dy)` is to be multiplied by: 0, or 1 where the
205
+ * difference was taken from halves ({@link halvedDelta_}). Every caller that
206
+ * writes `(dx, dy)` writes it too.
207
+ */
208
+ const PAIR_PRESCALE_ = 8;
209
+ /**
210
+ * Writes `(toX − fromX, toY − fromY)` from `PAIR_DELTA_` (`[toX, toY, fromX,
211
+ * fromY]`) into `PAIR_`'s difference and its prescale: as rounded, or from
212
+ * halves (prescale 1) where a difference would leave the doubles.
213
+ */
214
+ function halvedDelta_() {
215
+ const delta = PAIR_DELTA_;
216
+ const dx = delta[0] - delta[2];
217
+ const dy = delta[1] - delta[3];
218
+ if (dx - dx + (dy - dy) === 0) {
219
+ PAIR_[PAIR_DX_] = dx;
220
+ PAIR_[PAIR_DY_] = dy;
221
+ PAIR_[PAIR_PRESCALE_] = 0;
222
+ return;
223
+ }
224
+ PAIR_[PAIR_DX_] = delta[0] * 0.5 - delta[2] * 0.5;
225
+ PAIR_[PAIR_DY_] = delta[1] * 0.5 - delta[3] * 0.5;
226
+ PAIR_[PAIR_PRESCALE_] = 1;
227
+ }
228
+ /** The operands of {@link halvedDelta_}. */
229
+ const PAIR_DELTA_ = new Float64Array(4);
230
+ /**
231
+ * Operands, scratch and results of {@link scaledLengths_} and
232
+ * {@link scaledMove_}, passed here as `PAIR_`'s are: a pair's difference, two
233
+ * lengths whose sum is the reach the pair moves toward, the factor of the move,
234
+ * each end's share of it, and the move times each share.
235
+ */
236
+ const FORCE_ = new Float64Array(16);
237
+ const FORCE_DX_ = 0;
238
+ const FORCE_DY_ = 1;
239
+ const FORCE_REACH_ = 2;
240
+ const FORCE_REACH_OTHER_ = 3;
241
+ const FORCE_FACTOR_ = 4;
242
+ const FORCE_SHARE_ = 5;
243
+ const FORCE_SHARE_OTHER_ = 6;
244
+ const FORCE_MOVE_X_ = 7;
245
+ const FORCE_MOVE_Y_ = 8;
246
+ const FORCE_MOVE_OTHER_X_ = 9;
247
+ const FORCE_MOVE_OTHER_Y_ = 10;
248
+ /** The unit direction (x, y), then the overlap `reach − distance`, scaled. */
249
+ const FORCE_UNIT_X_ = 11;
250
+ const FORCE_UNIT_Y_ = 12;
251
+ const FORCE_OVERLAP_ = 13;
252
+ /** The power of two `(dx, dy)` is to be multiplied by (`predictedDelta_`). */
253
+ const FORCE_PRESCALE_ = 14;
254
+ /** A second factor of the move, 1 for none: alpha and a strength apart. */
255
+ const FORCE_SECOND_FACTOR_ = 15;
256
+ /**
257
+ * From `FORCE_`, writes the unit direction of `(dx, dy) · 2^prescale` and the
258
+ * overlap `reach − distance`, scaled by the power of two that brings the
259
+ * largest of the distance's components and the two reach lengths to [1, 2), and
260
+ * returns that power's exponent: no square or sum on the way leaves the
261
+ * doubles, whatever the lengths. The direction is scaled on its own, its
262
+ * longest component brought to [1, 2). `(dx, dy)` must not be zero.
263
+ */
264
+ function scaledLengths_() {
265
+ const pair = FORCE_;
266
+ const dx = pair[FORCE_DX_];
267
+ const dy = pair[FORCE_DY_];
268
+ const reach = pair[FORCE_REACH_];
269
+ const reachOther = pair[FORCE_REACH_OTHER_];
270
+ const longest = Math.max(Math.abs(dx), Math.abs(dy));
271
+ if (longest - longest + (reach - reach) + (reachOther - reachOther) !== 0) {
272
+ // A length that is not finite: no direction, no overlap.
273
+ pair[FORCE_UNIT_X_] = Number.NaN;
274
+ pair[FORCE_UNIT_Y_] = Number.NaN;
275
+ pair[FORCE_OVERLAP_] = Number.NaN;
276
+ return 0;
277
+ }
278
+ const longestExponent = binaryExponent(longest);
279
+ const distanceExponent = longestExponent + pair[FORCE_PRESCALE_];
280
+ let exponent = distanceExponent;
281
+ if (reach > 0) {
282
+ exponent = Math.max(exponent, binaryExponent(reach));
283
+ }
284
+ if (reachOther > 0) {
285
+ exponent = Math.max(exponent, binaryExponent(reachOther));
286
+ }
287
+ pair[FORCE_UNIT_X_] = dx;
288
+ pair[FORCE_UNIT_Y_] = dy;
289
+ scaleByPowerOfTwoInPlace(pair, FORCE_UNIT_X_, 0 - longestExponent);
290
+ scaleByPowerOfTwoInPlace(pair, FORCE_UNIT_Y_, 0 - longestExponent);
291
+ const x = pair[FORCE_UNIT_X_];
292
+ const y = pair[FORCE_UNIT_Y_];
293
+ const length = Math.sqrt(x * x + y * y);
294
+ pair[FORCE_UNIT_X_] = x / length;
295
+ pair[FORCE_UNIT_Y_] = y / length;
296
+ // The distance and the reach against the largest.
297
+ pair[FORCE_OVERLAP_] = length;
298
+ scaleByPowerOfTwoInPlace(pair, FORCE_OVERLAP_, distanceExponent - exponent);
299
+ const distance = pair[FORCE_OVERLAP_];
300
+ pair[FORCE_OVERLAP_] = reach;
301
+ scaleByPowerOfTwoInPlace(pair, FORCE_OVERLAP_, 0 - exponent);
302
+ const scaledReach = pair[FORCE_OVERLAP_];
303
+ pair[FORCE_OVERLAP_] = reachOther;
304
+ scaleByPowerOfTwoInPlace(pair, FORCE_OVERLAP_, 0 - exponent);
305
+ pair[FORCE_OVERLAP_] = scaledReach + pair[FORCE_OVERLAP_] - distance;
306
+ return exponent;
307
+ }
308
+ /**
309
+ * The move `u · (reach − distance) · factor · second factor` of a pair, `u` the
310
+ * unit direction of `(dx, dy)`, times each end's share, from `FORCE_`, into its
311
+ * move slots. The lengths are scaled first ({@link scaledLengths_}), and the
312
+ * factors and each share split into a significand and a power of two, so that
313
+ * the move is scaled back once, at the end: it overflows only where an end's
314
+ * part of it does, and underflows only where that part does.
315
+ */
316
+ function scaledMove_() {
317
+ const exponent = scaledLengths_();
318
+ scaledPart_(FORCE_SHARE_, FORCE_MOVE_X_, exponent);
319
+ scaledPart_(FORCE_SHARE_OTHER_, FORCE_MOVE_OTHER_X_, exponent);
320
+ }
321
+ /**
322
+ * Writes the scaled unit direction times the overlap, the factors and the share
323
+ * at `shareSlot`, into `moveSlot` and the next, scaled back by `2^exponent`.
324
+ */
325
+ function scaledPart_(shareSlot, moveSlot, exponent) {
326
+ const pair = FORCE_;
327
+ const factor = pair[FORCE_FACTOR_];
328
+ const second = pair[FORCE_SECOND_FACTOR_];
329
+ const share = pair[shareSlot];
330
+ if (factor - factor + (second - second) + (share - share) !== 0) {
331
+ pair[moveSlot] = Number.NaN;
332
+ pair[moveSlot + 1] = Number.NaN;
333
+ return;
334
+ }
335
+ if (factor === 0 || second === 0 || share === 0) {
336
+ pair[moveSlot] = 0;
337
+ pair[moveSlot + 1] = 0;
338
+ return;
339
+ }
340
+ const factorExponent = binaryExponent(factor);
341
+ const secondExponent = binaryExponent(second);
342
+ const shareExponent = binaryExponent(share);
343
+ // Each in [1, 2): their product with the scaled move stays in the doubles.
344
+ pair[moveSlot] = factor;
345
+ scaleByPowerOfTwoInPlace(pair, moveSlot, 0 - factorExponent);
346
+ pair[moveSlot + 1] = second;
347
+ scaleByPowerOfTwoInPlace(pair, moveSlot + 1, 0 - secondExponent);
348
+ const factors = pair[moveSlot] * pair[moveSlot + 1];
349
+ pair[moveSlot] = share;
350
+ scaleByPowerOfTwoInPlace(pair, moveSlot, 0 - shareExponent);
351
+ const weight = factors * pair[moveSlot] * pair[FORCE_OVERLAP_];
352
+ pair[moveSlot] = pair[FORCE_UNIT_X_] * weight;
353
+ pair[moveSlot + 1] = pair[FORCE_UNIT_Y_] * weight;
354
+ const back = exponent + factorExponent + secondExponent + shareExponent;
355
+ scaleByPowerOfTwoInPlace(pair, moveSlot, back);
356
+ scaleByPowerOfTwoInPlace(pair, moveSlot + 1, back);
357
+ }
358
+ /**
359
+ * Writes into `FORCE_SHARE_` and `FORCE_SHARE_OTHER_` the shares of a
360
+ * collision's push, `r₁² / (r₀² + r₁²)` for the active node and `r₀² / (r₀² +
361
+ * r₁²)` for the other, from the ratio of the radii in `FORCE_REACH_` and
362
+ * `FORCE_REACH_OTHER_`, so that no square leaves the doubles.
363
+ */
364
+ function collideShares_() {
365
+ const pair = FORCE_;
366
+ const radius = pair[FORCE_REACH_];
367
+ const otherRadius = pair[FORCE_REACH_OTHER_];
368
+ const ratio = otherRadius >= radius ? radius / otherRadius : otherRadius / radius;
369
+ const small = (ratio * ratio) / (1 + ratio * ratio);
370
+ const large = 1 / (1 + ratio * ratio);
371
+ pair[FORCE_SHARE_] = otherRadius >= radius ? large : small;
372
+ pair[FORCE_SHARE_OTHER_] = otherRadius >= radius ? small : large;
373
+ }
374
+ /**
375
+ * Sign of `hypot(dx, dy) − limit` (−1, 0 or 1), from `PAIR_`, `limitSquared`
376
+ * being `limit * limit` as rounded. The squares are compared directly while
377
+ * both are normal and finite (or the limit infinite); otherwise every term is
378
+ * first scaled by the power of two that brings the largest to [1, 2), so a
379
+ * distance or limit whose square underflows or overflows still compares
380
+ * correctly.
381
+ */
382
+ function compareDistance_() {
383
+ const dx = PAIR_[PAIR_DX_];
384
+ const dy = PAIR_[PAIR_DY_];
385
+ const prescale = PAIR_[PAIR_PRESCALE_];
386
+ // Against a difference taken from halves, half the limit.
387
+ const limit = prescale === 0 ? PAIR_[PAIR_LIMIT_] : PAIR_[PAIR_LIMIT_] * 2 ** -prescale;
388
+ const limitSquared = prescale === 0 ? PAIR_[PAIR_LIMIT_SQUARED_] : limit * limit;
389
+ const squared = dx * dx + dy * dy;
390
+ if (squared >= NORMAL_SQUARE_ &&
391
+ squared !== Infinity &&
392
+ (limitSquared >= NORMAL_SQUARE_ || limit === 0)) {
393
+ return squared > limitSquared ? 1 : squared < limitSquared ? -1 : 0;
394
+ }
395
+ if (limit === Infinity) {
396
+ return -1;
397
+ }
398
+ const largest = Math.max(Math.abs(dx), Math.abs(dy), limit);
399
+ if (largest === 0 || largest - largest !== 0) {
400
+ // Equal, or a length that is not finite: no order, as NaN compares.
401
+ return 0;
402
+ }
403
+ const exponent = 0 - binaryExponent(largest);
404
+ const scaled = COMPARE_;
405
+ scaled[0] = dx;
406
+ scaled[1] = dy;
407
+ scaled[2] = limit;
408
+ scaleByPowerOfTwoInPlace(scaled, 0, exponent);
409
+ scaleByPowerOfTwoInPlace(scaled, 1, exponent);
410
+ scaleByPowerOfTwoInPlace(scaled, 2, exponent);
411
+ const x = scaled[0];
412
+ const y = scaled[1];
413
+ const bound = scaled[2];
414
+ const scaledSquared = x * x + y * y;
415
+ const scaledLimit = bound * bound;
416
+ return scaledSquared > scaledLimit ? 1 : scaledSquared < scaledLimit ? -1 : 0;
417
+ }
418
+ /** Scratch of {@link compareDistance_}: the scaled lengths. */
419
+ const COMPARE_ = new Float64Array(3);
420
+ /**
421
+ * Adds `strength · scale · (dx, dy) / s` (from `PAIR_`) to the velocity of
422
+ * `node`, where `s` is the squared distance, or `distanceMin` times the
423
+ * distance below `distanceMin` (d3-force's clamp), and `scale` the power of two
424
+ * a monopole's strength was scaled down by so that its sum stays finite.
425
+ * Rounded as `s` is directly while the squares and the force are normal and
426
+ * finite; otherwise from the direction scaled to [1, 2) by a power of two and
427
+ * the distance kept as that power, so that a pair whose squared distance
428
+ * underflows or overflows still gets its force.
429
+ */
430
+ function addPull_(velocities, node) {
431
+ const dx = PAIR_[PAIR_DX_];
432
+ const dy = PAIR_[PAIR_DY_];
433
+ const strength = PAIR_[PAIR_STRENGTH_];
434
+ const scale = PAIR_[PAIR_STRENGTH_SCALE_];
435
+ const distanceMin = PAIR_[PAIR_DISTANCE_MIN_];
436
+ const distanceMin2 = PAIR_[PAIR_DISTANCE_MIN_SQUARED_];
437
+ const prescale = PAIR_[PAIR_PRESCALE_];
438
+ let squared = dx * dx + dy * dy;
439
+ if (prescale === 0 &&
440
+ squared >= NORMAL_SQUARE_ &&
441
+ distanceMin2 !== Infinity) {
442
+ if (squared < distanceMin2) {
443
+ // d3-force's clamp, √(distanceMin² · d²), while that product is a
444
+ // normal double.
445
+ const clamped = distanceMin2 * squared;
446
+ squared =
447
+ clamped >= NORMAL_SQUARE_ && clamped < Infinity
448
+ ? Math.sqrt(clamped)
449
+ : Number.NaN;
450
+ }
451
+ const weight = strength / squared;
452
+ const pullX = dx * weight;
453
+ const pullY = dy * weight;
454
+ if (squared >= NORMAL_SQUARE_ &&
455
+ squared < Infinity &&
456
+ pullX - pullX === 0 &&
457
+ pullY - pullY === 0) {
458
+ velocities[2 * node] += pullX * scale;
459
+ velocities[2 * node + 1] += pullY * scale;
460
+ saturate_(velocities, 2 * node);
461
+ saturate_(velocities, 2 * node + 1);
462
+ return;
463
+ }
464
+ }
465
+ if (strength === 0 ||
466
+ strength - strength !== 0 ||
467
+ dx - dx + (dy - dy) !== 0) {
468
+ // No force, or a charge or difference that is not finite: as the plain
469
+ // force.
470
+ velocities[2 * node] += dx * strength * scale;
471
+ velocities[2 * node + 1] += dy * strength * scale;
472
+ return;
473
+ }
474
+ // The direction scaled to [1, 2), the strength and `distanceMin` split
475
+ // into a significand and a power of two: the force is scaled back once.
476
+ const pull = PULL_;
477
+ const longest = Math.max(Math.abs(dx), Math.abs(dy));
478
+ const toDirection = longest > 0 ? 0 - binaryExponent(longest) : 0;
479
+ pull[0] = dx;
480
+ pull[1] = dy;
481
+ scaleByPowerOfTwoInPlace(pull, 0, toDirection);
482
+ scaleByPowerOfTwoInPlace(pull, 1, toDirection);
483
+ const x = pull[0];
484
+ const y = pull[1];
485
+ const scaledSquared = x * x + y * y;
486
+ const strengthExponent = binaryExponent(strength) + binaryExponent(scale);
487
+ pull[2] = strength;
488
+ scaleByPowerOfTwoInPlace(pull, 2, 0 - binaryExponent(strength));
489
+ const strengthSignificand = pull[2];
490
+ PAIR_[PAIR_LIMIT_] = distanceMin;
491
+ PAIR_[PAIR_LIMIT_SQUARED_] = distanceMin2;
492
+ let exponent;
493
+ if (compareDistance_() < 0) {
494
+ // strength · (dx / d) / distanceMin: the direction is a unit vector.
495
+ const minimumExponent = binaryExponent(distanceMin);
496
+ pull[2] = distanceMin;
497
+ scaleByPowerOfTwoInPlace(pull, 2, 0 - minimumExponent);
498
+ const root = Math.sqrt(scaledSquared);
499
+ const weight = strengthSignificand / pull[2];
500
+ pull[0] = (x / root) * weight;
501
+ pull[1] = (y / root) * weight;
502
+ exponent = strengthExponent - minimumExponent;
503
+ }
504
+ else {
505
+ // dx / d² = (x / scaledSquared) · 2^(toDirection − prescale).
506
+ pull[0] = (x / scaledSquared) * strengthSignificand;
507
+ pull[1] = (y / scaledSquared) * strengthSignificand;
508
+ exponent = strengthExponent + toDirection - prescale;
509
+ }
510
+ scaleByPowerOfTwoInPlace(pull, 0, exponent);
511
+ scaleByPowerOfTwoInPlace(pull, 1, exponent);
512
+ velocities[2 * node] += pull[0];
513
+ velocities[2 * node + 1] += pull[1];
514
+ saturate_(velocities, 2 * node);
515
+ saturate_(velocities, 2 * node + 1);
516
+ }
517
+ /** Scratch of {@link addPull_}: the scaled direction, then the force. */
518
+ const PULL_ = new Float64Array(3);
519
+ /**
520
+ * Charges repelling or attracting each other with strength / distance, every
521
+ * pair in `"exact"` mode or Barnes–Hut (Barnes and Hut, "A hierarchical O(N log
522
+ * N) force-calculation algorithm", Nature 324, 1986) over a `Quadtree`.
523
+ *
524
+ * Each cell keeps two monopoles: the sum of its positive charges at their
525
+ * centre, and the sum of its negative charges at theirs. A cell is summarised
526
+ * only when each of its monopoles looks small enough from the node (width / θ <
527
+ * the distance to that monopole's centre, d3-force's form of the criterion), so
528
+ * each monopole's error is bounded relative to its own charge over its
529
+ * distance, as for same-sign charges, and a cell is never skipped because its
530
+ * charges sum to 0. The error of a node's force is therefore bounded relative
531
+ * to its unsigned contributions, Σ |q_j| / d_j over the other bodies, not
532
+ * relative to the net force: where contributions of opposite signs cancel, the
533
+ * net force can be any number of times smaller than that error. A cell is
534
+ * always opened when the node lies inside it, enlarged by 20 % (Springel, "The
535
+ * cosmological simulation code GADGET-2", MNRAS 364, 2005, §3.1), so no node
536
+ * feels its own charge however large θ is: the self-interaction that Salmon and
537
+ * Warren ("Skeletons from the treecode closet", J. Comput. Phys. 111, 1994)
538
+ * show unbounds the error of the plain criterion. A cell that straddles
539
+ * `distanceMax` is opened too, so the cutoff applies to each body, as in
540
+ * `"exact"` mode. Centres are running charge-weighted means (a convex
541
+ * combination where a step would overflow), differences beyond the doubles are
542
+ * taken from halves, distances, the cutoff, the clamp and the force are scaled
543
+ * by powers of two wherever a square would underflow or overflow, a cell's
544
+ * charge sums by the power of two that keeps the total of every |charge|
545
+ * finite, and positions beyond the quadtree's ±1e150 are indexed scaled by a
546
+ * power of two (the cells scaled back), so any finite coordinates, distances
547
+ * down to the least subnormal and charges up to the double range keep their
548
+ * force; a velocity beyond the doubles saturates at ±`Number.MAX_VALUE`.
549
+ *
550
+ * `isD3` keeps d3-force's own approximation instead: one signed monopole at the
551
+ * |charge|-weighted centre, a cell summarised even when it holds the node,
552
+ * `distanceMax` tested against the cell's centre, cells whose charges sum to 0
553
+ * skipped, and coincident offsets drawn whenever one axis difference is 0.
554
+ */
555
+ export class ManyBodyForce {
556
+ charges;
557
+ options;
558
+ tree = new Quadtree();
559
+ /** Positive charge of each cell (its signed sum when `isD3`). */
560
+ values = new Float64Array(0);
561
+ centersX = new Float64Array(0);
562
+ centersY = new Float64Array(0);
563
+ /** Negative charge of each cell (unused when `isD3`). */
564
+ negativeValues = new Float64Array(0);
565
+ negativeCentersX = new Float64Array(0);
566
+ negativeCentersY = new Float64Array(0);
567
+ scratch = Float64Array.of(0, 0, 0, 0, NaN);
568
+ positions = new Float64Array(0);
569
+ velocities = new Float64Array(0);
570
+ order;
571
+ orderLength = 0;
572
+ isExact;
573
+ isD3;
574
+ isInert;
575
+ theta2;
576
+ distanceMin2;
577
+ distanceMax2;
578
+ /**
579
+ * The charges a cell sums, scaled down by `monopoleScale`, a power of two
580
+ * from 1 up: so far that the sum of every |charge| stays finite, and no
581
+ * further, so a charge loses no digit unless it is subnormal already.
582
+ */
583
+ scaledCharges;
584
+ monopoleScale;
585
+ /**
586
+ * Positions scaled into the quadtree's range when one lies beyond it (grown,
587
+ * then reused), and the power of two the tree's cells are to be multiplied
588
+ * by: 1 while the positions are indexed as they are.
589
+ */
590
+ treePositions = new Float64Array(0);
591
+ cellScale = 1;
592
+ constructor(charges, options) {
593
+ this.charges = charges;
594
+ this.options = options;
595
+ this.isExact = options.approximation === "exact";
596
+ this.isD3 = options.isD3;
597
+ this.order = new Uint32Array(charges.length);
598
+ this.isInert = charges.every((charge) => charge === 0);
599
+ this.theta2 = options.theta * options.theta;
600
+ this.distanceMin2 = options.distanceMin * options.distanceMin;
601
+ this.distanceMax2 = options.distanceMax * options.distanceMax;
602
+ // Σ |charge| · 2⁻⁶⁴ cannot overflow below 2⁶³ charges.
603
+ let total = 0;
604
+ for (const charge of charges) {
605
+ total += Math.abs(charge) * 2 ** -64;
606
+ }
607
+ const exponent = total > 0 ? Math.max(binaryExponent(total) + 64 - 1020, 0) : 0;
608
+ this.monopoleScale = 2 ** exponent;
609
+ this.scaledCharges = charges.map((charge) => charge * 2 ** -exponent);
610
+ }
611
+ apply(positions, velocities, alpha) {
612
+ if (this.isInert) {
613
+ return;
614
+ }
615
+ this.positions = positions;
616
+ this.velocities = velocities;
617
+ this.scratch[ALPHA] = alpha;
618
+ if (this.isExact) {
619
+ this.applyExact(positions, velocities, alpha);
620
+ return;
621
+ }
622
+ const tree = this.tree;
623
+ this.assignTree(positions);
624
+ const needed = tree.nodeCount();
625
+ this.values = grown(this.values, needed);
626
+ this.centersX = grown(this.centersX, needed);
627
+ this.centersY = grown(this.centersY, needed);
628
+ if (this.isD3) {
629
+ tree.visitAfter(this.accumulateD3);
630
+ }
631
+ else {
632
+ this.negativeValues = grown(this.negativeValues, needed);
633
+ this.negativeCentersX = grown(this.negativeCentersX, needed);
634
+ this.negativeCentersY = grown(this.negativeCentersY, needed);
635
+ tree.visitAfter(this.accumulate);
636
+ }
637
+ const visitor = this.isD3 ? this.visitD3 : this.visit;
638
+ for (let node = 0; node < this.charges.length; node++) {
639
+ this.scratch[NODE_X] = positions[2 * node];
640
+ this.scratch[NODE_Y] = positions[2 * node + 1];
641
+ this.scratch[SELF] = node;
642
+ tree.visit(visitor);
643
+ }
644
+ }
645
+ /**
646
+ * Indexes the positions, scaled by a power of two into the quadtree's range
647
+ * where one lies beyond it: the cells are then `cellScale` times the tree's,
648
+ * and every force still reads the positions themselves.
649
+ */
650
+ assignTree(positions) {
651
+ let largest = 0;
652
+ for (let index = 0; index < positions.length; index++) {
653
+ largest = Math.max(largest, Math.abs(positions[index]));
654
+ }
655
+ const shift = largest === largest ? treeShift_(largest) : 0;
656
+ if (shift === 0) {
657
+ this.cellScale = 1;
658
+ this.tree.assign(positions);
659
+ return;
660
+ }
661
+ if (this.treePositions.length !== positions.length) {
662
+ this.treePositions = new Float64Array(positions.length);
663
+ }
664
+ const scaled = this.treePositions;
665
+ const factor = 2 ** -shift;
666
+ for (let index = 0; index < positions.length; index++) {
667
+ scaled[index] = positions[index] * factor;
668
+ }
669
+ this.cellScale = 2 ** shift;
670
+ this.tree.assign(scaled);
671
+ }
672
+ /**
673
+ * Every pair, the others taken in the tree's leaf order: the order the
674
+ * Barnes–Hut walk sums them in, so exact and approximate runs differ only by
675
+ * the approximation, not by rounding that chaotic dynamics would amplify.
676
+ */
677
+ applyExact(positions, velocities, alpha) {
678
+ const { charges, distanceMin2, distanceMax2, tree, order, scratch } = this;
679
+ const { random, distanceMin, distanceMax } = this.options;
680
+ this.assignTree(positions);
681
+ this.orderLength = 0;
682
+ tree.visit(this.collectLeaves);
683
+ for (let node = 0; node < charges.length; node++) {
684
+ for (let slot = 0; slot < charges.length; slot++) {
685
+ const other = order[slot];
686
+ const charge = charges[other];
687
+ if (other === node || charge === 0) {
688
+ continue;
689
+ }
690
+ PAIR_DELTA_[0] = positions[2 * other];
691
+ PAIR_DELTA_[1] = positions[2 * other + 1];
692
+ PAIR_DELTA_[2] = positions[2 * node];
693
+ PAIR_DELTA_[3] = positions[2 * node + 1];
694
+ halvedDelta_();
695
+ PAIR_[PAIR_LIMIT_] = distanceMax;
696
+ PAIR_[PAIR_LIMIT_SQUARED_] = distanceMax2;
697
+ if (compareDistance_() >= 0) {
698
+ continue;
699
+ }
700
+ if (PAIR_[PAIR_DX_] === 0) {
701
+ drawPairJiggle(random, node, other, scratch, PREVIOUS_DRAW);
702
+ PAIR_[PAIR_DX_] = JIGGLE[0];
703
+ }
704
+ if (PAIR_[PAIR_DY_] === 0) {
705
+ drawPairJiggle(random, node, other, scratch, PREVIOUS_DRAW);
706
+ PAIR_[PAIR_DY_] = JIGGLE[0];
707
+ }
708
+ PAIR_[PAIR_STRENGTH_] = charge * alpha;
709
+ PAIR_[PAIR_STRENGTH_SCALE_] = 1;
710
+ PAIR_[PAIR_DISTANCE_MIN_] = distanceMin;
711
+ PAIR_[PAIR_DISTANCE_MIN_SQUARED_] = distanceMin2;
712
+ addPull_(velocities, node);
713
+ }
714
+ }
715
+ }
716
+ collectLeaves = (node) => {
717
+ const tree = this.tree;
718
+ if (tree.isLeaf(node)) {
719
+ for (let id = tree.nodeFirstPoint(node); id !== -1; id = tree.nextPoint(id)) {
720
+ this.order[this.orderLength++] = id;
721
+ }
722
+ }
723
+ return false;
724
+ };
725
+ /**
726
+ * `isD3`: signed charge and |charge|-weighted centre of every cell, children
727
+ * first.
728
+ */
729
+ accumulateD3 = (node) => {
730
+ const tree = this.tree;
731
+ let strength = 0;
732
+ let weight = 0;
733
+ let x = 0;
734
+ let y = 0;
735
+ if (tree.isLeaf(node)) {
736
+ const first = tree.nodeFirstPoint(node);
737
+ x = this.positions[2 * first];
738
+ y = this.positions[2 * first + 1];
739
+ for (let id = first; id !== -1; id = tree.nextPoint(id)) {
740
+ strength += this.scaledCharges[id];
741
+ }
742
+ this.values[node] = strength;
743
+ this.centersX[node] = x;
744
+ this.centersY[node] = y;
745
+ return false;
746
+ }
747
+ for (let quadrant = 0; quadrant < 4; quadrant++) {
748
+ const child = tree.nodeChild(node, quadrant);
749
+ if (child === -1) {
750
+ continue;
751
+ }
752
+ const childValue = this.values[child];
753
+ const magnitude = Math.abs(childValue);
754
+ if (magnitude !== 0) {
755
+ strength += childValue;
756
+ weight += magnitude;
757
+ x += magnitude * this.centersX[child];
758
+ y += magnitude * this.centersY[child];
759
+ }
760
+ }
761
+ this.values[node] = strength;
762
+ this.centersX[node] = x / weight;
763
+ this.centersY[node] = y / weight;
764
+ if (x - x + (y - y) !== 0) {
765
+ // A moment, |charge| times coordinate, left the doubles: the centre
766
+ // as a running weighted mean, a convex combination at every step.
767
+ let total = 0;
768
+ x = 0;
769
+ y = 0;
770
+ for (let quadrant = 0; quadrant < 4; quadrant++) {
771
+ const child = tree.nodeChild(node, quadrant);
772
+ const magnitude = child === -1 ? 0 : Math.abs(this.values[child]);
773
+ if (magnitude !== 0) {
774
+ total += magnitude;
775
+ const share = magnitude / total;
776
+ x = x * (1 - share) + this.centersX[child] * share;
777
+ y = y * (1 - share) + this.centersY[child] * share;
778
+ }
779
+ }
780
+ this.centersX[node] = x;
781
+ this.centersY[node] = y;
782
+ }
783
+ return false;
784
+ };
785
+ /**
786
+ * Positive and negative charge of every cell, scaled down by `monopoleScale`,
787
+ * each at its own charge-weighted centre, children first. A sign with no
788
+ * charge has its centre at the origin; it is never read.
789
+ */
790
+ accumulate = (node) => {
791
+ const { tree, values, negativeValues, scaledCharges } = this;
792
+ let positive = 0;
793
+ let negative = 0;
794
+ let positiveX = 0;
795
+ let positiveY = 0;
796
+ let negativeX = 0;
797
+ let negativeY = 0;
798
+ if (tree.isLeaf(node)) {
799
+ const first = tree.nodeFirstPoint(node);
800
+ for (let id = first; id !== -1; id = tree.nextPoint(id)) {
801
+ const charge = scaledCharges[id];
802
+ if (charge > 0) {
803
+ positive += charge;
804
+ }
805
+ else {
806
+ negative += charge;
807
+ }
808
+ }
809
+ const x = this.positions[2 * first];
810
+ const y = this.positions[2 * first + 1];
811
+ values[node] = positive;
812
+ this.centersX[node] = positive === 0 ? 0 : x;
813
+ this.centersY[node] = positive === 0 ? 0 : y;
814
+ negativeValues[node] = negative;
815
+ this.negativeCentersX[node] = negative === 0 ? 0 : x;
816
+ this.negativeCentersY[node] = negative === 0 ? 0 : y;
817
+ return false;
818
+ }
819
+ for (let quadrant = 0; quadrant < 4; quadrant++) {
820
+ const child = tree.nodeChild(node, quadrant);
821
+ if (child === -1) {
822
+ continue;
823
+ }
824
+ // Running charge-weighted means: a moment, charge times coordinate,
825
+ // overflows long before either does. Where a step's difference
826
+ // leaves the doubles, the convex combination, which cannot.
827
+ const childPositive = values[child];
828
+ if (childPositive !== 0) {
829
+ positive += childPositive;
830
+ const share = childPositive / positive;
831
+ const centerX = this.centersX[child];
832
+ const centerY = this.centersY[child];
833
+ const stepX = (centerX - positiveX) * share;
834
+ const stepY = (centerY - positiveY) * share;
835
+ positiveX =
836
+ stepX - stepX === 0
837
+ ? positiveX + stepX
838
+ : positiveX * (1 - share) + centerX * share;
839
+ positiveY =
840
+ stepY - stepY === 0
841
+ ? positiveY + stepY
842
+ : positiveY * (1 - share) + centerY * share;
843
+ }
844
+ const childNegative = negativeValues[child];
845
+ if (childNegative !== 0) {
846
+ negative += childNegative;
847
+ const share = childNegative / negative;
848
+ const centerX = this.negativeCentersX[child];
849
+ const centerY = this.negativeCentersY[child];
850
+ const stepX = (centerX - negativeX) * share;
851
+ const stepY = (centerY - negativeY) * share;
852
+ negativeX =
853
+ stepX - stepX === 0
854
+ ? negativeX + stepX
855
+ : negativeX * (1 - share) + centerX * share;
856
+ negativeY =
857
+ stepY - stepY === 0
858
+ ? negativeY + stepY
859
+ : negativeY * (1 - share) + centerY * share;
860
+ }
861
+ }
862
+ values[node] = positive;
863
+ this.centersX[node] = positiveX;
864
+ this.centersY[node] = positiveY;
865
+ negativeValues[node] = negative;
866
+ this.negativeCentersX[node] = negativeX;
867
+ this.negativeCentersY[node] = negativeY;
868
+ return false;
869
+ };
870
+ /**
871
+ * The Barnes–Hut walk for the node in `scratch`: a cell is summarised by its
872
+ * two monopoles, opened, or skipped whole (no charge, or every body beyond
873
+ * `distanceMax`); a leaf is summed body by body.
874
+ */
875
+ visit = (node, cell) => {
876
+ const positive = this.values[node];
877
+ const negative = this.negativeValues[node];
878
+ if (positive === 0 && negative === 0) {
879
+ return true;
880
+ }
881
+ if (this.tree.isLeaf(node)) {
882
+ this.applyLeaf(node);
883
+ return true;
884
+ }
885
+ const { scratch, distanceMax2, cellScale } = this;
886
+ const { distanceMax, distanceMin, theta } = this.options;
887
+ const x = scratch[NODE_X];
888
+ const y = scratch[NODE_Y];
889
+ // The cell in the positions' units: beyond the doubles at worst, which
890
+ // only opens it.
891
+ const minX = cell[0] * cellScale;
892
+ const minY = cell[1] * cellScale;
893
+ const maxX = cell[2] * cellScale;
894
+ const maxY = cell[3] * cellScale;
895
+ const width = maxX - minX;
896
+ const margin = width * CONTAINMENT_MARGIN;
897
+ if (x >= minX - margin &&
898
+ x <= maxX + margin &&
899
+ y >= minY - margin &&
900
+ y <= maxY + margin) {
901
+ return false;
902
+ }
903
+ if (distanceMax2 !== Infinity) {
904
+ // A gap beyond the doubles is beyond `distanceMax`.
905
+ const nearX = Math.max(minX - x, 0, x - maxX);
906
+ const nearY = Math.max(minY - y, 0, y - maxY);
907
+ PAIR_[PAIR_DX_] = nearX;
908
+ PAIR_[PAIR_DY_] = nearY;
909
+ PAIR_[PAIR_PRESCALE_] = 0;
910
+ PAIR_[PAIR_LIMIT_] = distanceMax;
911
+ PAIR_[PAIR_LIMIT_SQUARED_] = distanceMax2;
912
+ if (compareDistance_() >= 0) {
913
+ return true;
914
+ }
915
+ PAIR_[PAIR_DX_] = Math.max(x - minX, maxX - x);
916
+ PAIR_[PAIR_DY_] = Math.max(y - minY, maxY - y);
917
+ if (compareDistance_() >= 0) {
918
+ return false;
919
+ }
920
+ }
921
+ // The monopoles' offsets, from halves where a difference would leave
922
+ // the doubles.
923
+ PAIR_DELTA_[0] = this.centersX[node];
924
+ PAIR_DELTA_[1] = this.centersY[node];
925
+ PAIR_DELTA_[2] = x;
926
+ PAIR_DELTA_[3] = y;
927
+ halvedDelta_();
928
+ const positiveDx = PAIR_[PAIR_DX_];
929
+ const positiveDy = PAIR_[PAIR_DY_];
930
+ const positivePrescale = PAIR_[PAIR_PRESCALE_];
931
+ PAIR_DELTA_[0] = this.negativeCentersX[node];
932
+ PAIR_DELTA_[1] = this.negativeCentersY[node];
933
+ halvedDelta_();
934
+ const negativeDx = PAIR_[PAIR_DX_];
935
+ const negativeDy = PAIR_[PAIR_DY_];
936
+ const negativePrescale = PAIR_[PAIR_PRESCALE_];
937
+ // A monopole no farther than the cell's reach, width / θ (at a distance
938
+ // of 0 included), cannot be summarised: open the cell.
939
+ PAIR_[PAIR_LIMIT_] = width / theta;
940
+ PAIR_[PAIR_LIMIT_SQUARED_] = (width * width) / this.theta2;
941
+ if (positive !== 0) {
942
+ PAIR_[PAIR_DX_] = positiveDx;
943
+ PAIR_[PAIR_DY_] = positiveDy;
944
+ PAIR_[PAIR_PRESCALE_] = positivePrescale;
945
+ if (compareDistance_() <= 0) {
946
+ return false;
947
+ }
948
+ }
949
+ if (negative !== 0) {
950
+ PAIR_[PAIR_DX_] = negativeDx;
951
+ PAIR_[PAIR_DY_] = negativeDy;
952
+ PAIR_[PAIR_PRESCALE_] = negativePrescale;
953
+ if (compareDistance_() <= 0) {
954
+ return false;
955
+ }
956
+ }
957
+ const self = scratch[SELF];
958
+ const alpha = scratch[ALPHA];
959
+ PAIR_[PAIR_DISTANCE_MIN_] = distanceMin;
960
+ PAIR_[PAIR_DISTANCE_MIN_SQUARED_] = this.distanceMin2;
961
+ PAIR_[PAIR_STRENGTH_SCALE_] = this.monopoleScale;
962
+ if (positive !== 0) {
963
+ PAIR_[PAIR_DX_] = positiveDx;
964
+ PAIR_[PAIR_DY_] = positiveDy;
965
+ PAIR_[PAIR_PRESCALE_] = positivePrescale;
966
+ PAIR_[PAIR_STRENGTH_] = positive * alpha;
967
+ addPull_(this.velocities, self);
968
+ }
969
+ if (negative !== 0) {
970
+ PAIR_[PAIR_DX_] = negativeDx;
971
+ PAIR_[PAIR_DY_] = negativeDy;
972
+ PAIR_[PAIR_PRESCALE_] = negativePrescale;
973
+ PAIR_[PAIR_STRENGTH_] = negative * alpha;
974
+ addPull_(this.velocities, self);
975
+ }
976
+ return true;
977
+ };
978
+ /**
979
+ * Every body of the leaf `node` but the node in `scratch`, as `"exact"` sums
980
+ * them: the cutoff per body, coincident bodies parted by a jiggle.
981
+ */
982
+ applyLeaf(node) {
983
+ const { scratch, tree, distanceMin2, distanceMax2 } = this;
984
+ const { random, distanceMin, distanceMax } = this.options;
985
+ const self = scratch[SELF];
986
+ const alpha = scratch[ALPHA];
987
+ const first = tree.nodeFirstPoint(node);
988
+ if (first === self && tree.nextPoint(first) === -1) {
989
+ return;
990
+ }
991
+ PAIR_DELTA_[0] = this.positions[2 * first];
992
+ PAIR_DELTA_[1] = this.positions[2 * first + 1];
993
+ PAIR_DELTA_[2] = scratch[NODE_X];
994
+ PAIR_DELTA_[3] = scratch[NODE_Y];
995
+ halvedDelta_();
996
+ let dx = PAIR_[PAIR_DX_];
997
+ let dy = PAIR_[PAIR_DY_];
998
+ PAIR_[PAIR_LIMIT_] = distanceMax;
999
+ PAIR_[PAIR_LIMIT_SQUARED_] = distanceMax2;
1000
+ if (compareDistance_() >= 0) {
1001
+ return;
1002
+ }
1003
+ if (first !== self || tree.nextPoint(first) !== -1) {
1004
+ // The other point of the leaf, so that two coincident nodes part ways.
1005
+ const partner = first === self ? tree.nextPoint(first) : first;
1006
+ if (dx === 0) {
1007
+ drawPairJiggle(random, self, partner, scratch, PREVIOUS_DRAW);
1008
+ dx = JIGGLE[0];
1009
+ }
1010
+ if (dy === 0) {
1011
+ drawPairJiggle(random, self, partner, scratch, PREVIOUS_DRAW);
1012
+ dy = JIGGLE[0];
1013
+ }
1014
+ }
1015
+ PAIR_[PAIR_DISTANCE_MIN_] = distanceMin;
1016
+ PAIR_[PAIR_DISTANCE_MIN_SQUARED_] = distanceMin2;
1017
+ for (let id = first; id !== -1; id = tree.nextPoint(id)) {
1018
+ if (id !== self) {
1019
+ PAIR_[PAIR_DX_] = dx;
1020
+ PAIR_[PAIR_DY_] = dy;
1021
+ PAIR_[PAIR_STRENGTH_] = this.charges[id] * alpha;
1022
+ PAIR_[PAIR_STRENGTH_SCALE_] = 1;
1023
+ addPull_(this.velocities, self);
1024
+ }
1025
+ }
1026
+ }
1027
+ /** `isD3`: d3-force's walk, quirks included (see the class). */
1028
+ visitD3 = (node, cell) => {
1029
+ const value = this.values[node];
1030
+ if (value === 0 || value !== value) {
1031
+ return true;
1032
+ }
1033
+ const { scratch, tree, distanceMin2, distanceMax2, monopoleScale } = this;
1034
+ const { random } = this.options;
1035
+ const self = scratch[SELF];
1036
+ const alpha = scratch[ALPHA];
1037
+ PAIR_DELTA_[0] = this.centersX[node];
1038
+ PAIR_DELTA_[1] = this.centersY[node];
1039
+ PAIR_DELTA_[2] = scratch[NODE_X];
1040
+ PAIR_DELTA_[3] = scratch[NODE_Y];
1041
+ halvedDelta_();
1042
+ if (PAIR_[PAIR_PRESCALE_] !== 0) {
1043
+ return this.visitD3Wide(node, cell);
1044
+ }
1045
+ let dx = PAIR_[PAIR_DX_];
1046
+ let dy = PAIR_[PAIR_DY_];
1047
+ let squared = dx * dx + dy * dy;
1048
+ const width = (cell[2] - cell[0]) * this.cellScale;
1049
+ if ((width * width) / this.theta2 < squared) {
1050
+ if (squared < distanceMax2) {
1051
+ if (dx === 0) {
1052
+ drawJiggle(random, self, -1);
1053
+ dx = JIGGLE[0];
1054
+ squared += dx * dx;
1055
+ }
1056
+ if (dy === 0) {
1057
+ drawJiggle(random, self, -1);
1058
+ dy = JIGGLE[0];
1059
+ squared += dy * dy;
1060
+ }
1061
+ if (squared < distanceMin2) {
1062
+ squared = Math.sqrt(distanceMin2 * squared);
1063
+ }
1064
+ const pullX = ((dx * value * alpha) / squared) * monopoleScale;
1065
+ const pullY = ((dy * value * alpha) / squared) * monopoleScale;
1066
+ if (squared >= NORMAL_SQUARE_ &&
1067
+ squared < Infinity &&
1068
+ pullX - pullX === 0 &&
1069
+ pullY - pullY === 0) {
1070
+ this.velocities[2 * self] += pullX;
1071
+ this.velocities[2 * self + 1] += pullY;
1072
+ saturate_(this.velocities, 2 * self);
1073
+ saturate_(this.velocities, 2 * self + 1);
1074
+ }
1075
+ else {
1076
+ // A square, the clamp or the force left the doubles.
1077
+ PAIR_[PAIR_DX_] = dx;
1078
+ PAIR_[PAIR_DY_] = dy;
1079
+ PAIR_[PAIR_STRENGTH_] = value * alpha;
1080
+ PAIR_[PAIR_STRENGTH_SCALE_] = monopoleScale;
1081
+ PAIR_[PAIR_DISTANCE_MIN_] = this.options.distanceMin;
1082
+ PAIR_[PAIR_DISTANCE_MIN_SQUARED_] = distanceMin2;
1083
+ addPull_(this.velocities, self);
1084
+ }
1085
+ }
1086
+ return true;
1087
+ }
1088
+ if (!tree.isLeaf(node) || squared >= distanceMax2) {
1089
+ return false;
1090
+ }
1091
+ const first = tree.nodeFirstPoint(node);
1092
+ if (first !== self || tree.nextPoint(first) !== -1) {
1093
+ // The other point of the leaf, so that two coincident nodes part ways.
1094
+ const partner = first === self ? tree.nextPoint(first) : first;
1095
+ if (dx === 0) {
1096
+ drawPairJiggle(random, self, partner, scratch, PREVIOUS_DRAW);
1097
+ dx = JIGGLE[0];
1098
+ squared += dx * dx;
1099
+ }
1100
+ if (dy === 0) {
1101
+ drawPairJiggle(random, self, partner, scratch, PREVIOUS_DRAW);
1102
+ dy = JIGGLE[0];
1103
+ squared += dy * dy;
1104
+ }
1105
+ if (squared < distanceMin2) {
1106
+ squared = Math.sqrt(distanceMin2 * squared);
1107
+ }
1108
+ }
1109
+ const isPlain = squared >= NORMAL_SQUARE_ && squared < Infinity;
1110
+ for (let id = first; id !== -1; id = tree.nextPoint(id)) {
1111
+ if (id !== self) {
1112
+ const weight = (this.charges[id] * alpha) / squared;
1113
+ const pullX = dx * weight;
1114
+ const pullY = dy * weight;
1115
+ if (isPlain && pullX - pullX === 0 && pullY - pullY === 0) {
1116
+ this.velocities[2 * self] += pullX;
1117
+ this.velocities[2 * self + 1] += pullY;
1118
+ saturate_(this.velocities, 2 * self);
1119
+ saturate_(this.velocities, 2 * self + 1);
1120
+ continue;
1121
+ }
1122
+ // A square, the clamp or the force left the doubles.
1123
+ PAIR_[PAIR_DX_] = dx;
1124
+ PAIR_[PAIR_DY_] = dy;
1125
+ PAIR_[PAIR_PRESCALE_] = 0;
1126
+ PAIR_[PAIR_STRENGTH_] = this.charges[id] * alpha;
1127
+ PAIR_[PAIR_STRENGTH_SCALE_] = 1;
1128
+ PAIR_[PAIR_DISTANCE_MIN_] = this.options.distanceMin;
1129
+ PAIR_[PAIR_DISTANCE_MIN_SQUARED_] = distanceMin2;
1130
+ addPull_(this.velocities, self);
1131
+ }
1132
+ }
1133
+ return false;
1134
+ };
1135
+ /**
1136
+ * {@link visitD3} for a cell whose centre is so far from the node that the
1137
+ * difference leaves the doubles (taken from halves in `PAIR_`): d3-force's
1138
+ * tests on scaled lengths, and the force from `addPull_`. No offset is drawn,
1139
+ * as the two cannot coincide.
1140
+ */
1141
+ visitD3Wide(node, cell) {
1142
+ const { scratch, tree, distanceMin2, distanceMax2, monopoleScale } = this;
1143
+ const { distanceMin, distanceMax, theta } = this.options;
1144
+ const self = scratch[SELF];
1145
+ const alpha = scratch[ALPHA];
1146
+ const halfX = PAIR_[PAIR_DX_];
1147
+ const halfY = PAIR_[PAIR_DY_];
1148
+ const width = (cell[2] - cell[0]) * this.cellScale;
1149
+ PAIR_[PAIR_LIMIT_] = width / theta;
1150
+ PAIR_[PAIR_LIMIT_SQUARED_] = (width * width) / this.theta2;
1151
+ PAIR_[PAIR_DISTANCE_MIN_] = distanceMin;
1152
+ PAIR_[PAIR_DISTANCE_MIN_SQUARED_] = distanceMin2;
1153
+ if (compareDistance_() > 0) {
1154
+ PAIR_[PAIR_LIMIT_] = distanceMax;
1155
+ PAIR_[PAIR_LIMIT_SQUARED_] = distanceMax2;
1156
+ if (compareDistance_() < 0) {
1157
+ PAIR_[PAIR_STRENGTH_] = this.values[node] * alpha;
1158
+ PAIR_[PAIR_STRENGTH_SCALE_] = monopoleScale;
1159
+ addPull_(this.velocities, self);
1160
+ }
1161
+ return true;
1162
+ }
1163
+ if (!tree.isLeaf(node)) {
1164
+ return false;
1165
+ }
1166
+ PAIR_[PAIR_LIMIT_] = distanceMax;
1167
+ PAIR_[PAIR_LIMIT_SQUARED_] = distanceMax2;
1168
+ if (compareDistance_() >= 0) {
1169
+ return false;
1170
+ }
1171
+ for (let id = tree.nodeFirstPoint(node); id !== -1; id = tree.nextPoint(id)) {
1172
+ if (id !== self) {
1173
+ PAIR_[PAIR_DX_] = halfX;
1174
+ PAIR_[PAIR_DY_] = halfY;
1175
+ PAIR_[PAIR_PRESCALE_] = 1;
1176
+ PAIR_[PAIR_STRENGTH_] = this.charges[id] * alpha;
1177
+ PAIR_[PAIR_STRENGTH_SCALE_] = 1;
1178
+ addPull_(this.velocities, self);
1179
+ }
1180
+ }
1181
+ return false;
1182
+ }
1183
+ }
1184
+ /**
1185
+ * Pushes overlapping discs apart, nodes tested on their predicted positions
1186
+ * (position + velocity). The tree prunes cells by their largest radius, so the
1187
+ * result is exact whatever the many-body approximation. The pruning is widened
1188
+ * by how far any prediction has moved since the pass started (the "skin" of
1189
+ * Verlet's neighbour lists: Verlet, Phys. Rev. 159, 1967), so a node pushed
1190
+ * into another's reach by an earlier pair of the same pass is still tested, and
1191
+ * every pair of a chain of coincident nodes collides. The active node's own
1192
+ * prediction is refreshed after each push, and its walk repeated on the moved
1193
+ * prediction (skipping the pairs already pushed) until a walk pushes none, so
1194
+ * no later pair is tested on where it no longer stands. Where a squared radius,
1195
+ * reach or distance would overflow or underflow, the pair is settled on lengths
1196
+ * scaled by a power of two and the shares on the ratio of the radii, each
1197
+ * node's share applied before scaling back, so any finite radii and distances
1198
+ * push (radii of `Number.MAX_VALUE` included) and only a node's part of a
1199
+ * displacement beyond the doubles overflows.
1200
+ *
1201
+ * `isD3` keeps d3-force's behaviour instead: cells bounded on the predictions
1202
+ * made when the pass starts, so such a pair is missed until the next pass, and
1203
+ * only the newest node of a coincident chain tested (and its radius taken as
1204
+ * the leaf's).
1205
+ */
1206
+ export class CollideForce {
1207
+ radii;
1208
+ strength;
1209
+ iterations;
1210
+ random;
1211
+ isD3;
1212
+ tree = new Quadtree();
1213
+ predicted;
1214
+ /**
1215
+ * Per node, the walk (`scratch[7]`) that last pushed it against the active
1216
+ * node.
1217
+ */
1218
+ pushedIn;
1219
+ cellRadii = new Float64Array(0);
1220
+ // x and y of the active node's prediction, its radius and squared radius,
1221
+ // its index, the skin, 1 once its walk pushed a pair, the walk's number.
1222
+ scratch = new Float64Array(8);
1223
+ positions = new Float64Array(0);
1224
+ velocities = new Float64Array(0);
1225
+ /** The power of two the tree's cells are to be multiplied by. */
1226
+ cellScale = 1;
1227
+ constructor(radii, strength, iterations, random, isD3) {
1228
+ this.radii = radii;
1229
+ this.strength = strength;
1230
+ this.iterations = iterations;
1231
+ this.random = random;
1232
+ this.isD3 = isD3;
1233
+ this.predicted = new Float64Array(radii.length * 2);
1234
+ this.pushedIn = new Float64Array(radii.length);
1235
+ }
1236
+ apply(positions, velocities) {
1237
+ this.positions = positions;
1238
+ this.velocities = velocities;
1239
+ const { tree, scratch, radii, isD3 } = this;
1240
+ for (let iteration = 0; iteration < this.iterations; iteration++) {
1241
+ this.assignTree();
1242
+ scratch[5] = 0;
1243
+ this.cellRadii = grown(this.cellRadii, tree.nodeCount());
1244
+ tree.visitAfter(this.prepare);
1245
+ for (let node = 0; node < radii.length; node++) {
1246
+ const radius = radii[node];
1247
+ scratch[2] = radius;
1248
+ scratch[3] = radius * radius;
1249
+ scratch[4] = node;
1250
+ scratch[7] += 1;
1251
+ // A push moves the node's prediction, so cells the walk pruned on
1252
+ // the earlier one may hold a pair it now overlaps: walk again on
1253
+ // the moved prediction, skipping the pairs already pushed.
1254
+ do {
1255
+ this.notePrediction(node);
1256
+ scratch[6] = 0;
1257
+ tree.visit(this.visit);
1258
+ } while (!isD3 && scratch[6] !== 0);
1259
+ }
1260
+ }
1261
+ }
1262
+ /**
1263
+ * Indexes the predictions `position + velocity`, scaled by a power of two
1264
+ * into the quadtree's range where one lies beyond it (or beyond the doubles):
1265
+ * the cells are then `cellScale` times the tree's.
1266
+ */
1267
+ assignTree() {
1268
+ const { positions, velocities, predicted } = this;
1269
+ let largest = 0;
1270
+ for (let index = 0; index < predicted.length; index++) {
1271
+ largest = Math.max(largest, Math.abs(positions[index]), Math.abs(velocities[index]));
1272
+ }
1273
+ // A prediction is at most twice the largest term.
1274
+ const shift = largest === largest
1275
+ ? treeShift_(largest) + (largest > TREE_LIMIT_ / 2 ? 1 : 0)
1276
+ : 0;
1277
+ if (shift === 0) {
1278
+ this.cellScale = 1;
1279
+ for (let index = 0; index < predicted.length; index++) {
1280
+ predicted[index] = positions[index] + velocities[index];
1281
+ }
1282
+ }
1283
+ else {
1284
+ this.cellScale = 2 ** shift;
1285
+ const factor = 2 ** -shift;
1286
+ for (let index = 0; index < predicted.length; index++) {
1287
+ predicted[index] =
1288
+ positions[index] * factor + velocities[index] * factor;
1289
+ }
1290
+ }
1291
+ this.tree.assign(predicted);
1292
+ }
1293
+ /**
1294
+ * Writes the node's prediction into `scratch[0]` and `scratch[1]`, for the
1295
+ * pruning test: saturated at ±`Number.MAX_VALUE` beyond the doubles, which
1296
+ * only prunes less.
1297
+ */
1298
+ notePrediction(node) {
1299
+ const { positions, velocities, scratch } = this;
1300
+ scratch[0] = positions[2 * node] + velocities[2 * node];
1301
+ scratch[1] = positions[2 * node + 1] + velocities[2 * node + 1];
1302
+ saturate_(scratch, 0);
1303
+ saturate_(scratch, 1);
1304
+ }
1305
+ /** Largest radius under every cell (`isD3`: a leaf's newest node's). */
1306
+ prepare = (node) => {
1307
+ const tree = this.tree;
1308
+ let largest = 0;
1309
+ if (tree.isLeaf(node)) {
1310
+ for (let id = tree.nodeFirstPoint(node); id !== -1; id = tree.nextPoint(id)) {
1311
+ largest = this.isD3
1312
+ ? this.radii[id]
1313
+ : Math.max(largest, this.radii[id]);
1314
+ }
1315
+ }
1316
+ else {
1317
+ for (let quadrant = 0; quadrant < 4; quadrant++) {
1318
+ const child = tree.nodeChild(node, quadrant);
1319
+ if (child !== -1 && this.cellRadii[child] > largest) {
1320
+ largest = this.cellRadii[child];
1321
+ }
1322
+ }
1323
+ }
1324
+ this.cellRadii[node] = largest;
1325
+ return false;
1326
+ };
1327
+ visit = (node, cell) => {
1328
+ const { scratch, tree, positions, velocities, radii, cellScale } = this;
1329
+ const xi = scratch[0];
1330
+ const yi = scratch[1];
1331
+ const radius = scratch[2];
1332
+ const radiusSquared = scratch[3];
1333
+ const self = scratch[4];
1334
+ if (!tree.isLeaf(node)) {
1335
+ // Beyond the doubles, the reach and the cell only prune less.
1336
+ const reach = radius + this.cellRadii[node] + scratch[5];
1337
+ return (cell[0] * cellScale > xi + reach ||
1338
+ cell[2] * cellScale < xi - reach ||
1339
+ cell[1] * cellScale > yi + reach ||
1340
+ cell[3] * cellScale < yi - reach);
1341
+ }
1342
+ let first = tree.nodeFirstPoint(node);
1343
+ if (this.isD3) {
1344
+ // d3-quadtree lists a chain newest first, and d3-force tests only its head.
1345
+ for (let next = first; next !== -1; next = tree.nextPoint(next)) {
1346
+ first = next;
1347
+ }
1348
+ }
1349
+ for (let other = first; other !== -1; other = this.isD3 ? -1 : tree.nextPoint(other)) {
1350
+ if (other <= self || this.pushedIn[other] === scratch[7]) {
1351
+ continue;
1352
+ }
1353
+ let otherRadius = radii[other];
1354
+ let reach = radius + otherRadius;
1355
+ const pair = FORCE_;
1356
+ // From the walk's prediction, as d3-force; from quarters of the four
1357
+ // terms where that leaves the doubles.
1358
+ let prescale = 0;
1359
+ pair[FORCE_DX_] = xi - positions[2 * other] - velocities[2 * other];
1360
+ pair[FORCE_DY_] =
1361
+ yi - positions[2 * other + 1] - velocities[2 * other + 1];
1362
+ if (pair[FORCE_DX_] -
1363
+ pair[FORCE_DX_] +
1364
+ (pair[FORCE_DY_] - pair[FORCE_DY_]) !==
1365
+ 0 ||
1366
+ Math.abs(xi) === Number.MAX_VALUE ||
1367
+ Math.abs(yi) === Number.MAX_VALUE) {
1368
+ prescale = predictedDelta_(pair, FORCE_DX_, positions, velocities, 2 * self, 2 * other);
1369
+ }
1370
+ let dx = pair[FORCE_DX_];
1371
+ let dy = pair[FORCE_DY_];
1372
+ let squared = dx * dx + dy * dy;
1373
+ const otherSquared = otherRadius * otherRadius;
1374
+ if (!(prescale === 0 &&
1375
+ reach * reach >= NORMAL_SQUARE_ &&
1376
+ reach * reach < Infinity &&
1377
+ squared < Infinity &&
1378
+ (squared >= NORMAL_SQUARE_ || (dx === 0 && dy === 0)) &&
1379
+ radiusSquared + otherSquared < Infinity &&
1380
+ (radiusSquared >= NORMAL_SQUARE_ || radius === 0) &&
1381
+ (otherSquared >= NORMAL_SQUARE_ || otherRadius === 0))) {
1382
+ // A difference or a square left the doubles: the pair is settled
1383
+ // on scaled lengths and the ratio of the radii.
1384
+ pair[FORCE_PRESCALE_] = prescale;
1385
+ pair[FORCE_REACH_] = radius;
1386
+ pair[FORCE_REACH_OTHER_] = otherRadius;
1387
+ let overlaps = radius + otherRadius > 0;
1388
+ if (dx !== 0 || dy !== 0) {
1389
+ scaledLengths_();
1390
+ overlaps = pair[FORCE_OVERLAP_] > 0;
1391
+ }
1392
+ if (!overlaps) {
1393
+ continue;
1394
+ }
1395
+ if (dx === 0) {
1396
+ drawJiggle(this.random, other, self);
1397
+ pair[FORCE_DX_] = JIGGLE[0];
1398
+ }
1399
+ if (dy === 0) {
1400
+ drawJiggle(this.random, other, self);
1401
+ pair[FORCE_DY_] = JIGGLE[0];
1402
+ }
1403
+ pair[FORCE_FACTOR_] = this.strength;
1404
+ pair[FORCE_SECOND_FACTOR_] = 1;
1405
+ collideShares_();
1406
+ scaledMove_();
1407
+ velocities[2 * self] += pair[FORCE_MOVE_X_];
1408
+ velocities[2 * self + 1] += pair[FORCE_MOVE_Y_];
1409
+ velocities[2 * other] -= pair[FORCE_MOVE_OTHER_X_];
1410
+ velocities[2 * other + 1] -= pair[FORCE_MOVE_OTHER_Y_];
1411
+ }
1412
+ else {
1413
+ if (squared >= reach * reach) {
1414
+ continue;
1415
+ }
1416
+ if (dx === 0) {
1417
+ drawJiggle(this.random, other, self);
1418
+ dx = JIGGLE[0];
1419
+ squared += dx * dx;
1420
+ }
1421
+ if (dy === 0) {
1422
+ drawJiggle(this.random, other, self);
1423
+ dy = JIGGLE[0];
1424
+ squared += dy * dy;
1425
+ }
1426
+ const distance = Math.sqrt(squared);
1427
+ const push = ((reach - distance) / distance) * this.strength;
1428
+ dx *= push;
1429
+ dy *= push;
1430
+ otherRadius = otherSquared;
1431
+ reach = otherRadius / (radiusSquared + otherRadius);
1432
+ velocities[2 * self] += dx * reach;
1433
+ velocities[2 * self + 1] += dy * reach;
1434
+ reach = 1 - reach;
1435
+ velocities[2 * other] -= dx * reach;
1436
+ velocities[2 * other + 1] -= dy * reach;
1437
+ }
1438
+ saturate_(velocities, 2 * self);
1439
+ saturate_(velocities, 2 * self + 1);
1440
+ saturate_(velocities, 2 * other);
1441
+ saturate_(velocities, 2 * other + 1);
1442
+ if (!this.isD3) {
1443
+ this.noteShift(self);
1444
+ this.noteShift(other);
1445
+ this.pushedIn[other] = scratch[7];
1446
+ this.notePrediction(self);
1447
+ scratch[6] = 1;
1448
+ }
1449
+ }
1450
+ return false;
1451
+ };
1452
+ /**
1453
+ * Cells were bounded on the predictions made at the start of the pass; the
1454
+ * pruning test widens them by how far any prediction has moved since (in the
1455
+ * tree's units, scaled back: beyond the doubles it only prunes less).
1456
+ */
1457
+ noteShift(node) {
1458
+ const { predicted, positions, velocities, scratch, cellScale } = this;
1459
+ let shiftX;
1460
+ let shiftY;
1461
+ if (cellScale === 1) {
1462
+ shiftX = Math.abs(positions[2 * node] + velocities[2 * node] - predicted[2 * node]);
1463
+ shiftY = Math.abs(positions[2 * node + 1] +
1464
+ velocities[2 * node + 1] -
1465
+ predicted[2 * node + 1]);
1466
+ }
1467
+ else {
1468
+ const factor = 1 / cellScale;
1469
+ shiftX =
1470
+ Math.abs(positions[2 * node] * factor +
1471
+ velocities[2 * node] * factor -
1472
+ predicted[2 * node]) * cellScale;
1473
+ shiftY =
1474
+ Math.abs(positions[2 * node + 1] * factor +
1475
+ velocities[2 * node + 1] * factor -
1476
+ predicted[2 * node + 1]) * cellScale;
1477
+ }
1478
+ scratch[5] = Math.max(scratch[5], shiftX, shiftY);
1479
+ }
1480
+ }
1481
+ /** Pull of strength · alpha toward `(centerX, centerY)` on each axis. */
1482
+ export function applyGravity(positions, velocities, alpha, strength, centerX, centerY) {
1483
+ for (let index = 0; index < positions.length; index += 2) {
1484
+ let pullX = (centerX - positions[index]) * strength * alpha;
1485
+ let pullY = (centerY - positions[index + 1]) * strength * alpha;
1486
+ // A difference or a product that overflows: from halves, whose
1487
+ // difference cannot, doubled last, so that only a pull beyond the
1488
+ // doubles overflows (and its velocity saturates).
1489
+ if (pullX - pullX !== 0) {
1490
+ pullX =
1491
+ (centerX * 0.5 - positions[index] * 0.5) * (strength * alpha) * 2;
1492
+ }
1493
+ if (pullY - pullY !== 0) {
1494
+ pullY =
1495
+ (centerY * 0.5 - positions[index + 1] * 0.5) * (strength * alpha) * 2;
1496
+ }
1497
+ velocities[index] += pullX;
1498
+ velocities[index + 1] += pullY;
1499
+ saturate_(velocities, index);
1500
+ saturate_(velocities, index + 1);
1501
+ }
1502
+ }
1503
+ /**
1504
+ * Shifts every position so that their mean moves `strength` of the way to the
1505
+ * centre.
1506
+ */
1507
+ export function applyCentering(positions, strength, centerX, centerY) {
1508
+ const count = positions.length / 2;
1509
+ if (count === 0) {
1510
+ return;
1511
+ }
1512
+ let sumX = 0;
1513
+ let sumY = 0;
1514
+ for (let index = 0; index < positions.length; index += 2) {
1515
+ sumX += positions[index];
1516
+ sumY += positions[index + 1];
1517
+ }
1518
+ let meanX = sumX / count;
1519
+ let meanY = sumY / count;
1520
+ let halfMeanX = meanX * 0.5;
1521
+ let halfMeanY = meanY * 0.5;
1522
+ if (sumX - sumX + (sumY - sumY) !== 0) {
1523
+ // A sum that overflows: half the mean, each coordinate divided first,
1524
+ // whose partial sums stay within half the largest coordinate.
1525
+ halfMeanX = 0;
1526
+ halfMeanY = 0;
1527
+ for (let index = 0; index < positions.length; index += 2) {
1528
+ halfMeanX += positions[index] / (2 * count);
1529
+ halfMeanY += positions[index + 1] / (2 * count);
1530
+ }
1531
+ meanX = halfMeanX * 2;
1532
+ meanY = halfMeanY * 2;
1533
+ }
1534
+ sumX = (meanX - centerX) * strength;
1535
+ sumY = (meanY - centerY) * strength;
1536
+ // A mean, a difference or a product that overflows: from quarters (half
1537
+ // the mean may round just past half the largest coordinate), multiplied
1538
+ // back last, so that only a shift beyond the doubles overflows (and the
1539
+ // positions saturate).
1540
+ if (sumX - sumX !== 0) {
1541
+ sumX = (halfMeanX * 0.5 - centerX * 0.25) * strength * 4;
1542
+ }
1543
+ if (sumY - sumY !== 0) {
1544
+ sumY = (halfMeanY * 0.5 - centerY * 0.25) * strength * 4;
1545
+ }
1546
+ for (let index = 0; index < positions.length; index += 2) {
1547
+ positions[index] -= sumX;
1548
+ positions[index + 1] -= sumY;
1549
+ saturate_(positions, index);
1550
+ saturate_(positions, index + 1);
1551
+ }
1552
+ }
1553
+ /**
1554
+ * Velocity Verlet: v ← v · keep, x ← x + v; a pinned axis (finite entry of
1555
+ * `fixedPositions`) is set to its pin with zero velocity. A position beyond the
1556
+ * doubles saturates at ±`Number.MAX_VALUE`.
1557
+ */
1558
+ export function integrate(positions, velocities, keep, fixedPositions) {
1559
+ for (let index = 0; index < positions.length; index++) {
1560
+ const pin = fixedPositions === undefined ? NaN : fixedPositions[index];
1561
+ if (pin !== pin) {
1562
+ velocities[index] *= keep;
1563
+ positions[index] += velocities[index];
1564
+ saturate_(positions, index);
1565
+ }
1566
+ else {
1567
+ positions[index] = pin;
1568
+ velocities[index] = 0;
1569
+ }
1570
+ }
1571
+ }
1572
+ //# sourceMappingURL=_force-forces.js.map