@math.gl/geospatial 5.0.0-beta.10 → 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 (108) hide show
  1. package/dist/crs/index.cjs +54 -0
  2. package/dist/crs/index.cjs.map +2 -2
  3. package/dist/crs/index.d.ts +1 -0
  4. package/dist/crs/index.d.ts.map +1 -1
  5. package/dist/crs/index.js +1 -0
  6. package/dist/crs/index.js.map +1 -1
  7. package/dist/crs/spatial-reference-metadata.d.ts +20 -0
  8. package/dist/crs/spatial-reference-metadata.d.ts.map +1 -0
  9. package/dist/crs/spatial-reference-metadata.js +86 -0
  10. package/dist/crs/spatial-reference-metadata.js.map +1 -0
  11. package/dist/expressions.d.ts +1 -1
  12. package/dist/expressions.d.ts.map +1 -1
  13. package/dist/index.cjs +1030 -104
  14. package/dist/index.cjs.map +3 -3
  15. package/dist/index.d.ts +9 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +8 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/tasks/index.cjs +181 -84
  20. package/dist/tasks/index.cjs.map +2 -2
  21. package/dist/tasks/terrain-residency.d.ts.map +1 -1
  22. package/dist/tasks/terrain-residency.js +80 -18
  23. package/dist/tasks/terrain-residency.js.map +1 -1
  24. package/dist/terrain/cutout-skirts.d.ts +34 -0
  25. package/dist/terrain/cutout-skirts.d.ts.map +1 -0
  26. package/dist/terrain/cutout-skirts.js +29 -0
  27. package/dist/terrain/cutout-skirts.js.map +1 -0
  28. package/dist/terrain/depression-fill.d.ts +25 -0
  29. package/dist/terrain/depression-fill.d.ts.map +1 -0
  30. package/dist/terrain/depression-fill.js +106 -0
  31. package/dist/terrain/depression-fill.js.map +1 -0
  32. package/dist/terrain/hydrology.d.ts +42 -0
  33. package/dist/terrain/hydrology.d.ts.map +1 -0
  34. package/dist/terrain/hydrology.js +112 -0
  35. package/dist/terrain/hydrology.js.map +1 -0
  36. package/dist/terrain/index.cjs +1014 -88
  37. package/dist/terrain/index.cjs.map +3 -3
  38. package/dist/terrain/index.d.ts +10 -1
  39. package/dist/terrain/index.d.ts.map +1 -1
  40. package/dist/terrain/index.js +9 -0
  41. package/dist/terrain/index.js.map +1 -1
  42. package/dist/terrain/lod-screen-error.d.ts +28 -0
  43. package/dist/terrain/lod-screen-error.d.ts.map +1 -0
  44. package/dist/terrain/lod-screen-error.js +95 -0
  45. package/dist/terrain/lod-screen-error.js.map +1 -0
  46. package/dist/terrain/lod-select.d.ts +26 -10
  47. package/dist/terrain/lod-select.d.ts.map +1 -1
  48. package/dist/terrain/lod-select.js +27 -14
  49. package/dist/terrain/lod-select.js.map +1 -1
  50. package/dist/terrain/mesh-cutout.d.ts +40 -0
  51. package/dist/terrain/mesh-cutout.d.ts.map +1 -0
  52. package/dist/terrain/mesh-cutout.js +294 -0
  53. package/dist/terrain/mesh-cutout.js.map +1 -0
  54. package/dist/terrain/mesh-skirts.d.ts +8 -2
  55. package/dist/terrain/mesh-skirts.d.ts.map +1 -1
  56. package/dist/terrain/mesh-skirts.js +5 -4
  57. package/dist/terrain/mesh-skirts.js.map +1 -1
  58. package/dist/terrain/mixed-halo-update.d.ts.map +1 -1
  59. package/dist/terrain/mixed-halo-update.js +58 -23
  60. package/dist/terrain/mixed-halo-update.js.map +1 -1
  61. package/dist/terrain/mixed-vertex-halos.d.ts +24 -1
  62. package/dist/terrain/mixed-vertex-halos.d.ts.map +1 -1
  63. package/dist/terrain/mixed-vertex-halos.js +75 -58
  64. package/dist/terrain/mixed-vertex-halos.js.map +1 -1
  65. package/dist/terrain/regional-viewshed.d.ts +55 -0
  66. package/dist/terrain/regional-viewshed.d.ts.map +1 -0
  67. package/dist/terrain/regional-viewshed.js +119 -0
  68. package/dist/terrain/regional-viewshed.js.map +1 -0
  69. package/dist/terrain/sweep-polytope.d.ts +4 -0
  70. package/dist/terrain/sweep-polytope.d.ts.map +1 -1
  71. package/dist/terrain/sweep-polytope.js +15 -5
  72. package/dist/terrain/sweep-polytope.js.map +1 -1
  73. package/dist/terrain/sweep-rotating-capsule.d.ts +17 -0
  74. package/dist/terrain/sweep-rotating-capsule.d.ts.map +1 -0
  75. package/dist/terrain/sweep-rotating-capsule.js +118 -0
  76. package/dist/terrain/sweep-rotating-capsule.js.map +1 -0
  77. package/dist/terrain/sweep-rotation.d.ts +35 -0
  78. package/dist/terrain/sweep-rotation.d.ts.map +1 -0
  79. package/dist/terrain/sweep-rotation.js +114 -0
  80. package/dist/terrain/sweep-rotation.js.map +1 -0
  81. package/dist/terrain/watershed-accumulation.d.ts +20 -0
  82. package/dist/terrain/watershed-accumulation.d.ts.map +1 -0
  83. package/dist/terrain/watershed-accumulation.js +53 -0
  84. package/dist/terrain/watershed-accumulation.js.map +1 -0
  85. package/dist/turf/expressions.d.ts +1 -1
  86. package/dist/turf/expressions.d.ts.map +1 -1
  87. package/package.json +8 -8
  88. package/src/crs/index.ts +7 -0
  89. package/src/crs/spatial-reference-metadata.ts +118 -0
  90. package/src/expressions.ts +1 -1
  91. package/src/index.ts +57 -0
  92. package/src/tasks/terrain-residency.ts +86 -21
  93. package/src/terrain/cutout-skirts.ts +52 -0
  94. package/src/terrain/depression-fill.ts +125 -0
  95. package/src/terrain/hydrology.ts +149 -0
  96. package/src/terrain/index.ts +61 -1
  97. package/src/terrain/lod-screen-error.ts +128 -0
  98. package/src/terrain/lod-select.ts +65 -31
  99. package/src/terrain/mesh-cutout.ts +358 -0
  100. package/src/terrain/mesh-skirts.ts +10 -7
  101. package/src/terrain/mixed-halo-update.ts +54 -20
  102. package/src/terrain/mixed-vertex-halos.ts +94 -78
  103. package/src/terrain/regional-viewshed.ts +177 -0
  104. package/src/terrain/sweep-polytope.ts +49 -25
  105. package/src/terrain/sweep-rotating-capsule.ts +139 -0
  106. package/src/terrain/sweep-rotation.ts +149 -0
  107. package/src/terrain/watershed-accumulation.ts +67 -0
  108. package/src/turf/expressions.ts +1 -1
