@ac-kit/math-graph 0.1.0 → 0.2.1

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 (37) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +42 -16
  3. package/dist/layout/_force-forces.d.ts +140 -16
  4. package/dist/layout/_force-forces.d.ts.map +1 -1
  5. package/dist/layout/_force-forces.js +1204 -122
  6. package/dist/layout/_force-forces.js.map +1 -1
  7. package/dist/layout/_hierarchy-table.js.map +1 -1
  8. package/dist/layout/_layer-order.d.ts +52 -10
  9. package/dist/layout/_layer-order.d.ts.map +1 -1
  10. package/dist/layout/_layer-order.js +565 -73
  11. package/dist/layout/_layer-order.js.map +1 -1
  12. package/dist/layout/_layered-rank.d.ts +8 -4
  13. package/dist/layout/_layered-rank.d.ts.map +1 -1
  14. package/dist/layout/_layered-rank.js +113 -20
  15. package/dist/layout/_layered-rank.js.map +1 -1
  16. package/dist/layout/_treemap-tiling.d.ts +13 -2
  17. package/dist/layout/_treemap-tiling.d.ts.map +1 -1
  18. package/dist/layout/_treemap-tiling.js +70 -10
  19. package/dist/layout/_treemap-tiling.js.map +1 -1
  20. package/dist/layout/create-force-step.d.ts +39 -24
  21. package/dist/layout/create-force-step.d.ts.map +1 -1
  22. package/dist/layout/create-force-step.js +45 -12
  23. package/dist/layout/create-force-step.js.map +1 -1
  24. package/dist/layout/layered-layout.d.ts +15 -2
  25. package/dist/layout/layered-layout.d.ts.map +1 -1
  26. package/dist/layout/layered-layout.js +5 -1
  27. package/dist/layout/layered-layout.js.map +1 -1
  28. package/dist/layout/sankey-layout.d.ts +10 -1
  29. package/dist/layout/sankey-layout.d.ts.map +1 -1
  30. package/dist/layout/sankey-layout.js +5 -0
  31. package/dist/layout/sankey-layout.js.map +1 -1
  32. package/dist/layout/tidy-tree-layout.js.map +1 -1
  33. package/dist/layout/treemap-layout.d.ts +14 -5
  34. package/dist/layout/treemap-layout.d.ts.map +1 -1
  35. package/dist/layout/treemap-layout.js +13 -8
  36. package/dist/layout/treemap-layout.js.map +1 -1
  37. package/package.json +11 -9
@@ -1,3 +1,4 @@
1
+ import { binaryExponent, scaleByPowerOfTwoInPlace } from "@ac-kit/core";
1
2
  import { Quadtree } from "@ac-kit/math-geometry";
2
3
  /**
3
4
  * Where {@link drawJiggle} leaves its offset. Callers read it from here instead
@@ -41,9 +42,68 @@ function grown(array, length) {
41
42
  ? array
42
43
  : new Float64Array(Math.max(length, array.length * 2));
43
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
+ }
44
100
  /**
45
101
  * Springs between linked nodes, on positions advanced by their velocities (the
46
- * velocity-Verlet predictor); the correction goes to the velocities.
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).
47
107
  */
48
108
  export function applyLinkForce(positions, velocities, alpha, data, random) {
49
109
  const { sources, targets, distances, strengths, biases, iterations } = data;
@@ -51,32 +111,63 @@ export function applyLinkForce(positions, velocities, alpha, data, random) {
51
111
  for (let link = 0; link < sources.length; link++) {
52
112
  const source = sources[link] * 2;
53
113
  const target = targets[link] * 2;
54
- let dx = positions[target] +
55
- velocities[target] -
56
- positions[source] -
57
- velocities[source];
114
+ const pair = FORCE_;
115
+ const prescale = predictedDelta_(pair, FORCE_DX_, positions, velocities, target, source);
116
+ let dx = pair[FORCE_DX_];
58
117
  if (dx === 0) {
59
118
  drawJiggle(random, sources[link], targets[link]);
60
119
  dx = JIGGLE[0];
61
120
  }
62
- let dy = positions[target + 1] +
63
- velocities[target + 1] -
64
- positions[source + 1] -
65
- velocities[source + 1];
121
+ let dy = pair[FORCE_DY_];
66
122
  if (dy === 0) {
67
123
  drawJiggle(random, sources[link], targets[link]);
68
124
  dy = JIGGLE[0];
69
125
  }
70
- let scale = Math.sqrt(dx * dx + dy * dy);
71
- scale = ((scale - distances[link]) / scale) * alpha * strengths[link];
72
- dx *= scale;
73
- dy *= scale;
74
- let share = biases[link];
75
- velocities[target] -= dx * share;
76
- velocities[target + 1] -= dy * share;
77
- share = 1 - share;
78
- velocities[source] += dx * share;
79
- velocities[source + 1] += dy * share;
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);
80
171
  }
81
172
  }
