@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
package/dist/index.cjs CHANGED
@@ -73,6 +73,7 @@ __export(index_exports, {
73
73
  TerrainContourBoundaryAxis: () => TerrainContourBoundaryAxis,
74
74
  TerrainMorphStatus: () => TerrainMorphStatus,
75
75
  TerrainProfileViewStatus: () => TerrainProfileViewStatus,
76
+ TerrainRegionalViewStatus: () => TerrainRegionalViewStatus,
76
77
  TerrainSampleStatus: () => TerrainSampleStatus,
77
78
  TerrainSurface: () => TerrainSurface,
78
79
  TerrainVertexHaloStatus: () => TerrainVertexHaloStatus,
@@ -81,8 +82,10 @@ __export(index_exports, {
81
82
  WKTCRSSyntaxError: () => WKTCRSSyntaxError,
82
83
  WKTCRSValidationError: () => WKTCRSValidationError,
83
84
  WebMercatorViewport: () => web_mercator_exports.WebMercatorViewport,
85
+ accumulateTerrainWatersheds: () => accumulateTerrainWatersheds,
84
86
  addMetersToLngLat: () => web_mercator_exports.addMetersToLngLat,
85
87
  altitudeToFovy: () => web_mercator_exports.altitudeToFovy,
88
+ boundTerrainLodScreenError: () => boundTerrainLodScreenError,
86
89
  boundTerrainMeshError: () => boundTerrainMeshError,
87
90
  certifyTerrainMeshCoverage: () => certifyTerrainMeshCoverage,
88
91
  clipGeographicPolygon: () => clipGeographicPolygon,
@@ -101,6 +104,8 @@ __export(index_exports, {
101
104
  createOrthographicCutAtlas: () => createOrthographicCutAtlas,
102
105
  createSpatialReference: () => createSpatialReference,
103
106
  createTerrainContours: () => createTerrainContours,
107
+ createTerrainCutoutSkirts: () => createTerrainCutoutSkirts,
108
+ createTerrainDrainage: () => createTerrainDrainage,
104
109
  createTerrainFilteredPyramid: () => createTerrainFilteredPyramid,
105
110
  createTerrainGradientGrid: () => createTerrainGradientGrid,
106
111
  createTerrainGradientPyramid: () => createTerrainGradientPyramid,
@@ -109,6 +114,7 @@ __export(index_exports, {
109
114
  createTerrainMesh: () => createTerrainMesh,
110
115
  createTerrainMixedIsobands: () => createTerrainMixedIsobands,
111
116
  createTerrainMixedVertexTileHalos: () => createTerrainMixedVertexTileHalos,
117
+ createTerrainRegionalViewshed: () => createTerrainRegionalViewshed,
112
118
  createTerrainSkirt: () => createTerrainSkirt,
113
119
  createTerrainSlopeAspectGrid: () => createTerrainSlopeAspectGrid,
114
120
  createTerrainSurface: () => createTerrainSurface,
@@ -121,6 +127,7 @@ __export(index_exports, {
121
127
  encodePROJString: () => encodePROJString,
122
128
  encodeWKTCRS: () => encodeWKTCRS,
123
129
  evaluateTerrainLodMorph: () => evaluateTerrainLodMorph,
130
+ fillTerrainDepressions: () => fillTerrainDepressions,
124
131
  fitBounds: () => web_mercator_exports.fitBounds,
125
132
  flyToViewport: () => web_mercator_exports.flyToViewport,
126
133
  formatAngle: () => formatAngle,
@@ -141,6 +148,7 @@ __export(index_exports, {
141
148
  getMeterZoom: () => web_mercator_exports.getMeterZoom,
142
149
  getProjectionMatrix: () => web_mercator_exports.getProjectionMatrix,
143
150
  getProjectionParameters: () => web_mercator_exports.getProjectionParameters,
151
+ getTerrainCellMetrics: () => getTerrainCellMetrics,
144
152
  getTerrainHierarchyNode: () => getTerrainHierarchyNode,
145
153
  getTerrainMeshEdge: () => getTerrainMeshEdge,
146
154
  getTerrainProfileHorizon: () => getTerrainProfileHorizon,
@@ -187,6 +195,7 @@ __export(index_exports, {
187
195
  splitGeographicPolyline: () => splitGeographicPolyline,
188
196
  splitGlobeBounds: () => splitGlobeBounds,
189
197
  splitTerrainBreaklines: () => splitTerrainBreaklines,
198
+ splitTerrainMesh: () => splitTerrainMesh,
190
199
  standardGridZone: () => standardGridZone,
191
200
  stitchTerrainContourTiles: () => stitchTerrainContourTiles,
192
201
  stitchTerrainContours: () => stitchTerrainContours,
@@ -201,6 +210,10 @@ __export(index_exports, {
201
210
  sweepTerrainCylinder: () => sweepTerrainCylinder,
202
211
  sweepTerrainPlane: () => sweepTerrainPlane,
203
212
  sweepTerrainPolytope: () => sweepTerrainPolytope,
213
+ sweepTerrainRotatingBox: () => sweepTerrainRotatingBox,
214
+ sweepTerrainRotatingCapsule: () => sweepTerrainRotatingCapsule,
215
+ sweepTerrainRotatingPolytope: () => sweepTerrainRotatingPolytope,
216
+ sweepTerrainRotatingSphere: () => sweepTerrainRotatingSphere,
204
217
  sweepTerrainSphere: () => sweepTerrainSphere,
205
218
  sweepTerrainTaperedCapsule: () => sweepTerrainTaperedCapsule,
206
219
  sweepTerrainTriangleMesh: () => sweepTerrainTriangleMesh,
@@ -1082,10 +1095,10 @@ geodesic.Accumulator = {};
1082
1095
  return Math.abs(x) * (y < 0 || y === 0 && 1 / y < 0 ? -1 : 1);
1083
1096
  };
1084
1097
  m.sum = function(u, v) {
1085
- var s = u + v, up = s - v, vpp = s - up, t;
1086
- up -= u;
1098
+ var s = u + v, up2 = s - v, vpp = s - up2, t;
1099
+ up2 -= u;
1087
1100
  vpp -= v;
1088
- t = s ? 0 - (up + vpp) : s;
1101
+ t = s ? 0 - (up2 + vpp) : s;
1089
1102
  return { s, t };
1090
1103
  };
1091
1104
  m.polyval = function(N, p, s, x) {
@@ -4035,16 +4048,16 @@ function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, car
4035
4048
  const atPole = Math.abs(origin.x) <= poleTolerance && Math.abs(origin.y) <= poleTolerance;
4036
4049
  const radii = ellipsoid.radii;
4037
4050
  if (radii.x === radii.y && radii.x > 0 && radii.z > 0 && radii.z <= radii.x && (!atPole || origin.z !== 0)) {
4038
- const { east, up } = scratchAxisVectors;
4051
+ const { east, up: up2 } = scratchAxisVectors;
4039
4052
  if (atPole) {
4040
4053
  east.set(0, 1, 0);
4041
- up.set(0, 0, Math.sign(origin.z));
4054
+ up2.set(0, 0, Math.sign(origin.z));
4042
4055
  } else {
4043
4056
  const scale3 = Math.max(Math.abs(origin.x), Math.abs(origin.y));
4044
4057
  east.set(-origin.y / scale3, origin.x / scale3, 0).normalize();
4045
- ellipsoid.geodeticSurfaceNormal(origin, up);
4058
+ ellipsoid.geodeticSurfaceNormal(origin, up2);
4046
4059
  }
4047
- if (!(0, import_core9.eastNorthUpBasisFromDirections)(east, up, scratchBasis) || !(0, import_core9.localFrameToMatrix)(scratchBasis, origin, firstAxis, secondAxis, thirdAxis, result))
4060
+ if (!(0, import_core9.eastNorthUpBasisFromDirections)(east, up2, scratchBasis) || !(0, import_core9.localFrameToMatrix)(scratchBasis, origin, firstAxis, secondAxis, thirdAxis, result))
4048
4061
  throw new Error("Unsupported local frame");
4049
4062
  return result;
4050
4063
  }
@@ -4063,13 +4076,13 @@ function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, car
4063
4076
  thirdAxisVector.scale(sign2);
4064
4077
  }
4065
4078
  } else {
4066
- const { up, east, north } = scratchAxisVectors;
4079
+ const { up: up2, east, north } = scratchAxisVectors;
4067
4080
  const scale3 = Math.max(Math.abs(origin.x), Math.abs(origin.y));
4068
4081
  east.set(-origin.y / scale3, origin.x / scale3, 0).normalize();
4069
- ellipsoid.geodeticSurfaceNormal(origin, up);
4070
- north.copy(up).cross(east);
4071
- const { down, west, south } = scratchAxisVectors;
4072
- down.copy(up).scale(-1);
4082
+ ellipsoid.geodeticSurfaceNormal(origin, up2);
4083
+ north.copy(up2).cross(east);
4084
+ const { down: down2, west, south } = scratchAxisVectors;
4085
+ down2.copy(up2).scale(-1);
4073
4086
  west.copy(east).scale(-1);
4074
4087
  south.copy(north).scale(-1);
4075
4088
  firstAxisVector = scratchAxisVectors[firstAxis];
@@ -8039,8 +8052,8 @@ function createOctahedralCutGraph() {
8039
8052
  }
8040
8053
  function createOctahedralCutAtlas(options) {
8041
8054
  const graph = createOctahedralCutGraph(), atlas = new GeographicCutAtlas(graph, options), frames = new Map(graph.charts.map((c) => {
8042
- const center = unit(c.center), [right, up] = basis(center);
8043
- return [c.id, { center, right, up }];
8055
+ const center = unit(c.center), [right, up2] = basis(center);
8056
+ return [c.id, { center, right, up: up2 }];
8044
8057
  }));
8045
8058
  const project2 = (chart, p) => {
8046
8059
  const frame2 = frames.get(chart);
@@ -8562,12 +8575,12 @@ var TriaxialEllipsoid = class {
8562
8575
  basis(position2) {
8563
8576
  const p = this.surface(position2), normal2 = unit2(p.map((x, i) => x / this.axes[i] ** 2));
8564
8577
  const horizontal = Math.hypot(p[0], p[1]), meridian = horizontal ? [-p[1] / horizontal, p[0] / horizontal, 0] : [0, 1, 0];
8565
- const cross6 = (a, b) => [
8578
+ const cross7 = (a, b) => [
8566
8579
  a[1] * b[2] - a[2] * b[1],
8567
8580
  a[2] * b[0] - a[0] * b[2],
8568
8581
  a[0] * b[1] - a[1] * b[0]
8569
8582
  ];
8570
- const north = unit2(cross6(normal2, meridian)), east = unit2(cross6(north, normal2));
8583
+ const north = unit2(cross7(normal2, meridian)), east = unit2(cross7(north, normal2));
8571
8584
  return { north, east, normal: normal2 };
8572
8585
  }
8573
8586
  /** Cartesian initial-value geodesic. No global triaxial inverse is implied. */
@@ -10774,9 +10787,9 @@ function validateBatch(positions, output2) {
10774
10787
 
10775
10788
  // dist/terrain/mesh-skirts.js
10776
10789
  function createTerrainSkirt(mesh, options) {
10777
- const { positions, indices } = mesh, { height, edges: edges2 } = options;
10790
+ const { positions, indices } = mesh, { height, baseZ, edges: edges2 } = options;
10778
10791
  const maxVertices = options.maxVertices ?? 2e6, maxTriangles = options.maxTriangles ?? 4e6;
10779
- if (!Number.isFinite(height) || height <= 0 || !Number.isSafeInteger(maxVertices) || maxVertices < 0 || maxVertices > 4294967295 || !Number.isSafeInteger(maxTriangles) || maxTriangles < 0 || maxTriangles > 4294967295)
10792
+ if ((baseZ === void 0 ? !(Number.isFinite(height) && height > 0) : height !== void 0 || !Number.isFinite(baseZ)) || !Number.isSafeInteger(maxVertices) || maxVertices < 0 || maxVertices > 4294967295 || !Number.isSafeInteger(maxTriangles) || maxTriangles < 0 || maxTriangles > 4294967295)
10780
10793
  throw new Error("Invalid terrain skirt height or capacity");
10781
10794
  if (!(positions instanceof Float32Array || positions instanceof Float64Array) || positions.length < 3 || positions.length % 3 || !positions.every(Number.isFinite) || !(indices instanceof Uint16Array || indices instanceof Uint32Array) || indices.length % 3 || positions.length / 3 > maxVertices || indices.length / 3 > maxTriangles)
10782
10795
  throw new Error("Invalid terrain skirt mesh or capacity");
@@ -10832,7 +10845,7 @@ function createTerrainSkirt(mesh, options) {
10832
10845
  [b, lowerB]
10833
10846
  ]) {
10834
10847
  resultPositions.set(positions.subarray(3 * source, 3 * source + 3), 3 * target);
10835
- resultPositions[3 * target + 2] = positions[3 * source + 2] - height;
10848
+ resultPositions[3 * target + 2] = baseZ ?? positions[3 * source + 2] - height;
10836
10849
  if (!Number.isFinite(resultPositions[3 * target + 2]) || resultPositions[3 * target + 2] >= positions[3 * source + 2])
10837
10850
  throw new Error("Terrain skirt height cannot be represented in position precision");
10838
10851
  sourceVertexIndices[target - vertexCount] = source;
@@ -14369,56 +14382,48 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
14369
14382
  if (![maxSamples, maxTests].every((v) => Number.isSafeInteger(v) && v >= 0))
14370
14383
  throw new Error("Invalid mixed halo capacity");
14371
14384
  let count = 0;
14372
- const addresses = /* @__PURE__ */ new Set();
14385
+ let previousKey;
14373
14386
  let frame2;
14374
14387
  const sources = [...tiles].sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row).map((tile) => {
14375
- if (![tile.column, tile.row, tile.spacing].every(Number.isSafeInteger) || tile.spacing < 1 || 2 ** Math.round(Math.log2(tile.spacing)) !== tile.spacing)
14376
- throw new Error("Invalid mixed halo lattice");
14377
- const key3 = `${tile.spacing}/${tile.column}/${tile.row}`;
14378
- if (addresses.has(key3))
14379
- throw new Error("Duplicate mixed halo tile");
14380
- addresses.add(key3);
14381
14388
  count += (tile.field.width + 2) * (tile.field.height + 2);
14382
14389
  if (!Number.isSafeInteger(count) || count > maxSamples)
14383
14390
  throw new Error("Mixed halo sample capacity exceeded");
14384
- let field = preparation == null ? void 0 : preparation.fields.get(tile);
14385
- if (!field) {
14386
- field = new HeightField(tile.field);
14387
- preparation == null ? void 0 : preparation.fields.set(tile, field);
14391
+ let prepared2 = preparation == null ? void 0 : preparation.tiles.get(tile);
14392
+ if (!prepared2) {
14393
+ prepared2 = prepareMixedHaloTile(tile);
14394
+ preparation == null ? void 0 : preparation.tiles.set(tile, prepared2);
14395
+ }
14396
+ const { key: key3, source: field, columnStep: column, rowStep: row, frameOrigin: origin, scale: scale3 } = prepared2;
14397
+ if (previousKey === key3)
14398
+ throw new Error("Duplicate mixed halo tile");
14399
+ previousKey = key3;
14400
+ if (frame2) {
14401
+ if (frame2.reference !== field.heightReference)
14402
+ throw new Error("Mixed halo frames or height references differ");
14403
+ for (let i = 0; i < 2; i++) {
14404
+ if (column[i] !== frame2.column[i] || row[i] !== frame2.row[i] || origin[i] !== frame2.origin[i] && Math.abs(origin[i] - frame2.origin[i]) > Math.min(16 * Number.EPSILON * Math.max(scale3[i], frame2.scale[i]), 1e-9 * Math.max(Math.abs(column[i]), Math.abs(row[i]))))
14405
+ throw new Error("Mixed halo frames or height references differ");
14406
+ }
14388
14407
  }
14389
- if (field.registration !== "vertex")
14390
- throw new Error("Mixed halos require vertex registration");
14391
- const column = field.columnStep.map((v) => v / tile.spacing);
14392
- const row = field.rowStep.map((v) => v / tile.spacing);
14393
- const origin = field.origin.map((v, axis) => v - tile.column * column[axis] - tile.row * row[axis]);
14394
- const scale3 = field.origin.map((v, i) => Math.max(1, Math.abs(v), Math.abs(tile.column * column[i]), Math.abs(tile.row * row[i])));
14395
- if (!origin.every(Number.isFinite))
14396
- throw new Error("Mixed halo coordinate overflow");
14397
- if (frame2 && (frame2.reference !== field.heightReference || column.some((v, i) => v !== frame2.column[i]) || row.some((v, i) => v !== frame2.row[i]) || origin.some((v, i) => Math.abs(v - frame2.origin[i]) > Math.min(16 * Number.EPSILON * Math.max(scale3[i], frame2.scale[i]), 1e-9 * Math.max(Math.abs(column[i]), Math.abs(row[i]))))))
14398
- throw new Error("Mixed halo frames or height references differ");
14399
14408
  frame2 ?? (frame2 = { origin, column, row, reference: field.heightReference, scale: scale3 });
14400
- return { ...tile, source: field };
14409
+ return prepared2;
14401
14410
  });
14402
- for (const axis of ["column", "row"]) {
14403
- let min = Infinity, max = -Infinity;
14404
- for (const tile of sources) {
14405
- const size = axis === "column" ? tile.source.width : tile.source.height;
14406
- const low = tile[axis] - tile.spacing, high = tile[axis] + size * tile.spacing;
14407
- if (![low, high].every(Number.isSafeInteger))
14408
- throw new Error("Mixed halo lattice overflow");
14409
- min = Math.min(min, low);
14410
- max = Math.max(max, high);
14411
- }
14412
- if (sources.length && !Number.isSafeInteger(max - min))
14413
- throw new Error("Mixed halo lattice span overflow");
14414
- }
14411
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
14412
+ for (let i = 0; i < sources.length; i++) {
14413
+ const { haloBounds } = sources[i];
14414
+ minX = Math.min(minX, haloBounds.minX);
14415
+ minY = Math.min(minY, haloBounds.minY);
14416
+ maxX = Math.max(maxX, haloBounds.maxX);
14417
+ maxY = Math.max(maxY, haloBounds.maxY);
14418
+ }
14419
+ if (sources.length && (!Number.isSafeInteger(maxX - minX) || !Number.isSafeInteger(maxY - minY)))
14420
+ throw new Error("Mixed halo lattice span overflow");
14415
14421
  if (targets && targets.size === 0)
14416
14422
  return { tiles: [] };
14417
14423
  let index;
14418
14424
  if (sources.length > 8) {
14419
- const keys = preparation && sources.map((tile) => `${tile.spacing}/${tile.column}/${tile.row}/${tile.source.width}/${tile.source.height}`);
14420
14425
  const cached = preparation == null ? void 0 : preparation.layout;
14421
- if (keys && cached && keys.length === cached.keys.length && keys.every((key3, i) => key3 === cached.keys[i])) {
14426
+ if (cached && sources.length === cached.keys.length && sources.every((tile, i) => tile.layoutKey === cached.keys[i])) {
14422
14427
  index = cached.query;
14423
14428
  } else {
14424
14429
  index = createTerrainBoxIndex(sources.map((tile) => ({
@@ -14427,8 +14432,8 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
14427
14432
  maxX: tile.column + (tile.source.width - 1) * tile.spacing,
14428
14433
  maxY: tile.row + (tile.source.height - 1) * tile.spacing
14429
14434
  })));
14430
- if (preparation && keys)
14431
- preparation.layout = { keys, query: index };
14435
+ if (preparation)
14436
+ preparation.layout = { keys: sources.map((tile) => tile.layoutKey), query: index };
14432
14437
  }
14433
14438
  }
14434
14439
  let tests = 0;
@@ -14437,21 +14442,17 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
14437
14442
  throw new Error("Mixed halo tile-test budget exceeded");
14438
14443
  };
14439
14444
  return {
14440
- tiles: sources.filter((tile) => !targets || targets.has(`${tile.spacing}/${tile.column}/${tile.row}`)).map((tile) => {
14445
+ tiles: sources.filter((tile) => !targets || targets.has(tile.key)).map((tile) => {
14441
14446
  const source = tile.source, width = source.width + 2, height = source.height + 2;
14442
14447
  const heights = new Float64Array(width * height), validity = new Uint8Array(heights.length), statuses = new Uint8Array(heights.length);
14443
- const candidates = (index == null ? void 0 : index({
14444
- minX: tile.column - tile.spacing,
14445
- minY: tile.row - tile.spacing,
14446
- maxX: tile.column + source.width * tile.spacing,
14447
- maxY: tile.row + source.height * tile.spacing
14448
- }, charge).map((id) => sources[id])) ?? sources;
14448
+ const candidates = (index == null ? void 0 : index(tile.haloBounds, charge).map((id) => sources[id])) ?? sources;
14449
14449
  for (let y = 0; y < height; y++)
14450
14450
  for (let x = 0; x < width; x++) {
14451
14451
  const gx = tile.column + (x - 1) * tile.spacing, gy = tile.row + (y - 1) * tile.spacing;
14452
- if (![gx, gy].every(Number.isSafeInteger))
14452
+ if (!Number.isSafeInteger(gx) || !Number.isSafeInteger(gy))
14453
14453
  throw new Error("Mixed halo lattice overflow");
14454
- for (const candidate of candidates) {
14454
+ for (let candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
14455
+ const candidate = candidates[candidateIndex];
14455
14456
  charge();
14456
14457
  const cx = (gx - candidate.column) / candidate.spacing, cy = (gy - candidate.row) / candidate.spacing;
14457
14458
  const f = candidate.source;
@@ -14494,6 +14495,36 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
14494
14495
  })
14495
14496
  };
14496
14497
  }
14498
+ function prepareMixedHaloTile(tile) {
14499
+ const { column, row, spacing } = tile;
14500
+ if (![column, row, spacing].every(Number.isSafeInteger) || spacing < 1 || 2 ** Math.round(Math.log2(spacing)) !== spacing)
14501
+ throw new Error("Invalid mixed halo lattice");
14502
+ const source = new HeightField(tile.field);
14503
+ if (source.registration !== "vertex")
14504
+ throw new Error("Mixed halos require vertex registration");
14505
+ const columnStep = source.columnStep.map((v) => v / spacing);
14506
+ const rowStep = source.rowStep.map((v) => v / spacing);
14507
+ const frameOrigin = source.origin.map((v, i) => v - column * columnStep[i] - row * rowStep[i]);
14508
+ const scale3 = source.origin.map((v, i) => Math.max(1, Math.abs(v), Math.abs(column * columnStep[i]), Math.abs(row * rowStep[i])));
14509
+ if (!frameOrigin.every(Number.isFinite))
14510
+ throw new Error("Mixed halo coordinate overflow");
14511
+ const minX = column - spacing, minY = row - spacing;
14512
+ const maxX = column + source.width * spacing, maxY = row + source.height * spacing;
14513
+ if (![minX, minY, maxX, maxY].every(Number.isSafeInteger))
14514
+ throw new Error("Mixed halo lattice overflow");
14515
+ const key3 = `${spacing}/${column}/${row}`;
14516
+ return {
14517
+ ...tile,
14518
+ source,
14519
+ columnStep,
14520
+ rowStep,
14521
+ frameOrigin,
14522
+ scale: scale3,
14523
+ key: key3,
14524
+ layoutKey: `${key3}/${source.width}/${source.height}`,
14525
+ haloBounds: { minX, minY, maxX, maxY }
14526
+ };
14527
+ }
14497
14528
 
14498
14529
  // dist/terrain/mixed-halo-update.js
14499
14530
  var key2 = (t) => `${t.spacing}/${t.column}/${t.row}`;
@@ -14539,14 +14570,21 @@ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
14539
14570
  const budget = options.maxDependencyTests ?? 1e7;
14540
14571
  if (!Number.isSafeInteger(budget) || budget < 0)
14541
14572
  throw new Error("Invalid mixed halo dependency budget");
14542
- const old = new Map(previous == null ? void 0 : previous.sources.map((t) => [key2(t), t]));
14543
- const current = new Map(resident.map((t) => [key2(t), t]));
14544
- const cached = new Map(previous == null ? void 0 : previous.tiles.map((t) => [key2(t), t]));
14545
- const targets = /* @__PURE__ */ new Set();
14546
14573
  const unchangedLayout = (previous == null ? void 0 : previous.sources.length) === resident.length && resident.every((tile, i) => {
14547
14574
  const prior = previous.sources[i];
14548
- return key2(prior) === key2(tile) && prior.field.width === tile.field.width && prior.field.height === tile.field.height;
14575
+ return prior === tile || prior.column === tile.column && prior.row === tile.row && prior.spacing === tile.spacing && prior.field.width === tile.field.width && prior.field.height === tile.field.height;
14549
14576
  });
14577
+ const old = unchangedLayout ? void 0 : new Map(previous == null ? void 0 : previous.sources.map((t) => [key2(t), t]));
14578
+ const targets = /* @__PURE__ */ new Set();
14579
+ const initialized = previous !== null && preparations.has(previous);
14580
+ if (!initialized) {
14581
+ const cached = new Set(previous == null ? void 0 : previous.tiles.map(key2));
14582
+ for (const tile of resident) {
14583
+ const address = key2(tile);
14584
+ if (!cached.has(address))
14585
+ targets.add(address);
14586
+ }
14587
+ }
14550
14588
  let index = unchangedLayout && previous ? targetIndexes.get(previous) : void 0;
14551
14589
  let tests = 0;
14552
14590
  const charge = () => {
@@ -14558,12 +14596,13 @@ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
14558
14596
  for (const id of index(box, charge))
14559
14597
  targets.add(key2(resident[id]));
14560
14598
  }
14561
- for (const tile of resident) {
14562
- const address = key2(tile);
14563
- const prior = old.get(address);
14564
- if (!cached.has(address) || prior !== tile)
14565
- targets.add(address);
14566
- if (prior === tile || !previous)
14599
+ for (let i = 0; i < resident.length; i++) {
14600
+ const tile = resident[i];
14601
+ const prior = unchangedLayout ? previous.sources[i] : old == null ? void 0 : old.get(key2(tile));
14602
+ if (prior === tile)
14603
+ continue;
14604
+ targets.add(key2(tile));
14605
+ if (!previous)
14567
14606
  continue;
14568
14607
  if (!prior) {
14569
14608
  invalidate(bounds(tile));
@@ -14576,24 +14615,44 @@ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
14576
14615
  invalidate(dirty);
14577
14616
  }
14578
14617
  }
14579
- for (const [address, tile] of old) {
14580
- if (!current.has(address) && resident.length)
14581
- invalidate(bounds(tile));
14618
+ const removed = [];
14619
+ if (old == null ? void 0 : old.size) {
14620
+ const current = new Set(resident.map(key2));
14621
+ for (const [address, tile] of old) {
14622
+ if (current.has(address))
14623
+ continue;
14624
+ removed.push(address);
14625
+ if (resident.length)
14626
+ invalidate(bounds(tile));
14627
+ }
14582
14628
  }
14583
14629
  const priorPreparation = previous && preparations.get(previous);
14584
14630
  const preparation = {
14585
- fields: (priorPreparation == null ? void 0 : priorPreparation.fields) ?? /* @__PURE__ */ new WeakMap(),
14631
+ tiles: (priorPreparation == null ? void 0 : priorPreparation.tiles) ?? /* @__PURE__ */ new WeakMap(),
14586
14632
  layout: priorPreparation == null ? void 0 : priorPreparation.layout
14587
14633
  };
14588
14634
  const built = buildMixedVertexTileHalos(resident, options, targets, preparation).tiles;
14589
- for (const tile of built)
14590
- cached.set(key2(tile), tile);
14591
- const tiles = resident.map((t) => cached.get(key2(t))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
14635
+ let tiles;
14636
+ if (unchangedLayout && initialized) {
14637
+ let cursor = 0;
14638
+ tiles = previous.tiles.map((tile) => {
14639
+ const replacement = built[cursor];
14640
+ if ((replacement == null ? void 0 : replacement.spacing) !== tile.spacing || replacement.column !== tile.column || replacement.row !== tile.row)
14641
+ return tile;
14642
+ cursor++;
14643
+ return replacement;
14644
+ });
14645
+ } else {
14646
+ const cached = new Map(previous == null ? void 0 : previous.tiles.map((tile) => [key2(tile), tile]));
14647
+ for (const tile of built)
14648
+ cached.set(key2(tile), tile);
14649
+ tiles = resident.map((tile) => cached.get(key2(tile))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
14650
+ }
14592
14651
  const snapshot2 = {
14593
14652
  sources: resident.slice(),
14594
14653
  tiles,
14595
14654
  rebuilt: built.map(key2),
14596
- removed: [...old.keys()].filter((k) => !current.has(k)).sort()
14655
+ removed: removed.sort()
14597
14656
  };
14598
14657
  preparations.set(snapshot2, preparation);
14599
14658
  if (index)
@@ -15905,12 +15964,12 @@ function meshValidDomain(field, options, constraints) {
15905
15964
  const { width, height, origin, heightReference } = regular;
15906
15965
  const active = new Uint8Array(count);
15907
15966
  const boundary = /* @__PURE__ */ new Map();
15908
- const edgeKey2 = (a, b) => Math.min(a, b) * count + Math.max(a, b);
15967
+ const edgeKey3 = (a, b) => Math.min(a, b) * count + Math.max(a, b);
15909
15968
  for (let i = 0; i < regular.indices.length; i += 3) {
15910
15969
  for (let j = 0; j < 3; j++) {
15911
15970
  const a = regular.indices[i + j], b = regular.indices[i + (j + 1) % 3];
15912
15971
  active[a] = 1;
15913
- const key3 = edgeKey2(a, b);
15972
+ const key3 = edgeKey3(a, b);
15914
15973
  if (!boundary.delete(key3))
15915
15974
  boundary.set(key3, [a, b]);
15916
15975
  }
@@ -16374,15 +16433,75 @@ function measureGeographicTerrainSeam(a, b, probes, options = {}) {
16374
16433
  });
16375
16434
  }
16376
16435
 
16436
+ // dist/terrain/lod-screen-error.js
16437
+ function slack(value3) {
16438
+ return Math.abs(value3) * (2 * Number.EPSILON) + Number.MIN_VALUE;
16439
+ }
16440
+ function down(value3) {
16441
+ return value3 - slack(value3);
16442
+ }
16443
+ function up(value3) {
16444
+ return value3 + slack(value3);
16445
+ }
16446
+ function boundTerrainLodScreenError(bounds2, projection2) {
16447
+ if (bounds2.min.length !== 3 || bounds2.max.length !== 3 || !bounds2.min.every((value3, i) => Number.isFinite(value3) && value3 <= bounds2.max[i]) || !bounds2.max.every(Number.isFinite) || !Number.isFinite(bounds2.geometricError) || bounds2.geometricError < 0)
16448
+ throw new RangeError("Invalid terrain LOD screen-error bounds");
16449
+ return prepareTerrainLodScreenError(projection2)(bounds2);
16450
+ }
16451
+ function prepareTerrainLodScreenError(projection2) {
16452
+ const { width, height, depthRange = "negative-one-to-one", reversedDepth = false } = projection2;
16453
+ if (projection2.matrix.length !== 16)
16454
+ throw new RangeError("Invalid terrain LOD clip matrix");
16455
+ const matrix = Array.from(projection2.matrix);
16456
+ if (!matrix.every(Number.isFinite) || !Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0 || depthRange !== "negative-one-to-one" && depthRange !== "zero-to-one")
16457
+ throw new RangeError("Invalid terrain LOD projection");
16458
+ return ({ min, max, geometricError: error }) => {
16459
+ if (error === 0)
16460
+ return 0;
16461
+ function row(index) {
16462
+ let lower = matrix[12 + index];
16463
+ let upper = lower;
16464
+ let change = 0;
16465
+ for (let axis = 0; axis < 3; axis++) {
16466
+ const coefficient = matrix[4 * axis + index];
16467
+ const a = coefficient * min[axis];
16468
+ const b = coefficient * max[axis];
16469
+ lower = down(lower + down(Math.min(a, b)));
16470
+ upper = up(upper + up(Math.max(a, b)));
16471
+ change = up(change + up(Math.abs(coefficient) * error));
16472
+ }
16473
+ return { lower, upper, change };
16474
+ }
16475
+ const w = row(3);
16476
+ const z = row(2);
16477
+ const nearLow = reversedDepth ? down(w.lower - z.upper) : depthRange === "zero-to-one" ? z.lower : down(z.lower + w.lower);
16478
+ const nearHigh = reversedDepth ? up(w.upper - z.lower) : depthRange === "zero-to-one" ? z.upper : up(z.upper + w.upper);
16479
+ const nearChange = !reversedDepth && depthRange === "zero-to-one" ? z.change : up(z.change + w.change);
16480
+ if (up(nearHigh + nearChange) < 0)
16481
+ return 0;
16482
+ const denominator = down(w.lower - w.change);
16483
+ if (!(down(nearLow - nearChange) > 0 && denominator > 0))
16484
+ return Infinity;
16485
+ function pixelAxis(index, extent) {
16486
+ const coordinate = row(index);
16487
+ const magnitude2 = Math.max(Math.abs(coordinate.lower), Math.abs(coordinate.upper));
16488
+ const ndc = up(magnitude2 / denominator);
16489
+ const coupling = up(ndc * w.change);
16490
+ const numerator = up(coordinate.change + coupling);
16491
+ return up(up(numerator / denominator) * up(extent / 2));
16492
+ }
16493
+ const pixels = pixelAxis(0, width) + pixelAxis(1, height);
16494
+ return Number.isFinite(pixels) ? up(pixels) : Infinity;
16495
+ };
16496
+ }
16497
+
16377
16498
  // dist/terrain/lod-select.js
16378
16499
  function selectTerrainLod(roots2, view) {
16379
16500
  var _a;
16380
- const { position: position2, verticalFov, viewportHeight, targetPixels, hysteresis = 0.2, previouslyRefined, maxVisited = 1e5 } = view;
16381
- if (!position2.every(Number.isFinite) || !Number.isFinite(verticalFov) || verticalFov <= 0 || verticalFov >= Math.PI || !Number.isFinite(viewportHeight) || viewportHeight <= 0 || !Number.isFinite(targetPixels) || targetPixels <= 0 || !(hysteresis >= 0 && hysteresis < 1) || !Number.isSafeInteger(maxVisited) || maxVisited < 1)
16501
+ const { targetPixels, hysteresis = 0.2, previouslyRefined, maxVisited = 1e5 } = view;
16502
+ if (!Number.isFinite(targetPixels) || targetPixels <= 0 || !(hysteresis >= 0 && hysteresis < 1) || !Number.isSafeInteger(maxVisited) || maxVisited < 1)
16382
16503
  throw new Error("Invalid terrain LOD view");
16383
- const scale3 = viewportHeight / (2 * Math.tan(verticalFov / 2));
16384
- if (!Number.isFinite(scale3))
16385
- throw new Error("Terrain LOD projection scale overflow");
16504
+ const pixelError = "projection" in view ? prepareTerrainLodScreenError(view.projection) : createDistanceEstimator(view.position, view.verticalFov, view.viewportHeight);
16386
16505
  const selected = [];
16387
16506
  const refined = /* @__PURE__ */ new Set();
16388
16507
  const unavailable = [];
@@ -16395,14 +16514,13 @@ function selectTerrainLod(roots2, view) {
16395
16514
  if (seen.has(tile.id))
16396
16515
  throw new Error("Duplicate terrain LOD tile or cycle");
16397
16516
  seen.add(tile.id);
16398
- if (![...tile.min, ...tile.max, tile.geometricError].every(Number.isFinite) || tile.geometricError < 0 || tile.min.some((n, i) => n > tile.max[i]))
16517
+ if (tile.min.length !== 3 || tile.max.length !== 3 || ![...tile.min, ...tile.max, tile.geometricError].every(Number.isFinite) || tile.geometricError < 0 || tile.min.some((n, i) => n > tile.max[i]))
16399
16518
  throw new Error("Invalid terrain LOD tile bounds or error");
16400
16519
  if (!tile.resident) {
16401
16520
  unavailable.push(tile.id);
16402
16521
  continue;
16403
16522
  }
16404
- const distance = Math.hypot(...position2.map((n, i) => Math.max(tile.min[i] - n, n - tile.max[i], 0)));
16405
- const pixels = tile.geometricError === 0 ? 0 : tile.geometricError / distance * scale3;
16523
+ const pixels = pixelError(tile);
16406
16524
  const threshold = targetPixels * ((previouslyRefined == null ? void 0 : previouslyRefined.has(tile.id)) ? 1 - hysteresis : 1);
16407
16525
  if (pixels > threshold && ((_a = tile.children) == null ? void 0 : _a.length) && tile.children.every((child) => child.resident)) {
16408
16526
  if (pending.length + seen.size + tile.children.length > maxVisited)
@@ -16416,6 +16534,17 @@ function selectTerrainLod(roots2, view) {
16416
16534
  }
16417
16535
  return { selected, refined, unavailable };
16418
16536
  }
16537
+ function createDistanceEstimator(position2, verticalFov, viewportHeight) {
16538
+ if (!position2.every(Number.isFinite) || !Number.isFinite(verticalFov) || verticalFov <= 0 || verticalFov >= Math.PI || !Number.isFinite(viewportHeight) || viewportHeight <= 0)
16539
+ throw new Error("Invalid terrain LOD view");
16540
+ const scale3 = viewportHeight / (2 * Math.tan(verticalFov / 2));
16541
+ if (!Number.isFinite(scale3))
16542
+ throw new Error("Terrain LOD projection scale overflow");
16543
+ return (tile) => {
16544
+ const distance = Math.hypot(...position2.map((n, i) => Math.max(tile.min[i] - n, n - tile.max[i], 0)));
16545
+ return tile.geometricError === 0 ? 0 : tile.geometricError / distance * scale3;
16546
+ };
16547
+ }
16419
16548
 
16420
16549
  // dist/terrain/lod-stitch.js
16421
16550
  function stitchTerrainLodCut(input, seams) {
@@ -16512,14 +16641,14 @@ function splitTerrainBreaklines(input, options = {}) {
16512
16641
  throw new Error("Breakline output limit exceeded");
16513
16642
  knots.push({ t, point: point2 });
16514
16643
  };
16515
- const cross6 = (ax, ay, bx, by) => ax * by - ay * bx;
16644
+ const cross7 = (ax, ay, bx, by) => ax * by - ay * bx;
16516
16645
  for (let i = 0; i < lines.length; i++) {
16517
16646
  const a = lines[i];
16518
16647
  for (let j = i + 1; j < lines.length; j++) {
16519
16648
  const b = lines[j];
16520
16649
  const x = b.p[0] - a.p[0], y = b.p[1] - a.p[1];
16521
- const det = cross6(a.dx, a.dy, b.dx, b.dy);
16522
- const u = cross6(x, y, a.dx, a.dy), t = cross6(x, y, b.dx, b.dy);
16650
+ const det = cross7(a.dx, a.dy, b.dx, b.dy);
16651
+ const u = cross7(x, y, a.dx, a.dy), t = cross7(x, y, b.dx, b.dy);
16523
16652
  if (![det, u, t].every(Number.isFinite))
16524
16653
  throw new Error("Breakline intersection overflow");
16525
16654
  if (det === 0) {
@@ -16910,9 +17039,12 @@ var cross5 = (a, b) => [
16910
17039
  var dot4 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
16911
17040
  var edges = ([a, b, c]) => [sub2(b, a), sub2(c, b), sub2(a, c)];
16912
17041
  function sweepTerrainPolytope(surface2, collider, translation, { maxWork = 1e5 } = {}) {
17042
+ return queryTerrainPolytope(surface2.copyData(), surface2.origin, collider, translation, maxWork);
17043
+ }
17044
+ function queryTerrainPolytope(data, origin, collider, translation, maxWork, padding = 0) {
16913
17045
  if (!Number.isSafeInteger(maxWork) || maxWork < 0 || translation.length !== 3 || !translation.every(Number.isFinite) || collider.vertices.length < 4 || collider.faces.length < 4 || collider.vertices.some((point2) => point2.length !== 3 || !point2.every(Number.isFinite)))
16914
17046
  throw new RangeError("Invalid terrain polytope sweep");
16915
- const vertices = collider.vertices.map((point2) => sub2(point2, surface2.origin));
17047
+ const vertices = collider.vertices.map((point2) => sub2(point2, origin));
16916
17048
  const normals = [];
16917
17049
  const directions = [];
16918
17050
  for (const face of collider.faces) {
@@ -16925,7 +17057,7 @@ function sweepTerrainPolytope(surface2, collider, translation, { maxWork = 1e5 }
16925
17057
  normals.push(normal2);
16926
17058
  directions.push(...side);
16927
17059
  }
16928
- return sweepTriangles(surface2.copyData(), vertices, normals, directions, translation, maxWork);
17060
+ return sweepTriangles(data, vertices, normals, directions, translation, maxWork, void 0, padding);
16929
17061
  }
16930
17062
  function sweepTerrainTriangleMesh(surface2, collider, translation, { maxWork = 1e5 } = {}) {
16931
17063
  if (!Number.isSafeInteger(maxWork) || maxWork < 0 || translation.length !== 3 || !translation.every(Number.isFinite))
@@ -16955,7 +17087,7 @@ function sweepTerrainTriangleMesh(surface2, collider, translation, { maxWork = 1
16955
17087
  }
16956
17088
  return best ? { ...best, work } : { status: "miss", work };
16957
17089
  }
16958
- function sweepTriangles(data, vertices, normals, directions, translation, maxWork, movingTriangleNormal) {
17090
+ function sweepTriangles(data, vertices, normals, directions, translation, maxWork, movingTriangleNormal, padding = 0) {
16959
17091
  let work = 0;
16960
17092
  let best;
16961
17093
  const vertex = (index) => {
@@ -17001,6 +17133,8 @@ function sweepTriangles(data, vertices, normals, directions, translation, maxWor
17001
17133
  min = Math.min(min, projection2);
17002
17134
  max = Math.max(max, projection2);
17003
17135
  }
17136
+ min -= padding;
17137
+ max += padding;
17004
17138
  const speed = dot4(translation, unit3);
17005
17139
  if (![low, high, min, max, speed, length].every(Number.isFinite))
17006
17140
  throw new RangeError("Terrain polytope projection overflow");
@@ -17029,6 +17163,9 @@ function sweepTriangles(data, vertices, normals, directions, translation, maxWor
17029
17163
  return best ? { ...best, work } : { status: "miss", work };
17030
17164
  }
17031
17165
  function sweepTerrainBox(surface2, center, halfExtents, translation, options) {
17166
+ return sweepTerrainPolytope(surface2, createSweepBox(center, halfExtents), translation, options);
17167
+ }
17168
+ function createSweepBox(center, halfExtents) {
17032
17169
  if (halfExtents.length !== 3 || halfExtents.some((value3) => !(value3 > 0)))
17033
17170
  throw new RangeError("Terrain box half extents must be positive");
17034
17171
  const vertices = Array.from({ length: 8 }, (_, i) => [
@@ -17036,7 +17173,7 @@ function sweepTerrainBox(surface2, center, halfExtents, translation, options) {
17036
17173
  center[1] + (i & 2 ? 1 : -1) * halfExtents[1],
17037
17174
  center[2] + (i & 4 ? 1 : -1) * halfExtents[2]
17038
17175
  ]);
17039
- return sweepTerrainPolytope(surface2, {
17176
+ return {
17040
17177
  vertices,
17041
17178
  faces: [
17042
17179
  [0, 1, 3],
@@ -17052,7 +17189,102 @@ function sweepTerrainBox(surface2, center, halfExtents, translation, options) {
17052
17189
  [1, 5, 7],
17053
17190
  [1, 7, 3]
17054
17191
  ]
17055
- }, translation, options);
17192
+ };
17193
+ }
17194
+
17195
+ // dist/terrain/sweep-rotating-capsule.js
17196
+ function sweepTerrainRotatingCapsule(surface2, start, end, radius, { pivot, translation, rotation }, { maxWork = 1e5, fractionTolerance = 1e-5 } = {}) {
17197
+ var _a;
17198
+ const norm = Math.hypot(...rotation);
17199
+ if (![start, end, pivot, translation].every((p) => p.length === 3 && p.every(Number.isFinite)) || rotation.length !== 4 || !(norm > 0 && Number.isFinite(norm)) || !Number.isFinite(radius) || radius < 0 || !Number.isSafeInteger(maxWork) || maxWork < 0 || !(fractionTolerance >= Number.EPSILON && fractionTolerance <= 1))
17200
+ throw new RangeError("Invalid terrain capsule rigid motion");
17201
+ const sign2 = rotation[3] < 0 ? -1 : 1;
17202
+ const axisLength = Math.hypot(rotation[0], rotation[1], rotation[2]);
17203
+ const angle3 = 2 * Math.atan2(axisLength, Math.abs(rotation[3]));
17204
+ if (angle3 === 0) {
17205
+ return sweepTerrainCapsule(surface2, start, end, translation, radius, {
17206
+ maxWork,
17207
+ fractionTolerance
17208
+ });
17209
+ }
17210
+ const x = rotation[0] / axisLength * sign2;
17211
+ const y = rotation[1] / axisLength * sign2;
17212
+ const z = rotation[2] / axisLength * sign2;
17213
+ const offsets = [start, end].map((p) => p.map((v, i) => v - pivot[i]));
17214
+ const reach = Math.max(...offsets.map((p) => Math.hypot(...p)));
17215
+ const speed = Math.hypot(...translation) + angle3 * reach;
17216
+ const scale3 = Math.max(Math.hypot(...pivot), reach, speed, radius);
17217
+ if (!Number.isFinite(scale3))
17218
+ throw new RangeError("Terrain capsule rigid motion overflow");
17219
+ let work = 0;
17220
+ function probe(t) {
17221
+ if (work >= maxWork)
17222
+ return null;
17223
+ work++;
17224
+ const sin = Math.sin(angle3 * t);
17225
+ const cos = Math.cos(angle3 * t);
17226
+ const [a, b] = t === 0 ? [start, end] : offsets.map(([u, v, w]) => {
17227
+ const d = (x * u + y * v + z * w) * (1 - cos);
17228
+ const pos = [
17229
+ pivot[0] + (translation[0] * t + u * cos + (y * w - z * v) * sin + x * d),
17230
+ pivot[1] + (translation[1] * t + v * cos + (z * u - x * w) * sin + y * d),
17231
+ pivot[2] + (translation[2] * t + w * cos + (x * v - y * u) * sin + z * d)
17232
+ ];
17233
+ if (!pos.every(Number.isFinite))
17234
+ throw new RangeError("Terrain capsule pose overflow");
17235
+ return pos;
17236
+ });
17237
+ const query = surface2.nearestSegmentQuery(a, b, { maxWork: maxWork - work });
17238
+ work += query.work;
17239
+ return query;
17240
+ }
17241
+ const initial = probe(0);
17242
+ if ((initial == null ? void 0 : initial.result) && initial.result.distance <= radius)
17243
+ return { status: "hit", fraction: 0, lowerFraction: 0, work, contact: initial.result };
17244
+ if (!(initial == null ? void 0 : initial.complete))
17245
+ return { status: "incomplete", work };
17246
+ if (!initial.result || speed === 0)
17247
+ return { status: "miss", work };
17248
+ let clearUntil = 0;
17249
+ let witness;
17250
+ const pending = [[0, 1]];
17251
+ while (pending.length) {
17252
+ if (witness && witness.fraction - clearUntil <= fractionTolerance)
17253
+ return { status: "hit", lowerFraction: clearUntil, work, ...witness };
17254
+ const [lo, hi] = pending.pop();
17255
+ const mid = lo + (hi - lo) / 2;
17256
+ const query = probe(mid);
17257
+ const contact = query == null ? void 0 : query.result;
17258
+ if (contact && contact.distance <= radius) {
17259
+ witness = { fraction: mid, contact };
17260
+ if (mid - clearUntil <= fractionTolerance)
17261
+ return { status: "hit", lowerFraction: clearUntil, work, ...witness };
17262
+ if (mid === lo || mid === hi)
17263
+ return { status: "incomplete", work };
17264
+ pending.push([lo, mid]);
17265
+ continue;
17266
+ }
17267
+ if (!(query == null ? void 0 : query.complete))
17268
+ return { status: "incomplete", work };
17269
+ const travel = speed * Math.max(mid - lo, hi - mid);
17270
+ const allowance = 16 * Number.EPSILON * Math.max(scale3, (contact == null ? void 0 : contact.distance) ?? 0);
17271
+ if (!contact || contact.distance - radius > travel + allowance) {
17272
+ clearUntil = hi;
17273
+ continue;
17274
+ }
17275
+ if (hi - clearUntil <= fractionTolerance) {
17276
+ const final = (witness == null ? void 0 : witness.fraction) === hi ? witness.contact : (_a = probe(hi)) == null ? void 0 : _a.result;
17277
+ if (final && final.distance <= radius)
17278
+ return { status: "hit", fraction: hi, lowerFraction: clearUntil, work, contact: final };
17279
+ }
17280
+ if (mid === lo || mid === hi || hi - lo <= fractionTolerance / 4)
17281
+ return { status: "incomplete", work };
17282
+ pending.push([mid, hi], [lo, mid]);
17283
+ }
17284
+ return witness ? { status: "hit", lowerFraction: clearUntil, work, ...witness } : { status: "miss", work };
17285
+ }
17286
+ function sweepTerrainRotatingSphere(surface2, center, radius, motion, options) {
17287
+ return sweepTerrainRotatingCapsule(surface2, center, center, radius, motion, options);
17056
17288
  }
17057
17289
 
17058
17290
  // dist/terrain/sweep-cylinder.js
@@ -17249,4 +17481,698 @@ function discoverGeographicTerrainPoles(cut2) {
17249
17481
  }
17250
17482
  return { north: collect(90, "north"), south: collect(-90, "south") };
17251
17483
  }
17484
+
17485
+ // dist/terrain/sweep-rotation.js
17486
+ function sweepTerrainRotatingPolytope(surface2, collider, { pivot, translation, rotation }, { maxWork = 1e5, fractionTolerance = 1e-5 } = {}) {
17487
+ const norm = Math.hypot(...rotation);
17488
+ if (pivot.length !== 3 || translation.length !== 3 || rotation.length !== 4 || !pivot.every(Number.isFinite) || !translation.every(Number.isFinite) || !(norm > 0 && Number.isFinite(norm)) || !Number.isSafeInteger(maxWork) || maxWork < 0 || !(fractionTolerance >= Number.EPSILON && fractionTolerance <= 1))
17489
+ throw new RangeError("Invalid terrain rigid motion");
17490
+ const localPivot = pivot.map((v, i) => v - surface2.origin[i]);
17491
+ const offsets = collider.vertices.map((v) => v.map((x2, i) => x2 - pivot[i]));
17492
+ const radius = offsets.reduce((r, v) => Math.max(r, Math.hypot(...v)), 0);
17493
+ const sign2 = rotation[3] < 0 ? -1 : 1;
17494
+ const vectorNorm = Math.hypot(rotation[0], rotation[1], rotation[2]);
17495
+ const angle3 = 2 * Math.atan2(vectorNorm, Math.abs(rotation[3]));
17496
+ const speed = Math.hypot(...translation) + angle3 * radius;
17497
+ if (!Number.isFinite(speed))
17498
+ throw new RangeError("Terrain rigid motion overflow");
17499
+ const data = surface2.copyData();
17500
+ if (angle3 === 0) {
17501
+ const result = queryTerrainPolytope(data, surface2.origin, collider, translation, maxWork);
17502
+ return result.status === "hit" ? { ...result, lowerFraction: result.fraction } : result;
17503
+ }
17504
+ const [x, y, z] = rotation.slice(0, 3).map((v) => v / vectorNorm * sign2);
17505
+ const zero = [0, 0, 0];
17506
+ let work = 0;
17507
+ const pose = (t) => {
17508
+ const sin = Math.sin(angle3 * t);
17509
+ const cos = Math.cos(angle3 * t);
17510
+ return {
17511
+ faces: collider.faces,
17512
+ vertices: offsets.map(([a, b, c]) => {
17513
+ const projection2 = (x * a + y * b + z * c) * (1 - cos);
17514
+ return [
17515
+ localPivot[0] + translation[0] * t + a * cos + (y * c - z * b) * sin + x * projection2,
17516
+ localPivot[1] + translation[1] * t + b * cos + (z * a - x * c) * sin + y * projection2,
17517
+ localPivot[2] + translation[2] * t + c * cos + (x * b - y * a) * sin + z * projection2
17518
+ ];
17519
+ })
17520
+ };
17521
+ };
17522
+ const probe = (shape, padding = 0) => {
17523
+ if (work >= maxWork)
17524
+ return { status: "incomplete", work: 0 };
17525
+ work++;
17526
+ const result = queryTerrainPolytope(data, zero, shape, zero, maxWork - work, padding);
17527
+ work += result.work;
17528
+ return result;
17529
+ };
17530
+ const initial = probe(pose(0));
17531
+ if (initial.status === "hit")
17532
+ return { ...initial, lowerFraction: 0, work };
17533
+ if (initial.status === "incomplete")
17534
+ return { status: "incomplete", work };
17535
+ let clearUntil = 0;
17536
+ let witness;
17537
+ const pending = [[0, 1]];
17538
+ while (pending.length) {
17539
+ if (witness && witness.fraction - clearUntil <= fractionTolerance)
17540
+ return { ...witness, lowerFraction: clearUntil, work };
17541
+ const [lo, hi] = pending.pop();
17542
+ const mid = lo + (hi - lo) / 2;
17543
+ const shape = pose(mid);
17544
+ const padding = speed * Math.max(mid - lo, hi - mid);
17545
+ const expanded = probe(shape, padding + 8 * Number.EPSILON * (radius + padding));
17546
+ if (expanded.status === "miss") {
17547
+ clearUntil = hi;
17548
+ continue;
17549
+ }
17550
+ if (expanded.status === "incomplete")
17551
+ return { status: "incomplete", work };
17552
+ const hit = probe(shape);
17553
+ if (hit.status === "incomplete")
17554
+ return { status: "incomplete", work };
17555
+ if (hit.status === "hit") {
17556
+ witness = { ...hit, fraction: mid };
17557
+ if (mid - clearUntil <= fractionTolerance)
17558
+ return { ...witness, lowerFraction: clearUntil, work };
17559
+ pending.push([lo, mid]);
17560
+ } else if (hi - clearUntil <= fractionTolerance) {
17561
+ const end = (witness == null ? void 0 : witness.fraction) === hi ? witness : probe(pose(hi));
17562
+ if ((end == null ? void 0 : end.status) === "hit")
17563
+ return { ...end, fraction: hi, lowerFraction: clearUntil, work };
17564
+ if (hi - lo <= fractionTolerance / 4)
17565
+ return { status: "incomplete", work };
17566
+ pending.push([mid, hi], [lo, mid]);
17567
+ } else {
17568
+ if (mid === lo || mid === hi || hi - lo <= fractionTolerance / 4)
17569
+ return { status: "incomplete", work };
17570
+ pending.push([mid, hi], [lo, mid]);
17571
+ }
17572
+ }
17573
+ return witness ? { ...witness, lowerFraction: clearUntil, work } : { status: "miss", work };
17574
+ }
17575
+ function sweepTerrainRotatingBox(surface2, center, halfExtents, motion, options) {
17576
+ return sweepTerrainRotatingPolytope(surface2, createSweepBox(center, halfExtents), motion, options);
17577
+ }
17578
+
17579
+ // dist/terrain/regional-viewshed.js
17580
+ var TerrainRegionalViewStatus = {
17581
+ VISIBLE: 0,
17582
+ BLOCKED: 1,
17583
+ UNKNOWN: 2,
17584
+ MISSING_TARGET: 3,
17585
+ OBSERVER: 4
17586
+ };
17587
+ function createTerrainRegionalViewshed(grid, sample, options) {
17588
+ const { width, height, origin, spacing } = grid;
17589
+ const { observer, sampleStep, radius, targetOffset = 0, maxTargets = 1e5, maxSamples = 4e6 } = options;
17590
+ const count = width * height;
17591
+ if (![width, height, count, maxTargets, maxSamples].every(Number.isSafeInteger) || width < 1 || height < 1 || count > maxTargets || maxSamples < 1 || origin.length !== 2 || spacing.length !== 2 || observer.length !== 3 || ![...origin, ...spacing, ...observer, sampleStep, targetOffset].every(Number.isFinite) || spacing.some((value3) => value3 <= 0) || sampleStep <= 0 || targetOffset < 0 || radius !== void 0 && (!Number.isFinite(radius) || radius <= 0 || observer[2] <= -radius))
17592
+ throw new RangeError("Invalid regional viewshed grid or options");
17593
+ const statuses = new Uint8Array(count);
17594
+ const targetStatuses = new Uint8Array(count);
17595
+ const sampledCoverage = new Uint8Array(count);
17596
+ let samples = 0;
17597
+ function read(x, y) {
17598
+ if (samples >= maxSamples)
17599
+ throw new RangeError("Regional viewshed sample budget exceeded");
17600
+ samples++;
17601
+ const result = sample(x, y);
17602
+ if (!Number.isInteger(result.status) || result.status < 0 || result.status > TerrainSampleStatus.NOT_RESIDENT || result.status === TerrainSampleStatus.VALID && (!Number.isFinite(result.height) || radius !== void 0 && result.height <= -radius))
17603
+ throw new RangeError("Invalid regional viewshed sample");
17604
+ return result;
17605
+ }
17606
+ function sight(distance, elevation) {
17607
+ let rise = elevation - observer[2];
17608
+ let run = distance;
17609
+ if (radius !== void 0) {
17610
+ const theta = distance / radius;
17611
+ const radial = radius + elevation;
17612
+ const halfSine = Math.sin(theta / 2);
17613
+ rise -= radial * (2 * halfSine * halfSine);
17614
+ run = radial * Math.sin(theta);
17615
+ }
17616
+ if (!Number.isFinite(rise) || !Number.isFinite(run) || run <= 0)
17617
+ throw new RangeError("Regional viewshed sight calculation overflow");
17618
+ return [rise, run];
17619
+ }
17620
+ const observerSample = { ...read(observer[0], observer[1]) };
17621
+ const observerValid = observerSample.status === TerrainSampleStatus.VALID;
17622
+ for (let i = 0; i < count; i++) {
17623
+ const x = origin[0] + i % width * spacing[0];
17624
+ const y = origin[1] + Math.floor(i / width) * spacing[1];
17625
+ const dx = x - observer[0];
17626
+ const dy = y - observer[1];
17627
+ const distance = Math.hypot(dx, dy);
17628
+ if (!Number.isFinite(distance) || radius !== void 0 && distance / radius >= Math.PI)
17629
+ throw new RangeError("Regional viewshed distance outside supported range");
17630
+ const target = distance === 0 ? observerSample : read(x, y);
17631
+ targetStatuses[i] = target.status;
17632
+ if (target.status !== TerrainSampleStatus.VALID) {
17633
+ statuses[i] = TerrainRegionalViewStatus.MISSING_TARGET;
17634
+ continue;
17635
+ }
17636
+ if (distance === 0) {
17637
+ statuses[i] = TerrainRegionalViewStatus.OBSERVER;
17638
+ sampledCoverage[i] = 1;
17639
+ continue;
17640
+ }
17641
+ const [targetRise, targetRun] = sight(distance, target.height + targetOffset);
17642
+ const segments = Math.max(1, Math.ceil(distance / sampleStep));
17643
+ if (!Number.isSafeInteger(segments) || segments - 1 > maxSamples - samples)
17644
+ throw new RangeError("Regional viewshed sample budget exceeded");
17645
+ let complete = observerValid;
17646
+ let blocked = observerValid && observerSample.height > observer[2];
17647
+ for (let j = 1; j < segments; j++) {
17648
+ const fraction = j / segments;
17649
+ const station = read(observer[0] + dx * fraction, observer[1] + dy * fraction);
17650
+ if (station.status !== TerrainSampleStatus.VALID) {
17651
+ complete = false;
17652
+ } else if (!blocked) {
17653
+ const [rise, run] = sight(distance * fraction, station.height);
17654
+ blocked = compareTerrainSlopes(rise, run, targetRise, targetRun) >= 0;
17655
+ }
17656
+ }
17657
+ sampledCoverage[i] = complete ? 1 : 0;
17658
+ statuses[i] = blocked ? TerrainRegionalViewStatus.BLOCKED : complete ? TerrainRegionalViewStatus.VISIBLE : TerrainRegionalViewStatus.UNKNOWN;
17659
+ }
17660
+ return { statuses, targetStatuses, sampledCoverage, samples };
17661
+ }
17662
+
17663
+ // dist/terrain/hydrology.js
17664
+ function getTerrainCellMetrics(field) {
17665
+ if (field.registration !== "cell")
17666
+ throw new Error("Terrain cell metrics require cell registration");
17667
+ const [cx, cy] = field.columnStep;
17668
+ const [rx, ry] = field.rowStep;
17669
+ const determinant = cx * ry - cy * rx;
17670
+ const columnLength = Math.hypot(cx, cy);
17671
+ const rowLength = Math.hypot(rx, ry);
17672
+ const area = Math.abs(determinant);
17673
+ if (!(area > 0 && Number.isFinite(area) && Number.isFinite(columnLength + rowLength)))
17674
+ throw new RangeError("Invalid terrain cell geometry");
17675
+ const sign2 = Math.sign(determinant);
17676
+ const east = [sign2 * ry / rowLength, -sign2 * rx / rowLength];
17677
+ const south = [-sign2 * cy / columnLength, sign2 * cx / columnLength];
17678
+ return {
17679
+ area,
17680
+ faceLengths: [rowLength, rowLength, columnLength, columnLength],
17681
+ faceNormals: [[-east[0], -east[1]], east, [-south[0], -south[1]], south]
17682
+ };
17683
+ }
17684
+ function createTerrainDrainage(field, { outlets = [], maxCells = 4194304 } = {}) {
17685
+ const { width, height, columnStep, rowStep } = field;
17686
+ const count = width * height;
17687
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 2147483647)
17688
+ throw new RangeError("Terrain drainage exceeds its cell budget");
17689
+ const { area: cellArea } = getTerrainCellMetrics(field);
17690
+ for (const i of outlets) {
17691
+ if (!Number.isInteger(i) || i < 0 || i >= count || field.getHeight(i % width, Math.floor(i / width)) === void 0)
17692
+ throw new RangeError("Terrain outlet must identify a valid cell");
17693
+ }
17694
+ const { heights, validity } = field.copyData();
17695
+ const receiver = new Int32Array(count).fill(-1);
17696
+ const terminal = new Int32Array(count).fill(-1);
17697
+ const contributingCells = new Uint32Array(count);
17698
+ const incoming = new Uint8Array(count);
17699
+ const queue = new Int32Array(count);
17700
+ const outletSet = new Set(outlets);
17701
+ const offsets = [];
17702
+ for (let dy = -1; dy <= 1; dy++) {
17703
+ for (let dx = -1; dx <= 1; dx++) {
17704
+ if (!dx && !dy)
17705
+ continue;
17706
+ const distance = Math.hypot(dx * columnStep[0] + dy * rowStep[0], dx * columnStep[1] + dy * rowStep[1]);
17707
+ if (!(distance > 0 && Number.isFinite(distance)))
17708
+ throw new RangeError("Invalid terrain neighbor distance");
17709
+ offsets.push({ dx, dy, distance });
17710
+ }
17711
+ }
17712
+ for (let i = 0; i < count; i++) {
17713
+ if (!validity[i])
17714
+ continue;
17715
+ contributingCells[i] = 1;
17716
+ if (outletSet.has(i))
17717
+ continue;
17718
+ const col = i % width;
17719
+ const row = Math.floor(i / width);
17720
+ let steepest = 0;
17721
+ for (const { dx, dy, distance } of offsets) {
17722
+ if (col + dx < 0 || col + dx >= width || row + dy < 0 || row + dy >= height)
17723
+ continue;
17724
+ const j = i + dx + dy * width;
17725
+ if (!validity[j] || heights[j] >= heights[i])
17726
+ continue;
17727
+ if (dx && dy && (!validity[i + dx] || !validity[i + dy * width]))
17728
+ continue;
17729
+ const slope2 = (heights[i] - heights[j]) / distance;
17730
+ if (!Number.isFinite(slope2) || slope2 === 0)
17731
+ throw new RangeError("Terrain drainage slope is outside the representable range");
17732
+ if (slope2 > steepest) {
17733
+ steepest = slope2;
17734
+ receiver[i] = j;
17735
+ }
17736
+ }
17737
+ if (receiver[i] >= 0)
17738
+ incoming[receiver[i]]++;
17739
+ }
17740
+ let end = 0;
17741
+ for (let i = 0; i < count; i++)
17742
+ if (validity[i] && !incoming[i])
17743
+ queue[end++] = i;
17744
+ for (let cursor = 0; cursor < end; cursor++) {
17745
+ const i = queue[cursor];
17746
+ const next = receiver[i];
17747
+ if (next < 0)
17748
+ continue;
17749
+ contributingCells[next] += contributingCells[i];
17750
+ if (--incoming[next] === 0)
17751
+ queue[end++] = next;
17752
+ }
17753
+ for (let cursor = end - 1; cursor >= 0; cursor--) {
17754
+ const i = queue[cursor];
17755
+ const next = receiver[i];
17756
+ terminal[i] = next < 0 ? i : terminal[next];
17757
+ }
17758
+ return { receiver, terminal, contributingCells, cellArea };
17759
+ }
17760
+
17761
+ // dist/terrain/depression-fill.js
17762
+ function fillTerrainDepressions(field, { outlets, maxCells = 4194304 }) {
17763
+ if (field.registration !== "cell")
17764
+ throw new Error("Terrain depression fill requires cell registration");
17765
+ const { width, height } = field;
17766
+ const count = width * height;
17767
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 2147483647)
17768
+ throw new RangeError("Terrain depression fill exceeds its cell budget");
17769
+ if (!outlets.length)
17770
+ throw new RangeError("Terrain depression fill requires an outlet");
17771
+ for (const i of outlets) {
17772
+ if (!Number.isInteger(i) || i < 0 || i >= count || field.getHeight(i % width, Math.floor(i / width)) === void 0)
17773
+ throw new RangeError("Terrain outlet must identify a valid cell");
17774
+ }
17775
+ const { heights, validity } = field.copyData();
17776
+ const receiver = new Int32Array(count).fill(-2);
17777
+ const heap = new Int32Array(count);
17778
+ let size = 0;
17779
+ let disconnectedCells = field.validCount;
17780
+ const before = (a, b) => heights[a] < heights[b] || heights[a] === heights[b] && a < b;
17781
+ function push(cell) {
17782
+ let slot = size++;
17783
+ while (slot > 0) {
17784
+ const parent = Math.floor((slot - 1) / 2);
17785
+ if (!before(cell, heap[parent]))
17786
+ break;
17787
+ heap[slot] = heap[parent];
17788
+ slot = parent;
17789
+ }
17790
+ heap[slot] = cell;
17791
+ }
17792
+ function pop() {
17793
+ const first = heap[0];
17794
+ const tail = heap[--size];
17795
+ let slot = 0;
17796
+ let child = 1;
17797
+ while (child < size) {
17798
+ if (child + 1 < size && before(heap[child + 1], heap[child]))
17799
+ child++;
17800
+ if (!before(heap[child], tail))
17801
+ break;
17802
+ heap[slot] = heap[child];
17803
+ slot = child;
17804
+ child = slot * 2 + 1;
17805
+ }
17806
+ if (size)
17807
+ heap[slot] = tail;
17808
+ return first;
17809
+ }
17810
+ function visit(cell, parent) {
17811
+ if (!validity[cell] || receiver[cell] !== -2)
17812
+ return;
17813
+ receiver[cell] = parent;
17814
+ disconnectedCells--;
17815
+ if (parent >= 0)
17816
+ heights[cell] = Math.max(heights[cell], heights[parent]);
17817
+ push(cell);
17818
+ }
17819
+ for (const outlet of outlets)
17820
+ visit(outlet, -1);
17821
+ while (size) {
17822
+ const cell = pop();
17823
+ const column = cell % width;
17824
+ if (column > 0)
17825
+ visit(cell - 1, cell);
17826
+ if (column + 1 < width)
17827
+ visit(cell + 1, cell);
17828
+ if (cell >= width)
17829
+ visit(cell - width, cell);
17830
+ if (cell < count - width)
17831
+ visit(cell + width, cell);
17832
+ }
17833
+ return {
17834
+ field: new HeightField({
17835
+ width,
17836
+ height,
17837
+ heights,
17838
+ validity,
17839
+ origin: field.origin,
17840
+ columnStep: field.columnStep,
17841
+ rowStep: field.rowStep,
17842
+ registration: field.registration,
17843
+ diagonal: field.diagonal,
17844
+ heightReference: field.heightReference
17845
+ }),
17846
+ receiver,
17847
+ disconnectedCells
17848
+ };
17849
+ }
17850
+
17851
+ // dist/terrain/mesh-cutout.js
17852
+ function splitTerrainMesh(mesh, polygon2, { maxWork = 4e6, maxVertices = 5e5, maxTriangles = 5e5 } = {}) {
17853
+ if (![maxWork, maxVertices, maxTriangles].every((n) => Number.isSafeInteger(n) && n >= 0) || maxVertices > 4294967295 || maxTriangles > 4294967295 || !(mesh.positions instanceof Float32Array || mesh.positions instanceof Float64Array) || !(mesh.indices instanceof Uint16Array || mesh.indices instanceof Uint32Array) || mesh.positions.length % 3 || mesh.indices.length % 3 || mesh.positions.length / 3 > maxVertices || mesh.indices.length / 3 > maxTriangles || !mesh.positions.every(Number.isFinite))
17854
+ throw new RangeError("Invalid terrain cutout mesh or capacity");
17855
+ let work = 0;
17856
+ function charge(amount) {
17857
+ work += amount;
17858
+ if (work > maxWork)
17859
+ throw new RangeError("Terrain cutout work budget exceeded");
17860
+ }
17861
+ const ring = validatePolygon(polygon2, charge);
17862
+ const vertices = [];
17863
+ for (let i = 0; i < mesh.positions.length; i += 3)
17864
+ vertices.push([mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2]]);
17865
+ const faces = [];
17866
+ for (let i = 0; i < mesh.indices.length; i += 3) {
17867
+ const face = [mesh.indices[i], mesh.indices[i + 1], mesh.indices[i + 2]];
17868
+ if (face.some((id) => id >= vertices.length))
17869
+ throw new RangeError("Invalid terrain cutout index");
17870
+ checkTriangle(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
17871
+ faces.push(face);
17872
+ }
17873
+ validateTopology(vertices, faces, charge);
17874
+ const patch = createPiece();
17875
+ const remainder = createPiece();
17876
+ const intersections2 = ring.map(() => /* @__PURE__ */ new Map());
17877
+ let fragmentCount = 0;
17878
+ function addVertex(vertex) {
17879
+ if (vertices.length >= maxVertices || !vertex.every(Number.isFinite))
17880
+ throw new RangeError("Terrain cutout vertex budget or coordinate range exceeded");
17881
+ return vertices.push(vertex) - 1;
17882
+ }
17883
+ function intersection(a, b, da, db, line) {
17884
+ const key3 = edgeKey2(a, b);
17885
+ const cache = intersections2[line];
17886
+ const saved = cache.get(key3);
17887
+ if (saved !== void 0)
17888
+ return saved;
17889
+ const t = Math.abs(da) / (Math.abs(da) + Math.abs(db));
17890
+ if (!(t > 0 && t < 1))
17891
+ throw new RangeError("Unrepresentable terrain cut intersection");
17892
+ const u = vertices[a];
17893
+ const v = vertices[b];
17894
+ const id = addVertex([
17895
+ u[0] + t * (v[0] - u[0]),
17896
+ u[1] + t * (v[1] - u[1]),
17897
+ u[2] + t * (v[2] - u[2])
17898
+ ]);
17899
+ cache.set(key3, id);
17900
+ return id;
17901
+ }
17902
+ for (let source = 0; source < faces.length; source++) {
17903
+ let fragments = [{ ids: faces[source], inside: true }];
17904
+ for (let line = 0; line < ring.length; line++) {
17905
+ const next = [];
17906
+ const a = ring[line];
17907
+ const b = ring[(line + 1) % ring.length];
17908
+ for (const fragment of fragments) {
17909
+ const { ids } = fragment;
17910
+ charge(ids.length);
17911
+ const distances = ids.map((id) => cross6(a, b, vertices[id]));
17912
+ if (distances.some((d) => !Number.isFinite(d)))
17913
+ throw new RangeError("Invalid terrain cut coordinates");
17914
+ if (!distances.some((d) => d < 0))
17915
+ next.push(fragment);
17916
+ else if (!distances.some((d) => d > 0))
17917
+ next.push({ ...fragment, inside: false });
17918
+ else {
17919
+ const positive2 = [];
17920
+ const negative = [];
17921
+ for (let i = 0; i < ids.length; i++) {
17922
+ const j = (i + 1) % ids.length;
17923
+ const d = distances[i];
17924
+ const e = distances[j];
17925
+ if (d >= 0)
17926
+ positive2.push(ids[i]);
17927
+ if (d <= 0)
17928
+ negative.push(ids[i]);
17929
+ if (d < 0 && e > 0 || d > 0 && e < 0) {
17930
+ const id = intersection(ids[i], ids[j], d, e, line);
17931
+ positive2.push(id);
17932
+ negative.push(id);
17933
+ }
17934
+ }
17935
+ next.push({ ids: positive2, inside: fragment.inside }, { ids: negative, inside: false });
17936
+ }
17937
+ if (fragmentCount + next.length > maxTriangles)
17938
+ throw new RangeError("Terrain cutout fragment budget exceeded");
17939
+ }
17940
+ fragments = next;
17941
+ }
17942
+ fragmentCount += fragments.length;
17943
+ for (const { ids, inside } of fragments) {
17944
+ const piece = inside ? patch : remainder;
17945
+ if (ids.length === 3)
17946
+ emit(piece, ids, source);
17947
+ else {
17948
+ const center = [...vertices[ids[0]]];
17949
+ for (const id of ids) {
17950
+ for (let k = 0; k < 3; k++)
17951
+ center[k] += (vertices[id][k] - vertices[ids[0]][k]) / ids.length;
17952
+ }
17953
+ const hub = addVertex(center);
17954
+ for (let i = 0; i < ids.length; i++)
17955
+ emit(piece, [ids[i], ids[(i + 1) % ids.length], hub], source);
17956
+ }
17957
+ }
17958
+ }
17959
+ function emit(piece, face, source) {
17960
+ if (patch.sourceFaces.length + remainder.sourceFaces.length >= maxTriangles)
17961
+ throw new RangeError("Terrain cutout triangle budget exceeded");
17962
+ checkTriangle(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
17963
+ const [a, b, c] = faces[source].map((id) => vertices[id]);
17964
+ const area = cross6(a, b, c);
17965
+ for (let i = 0; i < 3; i++) {
17966
+ const id = face[i];
17967
+ if (!piece.ids.has(id)) {
17968
+ if (patch.ids.size + remainder.ids.size >= maxVertices)
17969
+ throw new RangeError("Terrain cutout output vertex budget exceeded");
17970
+ piece.ids.set(id, piece.ids.size);
17971
+ const p = vertices[id];
17972
+ piece.positions.push(...p);
17973
+ piece.sourceTriangles.push(source);
17974
+ piece.sourceWeights.push(cross6(b, c, p) / area, cross6(c, a, p) / area, cross6(a, b, p) / area);
17975
+ }
17976
+ piece.indices.push(piece.ids.get(id));
17977
+ addEdge(piece.boundary, id, face[(i + 1) % 3]);
17978
+ }
17979
+ piece.sourceFaces.push(source);
17980
+ }
17981
+ for (const [key3, inside] of patch.boundary) {
17982
+ const outside = remainder.boundary.get(key3);
17983
+ if (!outside)
17984
+ continue;
17985
+ const [a, b] = inside.edge;
17986
+ if (inside.count !== 1 || outside.count !== 1 || outside.edge[0] !== b)
17987
+ throw new Error("Nonconforming terrain cut boundary");
17988
+ patch.cutEdges.push(patch.ids.get(a), patch.ids.get(b));
17989
+ remainder.cutEdges.push(remainder.ids.get(b), remainder.ids.get(a));
17990
+ }
17991
+ return { patch: finish(patch), remainder: finish(remainder) };
17992
+ }
17993
+ function validatePolygon(polygon2, charge) {
17994
+ if (polygon2.length < 3 || polygon2.some((p) => p.length !== 2 || !p.every(Number.isFinite)))
17995
+ throw new RangeError("Invalid terrain cut polygon");
17996
+ const ring = [...polygon2];
17997
+ const orientation3 = cross6(ring[0], ring[1], ring[2]);
17998
+ if (orientation3 < 0)
17999
+ ring.reverse();
18000
+ for (let i = 0; i < ring.length; i++) {
18001
+ charge(ring.length);
18002
+ const j = (i + 1) % ring.length;
18003
+ for (let k = 0; k < ring.length; k++) {
18004
+ if (k === i || k === j)
18005
+ continue;
18006
+ const area = cross6(ring[i], ring[j], ring[k]);
18007
+ if (!(area > 0 && Number.isFinite(area)))
18008
+ throw new RangeError("Terrain cut polygon must be strictly convex");
18009
+ }
18010
+ }
18011
+ return ring;
18012
+ }
18013
+ function checkTriangle(a, b, c) {
18014
+ const area = cross6(a, b, c);
18015
+ const scale3 = Math.hypot(b[0] - a[0], b[1] - a[1]) * Math.hypot(c[0] - a[0], c[1] - a[1]);
18016
+ if (!(area > Number.EPSILON * scale3 && Number.isFinite(area)))
18017
+ throw new RangeError("Terrain cut requires upward nondegenerate XY triangles");
18018
+ }
18019
+ function validateTopology(vertices, faces, charge) {
18020
+ const edges2 = /* @__PURE__ */ new Map();
18021
+ const boxes = faces.map((face) => {
18022
+ for (let i = 0; i < 3; i++)
18023
+ addEdge(edges2, face[i], face[(i + 1) % 3]);
18024
+ const points = face.map((id) => vertices[id]);
18025
+ return {
18026
+ face,
18027
+ points,
18028
+ low: Math.min(...points.map((p) => p[0])),
18029
+ high: Math.max(...points.map((p) => p[0])),
18030
+ minY: Math.min(...points.map((p) => p[1])),
18031
+ maxY: Math.max(...points.map((p) => p[1]))
18032
+ };
18033
+ }).sort((a, b) => a.low - b.low);
18034
+ for (let i = 0; i < boxes.length; i++) {
18035
+ const a = boxes[i];
18036
+ for (let j = i + 1; j < boxes.length && boxes[j].low <= a.high; j++) {
18037
+ charge(1);
18038
+ const b = boxes[j];
18039
+ if (a.maxY < b.minY || b.maxY < a.minY)
18040
+ continue;
18041
+ if (!separates(a.points, b.points) && !separates(b.points, a.points))
18042
+ throw new RangeError("Terrain cut input has overlapping XY triangles");
18043
+ checkJunctions(a.face, b.face, vertices);
18044
+ checkJunctions(b.face, a.face, vertices);
18045
+ }
18046
+ }
18047
+ }
18048
+ function separates(a, b) {
18049
+ return a.some((p, i) => b.every((q) => cross6(p, a[(i + 1) % 3], q) <= 0));
18050
+ }
18051
+ function checkJunctions(a, b, vertices) {
18052
+ for (let i = 0; i < 3; i++) {
18053
+ const u = vertices[a[i]];
18054
+ const v = vertices[a[(i + 1) % 3]];
18055
+ const overlaps2 = b.filter((id) => {
18056
+ const p = vertices[id];
18057
+ if (cross6(u, v, p) !== 0)
18058
+ return false;
18059
+ const axis = Math.abs(v[0] - u[0]) >= Math.abs(v[1] - u[1]) ? 0 : 1;
18060
+ const low = Math.min(u[axis], v[axis]);
18061
+ const high = Math.max(u[axis], v[axis]);
18062
+ if (p[axis] > low && p[axis] < high)
18063
+ throw new RangeError("Terrain cut input has a T-junction");
18064
+ return p[axis] >= low && p[axis] <= high;
18065
+ });
18066
+ if (overlaps2.length >= 2 && (!overlaps2.includes(a[i]) || !overlaps2.includes(a[(i + 1) % 3])))
18067
+ throw new RangeError("Terrain cut input has an unwelded shared edge");
18068
+ }
18069
+ }
18070
+ function addEdge(edges2, a, b) {
18071
+ const key3 = edgeKey2(a, b);
18072
+ const entry = edges2.get(key3);
18073
+ if (!entry)
18074
+ edges2.set(key3, { edge: [a, b], count: 1 });
18075
+ else {
18076
+ if (entry.count !== 1 || entry.edge[0] !== b)
18077
+ throw new RangeError("Terrain cut mesh has inconsistent or nonmanifold edges");
18078
+ entry.count++;
18079
+ }
18080
+ }
18081
+ function edgeKey2(a, b) {
18082
+ return a < b ? a + "," + b : b + "," + a;
18083
+ }
18084
+ function cross6(a, b, c) {
18085
+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
18086
+ }
18087
+ function createPiece() {
18088
+ return {
18089
+ ids: /* @__PURE__ */ new Map(),
18090
+ positions: [],
18091
+ indices: [],
18092
+ sourceTriangles: [],
18093
+ sourceWeights: [],
18094
+ sourceFaces: [],
18095
+ boundary: /* @__PURE__ */ new Map(),
18096
+ cutEdges: []
18097
+ };
18098
+ }
18099
+ function finish(piece) {
18100
+ return {
18101
+ positions: Float64Array.from(piece.positions),
18102
+ indices: Uint32Array.from(piece.indices),
18103
+ sourceTriangles: Uint32Array.from(piece.sourceTriangles),
18104
+ sourceWeights: Float64Array.from(piece.sourceWeights),
18105
+ sourceFaces: Uint32Array.from(piece.sourceFaces),
18106
+ cutEdges: Uint32Array.from(piece.cutEdges)
18107
+ };
18108
+ }
18109
+
18110
+ // dist/terrain/cutout-skirts.js
18111
+ function createTerrainCutoutSkirts(cutout, { lift = 0, patch, remainder }) {
18112
+ if (!Number.isFinite(lift))
18113
+ throw new RangeError("Invalid terrain cutout lift");
18114
+ const positions = cutout.patch.positions.slice();
18115
+ for (let i = 2; i < positions.length; i += 3) {
18116
+ positions[i] += lift;
18117
+ if (!Number.isFinite(positions[i]))
18118
+ throw new RangeError("Terrain cutout lift overflow");
18119
+ }
18120
+ return {
18121
+ patch: skirtPiece({ ...cutout.patch, positions }, patch),
18122
+ remainder: skirtPiece(cutout.remainder, remainder)
18123
+ };
18124
+ }
18125
+ function skirtPiece(surface2, options) {
18126
+ if (!surface2.cutEdges.length)
18127
+ return { surface: surface2 };
18128
+ return {
18129
+ surface: surface2,
18130
+ skirt: createTerrainSkirt(surface2, { ...options, edges: surface2.cutEdges })
18131
+ };
18132
+ }
18133
+
18134
+ // dist/terrain/watershed-accumulation.js
18135
+ function accumulateTerrainWatersheds(receiver, { maxCells = 4194304 } = {}) {
18136
+ const count = receiver.length;
18137
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 2147483647)
18138
+ throw new RangeError("Terrain watershed accumulation exceeds its cell budget");
18139
+ const incoming = new Uint32Array(count);
18140
+ const contributingCells = new Uint32Array(count);
18141
+ const terminal = new Int32Array(count).fill(-1);
18142
+ const queue = new Int32Array(count);
18143
+ let active = 0;
18144
+ for (let i = 0; i < count; i++) {
18145
+ const next = receiver[i];
18146
+ if (next === -2)
18147
+ continue;
18148
+ if (next < -1 || next >= count || next >= 0 && receiver[next] === -2)
18149
+ throw new RangeError("Invalid terrain watershed receiver");
18150
+ active++;
18151
+ contributingCells[i] = 1;
18152
+ if (next >= 0)
18153
+ incoming[next]++;
18154
+ }
18155
+ let end = 0;
18156
+ for (let i = 0; i < count; i++) {
18157
+ if (contributingCells[i] && !incoming[i])
18158
+ queue[end++] = i;
18159
+ }
18160
+ for (let cursor = 0; cursor < end; cursor++) {
18161
+ const i = queue[cursor];
18162
+ const next = receiver[i];
18163
+ if (next < 0)
18164
+ continue;
18165
+ contributingCells[next] += contributingCells[i];
18166
+ if (--incoming[next] === 0)
18167
+ queue[end++] = next;
18168
+ }
18169
+ if (end !== active)
18170
+ throw new RangeError("Terrain watershed receiver graph contains a cycle");
18171
+ for (let cursor = end - 1; cursor >= 0; cursor--) {
18172
+ const i = queue[cursor];
18173
+ const next = receiver[i];
18174
+ terminal[i] = next < 0 ? i : terminal[next];
18175
+ }
18176
+ return { terminal, contributingCells };
18177
+ }
17252
18178
  //# sourceMappingURL=index.cjs.map