@math.gl/geometry 5.0.0-beta.1 → 5.0.0-beta.11

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 (179) hide show
  1. package/README.md +61 -0
  2. package/THIRD-PARTY-NOTICES.md +1 -1
  3. package/dist/color/color-lut-types.d.ts +16 -0
  4. package/dist/color/color-lut-types.d.ts.map +1 -0
  5. package/dist/color/color-lut-types.js +5 -0
  6. package/dist/color/color-lut-types.js.map +1 -0
  7. package/dist/color/index.cjs +132 -0
  8. package/dist/color/index.cjs.map +6 -0
  9. package/dist/color/index.d.ts +4 -0
  10. package/dist/color/index.d.ts.map +1 -0
  11. package/dist/color/index.js +5 -0
  12. package/dist/color/index.js.map +1 -0
  13. package/dist/color/sample-lut.d.ts +13 -0
  14. package/dist/color/sample-lut.d.ts.map +1 -0
  15. package/dist/color/sample-lut.js +132 -0
  16. package/dist/color/sample-lut.js.map +1 -0
  17. package/dist/culling/bounds.d.ts +20 -0
  18. package/dist/culling/bounds.d.ts.map +1 -0
  19. package/dist/culling/bounds.js +121 -0
  20. package/dist/culling/bounds.js.map +1 -0
  21. package/dist/culling/frustum-planes.d.ts +5 -0
  22. package/dist/culling/frustum-planes.d.ts.map +1 -0
  23. package/dist/culling/frustum-planes.js +37 -0
  24. package/dist/culling/frustum-planes.js.map +1 -0
  25. package/dist/culling/geometric-queries.d.ts +34 -0
  26. package/dist/culling/geometric-queries.d.ts.map +1 -0
  27. package/dist/culling/geometric-queries.js +208 -0
  28. package/dist/culling/geometric-queries.js.map +1 -0
  29. package/dist/culling/index.cjs +944 -508
  30. package/dist/culling/index.cjs.map +3 -3
  31. package/dist/culling/index.d.ts +7 -1
  32. package/dist/culling/index.d.ts.map +1 -1
  33. package/dist/culling/index.js +4 -0
  34. package/dist/culling/index.js.map +1 -1
  35. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.d.ts +3 -3
  36. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.d.ts.map +1 -1
  37. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.js +25 -8
  38. package/dist/culling/lib/bounding-volumes/axis-aligned-bounding-box.js.map +1 -1
  39. package/dist/culling/lib/culling-volume.d.ts +3 -0
  40. package/dist/culling/lib/culling-volume.d.ts.map +1 -1
  41. package/dist/culling/lib/culling-volume.js +7 -0
  42. package/dist/culling/lib/culling-volume.js.map +1 -1
  43. package/dist/culling/lib/ray.d.ts +5 -0
  44. package/dist/culling/lib/ray.d.ts.map +1 -1
  45. package/dist/culling/lib/ray.js +21 -0
  46. package/dist/culling/lib/ray.js.map +1 -1
  47. package/dist/culling/screen-ray.d.ts +22 -0
  48. package/dist/culling/screen-ray.d.ts.map +1 -0
  49. package/dist/culling/screen-ray.js +55 -0
  50. package/dist/culling/screen-ray.js.map +1 -0
  51. package/dist/curves/adaptive-sampling.d.ts +16 -0
  52. package/dist/curves/adaptive-sampling.d.ts.map +1 -0
  53. package/dist/curves/adaptive-sampling.js +59 -0
  54. package/dist/curves/adaptive-sampling.js.map +1 -0
  55. package/dist/curves/index.d.ts +4 -0
  56. package/dist/curves/index.d.ts.map +1 -1
  57. package/dist/curves/index.js +2 -0
  58. package/dist/curves/index.js.map +1 -1
  59. package/dist/curves/parallel-transport.d.ts +12 -0
  60. package/dist/curves/parallel-transport.d.ts.map +1 -0
  61. package/dist/curves/parallel-transport.js +83 -0
  62. package/dist/curves/parallel-transport.js.map +1 -0
  63. package/dist/index.cjs +1988 -934
  64. package/dist/index.cjs.map +3 -3
  65. package/dist/index.d.ts +17 -5
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +9 -2
  68. package/dist/index.js.map +1 -1
  69. package/dist/lighting/index.cjs +175 -0
  70. package/dist/lighting/index.cjs.map +6 -0
  71. package/dist/lighting/index.d.ts +4 -0
  72. package/dist/lighting/index.d.ts.map +1 -0
  73. package/dist/lighting/index.js +5 -0
  74. package/dist/lighting/index.js.map +1 -0
  75. package/dist/lighting/lighting-types.d.ts +16 -0
  76. package/dist/lighting/lighting-types.d.ts.map +1 -0
  77. package/dist/lighting/lighting-types.js +5 -0
  78. package/dist/lighting/lighting-types.js.map +1 -0
  79. package/dist/lighting/photometry.d.ts +36 -0
  80. package/dist/lighting/photometry.d.ts.map +1 -0
  81. package/dist/lighting/photometry.js +181 -0
  82. package/dist/lighting/photometry.js.map +1 -0
  83. package/dist/polygon/cut-by-grid.d.ts.map +1 -1
  84. package/dist/polygon/cut-by-grid.js +18 -0
  85. package/dist/polygon/cut-by-grid.js.map +1 -1
  86. package/dist/polygon/earcut.d.ts.map +1 -1
  87. package/dist/polygon/earcut.js +100 -34
  88. package/dist/polygon/earcut.js.map +1 -1
  89. package/dist/polygon/index.d.ts +2 -0
  90. package/dist/polygon/index.d.ts.map +1 -1
  91. package/dist/polygon/index.js +1 -0
  92. package/dist/polygon/index.js.map +1 -1
  93. package/dist/polygon/pole-of-inaccessibility.d.ts +21 -0
  94. package/dist/polygon/pole-of-inaccessibility.d.ts.map +1 -0
  95. package/dist/polygon/pole-of-inaccessibility.js +285 -0
  96. package/dist/polygon/pole-of-inaccessibility.js.map +1 -0
  97. package/dist/polygon/subdivide-triangle-mesh.d.ts +10 -0
  98. package/dist/polygon/subdivide-triangle-mesh.d.ts.map +1 -1
  99. package/dist/polygon/subdivide-triangle-mesh.js +67 -19
  100. package/dist/polygon/subdivide-triangle-mesh.js.map +1 -1
  101. package/dist/utils/compose-attribute-provenance.d.ts +13 -0
  102. package/dist/utils/compose-attribute-provenance.d.ts.map +1 -0
  103. package/dist/utils/compose-attribute-provenance.js +63 -0
  104. package/dist/utils/compose-attribute-provenance.js.map +1 -0
  105. package/dist/utils/compute-vertex-normals.d.ts +2 -2
  106. package/dist/utils/compute-vertex-normals.d.ts.map +1 -1
  107. package/dist/utils/compute-vertex-normals.js +3 -4
  108. package/dist/utils/compute-vertex-normals.js.map +1 -1
  109. package/dist/utils/geometry.d.ts +11 -4
  110. package/dist/utils/geometry.d.ts.map +1 -1
  111. package/dist/utils/geometry.js +19 -2
  112. package/dist/utils/geometry.js.map +1 -1
  113. package/dist/utils/index.d.ts +1 -3
  114. package/dist/utils/index.d.ts.map +1 -1
  115. package/dist/utils/index.js +0 -2
  116. package/dist/utils/index.js.map +1 -1
  117. package/dist/utils/mesh-processing.d.ts +16 -6
  118. package/dist/utils/mesh-processing.d.ts.map +1 -1
  119. package/dist/utils/mesh-processing.js +9 -6
  120. package/dist/utils/mesh-processing.js.map +1 -1
  121. package/dist/utils/primitive-iterator.d.ts +16 -8
  122. package/dist/utils/primitive-iterator.d.ts.map +1 -1
  123. package/dist/utils/primitive-iterator.js +32 -35
  124. package/dist/utils/primitive-iterator.js.map +1 -1
  125. package/dist/utils/project-bounds.d.ts +44 -0
  126. package/dist/utils/project-bounds.d.ts.map +1 -0
  127. package/dist/utils/project-bounds.js +93 -0
  128. package/dist/utils/project-bounds.js.map +1 -0
  129. package/dist/utils/project-texture-coordinates.d.ts +19 -0
  130. package/dist/utils/project-texture-coordinates.d.ts.map +1 -0
  131. package/dist/utils/project-texture-coordinates.js +49 -0
  132. package/dist/utils/project-texture-coordinates.js.map +1 -0
  133. package/dist/utils/qualify-surface-transition.d.ts +21 -0
  134. package/dist/utils/qualify-surface-transition.d.ts.map +1 -0
  135. package/dist/utils/qualify-surface-transition.js +140 -0
  136. package/dist/utils/qualify-surface-transition.js.map +1 -0
  137. package/package.json +15 -3
  138. package/src/color/color-lut-types.ts +19 -0
  139. package/src/color/index.ts +6 -0
  140. package/src/color/sample-lut.ts +175 -0
  141. package/src/culling/bounds.ts +152 -0
  142. package/src/culling/frustum-planes.ts +41 -0
  143. package/src/culling/geometric-queries.ts +299 -0
  144. package/src/culling/index.ts +39 -1
  145. package/src/culling/lib/bounding-volumes/axis-aligned-bounding-box.ts +26 -8
  146. package/src/culling/lib/culling-volume.ts +9 -1
  147. package/src/culling/lib/ray.ts +21 -0
  148. package/src/culling/screen-ray.ts +75 -0
  149. package/src/curves/adaptive-sampling.ts +85 -0
  150. package/src/curves/index.ts +4 -0
  151. package/src/curves/parallel-transport.ts +104 -0
  152. package/src/index.ts +71 -9
  153. package/src/lighting/index.ts +10 -0
  154. package/src/lighting/lighting-types.ts +20 -0
  155. package/src/lighting/photometry.ts +264 -0
  156. package/src/polygon/cut-by-grid.ts +18 -0
  157. package/src/polygon/earcut.ts +98 -37
  158. package/src/polygon/index.ts +6 -0
  159. package/src/polygon/pole-of-inaccessibility.ts +330 -0
  160. package/src/polygon/subdivide-triangle-mesh.ts +77 -17
  161. package/src/utils/compose-attribute-provenance.ts +74 -0
  162. package/src/utils/compute-vertex-normals.ts +5 -6
  163. package/src/utils/geometry.ts +32 -6
  164. package/src/utils/index.ts +5 -5
  165. package/src/utils/mesh-processing.ts +30 -14
  166. package/src/utils/primitive-iterator.ts +45 -43
  167. package/src/utils/project-bounds.ts +154 -0
  168. package/src/utils/project-texture-coordinates.ts +67 -0
  169. package/src/utils/qualify-surface-transition.ts +169 -0
  170. package/dist/utils/constants.d.ts +0 -52
  171. package/dist/utils/constants.d.ts.map +0 -1
  172. package/dist/utils/constants.js +0 -39
  173. package/dist/utils/constants.js.map +0 -1
  174. package/dist/utils/gl-type.d.ts +0 -17
  175. package/dist/utils/gl-type.d.ts.map +0 -1
  176. package/dist/utils/gl-type.js +0 -69
  177. package/dist/utils/gl-type.js.map +0 -1
  178. package/src/utils/constants.ts +0 -42
  179. package/src/utils/gl-type.ts +0 -87