82
173
  }
@@ -88,37 +179,434 @@ const ALPHA = 2;
88
179
  const SELF = 3;
89
180
  const PREVIOUS_DRAW = 4;
90
181
  /**
91
- * Charges repelling or attracting each other with strength / distance:
92
- * Barnes–Hut (Barnes and Hut, 1986) over a `Quadtree`, each cell standing for
93
- * its charges at their |charge|-weighted centre once it looks small enough
94
- * (width² / θ² < distance²), or every pair in `"exact"` mode.
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.
95
554
  */
96
555
  export class ManyBodyForce {
97
556
  charges;
98
557
  options;
99
558
  tree = new Quadtree();
559
+ /** Positive charge of each cell (its signed sum when `isD3`). */
100
560
  values = new Float64Array(0);
101
561
  centersX = new Float64Array(0);
102
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);
103
567
  scratch = Float64Array.of(0, 0, 0, 0, NaN);
104
568
  positions = new Float64Array(0);
105
569
  velocities = new Float64Array(0);
106
570
  order;
107
571
  orderLength = 0;
108
572
  isExact;
573
+ isD3;
109
574
  isInert;
110
575
  theta2;
111
576
  distanceMin2;
112
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;
113
592
  constructor(charges, options) {
114
593
  this.charges = charges;
115
594
  this.options = options;
116
595
  this.isExact = options.approximation === "exact";
596
+ this.isD3 = options.isD3;
117
597
  this.order = new Uint32Array(charges.length);
118
598
  this.isInert = charges.every((charge) => charge === 0);
119
599
  this.theta2 = options.theta * options.theta;
120
600
  this.distanceMin2 = options.distanceMin * options.distanceMin;
121
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);
122
610
  }
123
611
  apply(positions, velocities, alpha) {
124
612
  if (this.isInert) {
@@ -132,18 +620,54 @@ export class ManyBodyForce {
132
620
  return;
133
621
  }
134
622
  const tree = this.tree;
135
- tree.assign(positions);
623
+ this.assignTree(positions);
136
624
  const needed = tree.nodeCount();
137
625
  this.values = grown(this.values, needed);
138
626
  this.centersX = grown(this.centersX, needed);
139
627
  this.centersY = grown(this.centersY, needed);
140
- tree.visitAfter(this.accumulate);
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;
141
638
  for (let node = 0; node < this.charges.length; node++) {
142
639
  this.scratch[NODE_X] = positions[2 * node];
143
640
  this.scratch[NODE_Y] = positions[2 * node + 1];
144
641
  this.scratch[SELF] = node;
145
- tree.visit(this.visit);
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);
146
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);
147
671
  }
148
672
  /**
149
673
  * Every pair, the others taken in the tree's leaf order: the order the
@@ -152,41 +676,40 @@ export class ManyBodyForce {
152
676
  */
153
677
  applyExact(positions, velocities, alpha) {
154
678
  const { charges, distanceMin2, distanceMax2, tree, order, scratch } = this;
155
- const { random } = this.options;
156
- tree.assign(positions);
679
+ const { random, distanceMin, distanceMax } = this.options;
680
+ this.assignTree(positions);
157
681
  this.orderLength = 0;
158
682
  tree.visit(this.collectLeaves);
159
683
  for (let node = 0; node < charges.length; node++) {
160
- const x = positions[2 * node];
161
- const y = positions[2 * node + 1];
162
684
  for (let slot = 0; slot < charges.length; slot++) {
163
685
  const other = order[slot];
164
686
  const charge = charges[other];
165
687
  if (other === node || charge === 0) {
166
688
  continue;
167
689
  }
168
- let dx = positions[2 * other] - x;
169
- let dy = positions[2 * other + 1] - y;
170
- let squared = dx * dx + dy * dy;
171
- if (squared >= distanceMax2) {
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) {
172
698
  continue;
173
699
  }
174
- if (dx === 0) {
700
+ if (PAIR_[PAIR_DX_] === 0) {
175
701
  drawPairJiggle(random, node, other, scratch, PREVIOUS_DRAW);
176
- dx = JIGGLE[0];
177
- squared += dx * dx;
702
+ PAIR_[PAIR_DX_] = JIGGLE[0];
178
703
  }
179
- if (dy === 0) {
704
+ if (PAIR_[PAIR_DY_] === 0) {
180
705
  drawPairJiggle(random, node, other, scratch, PREVIOUS_DRAW);
181
- dy = JIGGLE[0];
182
- squared += dy * dy;
183
- }
184
- if (squared < distanceMin2) {
185
- squared = Math.sqrt(distanceMin2 * squared);
706
+ PAIR_[PAIR_DY_] = JIGGLE[0];
186
707
  }
187
- const weight = (charge * alpha) / squared;
188
- velocities[2 * node] += dx * weight;
189
- velocities[2 * node + 1] += dy * weight;
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);
190
713
  }
191
714
  }
192
715
  }
@@ -199,8 +722,11 @@ export class ManyBodyForce {
199
722
  }
200
723
  return false;
201
724
  };