@@ -0,0 +1,128 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {ProjectionDepthOptions} from '@math.gl/core';
6
+
7
+ /** Cartesian bounds and a Euclidean bound on displacement from any point in those bounds. */
8
+ export type TerrainLodErrorBounds = {
9
+ /** Lower corner in the input frame of the clip transform. */
10
+ min: readonly [number, number, number];
11
+ /** Upper corner in the input frame of the clip transform. */
12
+ max: readonly [number, number, number];
13
+ /** Maximum Euclidean displacement in input units. */
14
+ geometricError: number;
15
+ };
16
+
17
+ /** Projection parameters for a pixel-error certificate. */
18
+ export type TerrainLodProjection = ProjectionDepthOptions & {
19
+ /** Column-major Cartesian-to-clip matrix. Use a common local frame for matrix and bounds. */
20
+ matrix: ArrayLike<number>;
21
+ /** Viewport width in pixels. */
22
+ width: number;
23
+ /** Viewport height in pixels. */
24
+ height: number;
25
+ };
26
+
27
+ /** Pad outward enough to enclose each binary64 operation, including subnormal results. */
28
+ function slack(value: number): number {
29
+ return Math.abs(value) * (2 * Number.EPSILON) + Number.MIN_VALUE;
30
+ }
31
+
32
+ /** Lower enclosure of a rounded operation. */
33
+ function down(value: number): number {
34
+ return value - slack(value);
35
+ }
36
+
37
+ /** Upper enclosure of a rounded operation. */
38
+ function up(value: number): number {
39
+ return value + slack(value);
40
+ }
41
+
42
+ /** Bound 2D Euclidean pixel displacement under homogeneous projection.
43
+ * Returns Infinity when potentially visible geometry reaches the near plane or W=0,
44
+ * or when arithmetic cannot establish a finite bound. Fully near-clipped pairs
45
+ * and exact zero displacement contribute zero. Side and far clipping are ignored.
46
+ */
47
+ export function boundTerrainLodScreenError(
48
+ bounds: TerrainLodErrorBounds,
49
+ projection: TerrainLodProjection
50
+ ): number {
51
+ if (
52
+ bounds.min.length !== 3 ||
53
+ bounds.max.length !== 3 ||
54
+ !bounds.min.every((value, i) => Number.isFinite(value) && value <= bounds.max[i]) ||
55
+ !bounds.max.every(Number.isFinite) ||
56
+ !Number.isFinite(bounds.geometricError) ||
57
+ bounds.geometricError < 0
58
+ )
59
+ throw new RangeError('Invalid terrain LOD screen-error bounds');
60
+ return prepareTerrainLodScreenError(projection)(bounds);
61
+ }
62
+
63
+ /** @internal Validate and snapshot the camera once per resident cut selection. */
64
+ export function prepareTerrainLodScreenError(projection: TerrainLodProjection) {
65
+ const {width, height, depthRange = 'negative-one-to-one', reversedDepth = false} = projection;
66
+ if (projection.matrix.length !== 16) throw new RangeError('Invalid terrain LOD clip matrix');
67
+ const matrix = Array.from(projection.matrix);
68
+ if (
69
+ !matrix.every(Number.isFinite) ||
70
+ !Number.isFinite(width) ||
71
+ width <= 0 ||
72
+ !Number.isFinite(height) ||
73
+ height <= 0 ||
74
+ (depthRange !== 'negative-one-to-one' && depthRange !== 'zero-to-one')
75
+ )
76
+ throw new RangeError('Invalid terrain LOD projection');
77
+ return ({min, max, geometricError: error}: TerrainLodErrorBounds) => {
78
+ if (error === 0) return 0;
79
+
80
+ /** Enclose each clip row over the AABB and bound the row change for a displacement. */
81
+ function row(index: number) {
82
+ let lower = matrix[12 + index];
83
+ let upper = lower;
84
+ let change = 0;
85
+ for (let axis = 0; axis < 3; axis++) {
86
+ const coefficient = matrix[4 * axis + index];
87
+ const a = coefficient * min[axis];
88
+ const b = coefficient * max[axis];
89
+ lower = down(lower + down(Math.min(a, b)));
90
+ upper = up(upper + up(Math.max(a, b)));
91
+ change = up(change + up(Math.abs(coefficient) * error));
92
+ }
93
+ return {lower, upper, change};
94
+ }
95
+
96
+ const w = row(3);
97
+ const z = row(2);
98
+ // Near clipping uses W-Z for reversed depth, Z for zero-to-one, and Z+W otherwise.
99
+ const nearLow = reversedDepth
100
+ ? down(w.lower - z.upper)
101
+ : depthRange === 'zero-to-one'
102
+ ? z.lower
103
+ : down(z.lower + w.lower);
104
+ const nearHigh = reversedDepth
105
+ ? up(w.upper - z.lower)
106
+ : depthRange === 'zero-to-one'
107
+ ? z.upper
108
+ : up(z.upper + w.upper);
109
+ const nearChange =
110
+ !reversedDepth && depthRange === 'zero-to-one' ? z.change : up(z.change + w.change);
111
+ if (up(nearHigh + nearChange) < 0) return 0;
112
+ const denominator = down(w.lower - w.change);
113
+ if (!(down(nearLow - nearChange) > 0 && denominator > 0)) return Infinity;
114
+
115
+ /** Bound (dX - (X/W)dW) / (W+dW), in pixels. */
116
+ function pixelAxis(index: number, extent: number) {
117
+ const coordinate = row(index);
118
+ const magnitude = Math.max(Math.abs(coordinate.lower), Math.abs(coordinate.upper));
119
+ const ndc = up(magnitude / denominator);
120
+ const coupling = up(ndc * w.change);
121
+ const numerator = up(coordinate.change + coupling);
122
+ return up(up(numerator / denominator) * up(extent / 2));
123
+ }
124
+ // The L1 norm bounds the Euclidean norm without assuming the axis maxima coincide.
125
+ const pixels = pixelAxis(0, width) + pixelAxis(1, height);
126
+ return Number.isFinite(pixels) ? up(pixels) : Infinity;
127
+ };
128
+ }
@@ -2,48 +2,60 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
4
 