@@ -0,0 +1,330 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ // The pole of inaccessibility of a polygon is the interior point farthest from its outline, for
6
+ // example the position of a point label. This file finds that point with the grid refinement of
7
+ // Garcia-Castellanos and Lombardo, "Poles of inaccessibility: a calculation algorithm for the
8
+ // remotest places on Earth" (Scottish Geographical Journal 123(3), 2007), in its best-first form.
9
+ // A priority queue holds the candidate squares, ordered by the largest distance that a point in
10
+ // each square can have. The search splits a square into four only if the square can improve the
11
+ // best point by more than the precision.
12
+ //
13
+ // Polygon input can come from an untrusted source, for example a vector tile. Thus the work of
14
+ // the search has a limit. To score one candidate costs one point-to-segment test for each vertex.
15
+ // The search counts these tests against a budget, and returns the best point found when the
16
+ // budget is empty. A caller can share one budget across many polygons, so that many large
17
+ // polygons together cannot block the main thread. The first grid also has at most
18
+ // MAX_GRID_CELLS_PER_AXIS squares along the longer side, and the precision has a floor relative
19
+ // to the size of the polygon.
20
+
21
+ const MAX_GRID_CELLS_PER_AXIS = 64;
22
+ const MIN_RELATIVE_PRECISION = 1e-6;
23
+ /** Default budget for one search: point-to-segment distance tests. */
24
+ export const DEFAULT_POLE_SEARCH_SEGMENT_TESTS = 5e6;
25
+
26
+ /** Remaining work, in point-to-segment distance tests, shared by the searches that use it. */
27
+ export type PoleSearchBudget = {
28
+ segmentTests: number;
29
+ };
30
+
31
+ /**
32
+ * Returns the point inside a polygon farthest from its outline, to within `precision` in the
33
+ * polygon's units. `polygon` is GeoJSON-style: an outer ring followed by hole rings. Coordinates
34
+ * must be planar.
35
+ *
36
+ * The search spends at most `budget.segmentTests` point-to-segment distance tests and deducts
37
+ * what it spends, so one budget can bound several searches. When the budget runs out, the best
38
+ * point found so far is returned. The returned point is always strictly inside the polygon: not
39
+ * in a hole and not on an edge.
40
+ *
41
+ * Returns null for a polygon without vertices, with a non-finite coordinate, or with no area, and
42
+ * when the budget runs out before the search finds a point inside the polygon.
43
+ */
44
+ export function getPoleOfInaccessibility(
45
+ polygon: number[][][],
46
+ precision: number,
47
+ budget: PoleSearchBudget = {
48
+ segmentTests: DEFAULT_POLE_SEARCH_SEGMENT_TESTS
49
+ }
50
+ ): [number, number] | null {
51
+ const outline = polygon[0];
52
+ if (!outline || outline.length === 0) {
53
+ return null;
54
+ }
55
+ const vertexCount = countFiniteVertices(polygon);
56
+ if (vertexCount < 0) {
57
+ return null;
58
+ }
59
+
60
+ const box = getRingBox(outline);
61
+ const width = box.right - box.left;
62
+ const height = box.top - box.bottom;
63
+ if (width === 0 || height === 0) {
64
+ return null;
65
+ }
66
+ const longSide = Math.max(width, height);
67
+ const minTolerance = longSide * MIN_RELATIVE_PRECISION;
68
+ const tolerance = Math.max(
69
+ Number.isFinite(precision) && precision > 0 ? precision : 0,
70
+ minTolerance
71
+ );
72
+
73
+ const search = new PoleSearch(polygon, vertexCount, budget);
74
+
75
+ // Two cheap first guesses: the area centroid, which is inside most convex-ish shapes, and the
76
+ // middle of the bounding box.
77
+ const [centroidX, centroidY] = getAreaCentroid(polygon[0]);
78
+ if (!search.score(centroidX, centroidY, 0)) {
79
+ return null;
80
+ }
81
+ if (!search.score(box.left + width / 2, box.bottom + height / 2, 0)) {
82
+ return search.bestPoint();
83
+ }
84
+
85
+ // The first grid uses squares as wide as the polygon's short side, so a long, thin polygon is
86
+ // covered by squares that fit it. The cap keeps a sliver from starting with millions of them.
87
+ const side = Math.max(Math.min(width, height), longSide / MAX_GRID_CELLS_PER_AXIS);
88
+ const columns = Math.ceil(width / side);
89
+ const rows = Math.ceil(height / side);
90
+ for (let column = 0; column < columns; column++) {
91
+ for (let row = 0; row < rows; row++) {
92
+ const x = box.left + (column + 0.5) * side;
93
+ const y = box.bottom + (row + 0.5) * side;
94
+ if (!search.score(x, y, side / 2)) {
95
+ return search.bestPoint();
96
+ }
97
+ }
98
+ }
99
+
100
+ search.refine(tolerance, minTolerance);
101
+ return search.bestPoint();
102
+ }
103
+
104
+ /** Returns the number of vertices in all rings, or -1 if any coordinate is not finite. */
105
+ function countFiniteVertices(polygon: number[][][]): number {
106
+ let count = 0;
107
+ for (const ring of polygon) {
108
+ for (const point of ring) {
109
+ if (!Number.isFinite(point[0]) || !Number.isFinite(point[1])) {
110
+ return -1;
111
+ }
112
+ }
113
+ count += ring.length;
114
+ }
115
+ return count;
116
+ }
117
+
118
+ function getRingBox(ring: number[][]): {
119
+ left: number;
120
+ bottom: number;
121
+ right: number;
122
+ top: number;
123
+ } {
124
+ let left = Infinity;
125
+ let bottom = Infinity;
126
+ let right = -Infinity;
127
+ let top = -Infinity;
128
+ for (const point of ring) {
129
+ left = Math.min(left, point[0]);
130
+ right = Math.max(right, point[0]);
131
+ bottom = Math.min(bottom, point[1]);
132
+ top = Math.max(top, point[1]);
133
+ }
134
+ return {left, bottom, right, top};
135
+ }
136
+
137
+ /** The centroid of the area a ring encloses, or its first vertex when that area is zero. */
138
+ function getAreaCentroid(ring: number[][]): [number, number] {
139
+ let twiceArea = 0;
140
+ let sumX = 0;
141
+ let sumY = 0;
142
+ let previous = ring[ring.length - 1];
143
+ for (const current of ring) {
144
+ const cross = previous[0] * current[1] - current[0] * previous[1];
145
+ twiceArea += cross;
146
+ sumX += (previous[0] + current[0]) * cross;
147
+ sumY += (previous[1] + current[1]) * cross;
148
+ previous = current;
149
+ }
150
+ if (twiceArea === 0) {
151
+ return [ring[0][0], ring[0][1]];
152
+ }
153
+ return [sumX / (3 * twiceArea), sumY / (3 * twiceArea)];
154
+ }
155
+
156
+ /**
157
+ * The state of one search: the best point so far and a max-heap of candidate squares. The
158
+ * squares are kept in parallel arrays, and the heap holds their indices, ordered by `reach`.
159
+ */
160
+ class PoleSearch {
161
+ private readonly polygon: number[][][];
162
+ private readonly vertexCount: number;
163
+ private readonly budget: PoleSearchBudget;
164
+
165
+ private readonly centerX: number[] = [];
166
+ private readonly centerY: number[] = [];
167
+ private readonly halfSide: number[] = [];
168
+ /** The largest distance to the outline that any point of the square can have. */
169
+ private readonly reach: number[] = [];
170
+ private readonly heap: number[] = [];
171
+
172
+ private bestX = NaN;
173
+ private bestY = NaN;
174
+ private bestDistance = -Infinity;
175
+
176
+ constructor(polygon: number[][][], vertexCount: number, budget: PoleSearchBudget) {
177
+ this.polygon = polygon;
178
+ this.vertexCount = vertexCount;
179
+ this.budget = budget;
180
+ }
181
+
182
+ /** The best point so far, or null if no scored point is inside the polygon. */
183
+ bestPoint(): [number, number] | null {
184
+ return this.bestDistance > 0 ? [this.bestX, this.bestY] : null;
185
+ }
186
+
187
+ /**
188
+ * Scores the square centered at (x, y), keeps its center if it is the best so far, and queues
189
+ * the square if it has area. Returns false, without scoring, when the budget cannot pay.
190
+ */
191
+ score(x: number, y: number, half: number): boolean {
192
+ if (this.budget.segmentTests < this.vertexCount) {
193
+ return false;
194
+ }
195
+ this.budget.segmentTests -= this.vertexCount;
196
+ const distance = getSignedOutlineDistance(this.polygon, x, y);
197
+ if (distance > this.bestDistance) {
198
+ this.bestX = x;
199
+ this.bestY = y;
200
+ this.bestDistance = distance;
201
+ }
202
+ if (half > 0) {
203
+ // No point in the square is farther from the center than half its diagonal.
204
+ this.enqueue(x, y, half, distance + half * Math.SQRT2);
205
+ }
206
+ return true;
207
+ }
208
+
209
+ /**
210
+ * Splits the most promising squares until none can beat the best point by `tolerance`. While no
211
+ * scored point is inside the polygon, `tolerance` does not apply: the search continues while a
212
+ * square can hold an inside point and is larger than `minTolerance`.
213
+ */
214
+ refine(tolerance: number, minTolerance: number): void {
215
+ while (this.heap.length > 0) {
216
+ const index = this.dequeue();
217
+ const reach = this.reach[index];
218
+ if (this.bestDistance > 0 ? reach - this.bestDistance <= tolerance : reach <= 0) {
219
+ // The heap is ordered by reach, so no remaining square can do better either.
220
+ return;
221
+ }
222
+ if (this.bestDistance <= 0 && this.halfSide[index] * Math.SQRT2 <= minTolerance) {
223
+ // The square is too small to search further. Larger squares can remain in the heap.
224
+ continue;
225
+ }
226
+ const quarter = this.halfSide[index] / 2;
227
+ const x = this.centerX[index];
228
+ const y = this.centerY[index];
229
+ if (
230
+ !this.score(x - quarter, y - quarter, quarter) ||
231
+ !this.score(x + quarter, y - quarter, quarter) ||
232
+ !this.score(x - quarter, y + quarter, quarter) ||
233
+ !this.score(x + quarter, y + quarter, quarter)
234
+ ) {
235
+ return;
236
+ }
237
+ }
238
+ }
239
+
240
+ private enqueue(x: number, y: number, half: number, reach: number): void {
241
+ const index = this.reach.length;
242
+ this.centerX.push(x);
243
+ this.centerY.push(y);
244
+ this.halfSide.push(half);
245
+ this.reach.push(reach);
246
+
247
+ const {heap} = this;
248
+ let slot = heap.length;
249
+ heap.push(index);
250
+ while (slot > 0) {
251
+ const parentSlot = (slot - 1) >> 1;
252
+ if (this.reach[heap[parentSlot]] >= reach) {
253
+ break;
254
+ }
255
+ heap[slot] = heap[parentSlot];
256
+ slot = parentSlot;
257
+ }
258
+ heap[slot] = index;
259
+ }
260
+
261
+ private dequeue(): number {
262
+ const {heap, reach} = this;
263
+ const top = heap[0];
264
+ const moved = heap.pop() as number;
265
+ const size = heap.length;
266
+ if (size === 0) {
267
+ return top;
268
+ }
269
+ let slot = 0;
270
+ for (;;) {
271
+ let next = slot * 2 + 1;
272
+ if (next >= size) {
273
+ break;
274
+ }
275
+ if (next + 1 < size && reach[heap[next + 1]] > reach[heap[next]]) {
276
+ next += 1;
277
+ }
278
+ if (reach[heap[next]] <= reach[moved]) {
279
+ break;
280
+ }
281
+ heap[slot] = heap[next];
282
+ slot = next;
283
+ }
284
+ heap[slot] = moved;
285
+ return top;
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Distance from (x, y) to the nearest edge of any ring: positive inside the polygon, negative
291
+ * outside, and 0 on an edge. Inside is decided by the even-odd rule, so holes count as outside.
292
+ */
293
+ function getSignedOutlineDistance(polygon: number[][][], x: number, y: number): number {
294
+ let nearestSquared = Infinity;
295
+ let crossings = 0;
296
+ for (const ring of polygon) {
297
+ let start = ring[ring.length - 1];
298
+ for (const end of ring) {
299
+ // Count edges that cross the horizontal ray from (x, y) toward +x.
300
+ if (start[1] <= y !== end[1] <= y) {
301
+ const t = (y - start[1]) / (end[1] - start[1]);
302
+ if (start[0] + t * (end[0] - start[0]) > x) {
303
+ crossings++;
304
+ }
305
+ }
306
+ nearestSquared = Math.min(nearestSquared, getSquaredSegmentDistance(x, y, start, end));
307
+ start = end;
308
+ }
309
+ }
310
+ if (nearestSquared === 0) {
311
+ return 0;
312
+ }
313
+ const distance = Math.sqrt(nearestSquared);
314
+ return crossings % 2 === 1 ? distance : -distance;
315
+ }
316
+
317
+ /** Squared distance from (x, y) to the segment from `start` to `end`. */
318
+ function getSquaredSegmentDistance(x: number, y: number, start: number[], end: number[]): number {
319
+ const edgeX = end[0] - start[0];
320
+ const edgeY = end[1] - start[1];
321
+ const lengthSquared = edgeX * edgeX + edgeY * edgeY;
322
+ // Where the perpendicular from (x, y) meets the edge's line, as a fraction of the edge.
323
+ const along =
324
+ lengthSquared === 0
325
+ ? 0
326
+ : Math.max(0, Math.min(1, ((x - start[0]) * edgeX + (y - start[1]) * edgeY) / lengthSquared));
327
+ const offsetX = start[0] + along * edgeX - x;
328
+ const offsetY = start[1] + along * edgeY - y;
329
+ return offsetX * offsetX + offsetY * offsetY;
330
+ }
@@ -36,6 +36,15 @@ export type SubdivideTriangleMeshOptions = SubdivisionOptions &
36
36
  refinement?: 'transform-error';
37
37
  /** Positive, finite sampled error tolerance across target components, in target units. */
38
38
  tolerance: number;
39
+ /** Optional application metric in tolerance units. Receives fresh sample arrays.
40
+ * Must return a finite nonnegative value. Exceptions propagate.
41
+ * Does not change output coordinates or provide a continuous error guarantee.
42
+ */
43
+ errorMetric?: (sample: {
44
+ source: readonly number[];
45
+ exact: readonly number[];
46
+ interpolated: readonly number[];
47
+ }) => number;
39
48
  /** Positive maximum Euclidean source-edge length. Default Infinity. */
40
49
  maxEdgeLength?: number;
41
50
  }
@@ -44,6 +53,7 @@ export type SubdivideTriangleMeshOptions = SubdivisionOptions &
44
53
  refinement: 'source-edge';
45
54
  /** No target-space tolerance is evaluated in source-edge mode. */
46
55
  tolerance?: never;
56
+ errorMetric?: never;
47
57
  /** Positive, finite maximum Euclidean edge length across all source components. */
48
58
  maxEdgeLength: number;
49
59
  }