202
- /** Signed charge and |charge|-weighted centre of every cell, children first. */
203
- accumulate = (node) => {
725
+ /**
726
+ * `isD3`: signed charge and |charge|-weighted centre of every cell, children
727
+ * first.
728
+ */
729
+ accumulateD3 = (node) => {
204
730
  const tree = this.tree;
205
731
  let strength = 0;
206
732
  let weight = 0;
@@ -211,7 +737,7 @@ export class ManyBodyForce {
211
737
  x = this.positions[2 * first];
212
738
  y = this.positions[2 * first + 1];
213
739
  for (let id = first; id !== -1; id = tree.nextPoint(id)) {
214
- strength += this.charges[id];
740
+ strength += this.scaledCharges[id];
215
741
  }
216
742
  this.values[node] = strength;
217
743
  this.centersX[node] = x;
@@ -235,21 +761,291 @@ export class ManyBodyForce {
235
761
  this.values[node] = strength;
236
762
  this.centersX[node] = x / weight;
237
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
+ }
238
783
  return false;
239
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
+ */
240
875
  visit = (node, cell) => {
241
- const value = this.values[node];
242
- if (value === 0 || Number.isNaN(value)) {
876
+ const positive = this.values[node];
877
+ const negative = this.negativeValues[node];
878
+ if (positive === 0 && negative === 0) {
243
879
  return true;
244
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) {
245
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;
246
1034
  const { random } = this.options;
247
1035
  const self = scratch[SELF];
248
1036
  const alpha = scratch[ALPHA];
249
- let dx = this.centersX[node] - scratch[NODE_X];
250
- let dy = this.centersY[node] - scratch[NODE_Y];
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_];
251
1047
  let squared = dx * dx + dy * dy;
252
- const width = cell[2] - cell[0];
1048
+ const width = (cell[2] - cell[0]) * this.cellScale;
253
1049
  if ((width * width) / this.theta2 < squared) {
254
1050
  if (squared < distanceMax2) {
255
1051
  if (dx === 0) {
@@ -265,8 +1061,27 @@ export class ManyBodyForce {
265
1061
  if (squared < distanceMin2) {
266
1062
  squared = Math.sqrt(distanceMin2 * squared);
267
1063
  }
268
- this.velocities[2 * self] += (dx * value * alpha) / squared;
269
- this.velocities[2 * self + 1] += (dy * value * alpha) / squared;
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
+ }
270
1085
  }
271
1086
  return true;
272
1087
  }
@@ -291,75 +1106,211 @@ export class ManyBodyForce {
291
1106
  squared = Math.sqrt(distanceMin2 * squared);
292
1107
  }
293
1108
  }
1109
+ const isPlain = squared >= NORMAL_SQUARE_ && squared < Infinity;
294
1110
  for (let id = first; id !== -1; id = tree.nextPoint(id)) {
295
1111
  if (id !== self) {
296
1112
  const weight = (this.charges[id] * alpha) / squared;
297
- this.velocities[2 * self] += dx * weight;
298
- this.velocities[2 * self + 1] += dy * weight;
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);
299
1131
  }
300
1132
  }
301
1133
  return false;
302
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
+ }
303
1183
  }
304
1184
  /**
305
1185
  * Pushes overlapping discs apart, nodes tested on their predicted positions
306
1186
  * (position + velocity). The tree prunes cells by their largest radius, so the
307
- * result is exact whatever the many-body approximation. Its cells are bounded
308
- * on the predictions made when the pass starts, as d3-force's are: a node
309
- * pushed into another's reach by an earlier pair of the same pass can be missed
310
- * until the next pass. `isLive` widens the pruning by how far any prediction
311
- * has moved, so no pair is missed (and results differ from d3's).
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).
312
1205
  */
313
1206
  export class CollideForce {
314
1207
  radii;
315
1208
  strength;
316
1209
  iterations;
317
1210
  random;
318
- isLive;
1211
+ isD3;
319
1212
  tree = new Quadtree();
320
1213
  predicted;
1214
+ /**
1215
+ * Per node, the walk (`scratch[7]`) that last pushed it against the active
1216
+ * node.
1217
+ */
1218
+ pushedIn;
321
1219
  cellRadii = new Float64Array(0);
322
- scratch = new Float64Array(6);
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);
323
1223
  positions = new Float64Array(0);
324
1224
  velocities = new Float64Array(0);
325
- constructor(radii, strength, iterations, random, isLive = false) {
1225
+ /** The power of two the tree's cells are to be multiplied by. */
1226
+ cellScale = 1;
1227
+ constructor(radii, strength, iterations, random, isD3) {
326
1228
  this.radii = radii;
327
1229
  this.strength = strength;
328
1230
  this.iterations = iterations;
329
1231
  this.random = random;
330
- this.isLive = isLive;
1232
+ this.isD3 = isD3;
331
1233
  this.predicted = new Float64Array(radii.length * 2);
1234
+ this.pushedIn = new Float64Array(radii.length);
332
1235
  }
333
1236
  apply(positions, velocities) {
334
1237
  this.positions = positions;
335
1238
  this.velocities = velocities;
336
- const { tree, predicted, scratch, radii } = this;
1239
+ const { tree, scratch, radii, isD3 } = this;
337
1240
  for (let iteration = 0; iteration < this.iterations; iteration++) {
338
- for (let index = 0; index < predicted.length; index++) {
339
- predicted[index] = positions[index] + velocities[index];
340
- }
341
- tree.assign(predicted);
1241
+ this.assignTree();
342
1242
  scratch[5] = 0;
343
1243
  this.cellRadii = grown(this.cellRadii, tree.nodeCount());
344
1244
  tree.visitAfter(this.prepare);
345
1245
  for (let node = 0; node < radii.length; node++) {
346
1246
  const radius = radii[node];
347
- scratch[0] = positions[2 * node] + velocities[2 * node];
348
- scratch[1] = positions[2 * node + 1] + velocities[2 * node + 1];
349
1247
  scratch[2] = radius;
350
1248
  scratch[3] = radius * radius;
351
1249
  scratch[4] = node;
352
- tree.visit(this.visit);
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);
353
1259
  }
354
1260
  }
355
1261
  }
356
- /** Largest radius under every cell. */
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). */
357
1306
  prepare = (node) => {
358
1307
  const tree = this.tree;
359
1308
  let largest = 0;
360
1309
  if (tree.isLeaf(node)) {
361
1310
  for (let id = tree.nodeFirstPoint(node); id !== -1; id = tree.nextPoint(id)) {
362
- largest = Math.max(largest, this.radii[id]);
1311
+ largest = this.isD3
1312
+ ? this.radii[id]
1313
+ : Math.max(largest, this.radii[id]);
363
1314
  }
364
1315
  }
365
1316
  else {
@@ -374,78 +1325,179 @@ export class CollideForce {
374
1325
  return false;
375
1326
  };
376
1327
  visit = (node, cell) => {
377
- const { scratch, tree, positions, velocities, radii } = this;
1328
+ const { scratch, tree, positions, velocities, radii, cellScale } = this;
378
1329
  const xi = scratch[0];
379
1330
  const yi = scratch[1];
380
1331
  const radius = scratch[2];
381
1332
  const radiusSquared = scratch[3];
382
1333
  const self = scratch[4];
383
1334
  if (!tree.isLeaf(node)) {
1335
+ // Beyond the doubles, the reach and the cell only prune less.
384
1336
  const reach = radius + this.cellRadii[node] + scratch[5];
385
- return (cell[0] > xi + reach ||
386
- cell[2] < xi - reach ||
387
- cell[1] > yi + reach ||
388
- cell[3] < yi - reach);
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
+ }
389
1348
  }
390
- for (let other = tree.nodeFirstPoint(node); other !== -1; other = tree.nextPoint(other)) {
391
- if (other <= self) {
1349
+ for (let other = first; other !== -1; other = this.isD3 ? -1 : tree.nextPoint(other)) {
1350
+ if (other <= self || this.pushedIn[other] === scratch[7]) {
392
1351
  continue;
393
1352
  }
394
1353
  let otherRadius = radii[other];
395
1354
  let reach = radius + otherRadius;
396
- let dx = xi - positions[2 * other] - velocities[2 * other];
397
- let dy = yi - positions[2 * other + 1] - velocities[2 * other + 1];
398
- let squared = dx * dx + dy * dy;
399
- if (squared >= reach * reach) {
400
- continue;
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);
401
1369
  }
402
- if (dx === 0) {
403
- drawJiggle(this.random, other, self);
404
- dx = JIGGLE[0];
405
- squared += dx * dx;
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_];
406
1411
  }
407
- if (dy === 0) {
408
- drawJiggle(this.random, other, self);
409
- dy = JIGGLE[0];
410
- squared += dy * dy;
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;
411
1437
  }
412
- const distance = Math.sqrt(squared);
413
- const push = ((reach - distance) / distance) * this.strength;
414
- dx *= push;
415
- dy *= push;
416
- otherRadius *= otherRadius;
417
- reach = otherRadius / (radiusSquared + otherRadius);
418
- velocities[2 * self] += dx * reach;
419
- velocities[2 * self + 1] += dy * reach;
420
- reach = 1 - reach;
421
- velocities[2 * other] -= dx * reach;
422
- velocities[2 * other + 1] -= dy * reach;
423
- if (this.isLive) {
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) {
424
1443
  this.noteShift(self);
425
1444
  this.noteShift(other);
1445
+ this.pushedIn[other] = scratch[7];
1446
+ this.notePrediction(self);
1447
+ scratch[6] = 1;
426
1448
  }
427
1449
  }
428
1450
  return false;
429
1451
  };
430
1452
  /**
431
1453
  * Cells were bounded on the predictions made at the start of the pass; the
432
- * pruning test widens them by how far any prediction has moved since.
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).
433
1456
  */
434
1457
  noteShift(node) {
435
- const { predicted, positions, velocities, scratch } = this;
436
- const shiftX = Math.abs(positions[2 * node] + velocities[2 * node] - predicted[2 * node]);
437
- const shiftY = Math.abs(positions[2 * node + 1] +
438
- velocities[2 * node + 1] -
439
- predicted[2 * node + 1]);
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
+ }
440
1478
  scratch[5] = Math.max(scratch[5], shiftX, shiftY);
441
1479
  }
442
1480
  }
