@ac-kit/math-geometry 0.3.0 → 0.5.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 (75) hide show
  1. package/CHANGELOG.md +177 -0
  2. package/README.md +76 -5
  3. package/dist/_polygon3-cross.d.ts +23 -0
  4. package/dist/_polygon3-cross.d.ts.map +1 -0
  5. package/dist/_polygon3-cross.js +418 -0
  6. package/dist/_polygon3-cross.js.map +1 -0
  7. package/dist/_polyline-simplify.d.ts +11 -0
  8. package/dist/_polyline-simplify.d.ts.map +1 -0
  9. package/dist/_polyline-simplify.js +92 -0
  10. package/dist/_polyline-simplify.js.map +1 -0
  11. package/dist/_triangle3-cross.d.ts +66 -0
  12. package/dist/_triangle3-cross.d.ts.map +1 -0
  13. package/dist/_triangle3-cross.js +405 -0
  14. package/dist/_triangle3-cross.js.map +1 -0
  15. package/dist/convex-hull2.d.ts +26 -0
  16. package/dist/convex-hull2.d.ts.map +1 -0
  17. package/dist/convex-hull2.js +88 -0
  18. package/dist/convex-hull2.js.map +1 -0
  19. package/dist/index.d.ts +2 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +2 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/line2.d.ts +4 -0
  24. package/dist/line2.d.ts.map +1 -1
  25. package/dist/line2.js +26 -5
  26. package/dist/line2.js.map +1 -1
  27. package/dist/mesh/_index-kernels-u16.d.ts +46 -11
  28. package/dist/mesh/_index-kernels-u16.d.ts.map +1 -1
  29. package/dist/mesh/_index-kernels-u16.js +1442 -132
  30. package/dist/mesh/_index-kernels-u16.js.map +1 -1
  31. package/dist/mesh/_index-kernels-u32.d.ts +46 -11
  32. package/dist/mesh/_index-kernels-u32.d.ts.map +1 -1
  33. package/dist/mesh/_index-kernels-u32.js +1442 -132
  34. package/dist/mesh/_index-kernels-u32.js.map +1 -1
  35. package/dist/mesh/mesh3-kernels.d.ts +104 -20
  36. package/dist/mesh/mesh3-kernels.d.ts.map +1 -1
  37. package/dist/mesh/mesh3-kernels.js +123 -25
  38. package/dist/mesh/mesh3-kernels.js.map +1 -1
  39. package/dist/plane3.d.ts +4 -3
  40. package/dist/plane3.d.ts.map +1 -1
  41. package/dist/plane3.js +18 -35
  42. package/dist/plane3.js.map +1 -1
  43. package/dist/polygon2.d.ts +76 -4
  44. package/dist/polygon2.d.ts.map +1 -1
  45. package/dist/polygon2.js +366 -7
  46. package/dist/polygon2.js.map +1 -1
  47. package/dist/polygon3.d.ts +19 -3
  48. package/dist/polygon3.d.ts.map +1 -1
  49. package/dist/polygon3.js +40 -16
  50. package/dist/polygon3.js.map +1 -1
  51. package/dist/polyline2.d.ts +20 -0
  52. package/dist/polyline2.d.ts.map +1 -1
  53. package/dist/polyline2.js +25 -0
  54. package/dist/polyline2.js.map +1 -1
  55. package/dist/polyline3.d.ts +17 -0
  56. package/dist/polyline3.d.ts.map +1 -1
  57. package/dist/polyline3.js +22 -0
  58. package/dist/polyline3.js.map +1 -1
  59. package/dist/predicates2.d.ts +51 -0
  60. package/dist/predicates2.d.ts.map +1 -0
  61. package/dist/predicates2.js +172 -0
  62. package/dist/predicates2.js.map +1 -0
  63. package/dist/quadtree.d.ts +40 -23
  64. package/dist/quadtree.d.ts.map +1 -1
  65. package/dist/quadtree.js +196 -119
  66. package/dist/quadtree.js.map +1 -1
  67. package/dist/segment2.d.ts +6 -1
  68. package/dist/segment2.d.ts.map +1 -1
  69. package/dist/segment2.js +20 -4
  70. package/dist/segment2.js.map +1 -1
  71. package/dist/triangle3.d.ts +20 -1
  72. package/dist/triangle3.d.ts.map +1 -1
  73. package/dist/triangle3.js +38 -18
  74. package/dist/triangle3.js.map +1 -1
  75. package/package.json +8 -8
@@ -1,71 +1,351 @@
1
1
  // Generated from scripts/templates/index-kernels.liquid by scripts/generate-index-kernels.ts. Do not edit.
2
+ import { binaryExponent, binaryExponentAt, PreciseSum, scaleByPowerOfTwoInPlace, } from "@ac-kit/core";
2
3
  import { vec2Create, vec3Create, } from "@ac-kit/math-linear";
4
+ import { DotExactAccumulator, twoProductInRangeInPlace, twoSumInPlace, } from "@ac-kit/math-scalar";
5
+ import { triangle3Cross_, writeScaledComponents_, } from "../_triangle3-cross.js";
3
6
  import { ray3IntersectTriangle3 } from "../ray3.js";
4
7
  import { triangle3Create } from "../triangle3-record.js";
5
8
  import { triangle3Normal } from "../triangle3.js";
6
9
  // Scratch values, made by their creators and never handed out (S23).
7
10
  const TRIANGLE_ = triangle3Create();
11
+ /** A face's corners a, b and c, for `triangle3Cross_`. */
12
+ const CORNERS_ = new Float64Array(9);
8
13
  const BARYCENTRIC_ = vec2Create();
9
14
  const NORMAL_ = vec3Create();
15
+ const AREA_ = new PreciseSum();
16
+ /**
17
+ * The frame of the volume: the anchor (0–2), per axis the exponent e with 2^e
18
+ * above its extent (3–5), and 1 when some extent is so wide that a difference
19
+ * of two coordinates may overflow (6).
20
+ */
21
+ const FRAME_ = new Float64Array(7);
22
+ /**
23
+ * One face's doubled area as `[m, k]`, the area being m · 2^k: k is 0 when m is
24
+ * the area itself, otherwise m is between 1 and 4 (0 for a degenerate face,
25
+ * `NaN` for a non-finite one).
26
+ */
27
+ const FACE_AREA_ = new Float64Array(2);
28
+ /** One face's cross product `[x, y, z, k]`, the product being (x, y, z) · 2^k. */
29
+ const FACE_CROSS_ = new Float64Array(4);
30
+ /** A double computed and scaled in place, never boxed by a call. */
31
+ const VALUE_ = new Float64Array(1);
32
+ /** Two numbers TwoSum replaces by their sum and its error. */
33
+ const PAIR_ = new Float64Array(2);
34
+ /** The volume filter's operands, TwoSum and TwoProduct pairs in place. */
35
+ const FILTER_ = new Float64Array(36);
36
+ /**
37
+ * The accuracy a vertex's sum must be certified to: each component's bound
38
+ * within 2^−50 of the largest component, so that the unit normal stays within
39
+ * 2^−48 of the exact sum's direction.
40
+ */
41
+ const VERTEX_ACCURACY_ = 2 ** -50;
42
+ /**
43
+ * The bound, in units of u, on what a scaled product loses underflowing (each
44
+ * term below 2^−1070), far above it.
45
+ */
46
+ const SCALED_TERM_BOUND_ = 2 ** -1000;
47
+ /**
48
+ * The least exponent of a term the exact vertex sums add, inside a
49
+ * `DotExactAccumulator`'s span (from 2^−3350).
50
+ */
51
+ const EXACT_TERM_MIN_EXPONENT_ = -2166;
52
+ /** The exact sums of a vertex's components. */
53
+ const EXACT_SUMS_ = [
54
+ new DotExactAccumulator(),
55
+ new DotExactAccumulator(),
56
+ new DotExactAccumulator(),
57
+ ];
58
+ /** A term added to an exact sum, as a one-product dot product. */
59
+ const TERM_ = new Float64Array(1);
60
+ const ONE_ = Float64Array.of(1);
61
+ /** An exact sum, as significand and exponent. */
62
+ const SCALED_ = new Float64Array(2);
63
+ /** A vertex's exact sum, each `SUM_COMPONENTS_[i] · 2^SUM_EXPONENTS_[i]`. */
64
+ const SUM_COMPONENTS_ = new Float64Array(3);
65
+ const SUM_EXPONENTS_ = new Int32Array(3);
66
+ /** A vertex's exact sum as `[x, y, z, k]`. */
67
+ const VERTEX_SUM_ = new Float64Array(4);
10
68
  /**
11
69
  * The `Uint16Array` twin of the area-weighted vertex normals: the public
12
70
  * function checks the lengths and dispatches on the index type once. Writes
13
- * `positions.length` numbers into `out`. O(vertices + triangles).
71
+ * `positions.length` numbers into `out`. Each face adds its cross product,
72
+ * twice its area times its unit normal (`faceCross_`: within 2^−49 of its
73
+ * largest component, zero only for a degenerate face). While every face's
74
+ * product is plain (k = 0, its largest component in [2^−400, 2^402)), the sums
75
+ * are those products' as they come; otherwise a first pass finds, per vertex,
76
+ * the largest product among its faces, and each face adds its product scaled by
77
+ * the power of two that brings that vertex's largest to [1, 2): the weights
78
+ * keep their ratios, nothing overflows, and a vertex whose faces are all tiny
79
+ * beside other vertices' still gets its normal. Each sum keeps a running bound
80
+ * on its rounding errors (Higham, "Accuracy and Stability of Numerical
81
+ * Algorithms", §4.2: within u/(1 − u) of the partial sums' magnitudes, u =
82
+ * 2^−53); a vertex whose bound is not within 2^−50 of its largest component
83
+ * (its faces cancel, or it has very many) is summed again exactly
84
+ * (`exactVertexSums_`). O(vertices + triangles); no allocation once the
85
+ * per-vertex scratch has grown to the largest mesh.
14
86
  */
