@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
@@ -37,10 +37,13 @@ __export(index_exports, {
37
37
  TerrainContourBoundaryAxis: () => TerrainContourBoundaryAxis,
38
38
  TerrainMorphStatus: () => TerrainMorphStatus,
39
39
  TerrainProfileViewStatus: () => TerrainProfileViewStatus,
40
+ TerrainRegionalViewStatus: () => TerrainRegionalViewStatus,
40
41
  TerrainSampleStatus: () => TerrainSampleStatus,
41
42
  TerrainSurface: () => TerrainSurface,
42
43
  TerrainVertexHaloStatus: () => TerrainVertexHaloStatus,
43
44
  TiledHeightField: () => TiledHeightField,
45
+ accumulateTerrainWatersheds: () => accumulateTerrainWatersheds,
46
+ boundTerrainLodScreenError: () => boundTerrainLodScreenError,
44
47
  boundTerrainMeshError: () => boundTerrainMeshError,
45
48
  certifyTerrainMeshCoverage: () => certifyTerrainMeshCoverage,
46
49
  coordinateTerrainLodMorphs: () => coordinateTerrainLodMorphs,
@@ -48,6 +51,8 @@ __export(index_exports, {
48
51
  createDelatinTerrainMesh: () => createDelatinTerrainMesh,
49
52
  createMartiniTerrainMesh: () => createMartiniTerrainMesh,
50
53
  createTerrainContours: () => createTerrainContours,
54
+ createTerrainCutoutSkirts: () => createTerrainCutoutSkirts,
55
+ createTerrainDrainage: () => createTerrainDrainage,
51
56
  createTerrainFilteredPyramid: () => createTerrainFilteredPyramid,
52
57
  createTerrainGradientGrid: () => createTerrainGradientGrid,
53
58
  createTerrainGradientPyramid: () => createTerrainGradientPyramid,
@@ -56,6 +61,7 @@ __export(index_exports, {
56
61
  createTerrainMesh: () => createTerrainMesh,
57
62
  createTerrainMixedIsobands: () => createTerrainMixedIsobands,
58
63
  createTerrainMixedVertexTileHalos: () => createTerrainMixedVertexTileHalos,
64
+ createTerrainRegionalViewshed: () => createTerrainRegionalViewshed,
59
65
  createTerrainSkirt: () => createTerrainSkirt,
60
66
  createTerrainSlopeAspectGrid: () => createTerrainSlopeAspectGrid,
61
67
  createTerrainSurface: () => createTerrainSurface,
@@ -65,7 +71,9 @@ __export(index_exports, {
65
71
  discoverGeographicTerrainLodSeams: () => discoverGeographicTerrainLodSeams,
66
72
  discoverGeographicTerrainPoles: () => discoverGeographicTerrainPoles,
67
73
  evaluateTerrainLodMorph: () => evaluateTerrainLodMorph,
74
+ fillTerrainDepressions: () => fillTerrainDepressions,
68
75
  getGeographicTerrainNeighbor: () => getGeographicTerrainNeighbor,
76
+ getTerrainCellMetrics: () => getTerrainCellMetrics,
69
77
  getTerrainHierarchyNode: () => getTerrainHierarchyNode,
70
78
  getTerrainMeshEdge: () => getTerrainMeshEdge,
71
79
  getTerrainProfileHorizon: () => getTerrainProfileHorizon,
@@ -83,6 +91,7 @@ __export(index_exports, {
83
91
  simplifyTerrainContourPaths: () => simplifyTerrainContourPaths,
84
92
  simplifyTerrainContourPathsTopology: () => simplifyTerrainContourPathsTopology,
85
93
  splitTerrainBreaklines: () => splitTerrainBreaklines,
94
+ splitTerrainMesh: () => splitTerrainMesh,
86
95
  stitchTerrainContourTiles: () => stitchTerrainContourTiles,
87
96
  stitchTerrainContours: () => stitchTerrainContours,
88
97
  stitchTerrainLodCut: () => stitchTerrainLodCut,
@@ -92,6 +101,10 @@ __export(index_exports, {
92
101
  sweepTerrainCylinder: () => sweepTerrainCylinder,
93
102
  sweepTerrainPlane: () => sweepTerrainPlane,
94
103
  sweepTerrainPolytope: () => sweepTerrainPolytope,
104
+ sweepTerrainRotatingBox: () => sweepTerrainRotatingBox,
105
+ sweepTerrainRotatingCapsule: () => sweepTerrainRotatingCapsule,
106
+ sweepTerrainRotatingPolytope: () => sweepTerrainRotatingPolytope,
107
+ sweepTerrainRotatingSphere: () => sweepTerrainRotatingSphere,
95
108
  sweepTerrainSphere: () => sweepTerrainSphere,
96
109
  sweepTerrainTaperedCapsule: () => sweepTerrainTaperedCapsule,
97
110
  sweepTerrainTriangleMesh: () => sweepTerrainTriangleMesh,
@@ -428,9 +441,9 @@ function validateBatch(positions, output) {
428
441
 
429
442
  // dist/terrain/mesh-skirts.js
430
443
  function createTerrainSkirt(mesh, options) {
431
- const { positions, indices } = mesh, { height, edges: edges2 } = options;
444
+ const { positions, indices } = mesh, { height, baseZ, edges: edges2 } = options;
432
445
  const maxVertices = options.maxVertices ?? 2e6, maxTriangles = options.maxTriangles ?? 4e6;
433
- if (!Number.isFinite(height) || height <= 0 || !Number.isSafeInteger(maxVertices) || maxVertices < 0 || maxVertices > 4294967295 || !Number.isSafeInteger(maxTriangles) || maxTriangles < 0 || maxTriangles > 4294967295)
446
+ 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)
434
447
  throw new Error("Invalid terrain skirt height or capacity");
435
448
  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)
436
449
  throw new Error("Invalid terrain skirt mesh or capacity");
@@ -486,7 +499,7 @@ function createTerrainSkirt(mesh, options) {
486
499
  [b, lowerB]
487
500
  ]) {
488
501
  resultPositions.set(positions.subarray(3 * source, 3 * source + 3), 3 * target);
489
- resultPositions[3 * target + 2] = positions[3 * source + 2] - height;
502
+ resultPositions[3 * target + 2] = baseZ ?? positions[3 * source + 2] - height;
490
503
  if (!Number.isFinite(resultPositions[3 * target + 2]) || resultPositions[3 * target + 2] >= positions[3 * source + 2])
491
504
  throw new Error("Terrain skirt height cannot be represented in position precision");
492
505
  sourceVertexIndices[target - vertexCount] = source;
@@ -4054,56 +4067,48 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
4054
4067
  if (![maxSamples, maxTests].every((v) => Number.isSafeInteger(v) && v >= 0))
4055
4068
  throw new Error("Invalid mixed halo capacity");
4056
4069
  let count = 0;
4057
- const addresses = /* @__PURE__ */ new Set();
4070
+ let previousKey;
4058
4071
  let frame;
4059
4072
  const sources = [...tiles].sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row).map((tile) => {
4060
- if (![tile.column, tile.row, tile.spacing].every(Number.isSafeInteger) || tile.spacing < 1 || 2 ** Math.round(Math.log2(tile.spacing)) !== tile.spacing)
4061
- throw new Error("Invalid mixed halo lattice");
4062
- const key2 = `${tile.spacing}/${tile.column}/${tile.row}`;
4063
- if (addresses.has(key2))
4064
- throw new Error("Duplicate mixed halo tile");
4065
- addresses.add(key2);
4066
4073
  count += (tile.field.width + 2) * (tile.field.height + 2);
4067
4074
  if (!Number.isSafeInteger(count) || count > maxSamples)
4068
4075
  throw new Error("Mixed halo sample capacity exceeded");
4069
- let field = preparation == null ? void 0 : preparation.fields.get(tile);
4070
- if (!field) {
4071
- field = new HeightField(tile.field);
4072
- preparation == null ? void 0 : preparation.fields.set(tile, field);
4076
+ let prepared = preparation == null ? void 0 : preparation.tiles.get(tile);
4077
+ if (!prepared) {
4078
+ prepared = prepareMixedHaloTile(tile);
4079
+ preparation == null ? void 0 : preparation.tiles.set(tile, prepared);
4080
+ }
4081
+ const { key: key2, source: field, columnStep: column, rowStep: row, frameOrigin: origin, scale } = prepared;
4082
+ if (previousKey === key2)
4083
+ throw new Error("Duplicate mixed halo tile");
4084
+ previousKey = key2;
4085
+ if (frame) {
4086
+ if (frame.reference !== field.heightReference)
4087
+ throw new Error("Mixed halo frames or height references differ");
4088
+ for (let i = 0; i < 2; i++) {
4089
+ if (column[i] !== frame.column[i] || row[i] !== frame.row[i] || origin[i] !== frame.origin[i] && Math.abs(origin[i] - frame.origin[i]) > Math.min(16 * Number.EPSILON * Math.max(scale[i], frame.scale[i]), 1e-9 * Math.max(Math.abs(column[i]), Math.abs(row[i]))))
4090
+ throw new Error("Mixed halo frames or height references differ");
4091
+ }
4073
4092
  }
4074
- if (field.registration !== "vertex")
4075
- throw new Error("Mixed halos require vertex registration");
4076
- const column = field.columnStep.map((v) => v / tile.spacing);
4077
- const row = field.rowStep.map((v) => v / tile.spacing);
4078
- const origin = field.origin.map((v, axis) => v - tile.column * column[axis] - tile.row * row[axis]);
4079
- const scale = field.origin.map((v, i) => Math.max(1, Math.abs(v), Math.abs(tile.column * column[i]), Math.abs(tile.row * row[i])));
4080
- if (!origin.every(Number.isFinite))
4081
- throw new Error("Mixed halo coordinate overflow");
4082
- if (frame && (frame.reference !== field.heightReference || column.some((v, i) => v !== frame.column[i]) || row.some((v, i) => v !== frame.row[i]) || origin.some((v, i) => Math.abs(v - frame.origin[i]) > Math.min(16 * Number.EPSILON * Math.max(scale[i], frame.scale[i]), 1e-9 * Math.max(Math.abs(column[i]), Math.abs(row[i]))))))
4083
- throw new Error("Mixed halo frames or height references differ");
4084
4093
  frame ?? (frame = { origin, column, row, reference: field.heightReference, scale });
4085
- return { ...tile, source: field };
4094
+ return prepared;
4086
4095
  });
4087
- for (const axis of ["column", "row"]) {
4088
- let min = Infinity, max = -Infinity;
4089
- for (const tile of sources) {
4090
- const size = axis === "column" ? tile.source.width : tile.source.height;
4091
- const low = tile[axis] - tile.spacing, high = tile[axis] + size * tile.spacing;
4092
- if (![low, high].every(Number.isSafeInteger))
4093
- throw new Error("Mixed halo lattice overflow");
4094
- min = Math.min(min, low);
4095
- max = Math.max(max, high);
4096
- }
4097
- if (sources.length && !Number.isSafeInteger(max - min))
4098
- throw new Error("Mixed halo lattice span overflow");
4099
- }
4096
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
4097
+ for (let i = 0; i < sources.length; i++) {
4098
+ const { haloBounds } = sources[i];
4099
+ minX = Math.min(minX, haloBounds.minX);
4100
+ minY = Math.min(minY, haloBounds.minY);
4101
+ maxX = Math.max(maxX, haloBounds.maxX);
4102
+ maxY = Math.max(maxY, haloBounds.maxY);
4103
+ }
4104
+ if (sources.length && (!Number.isSafeInteger(maxX - minX) || !Number.isSafeInteger(maxY - minY)))
4105
+ throw new Error("Mixed halo lattice span overflow");
4100
4106
  if (targets && targets.size === 0)
4101
4107
  return { tiles: [] };
4102
4108
  let index;
4103
4109
  if (sources.length > 8) {
4104
- const keys = preparation && sources.map((tile) => `${tile.spacing}/${tile.column}/${tile.row}/${tile.source.width}/${tile.source.height}`);
4105
4110
  const cached = preparation == null ? void 0 : preparation.layout;
4106
- if (keys && cached && keys.length === cached.keys.length && keys.every((key2, i) => key2 === cached.keys[i])) {
4111
+ if (cached && sources.length === cached.keys.length && sources.every((tile, i) => tile.layoutKey === cached.keys[i])) {
4107
4112
  index = cached.query;
4108
4113
  } else {
4109
4114
  index = createTerrainBoxIndex(sources.map((tile) => ({
@@ -4112,8 +4117,8 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
4112
4117
  maxX: tile.column + (tile.source.width - 1) * tile.spacing,
4113
4118
  maxY: tile.row + (tile.source.height - 1) * tile.spacing
4114
4119
  })));
4115
- if (preparation && keys)
4116
- preparation.layout = { keys, query: index };
4120
+ if (preparation)
4121
+ preparation.layout = { keys: sources.map((tile) => tile.layoutKey), query: index };
4117
4122
  }
4118
4123
  }
4119
4124
  let tests = 0;
@@ -4122,21 +4127,17 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
4122
4127
  throw new Error("Mixed halo tile-test budget exceeded");
4123
4128
  };
4124
4129
  return {
4125
- tiles: sources.filter((tile) => !targets || targets.has(`${tile.spacing}/${tile.column}/${tile.row}`)).map((tile) => {
4130
+ tiles: sources.filter((tile) => !targets || targets.has(tile.key)).map((tile) => {
4126
4131
  const source = tile.source, width = source.width + 2, height = source.height + 2;
4127
4132
  const heights = new Float64Array(width * height), validity = new Uint8Array(heights.length), statuses = new Uint8Array(heights.length);
4128
- const candidates = (index == null ? void 0 : index({
4129
- minX: tile.column - tile.spacing,
4130
- minY: tile.row - tile.spacing,
4131
- maxX: tile.column + source.width * tile.spacing,
4132
- maxY: tile.row + source.height * tile.spacing
4133
- }, charge).map((id) => sources[id])) ?? sources;
4133
+ const candidates = (index == null ? void 0 : index(tile.haloBounds, charge).map((id) => sources[id])) ?? sources;
4134
4134
  for (let y = 0; y < height; y++)
4135
4135
  for (let x = 0; x < width; x++) {
4136
4136
  const gx = tile.column + (x - 1) * tile.spacing, gy = tile.row + (y - 1) * tile.spacing;
4137
- if (![gx, gy].every(Number.isSafeInteger))
4137
+ if (!Number.isSafeInteger(gx) || !Number.isSafeInteger(gy))
4138
4138
  throw new Error("Mixed halo lattice overflow");
4139
- for (const candidate of candidates) {
4139
+ for (let candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
4140
+ const candidate = candidates[candidateIndex];
4140
4141
  charge();
4141
4142
  const cx = (gx - candidate.column) / candidate.spacing, cy = (gy - candidate.row) / candidate.spacing;
4142
4143
  const f = candidate.source;
@@ -4179,6 +4180,36 @@ function buildMixedVertexTileHalos(tiles, options = {}, targets, preparation) {
4179
4180
  })
4180
4181
  };
4181
4182
  }
4183
+ function prepareMixedHaloTile(tile) {
4184
+ const { column, row, spacing } = tile;
4185
+ if (![column, row, spacing].every(Number.isSafeInteger) || spacing < 1 || 2 ** Math.round(Math.log2(spacing)) !== spacing)
4186
+ throw new Error("Invalid mixed halo lattice");
4187
+ const source = new HeightField(tile.field);
4188
+ if (source.registration !== "vertex")
4189
+ throw new Error("Mixed halos require vertex registration");
4190
+ const columnStep = source.columnStep.map((v) => v / spacing);
4191
+ const rowStep = source.rowStep.map((v) => v / spacing);
4192
+ const frameOrigin = source.origin.map((v, i) => v - column * columnStep[i] - row * rowStep[i]);
4193
+ const scale = source.origin.map((v, i) => Math.max(1, Math.abs(v), Math.abs(column * columnStep[i]), Math.abs(row * rowStep[i])));
4194
+ if (!frameOrigin.every(Number.isFinite))
4195
+ throw new Error("Mixed halo coordinate overflow");
4196
+ const minX = column - spacing, minY = row - spacing;
4197
+ const maxX = column + source.width * spacing, maxY = row + source.height * spacing;
4198
+ if (![minX, minY, maxX, maxY].every(Number.isSafeInteger))
4199
+ throw new Error("Mixed halo lattice overflow");
4200
+ const key2 = `${spacing}/${column}/${row}`;
4201
+ return {
4202
+ ...tile,
4203
+ source,
4204
+ columnStep,
4205
+ rowStep,
4206
+ frameOrigin,
4207
+ scale,
4208
+ key: key2,
4209
+ layoutKey: `${key2}/${source.width}/${source.height}`,
4210
+ haloBounds: { minX, minY, maxX, maxY }
4211
+ };
4212
+ }
4182
4213
 
4183
4214
  // dist/terrain/mixed-halo-update.js
4184
4215
  var key = (t) => `${t.spacing}/${t.column}/${t.row}`;
@@ -4224,14 +4255,21 @@ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
4224
4255
  const budget = options.maxDependencyTests ?? 1e7;
4225
4256
  if (!Number.isSafeInteger(budget) || budget < 0)
4226
4257
  throw new Error("Invalid mixed halo dependency budget");
4227
- const old = new Map(previous == null ? void 0 : previous.sources.map((t) => [key(t), t]));
4228
- const current = new Map(resident.map((t) => [key(t), t]));
4229
- const cached = new Map(previous == null ? void 0 : previous.tiles.map((t) => [key(t), t]));
4230
- const targets = /* @__PURE__ */ new Set();
4231
4258
  const unchangedLayout = (previous == null ? void 0 : previous.sources.length) === resident.length && resident.every((tile, i) => {
4232
4259
  const prior = previous.sources[i];
4233
- return key(prior) === key(tile) && prior.field.width === tile.field.width && prior.field.height === tile.field.height;
4260
+ 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;
4234
4261
  });
4262
+ const old = unchangedLayout ? void 0 : new Map(previous == null ? void 0 : previous.sources.map((t) => [key(t), t]));
4263
+ const targets = /* @__PURE__ */ new Set();
4264
+ const initialized = previous !== null && preparations.has(previous);
4265
+ if (!initialized) {
4266
+ const cached = new Set(previous == null ? void 0 : previous.tiles.map(key));
4267
+ for (const tile of resident) {
4268
+ const address = key(tile);
4269
+ if (!cached.has(address))
4270
+ targets.add(address);
4271
+ }
4272
+ }
4235
4273
  let index = unchangedLayout && previous ? targetIndexes.get(previous) : void 0;
4236
4274
  let tests = 0;
4237
4275
  const charge = () => {
@@ -4243,12 +4281,13 @@ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
4243
4281
  for (const id of index(box, charge))
4244
4282
  targets.add(key(resident[id]));
4245
4283
  }
4246
- for (const tile of resident) {
4247
- const address = key(tile);
4248
- const prior = old.get(address);
4249
- if (!cached.has(address) || prior !== tile)
4250
- targets.add(address);
4251
- if (prior === tile || !previous)
4284
+ for (let i = 0; i < resident.length; i++) {
4285
+ const tile = resident[i];
4286
+ const prior = unchangedLayout ? previous.sources[i] : old == null ? void 0 : old.get(key(tile));
4287
+ if (prior === tile)
4288
+ continue;
4289
+ targets.add(key(tile));
4290
+ if (!previous)
4252
4291
  continue;
4253
4292
  if (!prior) {
4254
4293
  invalidate(bounds(tile));
@@ -4261,24 +4300,44 @@ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
4261
4300
  invalidate(dirty);
4262
4301
  }
4263
4302
  }
4264
- for (const [address, tile] of old) {
4265
- if (!current.has(address) && resident.length)
4266
- invalidate(bounds(tile));
4303
+ const removed = [];
4304
+ if (old == null ? void 0 : old.size) {
4305
+ const current = new Set(resident.map(key));
4306
+ for (const [address, tile] of old) {
4307
+ if (current.has(address))
4308
+ continue;
4309
+ removed.push(address);
4310
+ if (resident.length)
4311
+ invalidate(bounds(tile));
4312
+ }
4267
4313
  }
4268
4314
  const priorPreparation = previous && preparations.get(previous);
4269
4315
  const preparation = {
4270
- fields: (priorPreparation == null ? void 0 : priorPreparation.fields) ?? /* @__PURE__ */ new WeakMap(),
4316
+ tiles: (priorPreparation == null ? void 0 : priorPreparation.tiles) ?? /* @__PURE__ */ new WeakMap(),
4271
4317
  layout: priorPreparation == null ? void 0 : priorPreparation.layout
4272
4318
  };
4273
4319
  const built = buildMixedVertexTileHalos(resident, options, targets, preparation).tiles;
4274
- for (const tile of built)
4275
- cached.set(key(tile), tile);
4276
- const tiles = resident.map((t) => cached.get(key(t))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
4320
+ let tiles;
4321
+ if (unchangedLayout && initialized) {
4322
+ let cursor = 0;
4323
+ tiles = previous.tiles.map((tile) => {
4324
+ const replacement = built[cursor];
4325
+ if ((replacement == null ? void 0 : replacement.spacing) !== tile.spacing || replacement.column !== tile.column || replacement.row !== tile.row)
4326
+ return tile;
4327
+ cursor++;
4328
+ return replacement;
4329
+ });
4330
+ } else {
4331
+ const cached = new Map(previous == null ? void 0 : previous.tiles.map((tile) => [key(tile), tile]));
4332
+ for (const tile of built)
4333
+ cached.set(key(tile), tile);
4334
+ tiles = resident.map((tile) => cached.get(key(tile))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
4335
+ }
4277
4336
  const snapshot = {
4278
4337
  sources: resident.slice(),
4279
4338
  tiles,
4280
4339
  rebuilt: built.map(key),
4281
- removed: [...old.keys()].filter((k) => !current.has(k)).sort()
4340
+ removed: removed.sort()
4282
4341
  };
4283
4342
  preparations.set(snapshot, preparation);
4284
4343
  if (index)
@@ -5590,12 +5649,12 @@ function meshValidDomain(field, options, constraints) {
5590
5649
  const { width, height, origin, heightReference } = regular;
5591
5650
  const active = new Uint8Array(count);
5592
5651
  const boundary = /* @__PURE__ */ new Map();
5593
- const edgeKey2 = (a, b) => Math.min(a, b) * count + Math.max(a, b);
5652
+ const edgeKey3 = (a, b) => Math.min(a, b) * count + Math.max(a, b);
5594
5653
  for (let i = 0; i < regular.indices.length; i += 3) {
5595
5654
  for (let j = 0; j < 3; j++) {
5596
5655
  const a = regular.indices[i + j], b = regular.indices[i + (j + 1) % 3];
5597
5656
  active[a] = 1;
5598
- const key2 = edgeKey2(a, b);
5657
+ const key2 = edgeKey3(a, b);
5599
5658
  if (!boundary.delete(key2))
5600
5659
  boundary.set(key2, [a, b]);
5601
5660
  }
@@ -6059,15 +6118,75 @@ function measureGeographicTerrainSeam(a, b, probes, options = {}) {
6059
6118
  });
6060
6119
  }
6061
6120
 
6121
+ // dist/terrain/lod-screen-error.js
6122
+ function slack(value) {
6123
+ return Math.abs(value) * (2 * Number.EPSILON) + Number.MIN_VALUE;
6124
+ }
6125
+ function down(value) {
6126
+ return value - slack(value);
6127
+ }
6128
+ function up(value) {
6129
+ return value + slack(value);
6130
+ }
6131
+ function boundTerrainLodScreenError(bounds2, projection) {
6132
+ if (bounds2.min.length !== 3 || bounds2.max.length !== 3 || !bounds2.min.every((value, i) => Number.isFinite(value) && value <= bounds2.max[i]) || !bounds2.max.every(Number.isFinite) || !Number.isFinite(bounds2.geometricError) || bounds2.geometricError < 0)
6133
+ throw new RangeError("Invalid terrain LOD screen-error bounds");
6134
+ return prepareTerrainLodScreenError(projection)(bounds2);
6135
+ }
6136
+ function prepareTerrainLodScreenError(projection) {
6137
+ const { width, height, depthRange = "negative-one-to-one", reversedDepth = false } = projection;
6138
+ if (projection.matrix.length !== 16)
6139
+ throw new RangeError("Invalid terrain LOD clip matrix");
6140
+ const matrix = Array.from(projection.matrix);
6141
+ if (!matrix.every(Number.isFinite) || !Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0 || depthRange !== "negative-one-to-one" && depthRange !== "zero-to-one")
6142
+ throw new RangeError("Invalid terrain LOD projection");
6143
+ return ({ min, max, geometricError: error }) => {
6144
+ if (error === 0)
6145
+ return 0;
6146
+ function row(index) {
6147
+ let lower = matrix[12 + index];
6148
+ let upper = lower;
6149
+ let change = 0;
6150
+ for (let axis = 0; axis < 3; axis++) {
6151
+ const coefficient = matrix[4 * axis + index];
6152
+ const a = coefficient * min[axis];
6153
+ const b = coefficient * max[axis];
6154
+ lower = down(lower + down(Math.min(a, b)));
6155
+ upper = up(upper + up(Math.max(a, b)));
6156
+ change = up(change + up(Math.abs(coefficient) * error));
6157
+ }
6158
+ return { lower, upper, change };
6159
+ }
6160
+ const w = row(3);
6161
+ const z = row(2);
6162
+ const nearLow = reversedDepth ? down(w.lower - z.upper) : depthRange === "zero-to-one" ? z.lower : down(z.lower + w.lower);
6163
+ const nearHigh = reversedDepth ? up(w.upper - z.lower) : depthRange === "zero-to-one" ? z.upper : up(z.upper + w.upper);
6164
+ const nearChange = !reversedDepth && depthRange === "zero-to-one" ? z.change : up(z.change + w.change);
6165
+ if (up(nearHigh + nearChange) < 0)
6166
+ return 0;
6167
+ const denominator = down(w.lower - w.change);
6168
+ if (!(down(nearLow - nearChange) > 0 && denominator > 0))
6169
+ return Infinity;
6170
+ function pixelAxis(index, extent) {
6171
+ const coordinate = row(index);
6172
+ const magnitude2 = Math.max(Math.abs(coordinate.lower), Math.abs(coordinate.upper));
6173
+ const ndc = up(magnitude2 / denominator);
6174
+ const coupling = up(ndc * w.change);
6175
+ const numerator = up(coordinate.change + coupling);
6176
+ return up(up(numerator / denominator) * up(extent / 2));
6177
+ }
6178
+ const pixels = pixelAxis(0, width) + pixelAxis(1, height);
6179
+ return Number.isFinite(pixels) ? up(pixels) : Infinity;
6180
+ };
6181
+ }
6182
+
6062
6183
  // dist/terrain/lod-select.js
6063
6184
  function selectTerrainLod(roots, view) {
6064
6185
  var _a;
6065
- const { position, verticalFov, viewportHeight, targetPixels, hysteresis = 0.2, previouslyRefined, maxVisited = 1e5 } = view;
6066
- if (!position.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)
6186
+ const { targetPixels, hysteresis = 0.2, previouslyRefined, maxVisited = 1e5 } = view;
6187
+ if (!Number.isFinite(targetPixels) || targetPixels <= 0 || !(hysteresis >= 0 && hysteresis < 1) || !Number.isSafeInteger(maxVisited) || maxVisited < 1)
6067
6188
  throw new Error("Invalid terrain LOD view");
6068
- const scale = viewportHeight / (2 * Math.tan(verticalFov / 2));
6069
- if (!Number.isFinite(scale))
6070
- throw new Error("Terrain LOD projection scale overflow");
6189
+ const pixelError = "projection" in view ? prepareTerrainLodScreenError(view.projection) : createDistanceEstimator(view.position, view.verticalFov, view.viewportHeight);
6071
6190
  const selected = [];
6072
6191
  const refined = /* @__PURE__ */ new Set();
6073
6192
  const unavailable = [];
@@ -6080,14 +6199,13 @@ function selectTerrainLod(roots, view) {
6080
6199
  if (seen.has(tile.id))
6081
6200
  throw new Error("Duplicate terrain LOD tile or cycle");
6082
6201
  seen.add(tile.id);
6083
- if (![...tile.min, ...tile.max, tile.geometricError].every(Number.isFinite) || tile.geometricError < 0 || tile.min.some((n, i) => n > tile.max[i]))
6202
+ 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]))
6084
6203
  throw new Error("Invalid terrain LOD tile bounds or error");
6085
6204
  if (!tile.resident) {
6086
6205
  unavailable.push(tile.id);
6087
6206
  continue;
6088
6207
  }
6089
- const distance = Math.hypot(...position.map((n, i) => Math.max(tile.min[i] - n, n - tile.max[i], 0)));
6090
- const pixels = tile.geometricError === 0 ? 0 : tile.geometricError / distance * scale;
6208
+ const pixels = pixelError(tile);
6091
6209
  const threshold = targetPixels * ((previouslyRefined == null ? void 0 : previouslyRefined.has(tile.id)) ? 1 - hysteresis : 1);
6092
6210
  if (pixels > threshold && ((_a = tile.children) == null ? void 0 : _a.length) && tile.children.every((child) => child.resident)) {
6093
6211
  if (pending.length + seen.size + tile.children.length > maxVisited)
@@ -6101,6 +6219,17 @@ function selectTerrainLod(roots, view) {
6101
6219
  }
6102
6220
  return { selected, refined, unavailable };
6103
6221
  }
6222
+ function createDistanceEstimator(position, verticalFov, viewportHeight) {
6223
+ if (!position.every(Number.isFinite) || !Number.isFinite(verticalFov) || verticalFov <= 0 || verticalFov >= Math.PI || !Number.isFinite(viewportHeight) || viewportHeight <= 0)
6224
+ throw new Error("Invalid terrain LOD view");
6225
+ const scale = viewportHeight / (2 * Math.tan(verticalFov / 2));
6226
+ if (!Number.isFinite(scale))
6227
+ throw new Error("Terrain LOD projection scale overflow");
6228
+ return (tile) => {
6229
+ const distance = Math.hypot(...position.map((n, i) => Math.max(tile.min[i] - n, n - tile.max[i], 0)));
6230
+ return tile.geometricError === 0 ? 0 : tile.geometricError / distance * scale;
6231
+ };
6232
+ }
6104
6233
 
6105
6234
  // dist/terrain/lod-stitch.js
6106
6235
  function stitchTerrainLodCut(input, seams) {
@@ -6197,14 +6326,14 @@ function splitTerrainBreaklines(input, options = {}) {
6197
6326
  throw new Error("Breakline output limit exceeded");
6198
6327
  knots.push({ t, point });
6199
6328
  };
6200
- const cross3 = (ax, ay, bx, by) => ax * by - ay * bx;
6329
+ const cross4 = (ax, ay, bx, by) => ax * by - ay * bx;
6201
6330
  for (let i = 0; i < lines.length; i++) {
6202
6331
  const a = lines[i];
6203
6332
  for (let j = i + 1; j < lines.length; j++) {
6204
6333
  const b = lines[j];
6205
6334
  const x = b.p[0] - a.p[0], y = b.p[1] - a.p[1];
6206
- const det = cross3(a.dx, a.dy, b.dx, b.dy);
6207
- const u = cross3(x, y, a.dx, a.dy), t = cross3(x, y, b.dx, b.dy);
6335
+ const det = cross4(a.dx, a.dy, b.dx, b.dy);
6336
+ const u = cross4(x, y, a.dx, a.dy), t = cross4(x, y, b.dx, b.dy);
6208
6337
  if (![det, u, t].every(Number.isFinite))
6209
6338
  throw new Error("Breakline intersection overflow");
6210
6339
  if (det === 0) {
@@ -6613,9 +6742,12 @@ var cross2 = (a, b) => [
6613
6742
  var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
6614
6743
  var edges = ([a, b, c]) => [sub2(b, a), sub2(c, b), sub2(a, c)];
6615
6744
  function sweepTerrainPolytope(surface, collider, translation, { maxWork = 1e5 } = {}) {
6745
+ return queryTerrainPolytope(surface.copyData(), surface.origin, collider, translation, maxWork);
6746
+ }
6747
+ function queryTerrainPolytope(data, origin, collider, translation, maxWork, padding = 0) {
6616
6748
  if (!Number.isSafeInteger(maxWork) || maxWork < 0 || translation.length !== 3 || !translation.every(Number.isFinite) || collider.vertices.length < 4 || collider.faces.length < 4 || collider.vertices.some((point) => point.length !== 3 || !point.every(Number.isFinite)))
6617
6749
  throw new RangeError("Invalid terrain polytope sweep");
6618
- const vertices = collider.vertices.map((point) => sub2(point, surface.origin));
6750
+ const vertices = collider.vertices.map((point) => sub2(point, origin));
6619
6751
  const normals = [];
6620
6752
  const directions = [];
6621
6753
  for (const face of collider.faces) {
@@ -6628,7 +6760,7 @@ function sweepTerrainPolytope(surface, collider, translation, { maxWork = 1e5 }
6628
6760
  normals.push(normal);
6629
6761
  directions.push(...side);
6630
6762
  }
6631
- return sweepTriangles(surface.copyData(), vertices, normals, directions, translation, maxWork);
6763
+ return sweepTriangles(data, vertices, normals, directions, translation, maxWork, void 0, padding);
6632
6764
  }
6633
6765
  function sweepTerrainTriangleMesh(surface, collider, translation, { maxWork = 1e5 } = {}) {
6634
6766
  if (!Number.isSafeInteger(maxWork) || maxWork < 0 || translation.length !== 3 || !translation.every(Number.isFinite))
@@ -6658,7 +6790,7 @@ function sweepTerrainTriangleMesh(surface, collider, translation, { maxWork = 1e
6658
6790
  }
6659
6791
  return best ? { ...best, work } : { status: "miss", work };
6660
6792
  }
6661
- function sweepTriangles(data, vertices, normals, directions, translation, maxWork, movingTriangleNormal) {
6793
+ function sweepTriangles(data, vertices, normals, directions, translation, maxWork, movingTriangleNormal, padding = 0) {
6662
6794
  let work = 0;
6663
6795
  let best;
6664
6796
  const vertex = (index) => {
@@ -6704,6 +6836,8 @@ function sweepTriangles(data, vertices, normals, directions, translation, maxWor
6704
6836
  min = Math.min(min, projection);
6705
6837
  max = Math.max(max, projection);
6706
6838
  }
6839
+ min -= padding;
6840
+ max += padding;
6707
6841
  const speed = dot(translation, unit);
6708
6842
  if (![low, high, min, max, speed, length].every(Number.isFinite))
6709
6843
  throw new RangeError("Terrain polytope projection overflow");
@@ -6732,6 +6866,9 @@ function sweepTriangles(data, vertices, normals, directions, translation, maxWor
6732
6866
  return best ? { ...best, work } : { status: "miss", work };
6733
6867
  }
6734
6868
  function sweepTerrainBox(surface, center, halfExtents, translation, options) {
6869
+ return sweepTerrainPolytope(surface, createSweepBox(center, halfExtents), translation, options);
6870
+ }
6871
+ function createSweepBox(center, halfExtents) {
6735
6872
  if (halfExtents.length !== 3 || halfExtents.some((value) => !(value > 0)))
6736
6873
  throw new RangeError("Terrain box half extents must be positive");
6737
6874
  const vertices = Array.from({ length: 8 }, (_, i) => [
@@ -6739,7 +6876,7 @@ function sweepTerrainBox(surface, center, halfExtents, translation, options) {
6739
6876
  center[1] + (i & 2 ? 1 : -1) * halfExtents[1],
6740
6877
  center[2] + (i & 4 ? 1 : -1) * halfExtents[2]
6741
6878
  ]);
6742
- return sweepTerrainPolytope(surface, {
6879
+ return {
6743
6880
  vertices,
6744
6881
  faces: [
6745
6882
  [0, 1, 3],
@@ -6755,7 +6892,102 @@ function sweepTerrainBox(surface, center, halfExtents, translation, options) {
6755
6892
  [1, 5, 7],
6756
6893
  [1, 7, 3]
6757
6894
  ]
6758
- }, translation, options);
6895
+ };
6896
+ }
6897
+
6898
+ // dist/terrain/sweep-rotating-capsule.js
6899
+ function sweepTerrainRotatingCapsule(surface, start, end, radius, { pivot, translation, rotation }, { maxWork = 1e5, fractionTolerance = 1e-5 } = {}) {
6900
+ var _a;
6901
+ const norm = Math.hypot(...rotation);
6902
+ 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))
6903
+ throw new RangeError("Invalid terrain capsule rigid motion");
6904
+ const sign2 = rotation[3] < 0 ? -1 : 1;
6905
+ const axisLength = Math.hypot(rotation[0], rotation[1], rotation[2]);
6906
+ const angle = 2 * Math.atan2(axisLength, Math.abs(rotation[3]));
6907
+ if (angle === 0) {
6908
+ return sweepTerrainCapsule(surface, start, end, translation, radius, {
6909
+ maxWork,
6910
+ fractionTolerance
6911
+ });
6912
+ }
6913
+ const x = rotation[0] / axisLength * sign2;
6914
+ const y = rotation[1] / axisLength * sign2;
6915
+ const z = rotation[2] / axisLength * sign2;
6916
+ const offsets = [start, end].map((p) => p.map((v, i) => v - pivot[i]));
6917
+ const reach = Math.max(...offsets.map((p) => Math.hypot(...p)));
6918
+ const speed = Math.hypot(...translation) + angle * reach;
6919
+ const scale = Math.max(Math.hypot(...pivot), reach, speed, radius);
6920
+ if (!Number.isFinite(scale))
6921
+ throw new RangeError("Terrain capsule rigid motion overflow");
6922
+ let work = 0;
6923
+ function probe(t) {
6924
+ if (work >= maxWork)
6925
+ return null;
6926
+ work++;
6927
+ const sin = Math.sin(angle * t);
6928
+ const cos = Math.cos(angle * t);
6929
+ const [a, b] = t === 0 ? [start, end] : offsets.map(([u, v, w]) => {
6930
+ const d = (x * u + y * v + z * w) * (1 - cos);
6931
+ const pos = [
6932
+ pivot[0] + (translation[0] * t + u * cos + (y * w - z * v) * sin + x * d),
6933
+ pivot[1] + (translation[1] * t + v * cos + (z * u - x * w) * sin + y * d),
6934
+ pivot[2] + (translation[2] * t + w * cos + (x * v - y * u) * sin + z * d)
6935
+ ];
6936
+ if (!pos.every(Number.isFinite))
6937
+ throw new RangeError("Terrain capsule pose overflow");
6938
+ return pos;
6939
+ });
6940
+ const query = surface.nearestSegmentQuery(a, b, { maxWork: maxWork - work });
6941
+ work += query.work;
6942
+ return query;
6943
+ }
6944
+ const initial = probe(0);
6945
+ if ((initial == null ? void 0 : initial.result) && initial.result.distance <= radius)
6946
+ return { status: "hit", fraction: 0, lowerFraction: 0, work, contact: initial.result };
6947
+ if (!(initial == null ? void 0 : initial.complete))
6948
+ return { status: "incomplete", work };
6949
+ if (!initial.result || speed === 0)
6950
+ return { status: "miss", work };
6951
+ let clearUntil = 0;
6952
+ let witness;
6953
+ const pending = [[0, 1]];
6954
+ while (pending.length) {
6955
+ if (witness && witness.fraction - clearUntil <= fractionTolerance)
6956
+ return { status: "hit", lowerFraction: clearUntil, work, ...witness };
6957
+ const [lo, hi] = pending.pop();
6958
+ const mid = lo + (hi - lo) / 2;
6959
+ const query = probe(mid);
6960
+ const contact = query == null ? void 0 : query.result;
6961
+ if (contact && contact.distance <= radius) {
6962
+ witness = { fraction: mid, contact };
6963
+ if (mid - clearUntil <= fractionTolerance)
6964
+ return { status: "hit", lowerFraction: clearUntil, work, ...witness };
6965
+ if (mid === lo || mid === hi)
6966
+ return { status: "incomplete", work };
6967
+ pending.push([lo, mid]);
6968
+ continue;
6969
+ }
6970
+ if (!(query == null ? void 0 : query.complete))
6971
+ return { status: "incomplete", work };
6972
+ const travel = speed * Math.max(mid - lo, hi - mid);
6973
+ const allowance = 16 * Number.EPSILON * Math.max(scale, (contact == null ? void 0 : contact.distance) ?? 0);
6974
+ if (!contact || contact.distance - radius > travel + allowance) {
6975
+ clearUntil = hi;
6976
+ continue;
6977
+ }
6978
+ if (hi - clearUntil <= fractionTolerance) {
6979
+ const final = (witness == null ? void 0 : witness.fraction) === hi ? witness.contact : (_a = probe(hi)) == null ? void 0 : _a.result;
6980
+ if (final && final.distance <= radius)
6981
+ return { status: "hit", fraction: hi, lowerFraction: clearUntil, work, contact: final };
6982
+ }
6983
+ if (mid === lo || mid === hi || hi - lo <= fractionTolerance / 4)
6984
+ return { status: "incomplete", work };
6985
+ pending.push([mid, hi], [lo, mid]);
6986
+ }
6987
+ return witness ? { status: "hit", lowerFraction: clearUntil, work, ...witness } : { status: "miss", work };
6988
+ }
6989
+ function sweepTerrainRotatingSphere(surface, center, radius, motion, options) {
6990
+ return sweepTerrainRotatingCapsule(surface, center, center, radius, motion, options);
6759
6991
  }
6760
6992
 
6761
6993
  // dist/terrain/sweep-cylinder.js
@@ -6952,4 +7184,698 @@ function discoverGeographicTerrainPoles(cut) {
6952
7184
  }
6953
7185
  return { north: collect(90, "north"), south: collect(-90, "south") };
6954
7186
  }
7187
+
7188
+ // dist/terrain/sweep-rotation.js
7189
+ function sweepTerrainRotatingPolytope(surface, collider, { pivot, translation, rotation }, { maxWork = 1e5, fractionTolerance = 1e-5 } = {}) {
7190
+ const norm = Math.hypot(...rotation);
7191
+ 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))
7192
+ throw new RangeError("Invalid terrain rigid motion");
7193
+ const localPivot = pivot.map((v, i) => v - surface.origin[i]);
7194
+ const offsets = collider.vertices.map((v) => v.map((x2, i) => x2 - pivot[i]));
7195
+ const radius = offsets.reduce((r, v) => Math.max(r, Math.hypot(...v)), 0);
7196
+ const sign2 = rotation[3] < 0 ? -1 : 1;
7197
+ const vectorNorm = Math.hypot(rotation[0], rotation[1], rotation[2]);
7198
+ const angle = 2 * Math.atan2(vectorNorm, Math.abs(rotation[3]));
7199
+ const speed = Math.hypot(...translation) + angle * radius;
7200
+ if (!Number.isFinite(speed))
7201
+ throw new RangeError("Terrain rigid motion overflow");
7202
+ const data = surface.copyData();
7203
+ if (angle === 0) {
7204
+ const result = queryTerrainPolytope(data, surface.origin, collider, translation, maxWork);
7205
+ return result.status === "hit" ? { ...result, lowerFraction: result.fraction } : result;
7206
+ }
7207
+ const [x, y, z] = rotation.slice(0, 3).map((v) => v / vectorNorm * sign2);
7208
+ const zero = [0, 0, 0];
7209
+ let work = 0;
7210
+ const pose = (t) => {
7211
+ const sin = Math.sin(angle * t);
7212
+ const cos = Math.cos(angle * t);
7213
+ return {
7214
+ faces: collider.faces,
7215
+ vertices: offsets.map(([a, b, c]) => {
7216
+ const projection = (x * a + y * b + z * c) * (1 - cos);
7217
+ return [
7218
+ localPivot[0] + translation[0] * t + a * cos + (y * c - z * b) * sin + x * projection,
7219
+ localPivot[1] + translation[1] * t + b * cos + (z * a - x * c) * sin + y * projection,
7220
+ localPivot[2] + translation[2] * t + c * cos + (x * b - y * a) * sin + z * projection
7221
+ ];
7222
+ })
7223
+ };
7224
+ };
7225
+ const probe = (shape, padding = 0) => {
7226
+ if (work >= maxWork)
7227
+ return { status: "incomplete", work: 0 };
7228
+ work++;
7229
+ const result = queryTerrainPolytope(data, zero, shape, zero, maxWork - work, padding);
7230
+ work += result.work;
7231
+ return result;
7232
+ };
7233
+ const initial = probe(pose(0));
7234
+ if (initial.status === "hit")
7235
+ return { ...initial, lowerFraction: 0, work };
7236
+ if (initial.status === "incomplete")
7237
+ return { status: "incomplete", work };
7238
+ let clearUntil = 0;
7239
+ let witness;
7240
+ const pending = [[0, 1]];
7241
+ while (pending.length) {
7242
+ if (witness && witness.fraction - clearUntil <= fractionTolerance)
7243
+ return { ...witness, lowerFraction: clearUntil, work };
7244
+ const [lo, hi] = pending.pop();
7245
+ const mid = lo + (hi - lo) / 2;
7246
+ const shape = pose(mid);
7247
+ const padding = speed * Math.max(mid - lo, hi - mid);
7248
+ const expanded = probe(shape, padding + 8 * Number.EPSILON * (radius + padding));
7249
+ if (expanded.status === "miss") {
7250
+ clearUntil = hi;
7251
+ continue;
7252
+ }
7253
+ if (expanded.status === "incomplete")
7254
+ return { status: "incomplete", work };
7255
+ const hit = probe(shape);
7256
+ if (hit.status === "incomplete")
7257
+ return { status: "incomplete", work };
7258
+ if (hit.status === "hit") {
7259
+ witness = { ...hit, fraction: mid };
7260
+ if (mid - clearUntil <= fractionTolerance)
7261
+ return { ...witness, lowerFraction: clearUntil, work };
7262
+ pending.push([lo, mid]);
7263
+ } else if (hi - clearUntil <= fractionTolerance) {
7264
+ const end = (witness == null ? void 0 : witness.fraction) === hi ? witness : probe(pose(hi));
7265
+ if ((end == null ? void 0 : end.status) === "hit")
7266
+ return { ...end, fraction: hi, lowerFraction: clearUntil, work };
7267
+ if (hi - lo <= fractionTolerance / 4)
7268
+ return { status: "incomplete", work };
7269
+ pending.push([mid, hi], [lo, mid]);
7270
+ } else {
7271
+ if (mid === lo || mid === hi || hi - lo <= fractionTolerance / 4)
7272
+ return { status: "incomplete", work };
7273
+ pending.push([mid, hi], [lo, mid]);
7274
+ }
7275
+ }
7276
+ return witness ? { ...witness, lowerFraction: clearUntil, work } : { status: "miss", work };
7277
+ }
7278
+ function sweepTerrainRotatingBox(surface, center, halfExtents, motion, options) {
7279
+ return sweepTerrainRotatingPolytope(surface, createSweepBox(center, halfExtents), motion, options);
7280
+ }
7281
+
7282
+ // dist/terrain/regional-viewshed.js
7283
+ var TerrainRegionalViewStatus = {
7284
+ VISIBLE: 0,
7285
+ BLOCKED: 1,
7286
+ UNKNOWN: 2,
7287
+ MISSING_TARGET: 3,
7288
+ OBSERVER: 4
7289
+ };
7290
+ function createTerrainRegionalViewshed(grid, sample, options) {
7291
+ const { width, height, origin, spacing } = grid;
7292
+ const { observer, sampleStep, radius, targetOffset = 0, maxTargets = 1e5, maxSamples = 4e6 } = options;
7293
+ const count = width * height;
7294
+ 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((value) => value <= 0) || sampleStep <= 0 || targetOffset < 0 || radius !== void 0 && (!Number.isFinite(radius) || radius <= 0 || observer[2] <= -radius))
7295
+ throw new RangeError("Invalid regional viewshed grid or options");
7296
+ const statuses = new Uint8Array(count);
7297
+ const targetStatuses = new Uint8Array(count);
7298
+ const sampledCoverage = new Uint8Array(count);
7299
+ let samples = 0;
7300
+ function read(x, y) {
7301
+ if (samples >= maxSamples)
7302
+ throw new RangeError("Regional viewshed sample budget exceeded");
7303
+ samples++;
7304
+ const result = sample(x, y);
7305
+ 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))
7306
+ throw new RangeError("Invalid regional viewshed sample");
7307
+ return result;
7308
+ }
7309
+ function sight(distance, elevation) {
7310
+ let rise = elevation - observer[2];
7311
+ let run = distance;
7312
+ if (radius !== void 0) {
7313
+ const theta = distance / radius;
7314
+ const radial = radius + elevation;
7315
+ const halfSine = Math.sin(theta / 2);
7316
+ rise -= radial * (2 * halfSine * halfSine);
7317
+ run = radial * Math.sin(theta);
7318
+ }
7319
+ if (!Number.isFinite(rise) || !Number.isFinite(run) || run <= 0)
7320
+ throw new RangeError("Regional viewshed sight calculation overflow");
7321
+ return [rise, run];
7322
+ }
7323
+ const observerSample = { ...read(observer[0], observer[1]) };
7324
+ const observerValid = observerSample.status === TerrainSampleStatus.VALID;
7325
+ for (let i = 0; i < count; i++) {
7326
+ const x = origin[0] + i % width * spacing[0];
7327
+ const y = origin[1] + Math.floor(i / width) * spacing[1];
7328
+ const dx = x - observer[0];
7329
+ const dy = y - observer[1];
7330
+ const distance = Math.hypot(dx, dy);
7331
+ if (!Number.isFinite(distance) || radius !== void 0 && distance / radius >= Math.PI)
7332
+ throw new RangeError("Regional viewshed distance outside supported range");
7333
+ const target = distance === 0 ? observerSample : read(x, y);
7334
+ targetStatuses[i] = target.status;
7335
+ if (target.status !== TerrainSampleStatus.VALID) {
7336
+ statuses[i] = TerrainRegionalViewStatus.MISSING_TARGET;
7337
+ continue;
7338
+ }
7339
+ if (distance === 0) {
7340
+ statuses[i] = TerrainRegionalViewStatus.OBSERVER;
7341
+ sampledCoverage[i] = 1;
7342
+ continue;
7343
+ }
7344
+ const [targetRise, targetRun] = sight(distance, target.height + targetOffset);
7345
+ const segments = Math.max(1, Math.ceil(distance / sampleStep));
7346
+ if (!Number.isSafeInteger(segments) || segments - 1 > maxSamples - samples)
7347
+ throw new RangeError("Regional viewshed sample budget exceeded");
7348
+ let complete = observerValid;
7349
+ let blocked = observerValid && observerSample.height > observer[2];
7350
+ for (let j = 1; j < segments; j++) {
7351
+ const fraction = j / segments;
7352
+ const station = read(observer[0] + dx * fraction, observer[1] + dy * fraction);
7353
+ if (station.status !== TerrainSampleStatus.VALID) {
7354
+ complete = false;
7355
+ } else if (!blocked) {
7356
+ const [rise, run] = sight(distance * fraction, station.height);
7357
+ blocked = compareTerrainSlopes(rise, run, targetRise, targetRun) >= 0;
7358
+ }
7359
+ }
7360
+ sampledCoverage[i] = complete ? 1 : 0;
7361
+ statuses[i] = blocked ? TerrainRegionalViewStatus.BLOCKED : complete ? TerrainRegionalViewStatus.VISIBLE : TerrainRegionalViewStatus.UNKNOWN;
7362
+ }
7363
+ return { statuses, targetStatuses, sampledCoverage, samples };
7364
+ }
7365
+
7366
+ // dist/terrain/hydrology.js
7367
+ function getTerrainCellMetrics(field) {
7368
+ if (field.registration !== "cell")
7369
+ throw new Error("Terrain cell metrics require cell registration");
7370
+ const [cx, cy] = field.columnStep;
7371
+ const [rx, ry] = field.rowStep;
7372
+ const determinant = cx * ry - cy * rx;
7373
+ const columnLength = Math.hypot(cx, cy);
7374
+ const rowLength = Math.hypot(rx, ry);
7375
+ const area = Math.abs(determinant);
7376
+ if (!(area > 0 && Number.isFinite(area) && Number.isFinite(columnLength + rowLength)))
7377
+ throw new RangeError("Invalid terrain cell geometry");
7378
+ const sign2 = Math.sign(determinant);
7379
+ const east = [sign2 * ry / rowLength, -sign2 * rx / rowLength];
7380
+ const south = [-sign2 * cy / columnLength, sign2 * cx / columnLength];
7381
+ return {
7382
+ area,
7383
+ faceLengths: [rowLength, rowLength, columnLength, columnLength],
7384
+ faceNormals: [[-east[0], -east[1]], east, [-south[0], -south[1]], south]
7385
+ };
7386
+ }
7387
+ function createTerrainDrainage(field, { outlets = [], maxCells = 4194304 } = {}) {
7388
+ const { width, height, columnStep, rowStep } = field;
7389
+ const count = width * height;
7390
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 2147483647)
7391
+ throw new RangeError("Terrain drainage exceeds its cell budget");
7392
+ const { area: cellArea } = getTerrainCellMetrics(field);
7393
+ for (const i of outlets) {
7394
+ if (!Number.isInteger(i) || i < 0 || i >= count || field.getHeight(i % width, Math.floor(i / width)) === void 0)
7395
+ throw new RangeError("Terrain outlet must identify a valid cell");
7396
+ }
7397
+ const { heights, validity } = field.copyData();
7398
+ const receiver = new Int32Array(count).fill(-1);
7399
+ const terminal = new Int32Array(count).fill(-1);
7400
+ const contributingCells = new Uint32Array(count);
7401
+ const incoming = new Uint8Array(count);
7402
+ const queue = new Int32Array(count);
7403
+ const outletSet = new Set(outlets);
7404
+ const offsets = [];
7405
+ for (let dy = -1; dy <= 1; dy++) {
7406
+ for (let dx = -1; dx <= 1; dx++) {
7407
+ if (!dx && !dy)
7408
+ continue;
7409
+ const distance = Math.hypot(dx * columnStep[0] + dy * rowStep[0], dx * columnStep[1] + dy * rowStep[1]);
7410
+ if (!(distance > 0 && Number.isFinite(distance)))
7411
+ throw new RangeError("Invalid terrain neighbor distance");
7412
+ offsets.push({ dx, dy, distance });
7413
+ }
7414
+ }
7415
+ for (let i = 0; i < count; i++) {
7416
+ if (!validity[i])
7417
+ continue;
7418
+ contributingCells[i] = 1;
7419
+ if (outletSet.has(i))
7420
+ continue;
7421
+ const col = i % width;
7422
+ const row = Math.floor(i / width);
7423
+ let steepest = 0;
7424
+ for (const { dx, dy, distance } of offsets) {
7425
+ if (col + dx < 0 || col + dx >= width || row + dy < 0 || row + dy >= height)
7426
+ continue;
7427
+ const j = i + dx + dy * width;
7428
+ if (!validity[j] || heights[j] >= heights[i])
7429
+ continue;
7430
+ if (dx && dy && (!validity[i + dx] || !validity[i + dy * width]))
7431
+ continue;
7432
+ const slope = (heights[i] - heights[j]) / distance;
7433
+ if (!Number.isFinite(slope) || slope === 0)
7434
+ throw new RangeError("Terrain drainage slope is outside the representable range");
7435
+ if (slope > steepest) {
7436
+ steepest = slope;
7437
+ receiver[i] = j;
7438
+ }
7439
+ }
7440
+ if (receiver[i] >= 0)
7441
+ incoming[receiver[i]]++;
7442
+ }
7443
+ let end = 0;
7444
+ for (let i = 0; i < count; i++)
7445
+ if (validity[i] && !incoming[i])
7446
+ queue[end++] = i;
7447
+ for (let cursor = 0; cursor < end; cursor++) {
7448
+ const i = queue[cursor];
7449
+ const next = receiver[i];
7450
+ if (next < 0)
7451
+ continue;
7452
+ contributingCells[next] += contributingCells[i];
7453
+ if (--incoming[next] === 0)
7454
+ queue[end++] = next;
7455
+ }
7456
+ for (let cursor = end - 1; cursor >= 0; cursor--) {
7457
+ const i = queue[cursor];
7458
+ const next = receiver[i];
7459
+ terminal[i] = next < 0 ? i : terminal[next];
7460
+ }
7461
+ return { receiver, terminal, contributingCells, cellArea };
7462
+ }
7463
+
7464
+ // dist/terrain/depression-fill.js
7465
+ function fillTerrainDepressions(field, { outlets, maxCells = 4194304 }) {
7466
+ if (field.registration !== "cell")
7467
+ throw new Error("Terrain depression fill requires cell registration");
7468
+ const { width, height } = field;
7469
+ const count = width * height;
7470
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 2147483647)
7471
+ throw new RangeError("Terrain depression fill exceeds its cell budget");
7472
+ if (!outlets.length)
7473
+ throw new RangeError("Terrain depression fill requires an outlet");
7474
+ for (const i of outlets) {
7475
+ if (!Number.isInteger(i) || i < 0 || i >= count || field.getHeight(i % width, Math.floor(i / width)) === void 0)
7476
+ throw new RangeError("Terrain outlet must identify a valid cell");
7477
+ }
7478
+ const { heights, validity } = field.copyData();
7479
+ const receiver = new Int32Array(count).fill(-2);
7480
+ const heap = new Int32Array(count);
7481
+ let size = 0;
7482
+ let disconnectedCells = field.validCount;
7483
+ const before = (a, b) => heights[a] < heights[b] || heights[a] === heights[b] && a < b;
7484
+ function push(cell) {
7485
+ let slot = size++;
7486
+ while (slot > 0) {
7487
+ const parent = Math.floor((slot - 1) / 2);
7488
+ if (!before(cell, heap[parent]))
7489
+ break;
7490
+ heap[slot] = heap[parent];
7491
+ slot = parent;
7492
+ }
7493
+ heap[slot] = cell;
7494
+ }
7495
+ function pop() {
7496
+ const first = heap[0];
7497
+ const tail = heap[--size];
7498
+ let slot = 0;
7499
+ let child = 1;
7500
+ while (child < size) {
7501
+ if (child + 1 < size && before(heap[child + 1], heap[child]))
7502
+ child++;
7503
+ if (!before(heap[child], tail))
7504
+ break;
7505
+ heap[slot] = heap[child];
7506
+ slot = child;
7507
+ child = slot * 2 + 1;
7508
+ }
7509
+ if (size)
7510
+ heap[slot] = tail;
7511
+ return first;
7512
+ }
7513
+ function visit(cell, parent) {
7514
+ if (!validity[cell] || receiver[cell] !== -2)
7515
+ return;
7516
+ receiver[cell] = parent;
7517
+ disconnectedCells--;
7518
+ if (parent >= 0)
7519
+ heights[cell] = Math.max(heights[cell], heights[parent]);
7520
+ push(cell);
7521
+ }
7522
+ for (const outlet of outlets)
7523
+ visit(outlet, -1);
7524
+ while (size) {
7525
+ const cell = pop();
7526
+ const column = cell % width;
7527
+ if (column > 0)
7528
+ visit(cell - 1, cell);
7529
+ if (column + 1 < width)
7530
+ visit(cell + 1, cell);
7531
+ if (cell >= width)
7532
+ visit(cell - width, cell);
7533
+ if (cell < count - width)
7534
+ visit(cell + width, cell);
7535
+ }
7536
+ return {
7537
+ field: new HeightField({
7538
+ width,
7539
+ height,
7540
+ heights,
7541
+ validity,
7542
+ origin: field.origin,
7543
+ columnStep: field.columnStep,
7544
+ rowStep: field.rowStep,
7545
+ registration: field.registration,
7546
+ diagonal: field.diagonal,
7547
+ heightReference: field.heightReference
7548
+ }),
7549
+ receiver,
7550
+ disconnectedCells
7551
+ };
7552
+ }
7553
+
7554
+ // dist/terrain/mesh-cutout.js
7555
+ function splitTerrainMesh(mesh, polygon2, { maxWork = 4e6, maxVertices = 5e5, maxTriangles = 5e5 } = {}) {
7556
+ 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))
7557
+ throw new RangeError("Invalid terrain cutout mesh or capacity");
7558
+ let work = 0;
7559
+ function charge(amount) {
7560
+ work += amount;
7561
+ if (work > maxWork)
7562
+ throw new RangeError("Terrain cutout work budget exceeded");
7563
+ }
7564
+ const ring = validatePolygon(polygon2, charge);
7565
+ const vertices = [];
7566
+ for (let i = 0; i < mesh.positions.length; i += 3)
7567
+ vertices.push([mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2]]);
7568
+ const faces = [];
7569
+ for (let i = 0; i < mesh.indices.length; i += 3) {
7570
+ const face = [mesh.indices[i], mesh.indices[i + 1], mesh.indices[i + 2]];
7571
+ if (face.some((id) => id >= vertices.length))
7572
+ throw new RangeError("Invalid terrain cutout index");
7573
+ checkTriangle(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
7574
+ faces.push(face);
7575
+ }
7576
+ validateTopology(vertices, faces, charge);
7577
+ const patch = createPiece();
7578
+ const remainder = createPiece();
7579
+ const intersections = ring.map(() => /* @__PURE__ */ new Map());
7580
+ let fragmentCount = 0;
7581
+ function addVertex(vertex) {
7582
+ if (vertices.length >= maxVertices || !vertex.every(Number.isFinite))
7583
+ throw new RangeError("Terrain cutout vertex budget or coordinate range exceeded");
7584
+ return vertices.push(vertex) - 1;
7585
+ }
7586
+ function intersection(a, b, da, db, line) {
7587
+ const key2 = edgeKey2(a, b);
7588
+ const cache = intersections[line];
7589
+ const saved = cache.get(key2);
7590
+ if (saved !== void 0)
7591
+ return saved;
7592
+ const t = Math.abs(da) / (Math.abs(da) + Math.abs(db));
7593
+ if (!(t > 0 && t < 1))
7594
+ throw new RangeError("Unrepresentable terrain cut intersection");
7595
+ const u = vertices[a];
7596
+ const v = vertices[b];
7597
+ const id = addVertex([
7598
+ u[0] + t * (v[0] - u[0]),
7599
+ u[1] + t * (v[1] - u[1]),
7600
+ u[2] + t * (v[2] - u[2])
7601
+ ]);
7602
+ cache.set(key2, id);
7603
+ return id;
7604
+ }
7605
+ for (let source = 0; source < faces.length; source++) {
7606
+ let fragments = [{ ids: faces[source], inside: true }];
7607
+ for (let line = 0; line < ring.length; line++) {
7608
+ const next = [];
7609
+ const a = ring[line];
7610
+ const b = ring[(line + 1) % ring.length];
7611
+ for (const fragment of fragments) {
7612
+ const { ids } = fragment;
7613
+ charge(ids.length);
7614
+ const distances = ids.map((id) => cross3(a, b, vertices[id]));
7615
+ if (distances.some((d) => !Number.isFinite(d)))
7616
+ throw new RangeError("Invalid terrain cut coordinates");
7617
+ if (!distances.some((d) => d < 0))
7618
+ next.push(fragment);
7619
+ else if (!distances.some((d) => d > 0))
7620
+ next.push({ ...fragment, inside: false });
7621
+ else {
7622
+ const positive = [];
7623
+ const negative = [];
7624
+ for (let i = 0; i < ids.length; i++) {
7625
+ const j = (i + 1) % ids.length;
7626
+ const d = distances[i];
7627
+ const e = distances[j];
7628
+ if (d >= 0)
7629
+ positive.push(ids[i]);
7630
+ if (d <= 0)
7631
+ negative.push(ids[i]);
7632
+ if (d < 0 && e > 0 || d > 0 && e < 0) {
7633
+ const id = intersection(ids[i], ids[j], d, e, line);
7634
+ positive.push(id);
7635
+ negative.push(id);
7636
+ }
7637
+ }
7638
+ next.push({ ids: positive, inside: fragment.inside }, { ids: negative, inside: false });
7639
+ }
7640
+ if (fragmentCount + next.length > maxTriangles)
7641
+ throw new RangeError("Terrain cutout fragment budget exceeded");
7642
+ }
7643
+ fragments = next;
7644
+ }
7645
+ fragmentCount += fragments.length;
7646
+ for (const { ids, inside } of fragments) {
7647
+ const piece = inside ? patch : remainder;
7648
+ if (ids.length === 3)
7649
+ emit(piece, ids, source);
7650
+ else {
7651
+ const center = [...vertices[ids[0]]];
7652
+ for (const id of ids) {
7653
+ for (let k = 0; k < 3; k++)
7654
+ center[k] += (vertices[id][k] - vertices[ids[0]][k]) / ids.length;
7655
+ }
7656
+ const hub = addVertex(center);
7657
+ for (let i = 0; i < ids.length; i++)
7658
+ emit(piece, [ids[i], ids[(i + 1) % ids.length], hub], source);
7659
+ }
7660
+ }
7661
+ }
7662
+ function emit(piece, face, source) {
7663
+ if (patch.sourceFaces.length + remainder.sourceFaces.length >= maxTriangles)
7664
+ throw new RangeError("Terrain cutout triangle budget exceeded");
7665
+ checkTriangle(vertices[face[0]], vertices[face[1]], vertices[face[2]]);
7666
+ const [a, b, c] = faces[source].map((id) => vertices[id]);
7667
+ const area = cross3(a, b, c);
7668
+ for (let i = 0; i < 3; i++) {
7669
+ const id = face[i];
7670
+ if (!piece.ids.has(id)) {
7671
+ if (patch.ids.size + remainder.ids.size >= maxVertices)
7672
+ throw new RangeError("Terrain cutout output vertex budget exceeded");
7673
+ piece.ids.set(id, piece.ids.size);
7674
+ const p = vertices[id];
7675
+ piece.positions.push(...p);
7676
+ piece.sourceTriangles.push(source);
7677
+ piece.sourceWeights.push(cross3(b, c, p) / area, cross3(c, a, p) / area, cross3(a, b, p) / area);
7678
+ }
7679
+ piece.indices.push(piece.ids.get(id));
7680
+ addEdge(piece.boundary, id, face[(i + 1) % 3]);
7681
+ }
7682
+ piece.sourceFaces.push(source);
7683
+ }
7684
+ for (const [key2, inside] of patch.boundary) {
7685
+ const outside = remainder.boundary.get(key2);
7686
+ if (!outside)
7687
+ continue;
7688
+ const [a, b] = inside.edge;
7689
+ if (inside.count !== 1 || outside.count !== 1 || outside.edge[0] !== b)
7690
+ throw new Error("Nonconforming terrain cut boundary");
7691
+ patch.cutEdges.push(patch.ids.get(a), patch.ids.get(b));
7692
+ remainder.cutEdges.push(remainder.ids.get(b), remainder.ids.get(a));
7693
+ }
7694
+ return { patch: finish(patch), remainder: finish(remainder) };
7695
+ }
7696
+ function validatePolygon(polygon2, charge) {
7697
+ if (polygon2.length < 3 || polygon2.some((p) => p.length !== 2 || !p.every(Number.isFinite)))
7698
+ throw new RangeError("Invalid terrain cut polygon");
7699
+ const ring = [...polygon2];
7700
+ const orientation2 = cross3(ring[0], ring[1], ring[2]);
7701
+ if (orientation2 < 0)
7702
+ ring.reverse();
7703
+ for (let i = 0; i < ring.length; i++) {
7704
+ charge(ring.length);
7705
+ const j = (i + 1) % ring.length;
7706
+ for (let k = 0; k < ring.length; k++) {
7707
+ if (k === i || k === j)
7708
+ continue;
7709
+ const area = cross3(ring[i], ring[j], ring[k]);
7710
+ if (!(area > 0 && Number.isFinite(area)))
7711
+ throw new RangeError("Terrain cut polygon must be strictly convex");
7712
+ }
7713
+ }
7714
+ return ring;
7715
+ }
7716
+ function checkTriangle(a, b, c) {
7717
+ const area = cross3(a, b, c);
7718
+ const scale = Math.hypot(b[0] - a[0], b[1] - a[1]) * Math.hypot(c[0] - a[0], c[1] - a[1]);
7719
+ if (!(area > Number.EPSILON * scale && Number.isFinite(area)))
7720
+ throw new RangeError("Terrain cut requires upward nondegenerate XY triangles");
7721
+ }
7722
+ function validateTopology(vertices, faces, charge) {
7723
+ const edges2 = /* @__PURE__ */ new Map();
7724
+ const boxes = faces.map((face) => {
7725
+ for (let i = 0; i < 3; i++)
7726
+ addEdge(edges2, face[i], face[(i + 1) % 3]);
7727
+ const points = face.map((id) => vertices[id]);
7728
+ return {
7729
+ face,
7730
+ points,
7731
+ low: Math.min(...points.map((p) => p[0])),
7732
+ high: Math.max(...points.map((p) => p[0])),
7733
+ minY: Math.min(...points.map((p) => p[1])),
7734
+ maxY: Math.max(...points.map((p) => p[1]))
7735
+ };
7736
+ }).sort((a, b) => a.low - b.low);
7737
+ for (let i = 0; i < boxes.length; i++) {
7738
+ const a = boxes[i];
7739
+ for (let j = i + 1; j < boxes.length && boxes[j].low <= a.high; j++) {
7740
+ charge(1);
7741
+ const b = boxes[j];
7742
+ if (a.maxY < b.minY || b.maxY < a.minY)
7743
+ continue;
7744
+ if (!separates(a.points, b.points) && !separates(b.points, a.points))
7745
+ throw new RangeError("Terrain cut input has overlapping XY triangles");
7746
+ checkJunctions(a.face, b.face, vertices);
7747
+ checkJunctions(b.face, a.face, vertices);
7748
+ }
7749
+ }
7750
+ }
7751
+ function separates(a, b) {
7752
+ return a.some((p, i) => b.every((q) => cross3(p, a[(i + 1) % 3], q) <= 0));
7753
+ }
7754
+ function checkJunctions(a, b, vertices) {
7755
+ for (let i = 0; i < 3; i++) {
7756
+ const u = vertices[a[i]];
7757
+ const v = vertices[a[(i + 1) % 3]];
7758
+ const overlaps2 = b.filter((id) => {
7759
+ const p = vertices[id];
7760
+ if (cross3(u, v, p) !== 0)
7761
+ return false;
7762
+ const axis = Math.abs(v[0] - u[0]) >= Math.abs(v[1] - u[1]) ? 0 : 1;
7763
+ const low = Math.min(u[axis], v[axis]);
7764
+ const high = Math.max(u[axis], v[axis]);
7765
+ if (p[axis] > low && p[axis] < high)
7766
+ throw new RangeError("Terrain cut input has a T-junction");
7767
+ return p[axis] >= low && p[axis] <= high;
7768
+ });
7769
+ if (overlaps2.length >= 2 && (!overlaps2.includes(a[i]) || !overlaps2.includes(a[(i + 1) % 3])))
7770
+ throw new RangeError("Terrain cut input has an unwelded shared edge");
7771
+ }
7772
+ }
7773
+ function addEdge(edges2, a, b) {
7774
+ const key2 = edgeKey2(a, b);
7775
+ const entry = edges2.get(key2);
7776
+ if (!entry)
7777
+ edges2.set(key2, { edge: [a, b], count: 1 });
7778
+ else {
7779
+ if (entry.count !== 1 || entry.edge[0] !== b)
7780
+ throw new RangeError("Terrain cut mesh has inconsistent or nonmanifold edges");
7781
+ entry.count++;
7782
+ }
7783
+ }
7784
+ function edgeKey2(a, b) {
7785
+ return a < b ? a + "," + b : b + "," + a;
7786
+ }
7787
+ function cross3(a, b, c) {
7788
+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
7789
+ }
7790
+ function createPiece() {
7791
+ return {
7792
+ ids: /* @__PURE__ */ new Map(),
7793
+ positions: [],
7794
+ indices: [],
7795
+ sourceTriangles: [],
7796
+ sourceWeights: [],
7797
+ sourceFaces: [],
7798
+ boundary: /* @__PURE__ */ new Map(),
7799
+ cutEdges: []
7800
+ };
7801
+ }
7802
+ function finish(piece) {
7803
+ return {
7804
+ positions: Float64Array.from(piece.positions),
7805
+ indices: Uint32Array.from(piece.indices),
7806
+ sourceTriangles: Uint32Array.from(piece.sourceTriangles),
7807
+ sourceWeights: Float64Array.from(piece.sourceWeights),
7808
+ sourceFaces: Uint32Array.from(piece.sourceFaces),
7809
+ cutEdges: Uint32Array.from(piece.cutEdges)
7810
+ };
7811
+ }
7812
+
7813
+ // dist/terrain/cutout-skirts.js
7814
+ function createTerrainCutoutSkirts(cutout, { lift = 0, patch, remainder }) {
7815
+ if (!Number.isFinite(lift))
7816
+ throw new RangeError("Invalid terrain cutout lift");
7817
+ const positions = cutout.patch.positions.slice();
7818
+ for (let i = 2; i < positions.length; i += 3) {
7819
+ positions[i] += lift;
7820
+ if (!Number.isFinite(positions[i]))
7821
+ throw new RangeError("Terrain cutout lift overflow");
7822
+ }
7823
+ return {
7824
+ patch: skirtPiece({ ...cutout.patch, positions }, patch),
7825
+ remainder: skirtPiece(cutout.remainder, remainder)
7826
+ };
7827
+ }
7828
+ function skirtPiece(surface, options) {
7829
+ if (!surface.cutEdges.length)
7830
+ return { surface };
7831
+ return {
7832
+ surface,
7833
+ skirt: createTerrainSkirt(surface, { ...options, edges: surface.cutEdges })
7834
+ };
7835
+ }
7836
+
7837
+ // dist/terrain/watershed-accumulation.js
7838
+ function accumulateTerrainWatersheds(receiver, { maxCells = 4194304 } = {}) {
7839
+ const count = receiver.length;
7840
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 2147483647)
7841
+ throw new RangeError("Terrain watershed accumulation exceeds its cell budget");
7842
+ const incoming = new Uint32Array(count);
7843
+ const contributingCells = new Uint32Array(count);
7844
+ const terminal = new Int32Array(count).fill(-1);
7845
+ const queue = new Int32Array(count);
7846
+ let active = 0;
7847
+ for (let i = 0; i < count; i++) {
7848
+ const next = receiver[i];
7849
+ if (next === -2)
7850
+ continue;
7851
+ if (next < -1 || next >= count || next >= 0 && receiver[next] === -2)
7852
+ throw new RangeError("Invalid terrain watershed receiver");
7853
+ active++;
7854
+ contributingCells[i] = 1;
7855
+ if (next >= 0)
7856
+ incoming[next]++;
7857
+ }
7858
+ let end = 0;
7859
+ for (let i = 0; i < count; i++) {
7860
+ if (contributingCells[i] && !incoming[i])
7861
+ queue[end++] = i;
7862
+ }
7863
+ for (let cursor = 0; cursor < end; cursor++) {
7864
+ const i = queue[cursor];
7865
+ const next = receiver[i];
7866
+ if (next < 0)
7867
+ continue;
7868
+ contributingCells[next] += contributingCells[i];
7869
+ if (--incoming[next] === 0)
7870
+ queue[end++] = next;
7871
+ }
7872
+ if (end !== active)
7873
+ throw new RangeError("Terrain watershed receiver graph contains a cycle");
7874
+ for (let cursor = end - 1; cursor >= 0; cursor--) {
7875
+ const i = queue[cursor];
7876
+ const next = receiver[i];
7877
+ terminal[i] = next < 0 ? i : terminal[next];
7878
+ }
7879
+ return { terminal, contributingCells };
7880
+ }
6955
7881
  //# sourceMappingURL=index.cjs.map