443
1481
  /** Pull of strength · alpha toward `(centerX, centerY)` on each axis. */
444
1482
  export function applyGravity(positions, velocities, alpha, strength, centerX, centerY) {
445
1483
  for (let index = 0; index < positions.length; index += 2) {
446
- velocities[index] += (centerX - positions[index]) * strength * alpha;
447
- velocities[index + 1] +=
448
- (centerY - positions[index + 1]) * strength * alpha;
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);
449
1501
  }
450
1502
  }
451
1503
  /**
@@ -463,23 +1515,53 @@ export function applyCentering(positions, strength, centerX, centerY) {
463
1515
  sumX += positions[index];
464
1516
  sumY += positions[index + 1];
465
1517
  }
466
- sumX = (sumX / count - centerX) * strength;
467
- sumY = (sumY / count - centerY) * strength;
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
+ }
468
1546
  for (let index = 0; index < positions.length; index += 2) {
469
1547
  positions[index] -= sumX;
470
1548
  positions[index + 1] -= sumY;
1549
+ saturate_(positions, index);
1550
+ saturate_(positions, index + 1);
471
1551
  }
472
1552
  }
473
1553
  /**
474
1554
  * Velocity Verlet: v ← v · keep, x ← x + v; a pinned axis (finite entry of
475
- * `fixedPositions`) is set to its pin with zero velocity.
1555
+ * `fixedPositions`) is set to its pin with zero velocity. A position beyond the
1556
+ * doubles saturates at ±`Number.MAX_VALUE`.
476
1557
  */
477
1558
  export function integrate(positions, velocities, keep, fixedPositions) {
478
1559
  for (let index = 0; index < positions.length; index++) {
479
1560
  const pin = fixedPositions === undefined ? NaN : fixedPositions[index];
480
- if (Number.isNaN(pin)) {
1561
+ if (pin !== pin) {
481
1562
  velocities[index] *= keep;
482
1563
  positions[index] += velocities[index];
1564
+ saturate_(positions, index);
483
1565
  }
484
1566
  else {
485
1567
  positions[index] = pin;