15
87
  export function mesh3VertexNormalsU16(out, positions, indices) {
88
+ const cross = FACE_CROSS_;
89
+ const vertexCount = out.length / 3;
90
+ if (vertexErrorsU16_.length < vertexCount) {
91
+ vertexErrorsU16_ = new Float64Array(Math.max(vertexCount, 2 * vertexErrorsU16_.length));
92
+ }
93
+ const errors = vertexErrorsU16_;
94
+ errors.fill(0, 0, vertexCount);
16
95
  out.fill(0);
96
+ let isPlain = true;
17
97
  for (let corner = 0; corner < indices.length; corner += 3) {
18
- const a = indices[corner] * 3;
19
- const b = indices[corner + 1] * 3;
20
- const c = indices[corner + 2] * 3;
21
- const abX = positions[b] - positions[a];
22
- const abY = positions[b + 1] - positions[a + 1];
23
- const abZ = positions[b + 2] - positions[a + 2];
24
- const acX = positions[c] - positions[a];
25
- const acY = positions[c + 1] - positions[a + 1];
26
- const acZ = positions[c + 2] - positions[a + 2];
27
- // The cross product is twice the area times the unit normal: the area
28
- // weight comes with it.
29
- const crossX = abY * acZ - abZ * acY;
30
- const crossY = abZ * acX - abX * acZ;
31
- const crossZ = abX * acY - abY * acX;
32
- // An index past the end reads NaN and writes nothing.
33
- out[a] = out[a] + crossX;
34
- out[a + 1] = out[a + 1] + crossY;
35
- out[a + 2] = out[a + 2] + crossZ;
36
- out[b] = out[b] + crossX;
37
- out[b + 1] = out[b + 1] + crossY;
38
- out[b + 2] = out[b + 2] + crossZ;
39
- out[c] = out[c] + crossX;
40
- out[c + 1] = out[c + 1] + crossY;
41
- out[c + 2] = out[c + 2] + crossZ;
42
- }
43
- for (let vertex = 0; vertex < out.length; vertex += 3) {
44
- const x = out[vertex];
45
- const y = out[vertex + 1];
46
- const z = out[vertex + 2];
47
- const length = Math.sqrt(x * x + y * y + z * z);
48
- if (length > 0 && length < Number.POSITIVE_INFINITY) {
49
- const inverse = 1 / length;
50
- out[vertex] = x * inverse;
51
- out[vertex + 1] = y * inverse;
52
- out[vertex + 2] = z * inverse;
98
+ const vertexA = indices[corner];
99
+ const vertexB = indices[corner + 1];
100
+ const vertexC = indices[corner + 2];
101
+ const a = vertexA * 3;
102
+ const b = vertexB * 3;
103
+ const c = vertexC * 3;
104
+ faceCrossU16_(positions, a, b, c);
105
+ if (cross[3] !== 0) {
106
+ isPlain = false;
107
+ break;
108
+ }
109
+ const crossX = cross[0];
110
+ const crossY = cross[1];
111
+ const crossZ = cross[2];
112
+ // An index past the end reads NaN and writes nothing (or NaN in the
113
+ // scratch's unused tail).
114
+ const sumAX = out[a] + crossX;
115
+ const sumAY = out[a + 1] + crossY;
116
+ const sumAZ = out[a + 2] + crossZ;
117
+ out[a] = sumAX;
118
+ out[a + 1] = sumAY;
119
+ out[a + 2] = sumAZ;
120
+ errors[vertexA] =
121
+ errors[vertexA] +
122
+ Math.max(Math.abs(sumAX), Math.abs(sumAY), Math.abs(sumAZ));
123
+ const sumBX = out[b] + crossX;
124
+ const sumBY = out[b + 1] + crossY;
125
+ const sumBZ = out[b + 2] + crossZ;
126
+ out[b] = sumBX;
127
+ out[b + 1] = sumBY;
128
+ out[b + 2] = sumBZ;
129
+ errors[vertexB] =
130
+ errors[vertexB] +
131
+ Math.max(Math.abs(sumBX), Math.abs(sumBY), Math.abs(sumBZ));
132
+ const sumCX = out[c] + crossX;
133
+ const sumCY = out[c + 1] + crossY;
134
+ const sumCZ = out[c + 2] + crossZ;
135
+ out[c] = sumCX;
136
+ out[c + 1] = sumCY;
137
+ out[c + 2] = sumCZ;
138
+ errors[vertexC] =
139
+ errors[vertexC] +
140
+ Math.max(Math.abs(sumCX), Math.abs(sumCY), Math.abs(sumCZ));
141
+ }
142
+ if (!isPlain) {
143
+ scaledVertexSumsU16_(out, positions, indices);
144
+ }
145
+ // u / (1 − u) per partial sum, widened by 4nu for the bound's own
146
+ // roundings over the n numbers it adds.
147
+ const factor = 1.0001 * UNIT_ROUNDOFF_ * (1 + 4 * indices.length * UNIT_ROUNDOFF_);
148
+ let uncertain = 0;
149
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
150
+ const at = 3 * vertex;
151
+ const largest = Math.max(Math.abs(out[at]), Math.abs(out[at + 1]), Math.abs(out[at + 2]));
152
+ if (errors[vertex] * factor > largest * VERTEX_ACCURACY_) {
153
+ errors[vertex] = -1;
154
+ uncertain++;
155
+ continue;
156
+ }
157
+ normalizeVertex_(out, at);
158
+ }
159
+ if (uncertain > 0) {
160
+ exactVertexSumsU16_(out, positions, indices);
161
+ }
162
+ }
163
+ /**
164
+ * Per vertex, the sum of the largest magnitudes of {@link mesh3VertexNormals}'s
165
+ * partial sums, the bound on every component's rounding errors in units of u,
166
+ * then −1 where that bound is too wide: grown to the largest mesh seen, then
167
+ * reused.
168
+ */
169
+ let vertexErrorsU16_ = new Float64Array(0);
170
+ /**
171
+ * Per vertex, the exponent of the largest cross product among its faces, for
172
+ * {@link scaledVertexSums_}: grown to the largest mesh seen, then reused.
173
+ */
174
+ let vertexExponentsU16_ = new Int32Array(0);
175
+ /**
176
+ * Rewrites `out` with each vertex's sum of its faces' cross products, every
177
+ * product scaled by the power of two that brings the vertex's largest to [1,
178
+ * 2): the same direction as the plain sum, with no product that overflows or
179
+ * underflows on the way. Rewrites `vertexErrors_` with the bound on the sums'
180
+ * roundings, an absolute 2^−1000 per term added for what a scaled product loses
181
+ * underflowing (each is below 2^−1070).
182
+ */
183
+ function scaledVertexSumsU16_(out, positions, indices) {
184
+ const cross = FACE_CROSS_;
185
+ const vertexCount = out.length / 3;
186
+ if (vertexExponentsU16_.length < vertexCount) {
187
+ vertexExponentsU16_ = new Int32Array(Math.max(vertexCount, 2 * vertexExponentsU16_.length));
188
+ }
189
+ const exponents = vertexExponentsU16_;
190
+ const errors = vertexErrorsU16_;
191
+ exponents.fill(NONE_, 0, vertexCount);
192
+ for (let face = 0; face < indices.length; face += 3) {
193
+ faceCrossU16_(positions, indices[face] * 3, indices[face + 1] * 3, indices[face + 2] * 3);
194
+ const largest = Math.max(Math.abs(cross[0]), Math.abs(cross[1]), Math.abs(cross[2]));
195
+ if (largest > 0 && largest < Number.POSITIVE_INFINITY) {
196
+ const exponent = cross[3] + binaryExponent(largest);
197
+ for (let corner = face; corner < face + 3; corner++) {
198
+ // A corner past the last vertex reads and writes nothing.
199
+ const vertex = indices[corner];
200
+ if (vertex < vertexCount) {
201
+ exponents[vertex] = Math.max(exponents[vertex], exponent);
202
+ }
203
+ }
204
+ }
205
+ }
206
+ out.fill(0);
207
+ errors.fill(0, 0, vertexCount);
208
+ for (let face = 0; face < indices.length; face += 3) {
209
+ faceCrossU16_(positions, indices[face] * 3, indices[face + 1] * 3, indices[face + 2] * 3);
210
+ const largest = Math.max(Math.abs(cross[0]), Math.abs(cross[1]), Math.abs(cross[2]));
211
+ if (largest === 0) {
53
212
  continue;
54
213
  }
55
- // The squares underflowed or overflowed, or the vertex has no normal.
56
- const scale = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
57
- if (scale === 0) {
214
+ for (let corner = face; corner < face + 3; corner++) {
215
+ const vertex = indices[corner];
216
+ if (vertex >= vertexCount) {
217
+ continue;
218
+ }
219
+ // A NaN product stays NaN; a product 2^1080 below the vertex's largest
220
+ // weighs nothing beside it.
221
+ const factor = largest < Number.POSITIVE_INFINITY
222
+ ? 2 ** Math.max(cross[3] - exponents[vertex], -1080)
223
+ : 1;
224
+ const at = vertex * 3;
225
+ out[at] = out[at] + cross[0] * factor;
226
+ out[at + 1] = out[at + 1] + cross[1] * factor;
227
+ out[at + 2] = out[at + 2] + cross[2] * factor;
228
+ errors[vertex] =
229
+ errors[vertex] +
230
+ Math.max(Math.abs(out[at]), Math.abs(out[at + 1]), Math.abs(out[at + 2])) +
231
+ SCALED_TERM_BOUND_;
232
+ }
233
+ }
234
+ }
235
+ /**
236
+ * Per vertex, where its faces start in `vertexFaces_`, for
237
+ * {@link exactVertexSums_}: grown to the largest mesh seen, then reused.
238
+ */
239
+ let vertexStartsU16_ = new Int32Array(0);
240
+ /** The faces (their first corner) of each vertex summed exactly, in turn. */
241
+ let vertexFacesU16_ = new Int32Array(0);
242
+ /**
243
+ * Rewrites, at each vertex `vertexErrors_` marks with −1, the unit normal of
244
+ * the exact sum of its faces' cross products (`faceCross_`'s, a face counted
245
+ * once per corner it has there), each component summed by a long accumulator
246
+ * and rounded once (`DotExactAccumulator`), at any exponent; the zero vector
247
+ * where that sum is zero. A component below 2^−2166, which no accumulator
248
+ * holds, is 2^1040 below its face's largest and well within that product's own
249
+ * bound, and is left out. The faces of those vertices are listed first
250
+ * (counted, then placed), so each is read once per corner at a marked vertex.
251
+ */
252
+ function exactVertexSumsU16_(out, positions, indices) {
253
+ const vertexCount = out.length / 3;
254
+ const errors = vertexErrorsU16_;
255
+ if (vertexStartsU16_.length < vertexCount + 2) {
256
+ vertexStartsU16_ = new Int32Array(Math.max(vertexCount + 2, 2 * vertexStartsU16_.length));
257
+ }
258
+ const starts = vertexStartsU16_;
259
+ starts.fill(0, 0, vertexCount + 2);
260
+ for (let corner = 0; corner < indices.length; corner++) {
261
+ const vertex = indices[corner];
262
+ if (vertex < vertexCount && errors[vertex] === -1) {
263
+ starts[vertex + 1] = starts[vertex + 1] + 1;
264
+ }
265
+ }
266
+ // Each vertex's end, then, placing its faces backwards, its start.
267
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
268
+ starts[vertex + 1] = starts[vertex + 1] + starts[vertex];
269
+ }
270
+ const total = starts[vertexCount];
271
+ if (vertexFacesU16_.length < total) {
272
+ vertexFacesU16_ = new Int32Array(Math.max(total, 2 * vertexFacesU16_.length));
273
+ }
274
+ const faces = vertexFacesU16_;
275
+ for (let corner = 0; corner < indices.length; corner++) {
276
+ const vertex = indices[corner];
277
+ if (vertex < vertexCount && errors[vertex] === -1) {
278
+ const at = starts[vertex + 1] - 1;
279
+ starts[vertex + 1] = at;
280
+ faces[at] = corner - (corner % 3);
281
+ }
282
+ }
283
+ // Now vertex v's faces are faces[starts[v + 1]] to faces[starts[v + 2]].
284
+ starts[vertexCount + 1] = total;
285
+ const cross = FACE_CROSS_;
286
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
287
+ if (errors[vertex] !== -1) {
58
288
  continue;
59
289
  }
60
- const scaledX = x / scale;
61
- const scaledY = y / scale;
62
- const scaledZ = z / scale;
63
- const scaledLength = Math.sqrt(scaledX * scaledX + scaledY * scaledY + scaledZ * scaledZ);
64
- out[vertex] = scaledX / scaledLength;
65
- out[vertex + 1] = scaledY / scaledLength;
66
- out[vertex + 2] = scaledZ / scaledLength;
290
+ EXACT_SUMS_[0].reset();
291
+ EXACT_SUMS_[1].reset();
292
+ EXACT_SUMS_[2].reset();
293
+ const end = starts[vertex + 2];
294
+ for (let at = starts[vertex + 1]; at < end; at++) {
295
+ const face = faces[at];
296
+ faceCrossU16_(positions, indices[face] * 3, indices[face + 1] * 3, indices[face + 2] * 3);
297
+ const exponent = cross[3];
298
+ for (let component = 0; component < 3; component++) {
299
+ const value = cross[component];
300
+ if (value !== 0 &&
301
+ binaryExponent(value) + exponent >= EXACT_TERM_MIN_EXPONENT_) {
302
+ TERM_[0] = value;
303
+ EXACT_SUMS_[component].addProducts(TERM_, ONE_, exponent);
304
+ }
305
+ }
306
+ }
307
+ for (let component = 0; component < 3; component++) {
308
+ EXACT_SUMS_[component].writeScaled(SCALED_, 0);
309
+ SUM_COMPONENTS_[component] = SCALED_[0];
310
+ SUM_EXPONENTS_[component] = SCALED_[1];
311
+ }
312
+ writeScaledComponents_(VERTEX_SUM_, SUM_COMPONENTS_, SUM_EXPONENTS_);
313
+ const at = 3 * vertex;
314
+ out[at] = VERTEX_SUM_[0];
315
+ out[at + 1] = VERTEX_SUM_[1];
316
+ out[at + 2] = VERTEX_SUM_[2];
317
+ normalizeVertex_(out, at);
67
318
  }