5
+ import {
6
+ prepareTerrainLodScreenError,
7
+ type TerrainLodErrorBounds,
8
+ type TerrainLodProjection
9
+ } from './lod-screen-error';
10
+
11
+ /** Cartesian coordinate triple. */
5
12
  type XYZ = readonly [number, number, number];
6
13
 
7
- export type TerrainLodCandidate = {
14
+ /** A tile and its error bound in the selector's Cartesian frame. */
15
+ export type TerrainLodCandidate = TerrainLodErrorBounds & {
16
+ /** Unique tile identifier within the tree. */
8
17
  id: string;
9
- min: XYZ;
10
- max: XYZ;
11
- /** World-space geometric error for this tile. */
12
- geometricError: number;
18
+ /** Whether this tile is available to render. */
13
19
  resident: boolean;
14
20
  /** Children must completely partition the parent terrain footprint. */
15
21
  children?: readonly TerrainLodCandidate[];
16
22
  };
17
23
 
18
- export type TerrainLodView = {
19
- position: XYZ;
20
- verticalFov: number;
21
- viewportHeight: number;
24
+ /** Controls shared by both LOD selection modes. */
25
+ type TerrainLodSelectionOptions = {
26
+ /** Maximum desired pixel error. */
22
27
  targetPixels: number;
23
28
  /** Fractional threshold reduction for previously refined tiles. */
24
29
  hysteresis?: number;
30
+ /** Tile IDs that refined in the previous selection. */
25
31
  previouslyRefined?: ReadonlySet<string>;
32
+ /** Maximum number of candidates visited during selection. */
26
33
  maxVisited?: number;
27
34
  };
28
35
 
36
+ /** Camera parameters for the distance-based pixel estimate. */
37
+ export type TerrainLodView = TerrainLodSelectionOptions & {
38
+ /** Camera position in the same frame as tile bounds. */
39
+ position: XYZ;
40
+ /** Vertical field of view in radians. */
41
+ verticalFov: number;
42
+ /** Viewport height in pixels. */
43
+ viewportHeight: number;
44
+ };
45
+
46
+ /** View using a conservative projection bound for LOD selection. */
47
+ export type TerrainLodCertifiedView = TerrainLodSelectionOptions & {
48
+ /** Cartesian-to-clip transform and viewport. */
49
+ projection: TerrainLodProjection;
50
+ };
51
+
29
52
  /** Select a resident cut using perspective screen-space error and complete child fallback. */
30
- export function selectTerrainLod(roots: readonly TerrainLodCandidate[], view: TerrainLodView) {
31
- const {
32
- position,
33
- verticalFov,
34
- viewportHeight,
35
- targetPixels,
36
- hysteresis = 0.2,
37
- previouslyRefined,
38
- maxVisited = 100_000
39
- } = view;
53
+ export function selectTerrainLod(
54
+ roots: readonly TerrainLodCandidate[],
55
+ view: TerrainLodView | TerrainLodCertifiedView
56
+ ) {
57
+ const {targetPixels, hysteresis = 0.2, previouslyRefined, maxVisited = 100_000} = view;
40
58
  if (
41
- !position.every(Number.isFinite) ||
42
- !Number.isFinite(verticalFov) ||
43
- verticalFov <= 0 ||
44
- verticalFov >= Math.PI ||
45
- !Number.isFinite(viewportHeight) ||
46
- viewportHeight <= 0 ||
47
59
  !Number.isFinite(targetPixels) ||
48
60
  targetPixels <= 0 ||
49
61
  !(hysteresis >= 0 && hysteresis < 1) ||
@@ -51,8 +63,10 @@ export function selectTerrainLod(roots: readonly TerrainLodCandidate[], view: Te
51
63
  maxVisited < 1
52
64
  )
53
65
  throw new Error('Invalid terrain LOD view');
54
- const scale = viewportHeight / (2 * Math.tan(verticalFov / 2));
55
- if (!Number.isFinite(scale)) throw new Error('Terrain LOD projection scale overflow');
66
+ const pixelError =
67
+ 'projection' in view
68
+ ? prepareTerrainLodScreenError(view.projection)
69
+ : createDistanceEstimator(view.position, view.verticalFov, view.viewportHeight);
56
70
  const selected: {tile: TerrainLodCandidate; pixels: number}[] = [];
57
71
  const refined = new Set<string>();
58
72
  const unavailable: string[] = [];
@@ -64,6 +78,8 @@ export function selectTerrainLod(roots: readonly TerrainLodCandidate[], view: Te
64
78
  if (seen.has(tile.id)) throw new Error('Duplicate terrain LOD tile or cycle');
65
79
  seen.add(tile.id);
66
80
  if (
81
+ tile.min.length !== 3 ||
82
+ tile.max.length !== 3 ||
67
83
  ![...tile.min, ...tile.max, tile.geometricError].every(Number.isFinite) ||
68
84
  tile.geometricError < 0 ||
69
85
  tile.min.some((n, i) => n > tile.max[i])
@@ -73,10 +89,7 @@ export function selectTerrainLod(roots: readonly TerrainLodCandidate[], view: Te
73
89
  unavailable.push(tile.id);
74
90
  continue;
75
91
  }
76
- const distance = Math.hypot(
77
- ...position.map((n, i) => Math.max(tile.min[i] - n, n - tile.max[i], 0))
78
- );
79
- const pixels = tile.geometricError === 0 ? 0 : (tile.geometricError / distance) * scale;
92
+ const pixels = pixelError(tile);
80
93
  const threshold = targetPixels * (previouslyRefined?.has(tile.id) ? 1 - hysteresis : 1);
81
94
  if (
82
95
  pixels > threshold &&
@@ -93,3 +106,24 @@ export function selectTerrainLod(roots: readonly TerrainLodCandidate[], view: Te
93
106
  }
94
107
  return {selected, refined, unavailable};
95
108
  }
109
+
110
+ /** Prepare the legacy distance-based pixel estimate. */
111
+ function createDistanceEstimator(position: XYZ, verticalFov: number, viewportHeight: number) {
112
+ if (
113
+ !position.every(Number.isFinite) ||
114
+ !Number.isFinite(verticalFov) ||
115
+ verticalFov <= 0 ||
116
+ verticalFov >= Math.PI ||
117
+ !Number.isFinite(viewportHeight) ||
118
+ viewportHeight <= 0
119
+ )
120
+ throw new Error('Invalid terrain LOD view');
121
+ const scale = viewportHeight / (2 * Math.tan(verticalFov / 2));
122
+ if (!Number.isFinite(scale)) throw new Error('Terrain LOD projection scale overflow');
123
+ return (tile: TerrainLodCandidate) => {
124
+ const distance = Math.hypot(
125
+ ...position.map((n, i) => Math.max(tile.min[i] - n, n - tile.max[i], 0))
126
+ );
127
+ return tile.geometricError === 0 ? 0 : (tile.geometricError / distance) * scale;
128
+ };
129
+ }
@@ -0,0 +1,358 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ type XY = readonly [number, number];
6
+ type XYZ = readonly [number, number, number];
7
+ type Face = [number, number, number];
8
+ type Edge = [number, number];
9
+
10
+ /** Indexed upward-facing terrain in a shared local Cartesian frame. */
11
+ export type TerrainCutoutInput = {
12
+ positions: Float32Array | Float64Array;
13
+ indices: Uint16Array | Uint32Array;
14
+ };
15
+
16
+ /** A detached surface with interpolation provenance in the original mesh. */
17
+ export type TerrainCutoutPiece = {
18
+ positions: Float64Array;
19
+ indices: Uint32Array;
20
+ /** Input triangle index for each output vertex. */
21
+ sourceTriangles: Uint32Array;
22
+ /** Three barycentric weights per output vertex in input triangle order. */
23
+ sourceWeights: Float64Array;
24
+ /** Input triangle index for each output triangle. */
25
+ sourceFaces: Uint32Array;
26
+ /** Directed boundary edges paired with the other piece in reverse order. */
27
+ cutEdges: Uint32Array;
28
+ };
29
+
30
+ /** Bounds for the splitter's working storage and pair/fragment checks. */
31
+ export type TerrainCutoutOptions = {
32
+ /** Maximum candidate topology checks and clipping vertex visits. */
33
+ maxWork?: number;
34
+ /** Maximum working vertices and, independently, total output vertices. */
35
+ maxVertices?: number;
36
+ /** Maximum intermediate fragments and, independently, total output triangles. */
37
+ maxTriangles?: number;
38
+ };
39
+
40
+ /** Both sides of a convex cut, with matching directed edges along the opening. */
41
+ export type TerrainCutout = {patch: TerrainCutoutPiece; remainder: TerrainCutoutPiece};
42
+
43
+ type Fragment = {ids: number[]; inside: boolean};
44
+ type Boundary = {edge: Edge; count: number};
45
+ type PieceBuilder = {
46
+ ids: Map<number, number>;
47
+ positions: number[];
48
+ indices: number[];
49
+ sourceTriangles: number[];
50
+ sourceWeights: number[];
51
+ sourceFaces: number[];
52
+ boundary: Map<string, Boundary>;
53
+ cutEdges: number[];
54
+ };
55
+
56
+ /** Split a conforming 2.5D terrain mesh by a strictly convex ring in local XY.
57
+ * Either ring winding is accepted. Ring vertices must omit a closing duplicate.
58
+ * Rejects overlapping sheets, nonconforming edges and unrepresentable slivers.
59
+ */
60
+ export function splitTerrainMesh(
61
+ mesh: TerrainCutoutInput,
62
+ polygon: readonly XY[],
63
+ {maxWork = 4_000_000, maxVertices = 500_000, maxTriangles = 500_000}: TerrainCutoutOptions = {}
64
+ ): TerrainCutout {
65
+ if (
66
+ ![maxWork, maxVertices, maxTriangles].every(n => Number.isSafeInteger(n) && n >= 0) ||
67
+ maxVertices > 0xffffffff ||
68
+ maxTriangles > 0xffffffff ||
69
+ !(mesh.positions instanceof Float32Array || mesh.positions instanceof Float64Array) ||
70
+ !(mesh.indices instanceof Uint16Array || mesh.indices instanceof Uint32Array) ||
71
+ mesh.positions.length % 3 ||
72
+ mesh.indices.length % 3 ||
73
+ mesh.positions.length / 3 > maxVertices ||
74
+ mesh.indices.length / 3 > maxTriangles ||
75
+ !mesh.positions.every(Number.isFinite)
76
+ )
77
+ throw new RangeError('Invalid terrain cutout mesh or capacity');
78
+
79
+ let work = 0;
80
+ /** Charge bounded work before performing a topology or clipping operation. */
81
+ function charge(amount: number) {
82
+ work += amount;
83
+ if (work > maxWork) throw new RangeError('Terrain cutout work budget exceeded');
84
+ }
85
+
86
+ const ring = validatePolygon(polygon, charge);
87
+ const vertices: XYZ[] = [];
88
+ for (let i = 0; i < mesh.positions.length; i += 3)
89
+ vertices.push([mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2]]);
90
+ const faces: Face[] = [];
91
+ for (let i = 0; i < mesh.indices.length; i += 3) {
92
+ const face: Face = [mesh.indices[i], mesh.indices[i + 1], mesh.indices[i + 2]];
93
+ if (face.some(id => id >= vertices.length))
94
+ throw new RangeError('Invalid terrain cutout index');
95
+ checkTriangle(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
96
+ faces.push(face);
97
+ }
98
+ validateTopology(vertices, faces, charge);
99
+
100
+ const patch = createPiece();
101
+ const remainder = createPiece();
102
+ const intersections = ring.map(() => new Map<string, number>());
103
+ let fragmentCount = 0;
104
+
105
+ /** Allocate a vertex once for both pieces and every incident fragment. */
106
+ function addVertex(vertex: XYZ) {
107
+ if (vertices.length >= maxVertices || !vertex.every(Number.isFinite))
108
+ throw new RangeError('Terrain cutout vertex budget or coordinate range exceeded');
109
+ return vertices.push(vertex) - 1;
110
+ }
111
+
112
+ /** Get the same intersection even when a shared edge is traversed backwards. */
113
+ function intersection(a: number, b: number, da: number, db: number, line: number) {
114
+ const key = edgeKey(a, b);
115
+ const cache = intersections[line];
116
+ const saved = cache.get(key);
117
+ if (saved !== undefined) return saved;
118
+ const t = Math.abs(da) / (Math.abs(da) + Math.abs(db));
119
+ if (!(t > 0 && t < 1)) throw new RangeError('Unrepresentable terrain cut intersection');
120
+ const u = vertices[a];
121
+ const v = vertices[b];
122
+ const id = addVertex([
123
+ u[0] + t * (v[0] - u[0]),
124
+ u[1] + t * (v[1] - u[1]),
125
+ u[2] + t * (v[2] - u[2])
126
+ ]);
127
+ cache.set(key, id);
128
+ return id;
129
+ }
130
+
131
+ for (let source = 0; source < faces.length; source++) {
132
+ let fragments: Fragment[] = [{ids: faces[source], inside: true}];
133
+ // Split both sides by every supporting line. This preserves matching
134
+ // subdivisions on remainder edges beyond the finite polygon segments.
135
+ for (let line = 0; line < ring.length; line++) {
136
+ const next: Fragment[] = [];
137
+ const a = ring[line];
138
+ const b = ring[(line + 1) % ring.length];
139
+ for (const fragment of fragments) {
140
+ const {ids} = fragment;
141
+ charge(ids.length);
142
+ const distances = ids.map(id => cross(a, b, vertices[id]));
143
+ if (distances.some(d => !Number.isFinite(d)))
144
+ throw new RangeError('Invalid terrain cut coordinates');
145
+ if (!distances.some(d => d < 0)) next.push(fragment);
146
+ else if (!distances.some(d => d > 0)) next.push({...fragment, inside: false});
147
+ else {
148
+ const positive: number[] = [];
149
+ const negative: number[] = [];
150
+ for (let i = 0; i < ids.length; i++) {
151
+ const j = (i + 1) % ids.length;
152
+ const d = distances[i];
153
+ const e = distances[j];
154
+ if (d >= 0) positive.push(ids[i]);
155
+ if (d <= 0) negative.push(ids[i]);
156
+ if ((d < 0 && e > 0) || (d > 0 && e < 0)) {
157
+ const id = intersection(ids[i], ids[j], d, e, line);
158
+ positive.push(id);
159
+ negative.push(id);
160
+ }
161
+ }
162
+ next.push({ids: positive, inside: fragment.inside}, {ids: negative, inside: false});
163
+ }
164
+ if (fragmentCount + next.length > maxTriangles)
165
+ throw new RangeError('Terrain cutout fragment budget exceeded');
166
+ }
167
+ fragments = next;
168
+ }
169
+ fragmentCount += fragments.length;
170
+ for (const {ids, inside} of fragments) {
171
+ const piece = inside ? patch : remainder;
172
+ if (ids.length === 3) emit(piece, ids as Face, source);
173
+ else {
174
+ // A center fan retains collinear boundary vertices and therefore pairs
175
+ // every constrained boundary segment with its neighbor.
176
+ const center = [...vertices[ids[0]]] as [number, number, number];
177
+ for (const id of ids) {
178
+ for (let k = 0; k < 3; k++)
179
+ center[k] += (vertices[id][k] - vertices[ids[0]][k]) / ids.length;
180
+ }
181
+ const hub = addVertex(center);
182
+ for (let i = 0; i < ids.length; i++)
183
+ emit(piece, [ids[i], ids[(i + 1) % ids.length], hub], source);
184
+ }
185
+ }
186
+ }
187
+
188
+ /** Emit a triangle and weld all of its edges by their shared topology IDs. */
189
+ function emit(piece: PieceBuilder, face: Face, source: number) {
190
+ if (patch.sourceFaces.length + remainder.sourceFaces.length >= maxTriangles)
191
+ throw new RangeError('Terrain cutout triangle budget exceeded');
192
+ checkTriangle(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
193
+ const [a, b, c] = faces[source].map(id => vertices[id]);
194
+ const area = cross(a, b, c);
195
+ for (let i = 0; i < 3; i++) {
196
+ const id = face[i];
197
+ if (!piece.ids.has(id)) {
198
+ if (patch.ids.size + remainder.ids.size >= maxVertices)
199
+ throw new RangeError('Terrain cutout output vertex budget exceeded');
200
+ piece.ids.set(id, piece.ids.size);
201
+ const p = vertices[id];
202
+ piece.positions.push(...p);
203
+ piece.sourceTriangles.push(source);
204
+ piece.sourceWeights.push(
205
+ cross(b, c, p) / area,
206
+ cross(c, a, p) / area,
207
+ cross(a, b, p) / area
208
+ );
209
+ }
210
+ piece.indices.push(piece.ids.get(id)!);
211
+ addEdge(piece.boundary, id, face[(i + 1) % 3]);
212
+ }
213
+ piece.sourceFaces.push(source);
214
+ }
215
+
216
+ for (const [key, inside] of patch.boundary) {
217
+ const outside = remainder.boundary.get(key);
218
+ if (!outside) continue;
219
+ const [a, b] = inside.edge;
220
+ if (inside.count !== 1 || outside.count !== 1 || outside.edge[0] !== b)
221
+ throw new Error('Nonconforming terrain cut boundary');
222
+ patch.cutEdges.push(patch.ids.get(a)!, patch.ids.get(b)!);
223
+ remainder.cutEdges.push(remainder.ids.get(b)!, remainder.ids.get(a)!);
224
+ }
225
+ return {patch: finish(patch), remainder: finish(remainder)};
226
+ }
227
+
228
+ /** Validate a simple strictly convex ring and normalize it to CCW. */
229
+ function validatePolygon(polygon: readonly XY[], charge: (amount: number) => void): XY[] {
230
+ if (polygon.length < 3 || polygon.some(p => p.length !== 2 || !p.every(Number.isFinite)))
231
+ throw new RangeError('Invalid terrain cut polygon');
232
+ const ring = [...polygon];
233
+ const orientation = cross(ring[0], ring[1], ring[2]);
234
+ if (orientation < 0) ring.reverse();
235
+ for (let i = 0; i < ring.length; i++) {
236
+ charge(ring.length);
237
+ const j = (i + 1) % ring.length;
238
+ for (let k = 0; k < ring.length; k++) {
239
+ if (k === i || k === j) continue;
240
+ const area = cross(ring[i], ring[j], ring[k]);
241
+ if (!(area > 0 && Number.isFinite(area)))
242
+ throw new RangeError('Terrain cut polygon must be strictly convex');
243
+ }
244
+ }
245
+ return ring;
246
+ }
247
+
248
+ /** Match TerrainSurface's relative degeneracy threshold without constructing an index. */
249
+ function checkTriangle(a: XYZ, b: XYZ, c: XYZ) {
250
+ const area = cross(a, b, c);
251
+ const scale = Math.hypot(b[0] - a[0], b[1] - a[1]) * Math.hypot(c[0] - a[0], c[1] - a[1]);
252
+ if (!(area > Number.EPSILON * scale && Number.isFinite(area)))
253
+ throw new RangeError('Terrain cut requires upward nondegenerate XY triangles');
254
+ }
255
+
256
+ /** Reject nonmanifold edges, overlaps and hanging vertices using an XY sweep. */
257
+ function validateTopology(vertices: XYZ[], faces: Face[], charge: (amount: number) => void) {
258
+ const edges = new Map<string, Boundary>();
259
+ const boxes = faces
260
+ .map(face => {
261
+ for (let i = 0; i < 3; i++) addEdge(edges, face[i], face[(i + 1) % 3]);
262
+ const points = face.map(id => vertices[id]);
263
+ return {
264
+ face,
265
+ points,
266
+ low: Math.min(...points.map(p => p[0])),
267
+ high: Math.max(...points.map(p => p[0])),
268
+ minY: Math.min(...points.map(p => p[1])),
269
+ maxY: Math.max(...points.map(p => p[1]))
270
+ };
271
+ })
272
+ .sort((a, b) => a.low - b.low);
273
+ for (let i = 0; i < boxes.length; i++) {
274
+ const a = boxes[i];
275
+ for (let j = i + 1; j < boxes.length && boxes[j].low <= a.high; j++) {
276
+ charge(1);
277
+ const b = boxes[j];
278
+ if (a.maxY < b.minY || b.maxY < a.minY) continue;
279
+ if (!separates(a.points, b.points) && !separates(b.points, a.points))
280
+ throw new RangeError('Terrain cut input has overlapping XY triangles');
281
+ checkJunctions(a.face, b.face, vertices);
282
+ checkJunctions(b.face, a.face, vertices);
283
+ }
284
+ }
285
+ }
286
+
287
+ /** Find a triangle edge whose exterior closed half-plane contains the other triangle. */
288
+ function separates(a: XYZ[], b: XYZ[]) {
289
+ return a.some((p, i) => b.every(q => cross(p, a[(i + 1) % 3], q) <= 0));
290
+ }
291
+
292
+ /** Reject a hanging vertex or coincident edge with distinct topology IDs. */
293
+ function checkJunctions(a: Face, b: Face, vertices: XYZ[]) {
294
+ for (let i = 0; i < 3; i++) {
295
+ const u = vertices[a[i]];
296
+ const v = vertices[a[(i + 1) % 3]];
297
+ const overlaps = b.filter(id => {
298
+ const p = vertices[id];
299
+ if (cross(u, v, p) !== 0) return false;
300
+ const axis = Math.abs(v[0] - u[0]) >= Math.abs(v[1] - u[1]) ? 0 : 1;
301
+ const low = Math.min(u[axis], v[axis]);
302
+ const high = Math.max(u[axis], v[axis]);
303
+ if (p[axis] > low && p[axis] < high)
304
+ throw new RangeError('Terrain cut input has a T-junction');
305
+ return p[axis] >= low && p[axis] <= high;
306
+ });
307
+ if (overlaps.length >= 2 && (!overlaps.includes(a[i]) || !overlaps.includes(a[(i + 1) % 3])))
308
+ throw new RangeError('Terrain cut input has an unwelded shared edge');
309
+ }
310
+ }
311
+
312
+ /** Track the first direction and incidence count of an indexed edge. */
313
+ function addEdge(edges: Map<string, Boundary>, a: number, b: number) {
314
+ const key = edgeKey(a, b);
315
+ const entry = edges.get(key);
316
+ if (!entry) edges.set(key, {edge: [a, b], count: 1});
317
+ else {
318
+ if (entry.count !== 1 || entry.edge[0] !== b)
319
+ throw new RangeError('Terrain cut mesh has inconsistent or nonmanifold edges');
320
+ entry.count++;
321
+ }
322
+ }
323
+
324
+ /** Shared key independent of the edge direction. */
325
+ function edgeKey(a: number, b: number) {
326
+ return a < b ? a + ',' + b : b + ',' + a;
327
+ }
328
+
329
+ /** Signed doubled triangle area in local XY. */
330
+ function cross(a: XY | XYZ, b: XY | XYZ, c: XY | XYZ) {
331
+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
332
+ }
333
+
334
+ /** Allocate detached output staging buffers. */
335
+ function createPiece(): PieceBuilder {
336
+ return {
337
+ ids: new Map(),
338
+ positions: [],
339
+ indices: [],
340
+ sourceTriangles: [],
341
+ sourceWeights: [],
342
+ sourceFaces: [],
343
+ boundary: new Map(),
344
+ cutEdges: []
345
+ };
346
+ }
347
+
348
+ /** Materialize the public typed arrays. */
349
+ function finish(piece: PieceBuilder): TerrainCutoutPiece {
350
+ return {
351
+ positions: Float64Array.from(piece.positions),
352
+ indices: Uint32Array.from(piece.indices),
353
+ sourceTriangles: Uint32Array.from(piece.sourceTriangles),
354
+ sourceWeights: Float64Array.from(piece.sourceWeights),
355
+ sourceFaces: Uint32Array.from(piece.sourceFaces),
356
+ cutEdges: Uint32Array.from(piece.cutEdges)
357
+ };
358
+ }
@@ -2,9 +2,11 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
4
 
5
- export type TerrainSkirtOptions = {
6
- /** Positive downward distance in the same units as positions. */
7
- height: number;
5
+ type TerrainSkirtVertical =
6
+ | {/** Positive downward distance. */ height: number; baseZ?: never}
7
+ | {/** Local elevation below every selected boundary vertex. */ baseZ: number; height?: never};
8
+
9
+ export type TerrainSkirtOptions = TerrainSkirtVertical & {
8
10
  /** Optional unordered pairs of boundary vertex IDs. Omit to skirt every boundary, including holes. */
9
11
  edges?: Uint16Array | Uint32Array;
10
12
  maxVertices?: number;
@@ -33,12 +35,13 @@ export function createTerrainSkirt(
33
35
  options: TerrainSkirtOptions
34
36
  ): TerrainSkirtMesh {
35
37
  const {positions, indices} = mesh,
36
- {height, edges} = options;
38
+ {height, baseZ, edges} = options;
37
39
  const maxVertices = options.maxVertices ?? 2_000_000,
38
40
  maxTriangles = options.maxTriangles ?? 4_000_000;
39
41
  if (
40
- !Number.isFinite(height) ||
41
- height <= 0 ||
42
+ (baseZ === undefined
43
+ ? !(Number.isFinite(height) && height! > 0)
44
+ : height !== undefined || !Number.isFinite(baseZ)) ||
42
45
  !Number.isSafeInteger(maxVertices) ||
43
46
  maxVertices < 0 ||
44
47
  maxVertices > 0xffffffff ||
@@ -133,7 +136,7 @@ export function createTerrainSkirt(
133
136
  [b, lowerB]
134
137
  ]) {
135
138
  resultPositions.set(positions.subarray(3 * source, 3 * source + 3), 3 * target);
136
- resultPositions[3 * target + 2] = positions[3 * source + 2] - height;
139
+ resultPositions[3 * target + 2] = baseZ ?? positions[3 * source + 2] - height!;
137
140
  if (
138
141
  !Number.isFinite(resultPositions[3 * target + 2]) ||
139
142
  resultPositions[3 * target + 2] >= positions[3 * source + 2]