@@ -66,9 +76,15 @@ export type SubdividedTriangleMesh = {
66
76
  };
67
77
 
68
78
  type Vertex = {source: number[]; target: number[]; weights: Map<number, number>};
69
- type Face = {vertices: [number, number, number]; sourceTriangle: number};
79
+ type Face = {
80
+ vertices: [number, number, number];
81
+ sourceTriangle: number;
82
+ /** Passed the error probes. Probes are deterministic, so an unsplit face is not probed again. */
83
+ accepted?: boolean;
84
+ };
70
85
 
71
86
  const EDGE_FRACTIONS = [0.25, 0.5, 0.75];
87
+ const EDGE_SAMPLE_ORDER = [1, 0, 2];
72
88
  const FACE_WEIGHTS = [
73
89
  [1 / 3, 1 / 3, 1 / 3],
74
90
  [0.5, 0.25, 0.25],
@@ -93,6 +109,7 @@ export function subdivideTriangleMesh(
93
109
  const {
94
110
  transform,
95
111
  tolerance,
112
+ errorMetric,
96
113
  refinement = 'transform-error',
97
114
  size = 2,
98
115
  targetSize = size,
@@ -104,6 +121,10 @@ export function subdivideTriangleMesh(
104
121
  validateOptions();
105
122
  const vertices: Vertex[] = [];
106
123
  let faces: Face[] = [];
124
+ /** Sampled errors per undirected edge, ordered from its lower vertex index. */
125
+ const edgeErrors = new Map<string, number[]>();
126
+ /** Projected midpoints of sampled edges, reused when the edge is split. */
127
+ const edgeMidpointTargets = new Map<string, number[]>();
107
128
  for (let i = 0; i < mesh.positions.length; i += size) {
108
129
  const source = Array.from({length: size}, (_, j) => mesh.positions[i + j]);
109
130
  if (!source.every(Number.isFinite)) throw new RangeError('Source positions must be finite');
@@ -128,11 +149,15 @@ export function subdivideTriangleMesh(
128
149
  splitEdges.add(edgeKey(a, b));
129
150
  }
130
151
  }
152
+ } else if (face.accepted) {
153
+ // Probed in an earlier pass and not split since.
131
154
  } else if (needsRefinement(face)) {
132
155
  const [a, b, c] = face.vertices;
133
156
  splitEdges.add(edgeKey(a, b));
134
157
  splitEdges.add(edgeKey(b, c));
135
158
  splitEdges.add(edgeKey(c, a));
159
+ } else {
160
+ face.accepted = true;
136
161
  }
137
162
  }
138
163
  if (!splitEdges.size) return buildResult();
@@ -148,11 +173,14 @@ export function subdivideTriangleMesh(
148
173
  function validateOptions(): void {
149
174
  if (
150
175
  typeof transform !== 'function' ||
176
+ (errorMetric !== undefined && typeof errorMetric !== 'function') ||
151
177
  (refinement !== 'transform-error' && refinement !== 'source-edge') ||
152
178
  (refinement === 'transform-error' &&
153
179
  (tolerance === undefined || !Number.isFinite(tolerance) || tolerance <= 0)) ||
154
180
  (refinement === 'source-edge' &&
155
- (tolerance !== undefined || !Number.isFinite(maxEdgeLength))) ||
181
+ (tolerance !== undefined ||
182
+ errorMetric !== undefined ||
183
+ !Number.isFinite(maxEdgeLength))) ||
156
184
  (size !== 2 && size !== 3) ||
157
185
  (targetSize !== 2 && targetSize !== 3) ||
158
186
  !(maxEdgeLength > 0) ||
@@ -186,7 +214,7 @@ export function subdivideTriangleMesh(
186
214
  return target;
187
215
  }
188
216
 
189
- function error(points: Vertex[], weights: number[]): number {
217
+ function error(points: Vertex[], weights: number[], keepExact?: number[][]): number {
190
218
  const source = blend(
191
219
  points.map(p => p.source),
192
220
  weights
@@ -195,26 +223,55 @@ export function subdivideTriangleMesh(
195
223
  points.map(p => p.target),
196
224
  weights
197
225
  );
198
- return Math.hypot(...project(source).map((value, i) => value - linearTarget[i]));
226
+ const exact = project(source);
227
+ keepExact?.push(exact);
228
+ if (!errorMetric) return Math.hypot(...exact.map((value, i) => value - linearTarget[i]));
229
+ const value = errorMetric({source, exact: exact.slice(), interpolated: linearTarget});
230
+ if (!Number.isFinite(value) || value < 0) {
231
+ throw new RangeError('errorMetric must return a finite nonnegative value');
232
+ }
233
+ return value;
234
+ }
235
+
236
+ /** Error at one edge fraction, cached per undirected edge for the neighbouring face.
237
+ * Blending two points is bitwise symmetric, so a->b at f is b->a at 1 - f.
238
+ */
239
+ function edgeError(a: number, b: number, sample: number): number {
240
+ const key = edgeKey(a, b);
241
+ let errors = edgeErrors.get(key);
242
+ if (!errors) {
243
+ errors = [];
244
+ edgeErrors.set(key, errors);
245
+ }
246
+ const slot = a <= b ? sample : EDGE_FRACTIONS.length - 1 - sample;
247
+ let value = errors[slot];
248
+ if (value === undefined) {
249
+ const fraction = EDGE_FRACTIONS[sample];
250
+ // The midpoint sample has the source coordinates that midpoint() would project.
251
+ const keepExact = fraction === 0.5 ? [] : undefined;
252
+ value = error([vertices[a], vertices[b]], [1 - fraction, fraction], keepExact);
253
+ errors[slot] = value;
254
+ if (keepExact) edgeMidpointTargets.set(key, keepExact[0]);
255
+ }
256
+ return value;
199
257
  }
200
258
 
201
259
  function needsRefinement(face: Face): boolean {
202
260
  const points = face.vertices.map(index => vertices[index]);
203
- let exceedsTolerance = false;
261
+ const limit = tolerance ?? Infinity;
204
262
  for (let i = 0; i < 3; i++) {
205
- const a = points[i];
206
- const b = points[(i + 1) % 3];
207
- const length = sourceEdgeLength(a, b);
208
- if (length > maxEdgeLength) exceedsTolerance = true;
209
- for (const fraction of EDGE_FRACTIONS) {
210
- if (error([a, b], [1 - fraction, fraction]) > (tolerance ?? Infinity))
211
- exceedsTolerance = true;
263
+ if (sourceEdgeLength(points[i], points[(i + 1) % 3]) > maxEdgeLength) return true;
264
+ }
265
+ // Midpoints first: a failed face splits all three edges and keeps their projections.
266
+ for (const sample of EDGE_SAMPLE_ORDER) {
267
+ for (let i = 0; i < 3; i++) {
268
+ if (edgeError(face.vertices[i], face.vertices[(i + 1) % 3], sample) > limit) return true;
212
269
  }
213
270
  }
214
271
  for (const weights of FACE_WEIGHTS) {
215
- if (error(points, weights) > (tolerance ?? Infinity)) exceedsTolerance = true;
272
+ if (error(points, weights) > limit) return true;
216
273
  }
217
- return exceedsTolerance;
274
+ return false;
218
275
  }
219
276
 
220
277
  function midpoint(a: number, b: number, midpoints: Map<string, number>): number {
@@ -234,7 +291,7 @@ export function subdivideTriangleMesh(
234
291
  // the original edge endpoints, so at most three source vertices contribute.
235
292
  if (weights.size > 3) throw new Error('Inconsistent mesh provenance');
236
293
  const index = vertices.length;
237
- vertices.push({source, target: project(source), weights});
294
+ vertices.push({source, target: edgeMidpointTargets.get(key) ?? project(source), weights});
238
295
  midpoints.set(key, index);
239
296
  return index;
240
297
  }
@@ -250,8 +307,11 @@ export function subdivideTriangleMesh(
250
307
  const bc = splitEdges.has(edgeKey(b, c)) ? midpoint(b, c, midpoints) : -1;
251
308
  const ca = splitEdges.has(edgeKey(c, a)) ? midpoint(c, a, midpoints) : -1;
252
309
  const count = Number(ab >= 0) + Number(bc >= 0) + Number(ca >= 0);
253
- if (count === 0) emit(a, b, c);
254
- else if (count === 3) {
310
+ if (count === 0) {
311
+ if (output.length >= maxTriangles)
312
+ throw new RangeError('Triangle mesh subdivision exceeded maxTriangles');
313
+ output.push(face);
314
+ } else if (count === 3) {
255
315
  emit(a, ab, ca);
256
316
  emit(ab, b, bc);
257
317
  emit(ca, bc, c);
@@ -0,0 +1,74 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {AttributeInterpolationProvenance} from './interpolate-packed-attributes';
5
+
6
+ /** Compose child→intermediate and intermediate→original barycentric provenance.
7
+ * Interpolate attributes only after composition, avoiding repeated integer rounding.
8
+ * More than three distinct contributors rejects: this contract describes source
9
+ * triangles, not arbitrary sparse blending. Zero-weight indices are ignored.
10
+ */
11
+ export function composeAttributeProvenance(
12
+ parent: AttributeInterpolationProvenance,
13
+ child: AttributeInterpolationProvenance,
14
+ options: {maxVertices?: number} = {}
15
+ ): {sourceVertexIndices: Uint32Array; sourceVertexWeights: Float64Array} {
16
+ const limit = options.maxVertices ?? 65536;
17
+ if (!Number.isSafeInteger(limit) || limit < 0 || limit > 0xffffffff)
18
+ throw new RangeError('Invalid provenance vertex limit');
19
+ validate(parent);
20
+ validate(child, parent.sourceVertexIndices.length / 3);
21
+ if (child.sourceVertexIndices.length / 3 > limit)
22
+ throw new RangeError('Provenance composition exceeded maxVertices');
23
+ const indices = new Uint32Array(child.sourceVertexIndices.length);
24
+ const weights = new Float64Array(indices.length);
25
+ for (let vertex = 0; vertex < indices.length / 3; vertex++) {
26
+ const contributors = new Map<number, number>();
27
+ for (let j = 0; j < 3; j++) {
28
+ const weight = child.sourceVertexWeights[3 * vertex + j];
29
+ if (!weight) continue;
30
+ const intermediate = child.sourceVertexIndices[3 * vertex + j];
31
+ for (let k = 0; k < 3; k++) {
32
+ const w = weight * parent.sourceVertexWeights[3 * intermediate + k];
33
+ if (!w) continue;
34
+ const index = parent.sourceVertexIndices[3 * intermediate + k];
35
+ contributors.set(index, (contributors.get(index) ?? 0) + w);
36
+ }
37
+ }
38
+ if (contributors.size > 3)
39
+ throw new RangeError('Composed vertex spans multiple source triangles');
40
+ const sum = Array.from(contributors.values()).reduce((a, b) => a + b, 0);
41
+ let slot = 3 * vertex;
42
+ for (const [index, weight] of contributors) {
43
+ indices[slot] = index;
44
+ weights[slot++] = weight / sum;
45
+ }
46
+ }
47
+ return {sourceVertexIndices: indices, sourceVertexWeights: weights};
48
+ }
49
+
50
+ function validate(p: AttributeInterpolationProvenance, count = 0x100000000) {
51
+ if (
52
+ !Number.isSafeInteger(p.sourceVertexIndices.length) ||
53
+ p.sourceVertexIndices.length < 0 ||
54
+ p.sourceVertexIndices.length % 3 ||
55
+ p.sourceVertexIndices.length !== p.sourceVertexWeights.length
56
+ )
57
+ throw new RangeError('Invalid provenance lengths');
58
+ for (let i = 0; i < p.sourceVertexIndices.length; i += 3) {
59
+ let sum = 0;
60
+ for (let j = 0; j < 3; j++) {
61
+ const w = p.sourceVertexWeights[i + j],
62
+ index = p.sourceVertexIndices[i + j];
63
+ if (
64
+ !Number.isFinite(w) ||
65
+ w < 0 ||
66
+ w > 1 ||
67
+ (w > 0 && (!Number.isSafeInteger(index) || index < 0 || index >= count))
68
+ )
69
+ throw new RangeError('Invalid provenance contributor');
70
+ sum += w;
71
+ }
72
+ if (Math.abs(sum - 1) > 1e-10) throw new RangeError('Provenance weights must sum to one');
73
+ }
74
+ }
@@ -3,17 +3,16 @@
3
3
  // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
4
 
5
5
  import {Vector3} from '@math.gl/core';
6
- import {GL} from './constants';
7
- import type {Geometry} from './geometry';
6
+ import type {GeometryInput} from './geometry';
8
7
  import {getAttributeValues, getPositionAttribute} from './geometry';
9
8
  import {makePrimitiveIterator} from './primitive-iterator';
10
9
 
11
10
  /** Computes smooth, area-weighted vertex normals for a triangle geometry. */
12
- export function computeVertexNormals(geometry: Geometry): Float32Array {
11
+ export function computeVertexNormals(geometry: GeometryInput): Float32Array {
13
12
  if (
14
- geometry.mode !== GL.TRIANGLES &&
15
- geometry.mode !== GL.TRIANGLE_STRIP &&
16
- geometry.mode !== GL.TRIANGLE_FAN
13
+ geometry.topology !== 'triangle-list' &&
14
+ geometry.topology !== 'triangle-strip' &&
15
+ geometry.topology !== 'triangle-fan'
17
16
  ) {
18
17
  throw new Error('Triangle geometry is required');
19
18
  }
@@ -3,28 +3,54 @@
3
3
  // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
4
 
5
5
  import type {TypedArray} from '@math.gl/core';
6
+ import type {PrimitiveTopology} from '../lib/geometry';
6
7
 
7
8
  /** A typed geometry attribute with either loaders.gl-style `value` or legacy `values` storage. */
8
9
  export type GeometryAttribute = {
10
+ /** Attribute data in canonical storage. */
9
11
  value?: TypedArray;
12
+ /** Alternate field for attribute data. */
10
13
  values?: TypedArray;
14
+ /** Number of components per element. */
11
15
  size?: number;
12
16
  };
13
17
 
14
18
  /** Minimal geometry shape understood by the geometry utilities. */
15
- export type Geometry = {
16
- mode: number;
19
+ export type GeometryInput = {
20
+ /** Connectivity of the indexed or sequential vertices. */
21
+ topology: PrimitiveTopology | 'line-loop' | 'triangle-fan';
22
+ /** Optional vertex indices in a packed array. */
17
23
  indices?: GeometryAttribute | TypedArray;
24
+ /** Vertex attributes keyed by semantic name. */
18
25
  attributes: Record<string, GeometryAttribute>;
19
26
  };
20
27
 
21
28
  /** Returns whether a value has the minimal geometry shape. */
22
- export function isGeometry(value: unknown): value is Geometry {
29
+ export function isGeometry(value: unknown): value is GeometryInput {
23
30
  if (!value || typeof value !== 'object') {
24
31
  return false;
25
32
  }
26
- const geometry = value as Partial<Geometry>;
27
- return typeof geometry.mode === 'number' && Boolean(geometry.attributes);
33
+ const {topology, attributes} = value as Partial<GeometryInput>;
34
+ if (
35
+ !attributes ||
36
+ typeof attributes !== 'object' ||
37
+ Array.isArray(attributes) ||
38
+ ArrayBuffer.isView(attributes)
39
+ ) {
40
+ return false;
41
+ }
42
+ switch (topology) {
43
+ case 'point-list':
44
+ case 'line-list':
45
+ case 'line-strip':
46
+ case 'line-loop':
47
+ case 'triangle-list':
48
+ case 'triangle-strip':
49
+ case 'triangle-fan':
50
+ return true;
51
+ default:
52
+ return false;
53
+ }
28
54
  }
29
55
 
30
56
  /** Returns the typed array stored in a geometry attribute. */
@@ -40,7 +66,7 @@ export function getAttributeValues(attribute: GeometryAttribute | TypedArray): T
40
66
  }
41
67
 
42
68
  /** Returns a geometry's position attribute. */
43
- export function getPositionAttribute(geometry: Geometry): GeometryAttribute {
69
+ export function getPositionAttribute(geometry: GeometryInput): GeometryAttribute {
44
70
  const position = geometry.attributes['POSITION'] || geometry.attributes['positions'];
45
71
  if (!position) {
46
72
  throw new Error('Geometry does not contain a position attribute');