68
319
  }
320
+ /**
321
+ * Replaces the vector at `out[at]` by its direction: unchanged when it is zero,
322
+ * `NaN`s when a component is.
323
+ */
324
+ function normalizeVertex_(out, at) {
325
+ const x = out[at];
326
+ const y = out[at + 1];
327
+ const z = out[at + 2];
328
+ const length = Math.sqrt(x * x + y * y + z * z);
329
+ if (length > 0 && length < Number.POSITIVE_INFINITY) {
330
+ const inverse = 1 / length;
331
+ out[at] = x * inverse;
332
+ out[at + 1] = y * inverse;
333
+ out[at + 2] = z * inverse;
334
+ return;
335
+ }
336
+ // The squares underflowed or overflowed, or the vertex has no normal.
337
+ const scale = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
338
+ if (scale === 0) {
339
+ return;
340
+ }
341
+ const scaledX = x / scale;
342
+ const scaledY = y / scale;
343
+ const scaledZ = z / scale;
344
+ const scaledLength = Math.sqrt(scaledX * scaledX + scaledY * scaledY + scaledZ * scaledZ);
345
+ out[at] = scaledX / scaledLength;
346
+ out[at + 1] = scaledY / scaledLength;
347
+ out[at + 2] = scaledZ / scaledLength;
348
+ }
69
349
  /**
70
350
  * The `Uint16Array` twin of the face normals: one unit normal per triangle, the
71
351
  * zero vector for a degenerate one. O(triangles).
@@ -90,104 +370,1100 @@ export function mesh3FaceNormalsU16(out, positions, indices) {
90
370
  out[corner + 2] = NORMAL_[2];
91
371
  }
92
372
  }
93
- /** The `Uint16Array` twin of the surface area. O(triangles). */
373
+ /** An exponent below every one a face can have: "no difference". */
374
+ const NONE_ = -4096;
375
+ /**
376
+ * Fills `FRAME_` for the triangles of `indices`: the anchor o, the least x, y
377
+ * and z of the vertices they use (a corner of their bounding box, the same in
378
+ * every face order, and a vertex no triangle uses is never read), then per axis
379
+ * e, 2^e above the box's extent along it (0 for a flat or non-finite one), then
380
+ * 1 where an extent reaches 2^1023.
381
+ */
382
+ function frameU16_(positions, indices) {
383
+ let minX = Number.POSITIVE_INFINITY;
384
+ let minY = Number.POSITIVE_INFINITY;
385
+ let minZ = Number.POSITIVE_INFINITY;
386
+ let maxX = Number.NEGATIVE_INFINITY;
387
+ let maxY = Number.NEGATIVE_INFINITY;
388
+ let maxZ = Number.NEGATIVE_INFINITY;
389
+ for (let corner = 0; corner < indices.length; corner++) {
390
+ const vertex = indices[corner] * 3;
391
+ const x = positions[vertex];
392
+ const y = positions[vertex + 1];
393
+ const z = positions[vertex + 2];
394
+ minX = Math.min(minX, x);
395
+ minY = Math.min(minY, y);
396
+ minZ = Math.min(minZ, z);
397
+ maxX = Math.max(maxX, x);
398
+ maxY = Math.max(maxY, y);
399
+ maxZ = Math.max(maxZ, z);
400
+ }
401
+ // Halves, so that the extent of a box across ±Number.MAX_VALUE is finite.
402
+ const halfX = maxX * 0.5 - minX * 0.5;
403
+ const halfY = maxY * 0.5 - minY * 0.5;
404
+ const halfZ = maxZ * 0.5 - minZ * 0.5;
405
+ const frame = FRAME_;
406
+ frame[0] = minX;
407
+ frame[1] = minY;
408
+ frame[2] = minZ;
409
+ frame[3] = halfX;
410
+ frame[4] = halfY;
411
+ frame[5] = halfZ;
412
+ frame[6] =
413
+ halfX >= 2 ** 1022 || halfY >= 2 ** 1022 || halfZ >= 2 ** 1022 ? 1 : 0;
414
+ for (let axis = 3; axis < 6; axis++) {
415
+ // The half extent becomes e: 2^e is above the extent.
416
+ const half = frame[axis];
417
+ frame[axis] =
418
+ half > 0 && half < Number.POSITIVE_INFINITY
419
+ ? Math.max(binaryExponentAt(frame, axis) + 2, -1021)
420
+ : 0;
421
+ }
422
+ }
423
+ /** The exact sum of six times the volume, from {@link exactSixVolume_}. */
424
+ const SIX_VOLUME_ = new DotExactAccumulator();
425
+ /**
426
+ * A face's corners a (0–2), b (3–5) and c (6–8), then the frame's anchor o
427
+ * (9–11), as they are; then a, b and c again as significands in ±[1, 2) (0 for
428
+ * a zero coordinate) with the exponents they are scaled by.
429
+ */
430
+ const VOLUME_FACTORS_ = new Float64Array(12);
431
+ const VOLUME_SIGNIFICANDS_ = new Float64Array(9);
432
+ const VOLUME_EXPONENTS_ = new Int32Array(9);
433
+ /** One product of three coordinates as two products of two doubles. */
434
+ const TRIPLE_LEFT_ = new Float64Array(2);
435
+ const TRIPLE_RIGHT_ = new Float64Array(2);
436
+ /**
437
+ * The 24 products of three coordinates whose sum is det[a − o, b − o, c − o] =
438
+ * det[a, b, c] − o · (a × b + b × c + c × a), four entries each: the slots in
439
+ * `VOLUME_FACTORS_` of the two factors taken as significands and of the third,
440
+ * then the sign.
441
+ */
442
+ const VOLUME_TERMS_ = volumeTerms_();
443
+ function volumeTerms_() {
444
+ const terms = [];
445
+ for (let i = 0; i < 3; i++) {
446
+ const j = (i + 1) % 3;
447
+ const k = (i + 2) % 3;
448
+ terms.push(i, 3 + j, 6 + k, 1, i, 3 + k, 6 + j, -1);
449
+ }
450
+ for (let k = 0; k < 3; k++) {
451
+ const i = (k + 1) % 3;
452
+ const j = (k + 2) % 3;
453
+ const o = 9 + k;
454
+ // −o_k ((a × b)_k + (b × c)_k + (c × a)_k), (u × v)_k = u_i v_j − u_j v_i.
455
+ terms.push(i, 3 + j, o, -1, j, 3 + i, o, 1);
456
+ terms.push(3 + i, 6 + j, o, -1, 3 + j, 6 + i, o, 1);
457
+ terms.push(6 + i, j, o, -1, 6 + j, i, o, 1);
458
+ }
459
+ return Int8Array.from(terms);
460
+ }
461
+ /**
462
+ * Replaces `values[slot]`, finite and nonzero, by its significand in ±[1, 2),
463
+ * exactly (subnormals included), and writes its exponent plus `shift` to
464
+ * `exponents[slot]`; 0 and a non-finite value stay, with `shift`. No double
465
+ * crosses a call.
466
+ */
467
+ function splitAt_(values, exponents, slot, shift) {
468
+ const value = values[slot];
469
+ if (value === 0 || value - value !== 0) {
470
+ exponents[slot] = shift;
471
+ return;
472
+ }
473
+ const exponent = binaryExponentAt(values, slot);
474
+ scaleByPowerOfTwoInPlace(values, slot, 0 - exponent);
475
+ exponents[slot] = exponent + shift;
476
+ }
477
+ /**
478
+ * Adds six times the signed volume of the face at `a`, `b` and `c` against the
479
+ * anchor o in `VOLUME_FACTORS_[9–11]` to `SIX_VOLUME_`, exactly, for any finite
480
+ * corners: det[a − o, b − o, c − o], the same for each rotation of the face,
481
+ * expanded into the 24 products of three coordinates of {@link VOLUME_TERMS_},
482
+ * so that no difference is ever rounded. Each is the product of two
483
+ * significands, exact by TwoProduct, times the third coordinate, scaled by the
484
+ * two exponents: two products of two doubles the long accumulator holds at any
485
+ * magnitude, so no term is lost to overflow or to the subnormals. Non-finite
486
+ * corners leave the accumulator's plain sum.
487
+ */
488
+ function exactSixVolumeU16_(positions, a, b, c) {
489
+ const factors = VOLUME_FACTORS_;
490
+ const significands = VOLUME_SIGNIFICANDS_;
491
+ const exponents = VOLUME_EXPONENTS_;
492
+ for (let axis = 0; axis < 3; axis++) {
493
+ factors[axis] = positions[a + axis];
494
+ factors[3 + axis] = positions[b + axis];
495
+ factors[6 + axis] = positions[c + axis];
496
+ }
497
+ for (let slot = 0; slot < 9; slot++) {
498
+ significands[slot] = factors[slot];
499
+ splitAt_(significands, exponents, slot, 0);
500
+ }
501
+ const terms = VOLUME_TERMS_;
502
+ const product = PAIR_;
503
+ const left = TRIPLE_LEFT_;
504
+ const right = TRIPLE_RIGHT_;
505
+ for (let term = 0; term < terms.length; term += 4) {
506
+ const first = terms[term];
507
+ const second = terms[term + 1];
508
+ const third = factors[terms[term + 2]];
509
+ if (significands[first] === 0 ||
510
+ significands[second] === 0 ||
511
+ third === 0) {
512
+ continue;
513
+ }
514
+ product[0] = significands[first];
515
+ product[1] = significands[second];
516
+ twoProductInRangeInPlace(product, 0);
517
+ left[0] = terms[term + 3] * third;
518
+ left[1] = left[0];
519
+ right[0] = product[0];
520
+ right[1] = product[1];
521
+ SIX_VOLUME_.addProducts(left, right, exponents[first] + exponents[second]);
522
+ }
523
+ }
524
+ /**
525
+ * Writes the cross product `(b − a) × (c − a)` of the triangle at `a`, `b` and
526
+ * `c` into `FACE_CROSS_` as `[x, y, z, k]`, the true product being `(x, y, z) ·
527
+ * 2^k` (`triangle3Cross_`): each component within 2^−49 of the largest of the
528
+ * exact product, with its sign wherever that bound cannot reach 0, for any
529
+ * finite corners, zeros exactly for a degenerate face and `NaN`s for a
530
+ * non-finite one. k is 0 while the largest component lies in [2^−400, 2^402);
531
+ * otherwise the largest lies in [1, 2).
532
+ */
533
+ function faceCrossU16_(positions, a, b, c) {
534
+ const corners = CORNERS_;
535
+ corners[0] = +positions[a];
536
+ corners[1] = +positions[a + 1];
537
+ corners[2] = +positions[a + 2];
538
+ corners[3] = +positions[b];
539
+ corners[4] = +positions[b + 1];
540
+ corners[5] = +positions[b + 2];
541
+ corners[6] = +positions[c];
542
+ corners[7] = +positions[c + 1];
543
+ corners[8] = +positions[c + 2];
544
+ triangle3Cross_(FACE_CROSS_, corners);
545
+ }
546
+ /**
547
+ * Writes the doubled area of the triangle at `a`, `b` and `c` into `FACE_AREA_`
548
+ * as `[m, k]`, the area being m · 2^k: the length of {@link faceCross_}'s
549
+ * product, whose components never square out of range.
550
+ */
551
+ function faceAreaU16_(positions, a, b, c) {
552
+ faceCrossU16_(positions, a, b, c);
553
+ const cross = FACE_CROSS_;
554
+ const x = cross[0];
555
+ const y = cross[1];
556
+ const z = cross[2];
557
+ FACE_AREA_[0] = Math.sqrt(x * x + y * y + z * z);
558
+ FACE_AREA_[1] = cross[3];
559
+ }
560
+ /**
561
+ * The `Uint16Array` twin of the surface area: each face's area from its edges
562
+ * and cross product scaled by powers of two (`faceArea_`), so no square
563
+ * overflows or underflows at any size or distance from the origin, rounded once
564
+ * per face and summed exactly: the same number in every face order.
565
+ * O(triangles), no allocation.
566
+ */
94
567
  export function mesh3SurfaceAreaU16(positions, indices) {
95
- let doubleArea = 0;
568
+ const sum = AREA_;
569
+ const area = FACE_AREA_;
570
+ const value = VALUE_;
571
+ sum.reset();
96
572
  for (let corner = 0; corner < indices.length; corner += 3) {
97
- const a = indices[corner] * 3;
98
- const b = indices[corner + 1] * 3;
99
- const c = indices[corner + 2] * 3;
100
- const abX = positions[b] - positions[a];
101
- const abY = positions[b + 1] - positions[a + 1];
102
- const abZ = positions[b + 2] - positions[a + 2];
103
- const acX = positions[c] - positions[a];
104
- const acY = positions[c + 1] - positions[a + 1];
105
- const acZ = positions[c + 2] - positions[a + 2];
106
- const crossX = abY * acZ - abZ * acY;
107
- const crossY = abZ * acX - abX * acZ;
108
- const crossZ = abX * acY - abY * acX;
109
- doubleArea += Math.sqrt(crossX * crossX + crossY * crossY + crossZ * crossZ);
110
- }
111
- return 0.5 * doubleArea;
573
+ faceAreaU16_(positions, indices[corner] * 3, indices[corner + 1] * 3, indices[corner + 2] * 3);
574
+ if (area[0] === 0) {
575
+ continue;
576
+ }
577
+ value[0] = area[0];
578
+ if (area[1] === 0) {
579
+ value[0] = area[0] * 0.5;
580
+ }
581
+ else {
582
+ scaleByPowerOfTwoInPlace(value, 0, area[1] - 1);
583
+ }
584
+ sum.addRange(value, 0, 1);
585
+ }
586
+ sum.writeValue(value, 0);
587
+ // `+ 0`: an empty sum is −0, as `Math.sumPrecise`'s.
588
+ return value[0] + 0;
112
589
  }
590
+ /** The unit roundoff, 2^−53. */
591
+ const UNIT_ROUNDOFF_ = 2 ** -53;
592
+ /** Veltkamp's splitter, 2^27 + 1, for exact Dekker products in range. */
593
+ const SPLITTER_ = 134217729;
113
594
  /**
114
- * The `Uint16Array` twin of the signed volume, summed from the first triangle's
115
- * first vertex so that a mesh far from the origin, or a vertex no triangle
116
- * uses, loses no digits. O(triangles).
117
- */
118
- export function mesh3VolumeU16(positions, indices) {
119
- // The first triangle's first vertex, so that a vertex no triangle uses (or
120
- // one far away) cannot cost the sum its digits.
121
- const anchor = indices.length > 0 ? indices[0] * 3 : 0;
122
- const originX = positions[anchor];
123
- const originY = positions[anchor + 1];
124
- const originZ = positions[anchor + 2];
125
- let sixVolumes = 0;
595
+ * The adaptive filter of {@link mesh3Volume}: six times the volume, over the
596
+ * same value as the exact sum, Σ (a − o) · ((b − a) × (c − a)) with `a − o` and
597
+ * the edges exactly as TwoSum's pairs, in doubled precision. Each edge
598
+ * component is split once and reused across both cross-product terms; every
599
+ * product and sum runs in scalar registers with no typed-array traffic or
600
+ * range-scaling checks (the caller guarantees extents below 2^300 and anchor
601
+ * below 2^1000, so no intermediate reaches 2^903). What that drops is bounded
602
+ * rigorously: per face, below (128u + 9γ_N)·u·Σ |a − o|ₖ (|p| + |q|)ₖ over the
603
+ * products p, q of each cross component (u = 2^−53: the neglected low-by-low
604
+ * products, the products of two edge errors, each below u² of the product of
605
+ * the edges, and the roundings of the low parts, the edges' first-order terms,
606
+ * each below 2.01u (|p| + |q|), included), plus the plain sum's rounding, γ_N Σ
607
+ * |parts| for its N parts (Higham, "Accuracy and Stability of Numerical
608
+ * Algorithms", §4.2), plus an absolute 2^−1065 per face and per cross product
609
+ * component, the latter times the frame's bound 2^e on `a − o`, for products in
610
+ * the subnormal range. Then {@link certifySixVolume_} rounds the sixth of the
611
+ * total and proves it.
612
+ */
613
+ function certifiedSixVolumeU16_(positions, indices) {
614
+ const negOX = -FRAME_[0];
615
+ const negOY = -FRAME_[1];
616
+ const negOZ = -FRAME_[2];
617
+ let high = 0;
618
+ let low = 0;
619
+ let lowMagnitude = 0;
620
+ let magnitude = 0;
126
621
  for (let corner = 0; corner < indices.length; corner += 3) {
127
622
  const a = indices[corner] * 3;
128
623
  const b = indices[corner + 1] * 3;
129
624
  const c = indices[corner + 2] * 3;
130
- const aX = positions[a] - originX;
131
- const aY = positions[a + 1] - originY;
132
- const aZ = positions[a + 2] - originZ;
133
- const bX = positions[b] - originX;
134
- const bY = positions[b + 1] - originY;
135
- const bZ = positions[b + 2] - originZ;
136
- const cX = positions[c] - originX;
137
- const cY = positions[c + 1] - originY;
138
- const cZ = positions[c + 2] - originZ;
139
- sixVolumes +=
140
- aX * (bY * cZ - bZ * cY) +
141
- aY * (bZ * cX - bX * cZ) +
142
- aZ * (bX * cY - bY * cX);
143
- }
144
- return sixVolumes / 6;
625
+ const paX = positions[a];
626
+ const paY = positions[a + 1];
627
+ const paZ = positions[a + 2];
628
+ const pbX = positions[b];
629
+ const pbY = positions[b + 1];
630
+ const pbZ = positions[b + 2];
631
+ const pcX = positions[c];
632
+ const pcY = positions[c + 1];
633
+ const pcZ = positions[c + 2];
634
+ // The edges and their exact errors (TwoSum).
635
+ const abX = pbX - paX;
636
+ let t = abX - pbX;
637
+ const abXErr = pbX - (abX - t) + (-paX - t);
638
+ const abY = pbY - paY;
639
+ t = abY - pbY;
640
+ const abYErr = pbY - (abY - t) + (-paY - t);
641
+ const abZ = pbZ - paZ;
642
+ t = abZ - pbZ;
643
+ const abZErr = pbZ - (abZ - t) + (-paZ - t);
644
+ const acX = pcX - paX;
645
+ t = acX - pcX;
646
+ const acXErr = pcX - (acX - t) + (-paX - t);
647
+ const acY = pcY - paY;
648
+ t = acY - pcY;
649
+ const acYErr = pcY - (acY - t) + (-paY - t);
650
+ const acZ = pcZ - paZ;
651
+ t = acZ - pcZ;
652
+ const acZErr = pcZ - (acZ - t) + (-paZ - t);
653
+ // Split each edge component once (reused in two cross products).
654
+ let s = SPLITTER_ * abX;
655
+ const abXHi = s - (s - abX);
656
+ const abXLo = abX - abXHi;
657
+ s = SPLITTER_ * abY;
658
+ const abYHi = s - (s - abY);
659
+ const abYLo = abY - abYHi;
660
+ s = SPLITTER_ * abZ;
661
+ const abZHi = s - (s - abZ);
662
+ const abZLo = abZ - abZHi;
663
+ s = SPLITTER_ * acX;
664
+ const acXHi = s - (s - acX);
665
+ const acXLo = acX - acXHi;
666
+ s = SPLITTER_ * acY;
667
+ const acYHi = s - (s - acY);
668
+ const acYLo = acY - acYHi;
669
+ s = SPLITTER_ * acZ;
670
+ const acZHi = s - (s - acZ);
671
+ const acZLo = acZ - acZHi;
672
+ // Cross X = abY * acZ - abZ * acY, then X term of dot product.
673
+ const pX = abY * acZ;
674
+ const pXErr = abYLo * acZLo - (pX - abYHi * acZHi - abYLo * acZHi - abYHi * acZLo);
675
+ const qX = abZ * acY;
676
+ const qXErr = abZLo * acYLo - (qX - abZHi * acYHi - abZLo * acYHi - abZHi * acYLo);
677
+ const cX = pX - qX;
678
+ let r = cX + qX;
679
+ const cXLo = pX -
680
+ r +
681
+ (-qX - (cX - r)) +
682
+ pXErr -
683
+ qXErr +
684
+ (abY * acZErr + abYErr * acZ - (abZ * acYErr + abZErr * acY));
685
+ const ax = paX + negOX;
686
+ r = ax - negOX;
687
+ const axLo = paX - r + (negOX - (ax - r));
688
+ let faceMag = Math.abs(ax) * (Math.abs(pX) + Math.abs(qX));
689
+ s = SPLITTER_ * ax;
690
+ const axHi = s - (s - ax);
691
+ const axSp = ax - axHi;
692
+ s = SPLITTER_ * cX;
693
+ const cXHi = s - (s - cX);
694
+ const cXSp = cX - cXHi;
695
+ const tX = ax * cX;
696
+ let faceLow = axSp * cXSp -
697
+ (tX - axHi * cXHi - axSp * cXHi - axHi * cXSp) +
698
+ ax * cXLo +
699
+ axLo * cX;
700
+ // Cross Y = abZ * acX - abX * acZ, then Y term of dot product.
701
+ const pY = abZ * acX;
702
+ const pYErr = abZLo * acXLo - (pY - abZHi * acXHi - abZLo * acXHi - abZHi * acXLo);
703
+ const qY = abX * acZ;
704
+ const qYErr = abXLo * acZLo - (qY - abXHi * acZHi - abXLo * acZHi - abXHi * acZLo);
705
+ const cY = pY - qY;
706
+ r = cY + qY;
707
+ const cYLo = pY -
708
+ r +
709
+ (-qY - (cY - r)) +
710
+ pYErr -
711
+ qYErr +
712
+ (abZ * acXErr + abZErr * acX - (abX * acZErr + abXErr * acZ));
713
+ const ay = paY + negOY;
714
+ r = ay - negOY;
715
+ const ayLo = paY - r + (negOY - (ay - r));
716
+ faceMag += Math.abs(ay) * (Math.abs(pY) + Math.abs(qY));
717
+ s = SPLITTER_ * ay;
718
+ const ayHi = s - (s - ay);
719
+ const aySp = ay - ayHi;
720
+ s = SPLITTER_ * cY;
721
+ const cYHi = s - (s - cY);
722
+ const cYSp = cY - cYHi;
723
+ const tY = ay * cY;
724
+ faceLow +=
725
+ aySp * cYSp -
726
+ (tY - ayHi * cYHi - aySp * cYHi - ayHi * cYSp) +
727
+ ay * cYLo +
728
+ ayLo * cY;
729
+ // Cross Z = abX * acY - abY * acX, then Z term of dot product.
730
+ const pZ = abX * acY;
731
+ const pZErr = abXLo * acYLo - (pZ - abXHi * acYHi - abXLo * acYHi - abXHi * acYLo);
732
+ const qZ = abY * acX;
733
+ const qZErr = abYLo * acXLo - (qZ - abYHi * acXHi - abYLo * acXHi - abYHi * acXLo);
734
+ const cZ = pZ - qZ;
735
+ r = cZ + qZ;
736
+ const cZLo = pZ -
737
+ r +
738
+ (-qZ - (cZ - r)) +
739
+ pZErr -
740
+ qZErr +
741
+ (abX * acYErr + abXErr * acY - (abY * acXErr + abYErr * acX));
742
+ const az = paZ + negOZ;
743
+ r = az - negOZ;
744
+ const azLo = paZ - r + (negOZ - (az - r));
745
+ magnitude += faceMag + Math.abs(az) * (Math.abs(pZ) + Math.abs(qZ));
746
+ s = SPLITTER_ * az;
747
+ const azHi = s - (s - az);
748
+ const azSp = az - azHi;
749
+ s = SPLITTER_ * cZ;
750
+ const cZHi = s - (s - cZ);
751
+ const cZSp = cZ - cZHi;
752
+ const tZ = az * cZ;
753
+ faceLow +=
754
+ azSp * cZSp -
755
+ (tZ - azHi * cZHi - azSp * cZHi - azHi * cZSp) +
756
+ az * cZLo +
757
+ azLo * cZ;
758
+ // Sum the face's three high terms first, then add once to `high` so the
759
+ // loop-carried dependency chain is one TwoSum per face instead of three.
760
+ const s01 = tX + tY;
761
+ r = s01 - tY;
762
+ const e01 = tX - r + (tY - (s01 - r));
763
+ const fHi = s01 + tZ;
764
+ r = fHi - tZ;
765
+ const e02 = s01 - r + (tZ - (fHi - r));
766
+ const nextHigh = high + fHi;
767
+ r = nextHigh - fHi;
768
+ const carry = high - r + (fHi - (nextHigh - r));
769
+ high = nextHigh;
770
+ low += carry + (faceLow + e01 + e02);
771
+ lowMagnitude += Math.abs(carry);
772
+ }
773
+ const filter = FILTER_;
774
+ filter[22] = high;
775
+ filter[23] = low;
776
+ filter[0] = magnitude;
777
+ filter[1] = lowMagnitude;
778
+ return certifySixVolumeU16_(indices.length);
779
+ }
780
+ /*
781
+ * Faithful rounding (`rounding: "faithful"`): what a first stage at about the
782
+ * plain sum's cost can prove. The contract is a result within one unit in the
783
+ * last place of the default one, R: r and R equal or adjacent doubles, counted
784
+ * through the subnormals. A first stage may return r only where a rigorous
785
+ * bound proves it; anywhere else the default computation runs.
786
+ *
787
+ * Notation (Higham, "Accuracy and Stability of Numerical Algorithms", 2nd ed.,
788
+ * §2.2 and §3.1): u = 2^−53, η = 2^−1075, γ_k = k·u / (1 − k·u). Rounding to
789
+ * nearest gives fl(a ∘ b) = (a ∘ b)(1 + δ) + ε with |δ| ≤ u and |ε| ≤ η, ε = 0
790
+ * for a sum or difference (an underflowing sum is exact). So |fl(z) − z| ≤
791
+ * u·|fl(z)| for a sum or a difference at any magnitude, but for a product or a
792
+ * quotient only |fl(z) − z| ≤ u·|fl(z)| + η: fl(3·2^−1074 · 0.5) = 2^−1073
793
+ * is η from 1.5·2^−1074, far beyond u of it. Away from the subnormals, k
794
+ * factors 1 + δ in a chain compose to 1 + θ_k with |θ_k| ≤ γ_k (Lemma 3.1);
795
+ * each product or quotient that may underflow adds its η, carried through
796
+ * the rest of the chain. The compensated sum (Neumaier's, the same values as
797
+ * Ogita, Rump and Oishi's Sum2, "Accurate Sum and Dot Product", SIAM J. Sci.
798
+ * Comput. 26, 2005, Proposition 4.5) of n terms x_i, with res = fl(sum +
799
+ * compensation), keeps |res − Σ x_i| ≤ u·|Σ x_i| + γ²_{n−1}·Σ |x_i|,
800
+ * underflow included, since each error-free sum stays exact there.
801
+ *
802
+ * Volume: no uniform error bound on a plain pass proves one ulp. R = RN(T /
803
+ * 6), T = Σ_f T_f and T_f = Σ_k (a − o)_k (p_k − q_k), p_k and q_k the exact
804
+ * products of the exact edges. A plain evaluation rounds a − o, the edges,
805
+ * both products, their difference, the product by a − o and two sums:
806
+ * |T̂_f − T_f| ≤ γ_8·M_f (plus η per product below the normal range) with M_f
807
+ * = Σ_k |a − o|_k (|p_k| + |q_k|), and the sum adds γ²_{n−1}·Σ |T̂_f|. r6,
808
+ * the rounded total, is faithful to T only when |T − r6| stays below the gap
809
+ * from r6 to its neighbour toward T, at most 2^(e − 52) ≤ 2u·|r6| for 2^e ≤
810
+ * |r6|. But M = Σ M_f ≥ |T|, so the bound, about 8u·M, exceeds every such gap
811
+ * for every nonzero volume: a test against it can never pass. The bound is
812
+ * not merely pessimistic; already the rounding of one product and of its
813
+ * product by a − o reach u·|T| each on a face whose term dominates, and a
814
+ * plain compensated sum is 2 ulps off on a near-cancelling tetrahedron of the
815
+ * tests. A running error bound (Wilkinson) is no better, since it sums u
816
+ * times every computed intermediate, at least 2u·|T|.
817
+ *
818
+ * That rules out certifying a plain pass by an error bound that holds for
819
+ * every input, not every cheap certification. Where no operation of the plain
820
+ * pass rounds (coordinates on a coarse dyadic grid, as a voxel or small-integer
821
+ * box mesh has them, whose products and sums all fit in 53 bits), T̂ = T, and
822
+ * a check of that grid would prove R at about plain cost. It covers only such
823
+ * meshes: a tessellated, generated or scanned surface has full-precision
824
+ * coordinates, whose products round, and the doubled-precision filter already
825
+ * certifies a grid mesh unless its volume cancels by some 2^44. So no such
826
+ * check is added. In general the roundings of the products must be removed, by
827
+ * TwoProduct (Dekker's, no fused multiply-add in JavaScript): a
828
+ * doubled-precision first stage, which is what the default filter already is.
829
+ * And the division by 6 rounds again: a faithful r6 can give fl(r6 / 6) two
830
+ * ulps from R, so even that stage has to enclose T / 6 and check it against
831
+ * the midpoints, as the default filter does. `"faithful"` volume therefore
832
+ * runs the default computation; a looser
833
+ * contract with a proven k (k ulps of M / 6, not of the volume, since T may
834
+ * cancel) or a doubled stage are the alternatives.
835
+ *
836
+ * Centroid: see {@link faithfulCentroid_}, which can be proven at plain cost,
837
+ * but only where the result is large beside the mesh's extent.
838
+ */
839
+ /**
840
+ * The end of {@link certifiedSixVolume_}, from the sums it leaves in `FILTER_`
841
+ * (the high and low parts at 22 and 23, the magnitudes of the products and of
842
+ * the low parts at 0 and 1), for `cornerCount` corners: kept apart, its doubles
843
+ * read from there (a double passed to a call the engine does not inline is
844
+ * boxed).
845
+ */
846
+ function certifySixVolumeU16_(cornerCount) {
847
+ const filter = FILTER_;
848
+ const magnitude = filter[0];
849
+ const lowMagnitude = filter[1];
850
+ twoSumInPlace(filter, 22);
851
+ const total = filter[22];
852
+ const difference = filter[23];
853
+ // Each face adds 2 terms into `low` (`carry` and `faceLow + e01 + e02`);
854
+ // the face-local low terms, the edges' first-order ones included, have sum
855
+ // of magnitudes at most 8.3u · faceMag, so their internal rounding is below
856
+ // 128u² · magnitude and their contribution to `low`'s rounding is below
857
+ // 9 · gamma · u · magnitude.
858
+ const parts = (cornerCount / 3) * 2 + 2;
859
+ const gamma = (parts * UNIT_ROUNDOFF_) / (1 - parts * UNIT_ROUNDOFF_);
860
+ if (!(gamma < 0.01)) {
861
+ return false;
862
+ }
863
+ // Below 2^−969 a product's TwoProduct error is no longer exact and a product
864
+ // may underflow: at most 2^−1065 for each of a face's three terms and for
865
+ // each component of its cross product, which a − o then multiplies, below
866
+ // 2^e along its axis.
867
+ const reach = 3 + 2 ** FRAME_[3] + 2 ** FRAME_[4] + 2 ** FRAME_[5];
868
+ const bound = (128 * UNIT_ROUNDOFF_ + 9 * gamma) *
869
+ UNIT_ROUNDOFF_ *
870
+ magnitude *
871
+ (1 + 2 * gamma) +
872
+ gamma * lowMagnitude * (1 + 2 * gamma) +
873
+ (cornerCount / 3) * 2 ** -1065 * reach;
874
+ const size = Math.abs(total);
875
+ if (!(size >= 2 ** -960 && size < 2 ** 1000)) {
876
+ return false;
877
+ }
878
+ // The volume is T / 6, T within `bound` of total + difference. Its
879
+ // candidate q = fl(total / 6): 6q = pair[0] + pair[1] exactly (TwoProduct),
880
+ // and total − pair[0] is exact (Sterbenz), so `offset` is (T − 6q) / 6 up to
881
+ // the bound's sixth and a few roundings of u times some units of q's last
882
+ // place, far below 2^−40 of it. T / 6 rounds to q while it stays short of
883
+ // the nearer midpoint: half a unit in the last place, a quarter at a power
884
+ // of two (on either side, conservatively).
885
+ const quotient = total / 6;
886
+ const pair = PAIR_;
887
+ pair[0] = quotient;
888
+ pair[1] = 6;
889
+ twoProductInRangeInPlace(pair, 0);
890
+ const offset = (total - pair[0] - pair[1] + difference) / 6;
891
+ filter[24] = quotient;
892
+ const exponent = binaryExponentAt(filter, 24);
893
+ const isPowerOfTwo = Math.abs(quotient) === 2 ** exponent;
894
+ const half = 2 ** (exponent - (isPowerOfTwo ? 54 : 53));
895
+ if (!(Math.abs(offset) + (bound / 6) * (1 + 2 ** -40) + half * 2 ** -40 < half)) {
896
+ return false;
897
+ }
898
+ VALUE_[0] = quotient;
899
+ return true;
145
900
  }
146
901
  /**
147
- * The `Uint16Array` twin of the surface centroid, relative to the first
148
- * triangle's first vertex. A zero total area divides zero by zero: `NaN`.
149
- * O(triangles).
902
+ * The `Uint16Array` twin of the signed volume: six times it is T = `Σ det[a −
903
+ * o, b − o, c − o]` over the faces, o being the frame's anchor (any point gives
904
+ * the same volume for a closed mesh), every coordinate exact. An ordinary mesh
905
+ * is certified by the doubled-precision filter, which proves the rounded T / 6;
906
+ * anywhere else every face's term is summed exactly in a long accumulator
907
+ * ({@link exactSixVolume_}), whatever the magnitudes, and T / 6 is rounded once
908
+ * from it ({@link roundQuotient_}): the same number in every face order and for
909
+ * every rotation of a face's corners, and a vertex no triangle uses is never
910
+ * read. Written to `out[0]`: a double returned from a call the engine does not
911
+ * inline is boxed. O(triangles), no allocation.
912
+ */
913
+ export function mesh3VolumeU16(out, positions, indices) {
914
+ const frame = FRAME_;
915
+ frameU16_(positions, indices);
916
+ const isWide = frame[6] === 1;
917
+ // The filter: an ordinary mesh (no extent from 2^300 up, anchor below
918
+ // 2^1000) is summed in doubled precision with a rigorous error bound, and
919
+ // the exact sums below run only when that bound cannot certify the rounded
920
+ // result.
921
+ if (!isWide &&
922
+ frame[3] <= 300 &&
923
+ frame[4] <= 300 &&
924
+ frame[5] <= 300 &&
925
+ Math.abs(frame[0]) < 2 ** 1000 &&
926
+ Math.abs(frame[1]) < 2 ** 1000 &&
927
+ Math.abs(frame[2]) < 2 ** 1000 &&
928
+ certifiedSixVolumeU16_(positions, indices)) {
929
+ out[0] = VALUE_[0];
930
+ return;
931
+ }
932
+ const sum = SIX_VOLUME_;
933
+ sum.reset();
934
+ VOLUME_FACTORS_[9] = frame[0];
935
+ VOLUME_FACTORS_[10] = frame[1];
936
+ VOLUME_FACTORS_[11] = frame[2];
937
+ for (let corner = 0; corner < indices.length; corner += 3) {
938
+ exactSixVolumeU16_(positions, indices[corner] * 3, indices[corner + 1] * 3, indices[corner + 2] * 3);
939
+ }
940
+ const reads = QUOTIENT_READS_;
941
+ readPieces_(sum, reads, 4);
942
+ if (reads[4] - reads[4] !== 0) {
943
+ // A non-finite corner: the plain sum's sixth.
944
+ out[0] = reads[4] / 6;
945
+ return;
946
+ }
947
+ // The divisor 6 as 3 · 2^1 (`roundQuotient_` divides by 3 times it).
948
+ reads[0] = 1;
949
+ reads[1] = 1;
950
+ reads[2] = 0;
951
+ reads[3] = 0;
952
+ // An exact zero is +0; a nonzero volume that rounds to zero keeps its sign.
953
+ roundQuotientU16_(out, 0, positions, indices, VOLUME_AXIS_);
954
+ }
955
+ /**
956
+ * The sums {@link faithfulCentroid_} leaves for {@link certifyCentroid_}: the
957
+ * weights' compensated sum (0, 1), the weighted offsets' per axis (2–4, their
958
+ * compensations 5–7), the first corner o′ (8–10), the sum of the faces' cross
959
+ * product magnitudes P (11), the least (12–14) and greatest (15–17) coordinates
960
+ * per axis, and the result (18–20).
961
+ */
962
+ const CENTROID_FILTER_ = new Float64Array(21);
963
+ /**
964
+ * The faithful first stage of {@link mesh3Centroid}, at about a plain sum's
965
+ * cost: in one pass, each face's weight w = ‖ĉ‖ from its plain cross product ĉ,
966
+ * its corners' offsets from the first corner o′ summed into ŝ, and w and w·ŝ
967
+ * summed with Neumaier's compensation, while the bounding box and Σ P, P = Σ_k
968
+ * (|p̂_k| + |q̂_k|) over the six rounded products of ĉ, are kept for the bound.
969
+ * Then {@link certifyCentroid_} proves the result or returns `false`, and the
970
+ * default computation runs.
971
+ *
972
+ * The bound (notation and the compensated sum's error: the block above the
973
+ * volume kernel). R, the default result per axis, is RN(Q), Q = Σ ω_f c_f / Σ
974
+ * ω_f the exact mean of the faces' centroids c_f under the default weights ω_f,
975
+ * rounded once ({@link roundQuotient_}). Let x be the axis's extent, n the face
976
+ * count, and recall that |fl(z) − z| ≤ u·|fl(z)| holds for a sum or a
977
+ * difference (exact in the subnormals) but a product or a quotient may lose up
978
+ * to η more there: fl(1.5 · 2^−1074) = 2^−1073, an error of 2^−1075.
979
+ *
980
+ * 1. The weights. Each edge rounds once, each product once more and may underflow,
981
+ * each difference once: |ĉ_k − X_k| ≤ 4.002u (|p̂_k| + |q̂_k|) + 2.01η
982
+ * against the exact cross product X of the exact corners. The squares, their
983
+ * sum and the root put w within 2.53u·w + 2^−535 of ‖ĉ‖, the 2^−535 only
984
+ * where the squares' sum is below 2^−970 and ĉ ≠ 0. So |w − ‖X‖| ≤ 2.53u·w +
985
+ * 4.02u·P + 2^−535 + 6.03η. The default weight is `triangle3Cross_`'s
986
+ * product, each component within 2^−49 of the largest of X, then squared,
987
+ * summed and rooted, and taken as m · 2^k exactly: |ω_f − ‖X‖| ≤ 30.3u·‖X‖.
988
+ * Together |ω_f − w_f| ≤ ε_f, Σ ε_f ≤ 33u·Σ w + 4.03u·Σ P / (1 − γ_n) +
989
+ * 2^−534 per such tiny face + n·2^−1072 =: E_w.
990
+ * 2. Changing the weights moves the mean by Σ (ω_f − w_f)(c_f − q_w) / Σ ω_f, and
991
+ * every c_f and q_w lies in the box: |Q − q_w| ≤ x·E_w / (Σ w − E_w), q_w
992
+ * the exact mean under the weights w.
993
+ * 3. The pass, under the weights w: ŝ = fl(fl(â + b̂) + ĉ) of the three offsets â
994
+ * = fl(a − o′) from the first corner o′, each below x, is within 8.01u·x of
995
+ * the exact 3·(c_f − o′); w·ŝ rounds once more (3.0001u·w·x + η); the
996
+ * compensated sums add (u + γ²_{n−1})·Σ |w·ŝ| for the offsets and (u +
997
+ * γ²_{n−1})·Σ w for the weights; 3·Σw and the quotient round once each, and
998
+ * may each lose η. With |q_w − o′| ≤ x, the quotient q̂ is within x·(7.7u +
999
+ * 2.1γ²_n + 2^−1074 / Σ w) + n·2^−1074 / Σ w + η of q_w − o′.
1000
+ *
1001
+ * So |Q − o′ − q̂| ≤ B = x·(E_w / (Σ w − E_w) + 7.7u + 2.1γ²_n + 2^−1074 / Σ w) +
1002
+ * n·2^−1074 / Σ w + 2^−1071. The bound is evaluated in doubles, rounded upward
1003
+ * by a factor 1 + 2^−38, with 3u·|q̂| and 2^−1073 for the roundings of q̂ ± B
1004
+ * (sums: within u of their result, exact in the subnormals). So o′ + fl(q̂ − B)
1005
+ * ≤ Q ≤ o′ + fl(q̂ + B), and as RN is monotone and fl(o′ + v) = RN(o′ + v), R
1006
+ * lies between fl(o′ + fl(q̂ − B)) and fl(o′ + fl(q̂ + B)); the result r =
1007
+ * fl(o′ + q̂) is returned when both are r or its neighbour, the neighbour's gap
1008
+ * read from r's exponent, 2^−1074 through the subnormals and half a gap toward
1009
+ * zero at a normal power of two.
1010
+ *
1011
+ * Every term is a multiple of x·u, so the proof needs |r| about 2^7 times x or
1012
+ * more: a mesh far from the origin beside its size. Nearer, a plain pass cannot
1013
+ * prove one ulp (its offsets alone round by about u·x, against a gap of about
1014
+ * u·|r|), and the default computation runs after it.
150
1015
  */
151
- export function mesh3CentroidU16(out, positions, indices) {
152
- const anchor = indices.length > 0 ? indices[0] * 3 : 0;
153
- const originX = positions[anchor];
154
- const originY = positions[anchor + 1];
155
- const originZ = positions[anchor + 2];
156
- let weight = 0;
1016
+ function faithfulCentroidU16_(out, positions, indices) {
1017
+ if (indices.length === 0) {
1018
+ return false;
1019
+ }
1020
+ const first = indices[0] * 3;
1021
+ const anchorX = positions[first];
1022
+ const anchorY = positions[first + 1];
1023
+ const anchorZ = positions[first + 2];
1024
+ let minX = anchorX;
1025
+ let minY = anchorY;
1026
+ let minZ = anchorZ;
1027
+ let maxX = anchorX;
1028
+ let maxY = anchorY;
1029
+ let maxZ = anchorZ;
1030
+ let weightSum = 0;
1031
+ let weightCompensation = 0;
157
1032
  let sumX = 0;
158
1033
  let sumY = 0;
159
1034
  let sumZ = 0;
1035
+ let compensationX = 0;
1036
+ let compensationY = 0;
1037
+ let compensationZ = 0;
1038
+ let crossMagnitude = 0;
1039
+ let tinyCount = 0;
1040
+ for (let corner = 0; corner < indices.length; corner += 3) {
1041
+ const a = indices[corner] * 3;
1042
+ const b = indices[corner + 1] * 3;
1043
+ const c = indices[corner + 2] * 3;
1044
+ const aX = positions[a];
1045
+ const aY = positions[a + 1];
1046
+ const aZ = positions[a + 2];
1047
+ const bX = positions[b];
1048
+ const bY = positions[b + 1];
1049
+ const bZ = positions[b + 2];
1050
+ const cX = positions[c];
1051
+ const cY = positions[c + 1];
1052
+ const cZ = positions[c + 2];
1053
+ minX = Math.min(minX, aX, bX, cX);
1054
+ minY = Math.min(minY, aY, bY, cY);
1055
+ minZ = Math.min(minZ, aZ, bZ, cZ);
1056
+ maxX = Math.max(maxX, aX, bX, cX);
1057
+ maxY = Math.max(maxY, aY, bY, cY);
1058
+ maxZ = Math.max(maxZ, aZ, bZ, cZ);
1059
+ const abX = bX - aX;
1060
+ const abY = bY - aY;
1061
+ const abZ = bZ - aZ;
1062
+ const acX = cX - aX;
1063
+ const acY = cY - aY;
1064
+ const acZ = cZ - aZ;
1065
+ const pX = abY * acZ;
1066
+ const qX = abZ * acY;
1067
+ const pY = abZ * acX;
1068
+ const qY = abX * acZ;
1069
+ const pZ = abX * acY;
1070
+ const qZ = abY * acX;
1071
+ const crossX = pX - qX;
1072
+ const crossY = pY - qY;
1073
+ const crossZ = pZ - qZ;
1074
+ const areaSquared = crossX * crossX + crossY * crossY + crossZ * crossZ;
1075
+ if (areaSquared < 2 ** -970 &&
1076
+ (crossX !== 0 || crossY !== 0 || crossZ !== 0)) {
1077
+ tinyCount++;
1078
+ }
1079
+ const weight = Math.sqrt(areaSquared);
1080
+ const weightedX = weight * (aX - anchorX + (bX - anchorX) + (cX - anchorX));
1081
+ const weightedY = weight * (aY - anchorY + (bY - anchorY) + (cY - anchorY));
1082
+ const weightedZ = weight * (aZ - anchorZ + (bZ - anchorZ) + (cZ - anchorZ));
1083
+ // Neumaier: each branch is the exact error of the rounded sum.
1084
+ let next = weightSum + weight;
1085
+ weightCompensation +=
1086
+ weightSum >= weight
1087
+ ? weightSum - next + weight
1088
+ : weight - next + weightSum;
1089
+ weightSum = next;
1090
+ next = sumX + weightedX;
1091
+ compensationX +=
1092
+ Math.abs(sumX) >= Math.abs(weightedX)
1093
+ ? sumX - next + weightedX
1094
+ : weightedX - next + sumX;
1095
+ sumX = next;
1096
+ next = sumY + weightedY;
1097
+ compensationY +=
1098
+ Math.abs(sumY) >= Math.abs(weightedY)
1099
+ ? sumY - next + weightedY
1100
+ : weightedY - next + sumY;
1101
+ sumY = next;
1102
+ next = sumZ + weightedZ;
1103
+ compensationZ +=
1104
+ Math.abs(sumZ) >= Math.abs(weightedZ)
1105
+ ? sumZ - next + weightedZ
1106
+ : weightedZ - next + sumZ;
1107
+ sumZ = next;
1108
+ crossMagnitude +=
1109
+ Math.abs(pX) +
1110
+ Math.abs(qX) +
1111
+ Math.abs(pY) +
1112
+ Math.abs(qY) +
1113
+ Math.abs(pZ) +
1114
+ Math.abs(qZ);
1115
+ }
1116
+ const filter = CENTROID_FILTER_;
1117
+ filter[0] = weightSum;
1118
+ filter[1] = weightCompensation;
1119
+ filter[2] = sumX;
1120
+ filter[3] = sumY;
1121
+ filter[4] = sumZ;
1122
+ filter[5] = compensationX;
1123
+ filter[6] = compensationY;
1124
+ filter[7] = compensationZ;
1125
+ filter[8] = anchorX;
1126
+ filter[9] = anchorY;
1127
+ filter[10] = anchorZ;
1128
+ filter[11] = crossMagnitude;
1129
+ filter[12] = minX;
1130
+ filter[13] = minY;
1131
+ filter[14] = minZ;
1132
+ filter[15] = maxX;
1133
+ filter[16] = maxY;
1134
+ filter[17] = maxZ;
1135
+ return certifyCentroidU16_(out, indices.length / 3, tinyCount);
1136
+ }
1137
+ /**
1138
+ * The end of {@link faithfulCentroid_}, from the sums it leaves in
1139
+ * `CENTROID_FILTER_`, for `faceCount` faces of which `tinyCount` have a nonzero
1140
+ * cross product whose squares sum below 2^−970: writes `out` and returns `true`
1141
+ * where the bound proves each component within one ulp of the default one,
1142
+ * `false` otherwise. Kept apart, as {@link certifySixVolume_} is, so that no
1143
+ * double crosses a call.
1144
+ */
1145
+ function certifyCentroidU16_(out, faceCount, tinyCount) {
1146
+ const filter = CENTROID_FILTER_;
1147
+ const gamma = (faceCount * UNIT_ROUNDOFF_) / (1 - faceCount * UNIT_ROUNDOFF_);
1148
+ const gammaSquared = gamma * gamma;
1149
+ const weight = filter[0] + filter[1];
1150
+ const thrice = 3 * weight;
1151
+ // Σ w lies within (u + γ²)·Σ w of `weight`; E_w bounds Σ |ω_f − w_f|.
1152
+ const weightError = (33 *
1153
+ UNIT_ROUNDOFF_ *
1154
+ weight *
1155
+ (1 + 2 * UNIT_ROUNDOFF_ + 2 * gammaSquared) +
1156
+ (4.03 * UNIT_ROUNDOFF_ * filter[11]) / (1 - gamma) +
1157
+ tinyCount * 2 ** -534 +
1158
+ faceCount * 2 ** -1072) *
1159
+ (1 + 2 ** -40);
1160
+ const margin = (weight * (1 - 2 * UNIT_ROUNDOFF_ - 2 * gammaSquared) - weightError) *
1161
+ (1 - 2 ** -40);
1162
+ if (!(gamma < 2 ** -20 && weight - weight === 0 && margin > 0)) {
1163
+ return false;
1164
+ }
1165
+ const relative = (weightError / margin) * (1 + 2 ** -40) +
1166
+ 7.7 * UNIT_ROUNDOFF_ +
1167
+ 2.1 * gammaSquared +
1168
+ 2 ** -1074 / margin;
1169
+ const absolute = (faceCount * 2 ** -1074) / margin + 2 ** -1071;
1170
+ for (let axis = 0; axis < 3; axis++) {
1171
+ const extent = filter[15 + axis] - filter[12 + axis];
1172
+ if (!(extent < 2 ** 1000)) {
1173
+ return false;
1174
+ }
1175
+ const anchor = filter[8 + axis];
1176
+ const value = (filter[2 + axis] + filter[5 + axis]) / thrice;
1177
+ const size = Math.abs(value);
1178
+ const bound = (extent * relative + 3 * UNIT_ROUNDOFF_ * size + absolute) *
1179
+ (1 + 2 ** -38) +
1180
+ 2 ** -1073;
1181
+ const rounded = anchor + value;
1182
+ const below = anchor + (value - bound);
1183
+ const above = anchor + (value + bound);
1184
+ // The gaps from `rounded` to its neighbours: 2^(e − 52) away from zero
1185
+ // (2^−1074 through the subnormals), half that toward zero at a normal
1186
+ // power of two.
1187
+ const magnitude = Math.abs(rounded);
1188
+ filter[18 + axis] = rounded;
1189
+ let away = 2 ** -1074;
1190
+ let toward = away;
1191
+ if (magnitude !== 0) {
1192
+ const exponent = binaryExponentAt(filter, 18 + axis);
1193
+ away = 2 ** (Math.max(exponent, -1022) - 52);
1194
+ toward =
1195
+ exponent > -1022 && magnitude === 2 ** exponent ? away / 2 : away;
1196
+ }
1197
+ // Exact differences: neighbours are within a factor of two (Sterbenz).
1198
+ if (!(rounded - below <= (rounded > 0 ? toward : away) &&
1199
+ above - rounded <= (rounded < 0 ? toward : away))) {
1200
+ return false;
1201
+ }
1202
+ }
1203
+ out[0] = filter[18];
1204
+ out[1] = filter[19];
1205
+ out[2] = filter[20];
1206
+ return true;
1207
+ }
1208
+ /**
1209
+ * The default centroid's exact sums: Σ ω, then Σ ω (a + b + c) per axis, ω each
1210
+ * face's doubled area m · 2^k (`faceArea_`), at any magnitude.
1211
+ */
1212
+ const CENTROID_SUMS_ = [
1213
+ new DotExactAccumulator(),
1214
+ new DotExactAccumulator(),
1215
+ new DotExactAccumulator(),
1216
+ new DotExactAccumulator(),
1217
+ ];
1218
+ /** Σ ω (a + b + c − 3μ) along one axis, for a midpoint μ the rounding tests. */
1219
+ const CENTROID_RESIDUAL_ = new DotExactAccumulator();
1220
+ /**
1221
+ * A face's m, six times, and its corners along one axis then −μ's high part
1222
+ * thrice.
1223
+ */
1224
+ const CENTROID_LEFT_ = new Float64Array(6);
1225
+ const CENTROID_RIGHT_ = new Float64Array(6);
1226
+ const CENTROID_LEFT_THREE_ = CENTROID_LEFT_.subarray(0, 3);
1227
+ const CENTROID_RIGHT_THREE_ = CENTROID_RIGHT_.subarray(0, 3);
1228
+ const CENTROID_SINGLE_ = new Float64Array(1);
1229
+ const CENTROID_FACTOR_ = new Float64Array(1);
1230
+ /**
1231
+ * A divisor's and a numerator's sums, each as two pieces of 53 bits
1232
+ * (significand then exponent): the divisor over 3 (the centroid's weights, or 2
1233
+ * for the volume) at 0–3, the numerator (an axis's sum, or six times the
1234
+ * volume) at 4–7; then two scratch slots.
1235
+ */
1236
+ const QUOTIENT_READS_ = new Float64Array(10);
1237
+ /** The `axis` {@link roundQuotient_} takes for the volume. */
1238
+ const VOLUME_AXIS_ = 3;
1239
+ /**
1240
+ * Writes `sum` to `reads` at `at` as two pieces of 53 bits, significand then
1241
+ * exponent each, whose sum is within 2^−106 of it: the sum rounded, then what
1242
+ * is left of it rounded. Leaves `sum` less its first piece.
1243
+ */
1244
+ function readPieces_(sum, reads, at) {
1245
+ sum.writeScaled(reads, at);
1246
+ const single = CENTROID_SINGLE_;
1247
+ single[0] = -reads[at];
1248
+ if (single[0] !== 0 && single[0] - single[0] === 0) {
1249
+ sum.addProducts(single, ONE_, reads[at + 1] | 0);
1250
+ }
1251
+ sum.writeScaled(reads, at + 2);
1252
+ }
1253
+ /**
1254
+ * The sign of `Σ ω (a + b + c) − 3μ · Σ ω` along `axis`, μ = σ (units + 1/2) ·
1255
+ * 2^g the midpoint the rounding of the centroid tests: exact, from a second
1256
+ * pass over the faces. Runs only where the doubled-precision quotient lies
1257
+ * within 2^−41 of a unit of that midpoint.
1258
+ */
1259
+ function centroidResidualSignU16_(positions, indices, axis, sign, gridExponent) {
1260
+ const residual = CENTROID_RESIDUAL_;
1261
+ const left = CENTROID_LEFT_;
1262
+ const right = CENTROID_RIGHT_;
1263
+ const single = CENTROID_SINGLE_;
1264
+ const area = FACE_AREA_;
1265
+ const factor = CENTROID_FACTOR_;
1266
+ const reads = QUOTIENT_READS_;
1267
+ residual.reset();
1268
+ // The units of the candidate, in `reads[8]`: a double crossing a call is
1269
+ // boxed.
1270
+ const high = -sign * reads[8] * 2 ** gridExponent;
1271
+ factor[0] = -3 * sign;
1272
+ for (let corner = 0; corner < indices.length; corner += 3) {
1273
+ const a = indices[corner] * 3;
1274
+ const b = indices[corner + 1] * 3;
1275
+ const c = indices[corner + 2] * 3;
1276
+ faceAreaU16_(positions, a, b, c);
1277
+ if (area[0] === 0) {
1278
+ continue;
1279
+ }
1280
+ const exponent = area[1] | 0;
1281
+ for (let slot = 0; slot < 6; slot++) {
1282
+ left[slot] = area[0];
1283
+ }
1284
+ right[0] = positions[a + axis];
1285
+ right[1] = positions[b + axis];
1286
+ right[2] = positions[c + axis];
1287
+ right[3] = high;
1288
+ right[4] = high;
1289
+ right[5] = high;
1290
+ residual.addProducts(left, right, exponent);
1291
+ single[0] = area[0];
1292
+ residual.addProducts(single, factor, (exponent + gridExponent - 1) | 0);
1293
+ }
1294
+ residual.writeScaled(reads, 8);
1295
+ return reads[8] > 0 ? 1 : reads[8] < 0 ? -1 : 0;
1296
+ }
1297
+ /**
1298
+ * The sign of `T − 6μ`, T six times the volume and μ = σ (units + 1/2) · 2^g
1299
+ * the midpoint the rounding of the volume tests: exact, from `SIX_VOLUME_`,
1300
+ * which {@link readPieces_} left less its first piece. Runs only where the
1301
+ * doubled-precision quotient lies within 2^−41 of a unit of that midpoint.
1302
+ */
1303
+ function volumeResidualSign_(sign, gridExponent) {
1304
+ const sum = SIX_VOLUME_;
1305
+ const single = CENTROID_SINGLE_;
1306
+ const factor = CENTROID_FACTOR_;
1307
+ const reads = QUOTIENT_READS_;
1308
+ single[0] = reads[4];
1309
+ sum.addProducts(single, ONE_, reads[5] | 0);
1310
+ // The units of the candidate, in `reads[8]`: a double crossing a call is
1311
+ // boxed.
1312
+ single[0] = reads[8];
1313
+ factor[0] = -6 * sign;
1314
+ sum.addProducts(single, factor, gridExponent);
1315
+ single[0] = -3 * sign;
1316
+ sum.addProducts(single, ONE_, gridExponent);
1317
+ sum.writeScaled(reads, 8);
1318
+ return reads[8] > 0 ? 1 : reads[8] < 0 ? -1 : 0;
1319
+ }
1320
+ /**
1321
+ * Writes to `out[at]` the binary64 nearest a quotient, ties to even, from the
1322
+ * two-piece reads of its numerator and of a third of its divisor in
1323
+ * `QUOTIENT_READS_`: the centroid along `axis` (0–2), or the volume
1324
+ * ({@link VOLUME_AXIS_}). Their quotient in doubled precision (Dekker's
1325
+ * division, within 2^−99 of the exact one), rounded at the result's last bit,
1326
+ * 2^−1074 through the subnormals, `±Infinity` beyond `Number.MAX_VALUE`; where
1327
+ * it lies within 2^−41 of a unit of a midpoint, the exact residual decides.
1328
+ * `NaN` for a zero divisor or a non-finite numerator.
1329
+ */
1330
+ function roundQuotientU16_(out, at, positions, indices, axis) {
1331
+ const reads = QUOTIENT_READS_;
1332
+ const weight = reads[0];
1333
+ const numerator = reads[4];
1334
+ if (!(weight > 0 && weight - weight === 0 && numerator - numerator === 0)) {
1335
+ out[at] = Number.NaN;
1336
+ return;
1337
+ }
1338
+ if (numerator === 0) {
1339
+ out[at] = 0;
1340
+ return;
1341
+ }
1342
+ // The second pieces against the first: exact but in the subnormals, where
1343
+ // they are below 2^−1022 of it.
1344
+ reads[8] = reads[2];
1345
+ if (reads[8] !== 0) {
1346
+ scaleByPowerOfTwoInPlace(reads, 8, (reads[3] - reads[1]) | 0);
1347
+ }
1348
+ reads[9] = reads[6];
1349
+ if (reads[9] !== 0) {
1350
+ scaleByPowerOfTwoInPlace(reads, 9, (reads[7] - reads[5]) | 0);
1351
+ }
1352
+ const sign = numerator < 0 ? -1 : 1;
1353
+ const high = sign * numerator;
1354
+ const low = sign * reads[9];
1355
+ // 3 Σ ω as divisorHigh + divisorLow, then the quotient as quotientHigh +
1356
+ // quotientLow, times 2^exponent.
1357
+ const pair = PAIR_;
1358
+ pair[0] = 3;
1359
+ pair[1] = weight;
1360
+ twoProductInRangeInPlace(pair, 0);
1361
+ const divisorHigh = pair[0];
1362
+ const divisorLow = pair[1] + 3 * reads[8];
1363
+ const quotientHigh = high / divisorHigh;
1364
+ pair[0] = quotientHigh;
1365
+ pair[1] = divisorHigh;
1366
+ twoProductInRangeInPlace(pair, 0);
1367
+ const remainder = high - pair[0] - pair[1] + low - quotientHigh * divisorLow;
1368
+ const quotientLow = remainder / divisorHigh;
1369
+ const exponent = (reads[5] - reads[1]) | 0;
1370
+ // quotientHigh is within 2^−51 of the quotient, in (1/6, 2/3): its binade,
1371
+ // moved where the low part takes the quotient across a power of two.
1372
+ let binade = quotientHigh >= 0.5 ? -1 : quotientHigh >= 0.25 ? -2 : -3;
1373
+ if (quotientHigh - 2 ** binade + quotientLow < 0) {
1374
+ binade--;
1375
+ }
1376
+ else if (quotientHigh - 2 ** (binade + 1) + quotientLow >= 0) {
1377
+ binade++;
1378
+ }
1379
+ const leading = binade + exponent;
1380
+ if (leading > 1023) {
1381
+ out[at] = sign * Number.POSITIVE_INFINITY;
1382
+ return;
1383
+ }
1384
+ if (leading < -1077) {
1385
+ // Below a quarter of the least subnormal, within 2^−99: far from half
1386
+ // of it, the midpoint to 2^−1074. Nearer, the general rounding below and,
1387
+ // close to that midpoint, the exact residual decide.
1388
+ out[at] = sign < 0 ? -0 : 0;
1389
+ return;
1390
+ }
1391
+ const gridExponent = Math.max(leading - 52, -1074);
1392
+ const shift = exponent - gridExponent;
1393
+ // The quotient in units of the last place: an integer, or one and a half,
1394
+ // from the high part (exact), then the low part's whole units and fraction.
1395
+ const scaledHigh = quotientHigh * 2 ** shift;
1396
+ const highUnits = Math.floor(scaledHigh);
1397
+ const scaledLow = scaledHigh - highUnits + quotientLow * 2 ** shift;
1398
+ const lowUnits = Math.floor(scaledLow);
1399
+ let units = highUnits + lowUnits;
1400
+ const fraction = scaledLow - lowUnits;
1401
+ const slack = scaledHigh * 2 ** -96 + 2 ** -50;
1402
+ if (fraction > 0.5 + slack) {
1403
+ units++;
1404
+ }
1405
+ else if (!(fraction < 0.5 - slack)) {
1406
+ reads[8] = units;
1407
+ // The residual's sign is the quotient's against the midpoint; the
1408
+ // magnitude's is that times the sign.
1409
+ const side = sign *
1410
+ (axis === VOLUME_AXIS_
1411
+ ? volumeResidualSign_(sign, gridExponent)
1412
+ : centroidResidualSignU16_(positions, indices, axis, sign, gridExponent));
1413
+ if (side > 0 || (side === 0 && units % 2 === 1)) {
1414
+ units++;
1415
+ }
1416
+ }
1417
+ out[at] = sign * units * 2 ** gridExponent;
1418
+ }
1419
+ /**
1420
+ * The `Uint16Array` twin of the surface centroid: `Σ ω (a + b + c) / (3 Σ ω)`,
1421
+ * ω each face's doubled area (`faceArea_`, as m · 2^k), both sums exact in long
1422
+ * accumulators at any magnitude, their quotient rounded once
1423
+ * ({@link roundQuotient_}): the same number in every face order, correctly
1424
+ * rounded for those weights at any size or distance from the origin, and a
1425
+ * vertex no triangle uses is never read. A zero total area divides zero by
1426
+ * zero: `NaN`. With `faithful`, the first stage {@link faithfulCentroid_} runs
1427
+ * first and the rest only where it cannot prove its result. O(triangles), no
1428
+ * allocation.
1429
+ */
1430
+ export function mesh3CentroidU16(out, positions, indices, faithful = false) {
1431
+ if (faithful && faithfulCentroidU16_(out, positions, indices)) {
1432
+ return;
1433
+ }
1434
+ const area = FACE_AREA_;
1435
+ const left = CENTROID_LEFT_THREE_;
1436
+ const right = CENTROID_RIGHT_THREE_;
1437
+ const single = CENTROID_SINGLE_;
1438
+ for (let sum = 0; sum < CENTROID_SUMS_.length; sum++) {
1439
+ CENTROID_SUMS_[sum].reset();
1440
+ }
160
1441
  for (let corner = 0; corner < indices.length; corner += 3) {
161
1442
  const a = indices[corner] * 3;
162
1443
  const b = indices[corner + 1] * 3;
163
1444
  const c = indices[corner + 2] * 3;
164
- const aX = positions[a] - originX;
165
- const aY = positions[a + 1] - originY;
166
- const aZ = positions[a + 2] - originZ;
167
- const bX = positions[b] - originX;
168
- const bY = positions[b + 1] - originY;
169
- const bZ = positions[b + 2] - originZ;
170
- const cX = positions[c] - originX;
171
- const cY = positions[c + 1] - originY;
172
- const cZ = positions[c + 2] - originZ;
173
- const abX = positions[b] - positions[a];
174
- const abY = positions[b + 1] - positions[a + 1];
175
- const abZ = positions[b + 2] - positions[a + 2];
176
- const acX = positions[c] - positions[a];
177
- const acY = positions[c + 1] - positions[a + 1];
178
- const acZ = positions[c + 2] - positions[a + 2];
179
- const crossX = abY * acZ - abZ * acY;
180
- const crossY = abZ * acX - abX * acZ;
181
- const crossZ = abX * acY - abY * acX;
182
- const doubleArea = Math.sqrt(crossX * crossX + crossY * crossY + crossZ * crossZ);
183
- weight += doubleArea;
184
- sumX += doubleArea * (aX + bX + cX);
185
- sumY += doubleArea * (aY + bY + cY);
186
- sumZ += doubleArea * (aZ + bZ + cZ);
187
- }
188
- out[0] = originX + sumX / (3 * weight);
189
- out[1] = originY + sumY / (3 * weight);
190
- out[2] = originZ + sumZ / (3 * weight);
1445
+ faceAreaU16_(positions, a, b, c);
1446
+ if (area[0] === 0) {
1447
+ continue;
1448
+ }
1449
+ const exponent = area[1] | 0;
1450
+ single[0] = area[0];
1451
+ CENTROID_SUMS_[0].addProducts(single, ONE_, exponent);
1452
+ left[0] = area[0];
1453
+ left[1] = area[0];
1454
+ left[2] = area[0];
1455
+ for (let axis = 0; axis < 3; axis++) {
1456
+ right[0] = positions[a + axis];
1457
+ right[1] = positions[b + axis];
1458
+ right[2] = positions[c + axis];
1459
+ CENTROID_SUMS_[axis + 1].addProducts(left, right, exponent);
1460
+ }
1461
+ }
1462
+ readPieces_(CENTROID_SUMS_[0], QUOTIENT_READS_, 0);
1463
+ for (let axis = 0; axis < 3; axis++) {
1464
+ readPieces_(CENTROID_SUMS_[axis + 1], QUOTIENT_READS_, 4);
1465
+ roundQuotientU16_(out, axis, positions, indices, axis);
1466
+ }
191
1467
  }
192
1468
  /**
193
1469
  * The `Uint16Array` twin of the nearest ray hit: the triangle index, `−1` for a
@@ -226,7 +1502,9 @@ export function mesh3IntersectRay3U16(out, ray, positions, indices, cullBackFace
226
1502
  }
227
1503
  /**
228
1504
  * The `Uint16Array` twin of the triangle depths: `z / w` of each triangle's
229
- * centroid under `viewProjection`. O(triangles).
1505
+ * centroid under `viewProjection`. A centroid whose coordinates overflow when
1506
+ * summed takes halves; one whose transformed z or w overflows is scaled by a
1507
+ * power of two first, which leaves `z / w` unchanged. O(triangles).
230
1508
  */
231
1509
  export function mesh3TriangleDepthsU16(out, positions, indices, viewProjection) {
232
1510
  const m2 = viewProjection[2];
@@ -241,11 +1519,43 @@ export function mesh3TriangleDepthsU16(out, positions, indices, viewProjection)
241
1519
  const a = indices[corner] * 3;
242
1520
  const b = indices[corner + 1] * 3;
243
1521
  const c = indices[corner + 2] * 3;
244
- const x = (positions[a] + positions[b] + positions[c]) / 3;
245
- const y = (positions[a + 1] + positions[b + 1] + positions[c + 1]) / 3;
246
- const z = (positions[a + 2] + positions[b + 2] + positions[c + 2]) / 3;
247
- out[triangle] =
248
- (m2 * x + m6 * y + m10 * z + m14) / (m3 * x + m7 * y + m11 * z + m15);
1522
+ let x = (positions[a] + positions[b] + positions[c]) / 3;
1523
+ let y = (positions[a + 1] + positions[b + 1] + positions[c + 1]) / 3;
1524
+ let z = (positions[a + 2] + positions[b + 2] + positions[c + 2]) / 3;
1525
+ if (x - x !== 0 || y - y !== 0 || z - z !== 0) {
1526
+ // Quarters, when the sum overflowed: the centroid a wider sum would give.
1527
+ x =
1528
+ ((positions[a] * 0.25 + positions[b] * 0.25 + positions[c] * 0.25) /
1529
+ 3) *
1530
+ 4;
1531
+ y =
1532
+ ((positions[a + 1] * 0.25 +
1533
+ positions[b + 1] * 0.25 +
1534
+ positions[c + 1] * 0.25) /
1535
+ 3) *
1536
+ 4;
1537
+ z =
1538
+ ((positions[a + 2] * 0.25 +
1539
+ positions[b + 2] * 0.25 +
1540
+ positions[c + 2] * 0.25) /
1541
+ 3) *
1542
+ 4;
1543
+ }
1544
+ let depth = m2 * x + m6 * y + m10 * z + m14;
1545
+ let w = m3 * x + m7 * y + m11 * z + m15;
1546
+ if (depth - depth !== 0 || w - w !== 0) {
1547
+ // The homogeneous point (x, y, z, 1) scaled by a power of two, so that
1548
+ // its largest coordinate is below 1: the ratio is the same.
1549
+ const largest = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
1550
+ if (largest > 1 && largest < Number.POSITIVE_INFINITY) {
1551
+ const scale = 2 ** -(binaryExponent(largest) + 1);
1552
+ depth =
1553
+ m2 * (x * scale) + m6 * (y * scale) + m10 * (z * scale) + m14 * scale;
1554
+ w =
1555
+ m3 * (x * scale) + m7 * (y * scale) + m11 * (z * scale) + m15 * scale;
1556
+ }
1557
+ }
1558
+ out[triangle] = depth / w;
249
1559
  }
250
1560
  }
251
1561
  /**