@math.gl/geospatial 5.0.0-beta.5 → 5.0.0-beta.6

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 (139) hide show
  1. package/dist/index.cjs +1526 -192
  2. package/dist/index.cjs.map +3 -3
  3. package/dist/index.d.ts +38 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +19 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/terrain/bounds-regions.d.ts +15 -0
  8. package/dist/terrain/bounds-regions.d.ts.map +1 -0
  9. package/dist/terrain/bounds-regions.js +84 -0
  10. package/dist/terrain/bounds-regions.js.map +1 -0
  11. package/dist/terrain/bounds-update.d.ts +11 -0
  12. package/dist/terrain/bounds-update.d.ts.map +1 -0
  13. package/dist/terrain/bounds-update.js +10 -0
  14. package/dist/terrain/bounds-update.js.map +1 -0
  15. package/dist/terrain/box-index.d.ts +9 -0
  16. package/dist/terrain/box-index.d.ts.map +1 -0
  17. package/dist/terrain/box-index.js +43 -0
  18. package/dist/terrain/box-index.js.map +1 -0
  19. package/dist/terrain/contour-simplify.d.ts +1 -0
  20. package/dist/terrain/contour-simplify.d.ts.map +1 -1
  21. package/dist/terrain/contour-simplify.js +5 -1
  22. package/dist/terrain/contour-simplify.js.map +1 -1
  23. package/dist/terrain/contour-topology.d.ts +30 -0
  24. package/dist/terrain/contour-topology.d.ts.map +1 -0
  25. package/dist/terrain/contour-topology.js +236 -0
  26. package/dist/terrain/contour-topology.js.map +1 -0
  27. package/dist/terrain/delatin-regions.d.ts +14 -0
  28. package/dist/terrain/delatin-regions.d.ts.map +1 -0
  29. package/dist/terrain/delatin-regions.js +15 -0
  30. package/dist/terrain/delatin-regions.js.map +1 -0
  31. package/dist/terrain/dirty-regions.d.ts +11 -0
  32. package/dist/terrain/dirty-regions.d.ts.map +1 -0
  33. package/dist/terrain/dirty-regions.js +34 -0
  34. package/dist/terrain/dirty-regions.js.map +1 -0
  35. package/dist/terrain/gradient-pyramid-regions.d.ts +15 -0
  36. package/dist/terrain/gradient-pyramid-regions.d.ts.map +1 -0
  37. package/dist/terrain/gradient-pyramid-regions.js +112 -0
  38. package/dist/terrain/gradient-pyramid-regions.js.map +1 -0
  39. package/dist/terrain/gradient-pyramid-update.d.ts +11 -0
  40. package/dist/terrain/gradient-pyramid-update.d.ts.map +1 -0
  41. package/dist/terrain/gradient-pyramid-update.js +17 -0
  42. package/dist/terrain/gradient-pyramid-update.js.map +1 -0
  43. package/dist/terrain/index.cjs +1422 -88
  44. package/dist/terrain/index.cjs.map +3 -3
  45. package/dist/terrain/index.d.ts +38 -0
  46. package/dist/terrain/index.d.ts.map +1 -1
  47. package/dist/terrain/index.js +19 -0
  48. package/dist/terrain/index.js.map +1 -1
  49. package/dist/terrain/isobands.d.ts +24 -0
  50. package/dist/terrain/isobands.d.ts.map +1 -0
  51. package/dist/terrain/isobands.js +281 -0
  52. package/dist/terrain/isobands.js.map +1 -0
  53. package/dist/terrain/lod-morph-evaluate.d.ts +8 -0
  54. package/dist/terrain/lod-morph-evaluate.d.ts.map +1 -0
  55. package/dist/terrain/lod-morph-evaluate.js +30 -0
  56. package/dist/terrain/lod-morph-evaluate.js.map +1 -0
  57. package/dist/terrain/lod-morph.d.ts +35 -0
  58. package/dist/terrain/lod-morph.d.ts.map +1 -0
  59. package/dist/terrain/lod-morph.js +87 -0
  60. package/dist/terrain/lod-morph.js.map +1 -0
  61. package/dist/terrain/martini-regions.d.ts +14 -0
  62. package/dist/terrain/martini-regions.d.ts.map +1 -0
  63. package/dist/terrain/martini-regions.js +26 -0
  64. package/dist/terrain/martini-regions.js.map +1 -0
  65. package/dist/terrain/mesh-error.d.ts.map +1 -1
  66. package/dist/terrain/mesh-error.js +9 -1
  67. package/dist/terrain/mesh-error.js.map +1 -1
  68. package/dist/terrain/mesh-regions-data.d.ts +24 -0
  69. package/dist/terrain/mesh-regions-data.d.ts.map +1 -0
  70. package/dist/terrain/mesh-regions-data.js +80 -0
  71. package/dist/terrain/mesh-regions-data.js.map +1 -0
  72. package/dist/terrain/mesh-regions.d.ts +12 -0
  73. package/dist/terrain/mesh-regions.d.ts.map +1 -0
  74. package/dist/terrain/mesh-regions.js +10 -0
  75. package/dist/terrain/mesh-regions.js.map +1 -0
  76. package/dist/terrain/mesh-update.d.ts +11 -0
  77. package/dist/terrain/mesh-update.d.ts.map +1 -0
  78. package/dist/terrain/mesh-update.js +10 -0
  79. package/dist/terrain/mesh-update.js.map +1 -0
  80. package/dist/terrain/mixed-gradient-update.d.ts +15 -0
  81. package/dist/terrain/mixed-gradient-update.d.ts.map +1 -0
  82. package/dist/terrain/mixed-gradient-update.js +24 -0
  83. package/dist/terrain/mixed-gradient-update.js.map +1 -0
  84. package/dist/terrain/mixed-halo-update.d.ts +16 -0
  85. package/dist/terrain/mixed-halo-update.d.ts.map +1 -0
  86. package/dist/terrain/mixed-halo-update.js +46 -0
  87. package/dist/terrain/mixed-halo-update.js.map +1 -0
  88. package/dist/terrain/mixed-vertex-halos.d.ts +32 -0
  89. package/dist/terrain/mixed-vertex-halos.d.ts.map +1 -0
  90. package/dist/terrain/mixed-vertex-halos.js +125 -0
  91. package/dist/terrain/mixed-vertex-halos.js.map +1 -0
  92. package/dist/terrain/persistent-bounds.d.ts +16 -0
  93. package/dist/terrain/persistent-bounds.d.ts.map +1 -0
  94. package/dist/terrain/persistent-bounds.js +51 -0
  95. package/dist/terrain/persistent-bounds.js.map +1 -0
  96. package/dist/terrain/persistent-gradients.d.ts +16 -0
  97. package/dist/terrain/persistent-gradients.d.ts.map +1 -0
  98. package/dist/terrain/persistent-gradients.js +69 -0
  99. package/dist/terrain/persistent-gradients.js.map +1 -0
  100. package/dist/terrain/persistent-hierarchy-data.d.ts +41 -0
  101. package/dist/terrain/persistent-hierarchy-data.d.ts.map +1 -0
  102. package/dist/terrain/persistent-hierarchy-data.js +130 -0
  103. package/dist/terrain/persistent-hierarchy-data.js.map +1 -0
  104. package/dist/terrain/sample-triangle-height.d.ts +4 -0
  105. package/dist/terrain/sample-triangle-height.d.ts.map +1 -0
  106. package/dist/terrain/sample-triangle-height.js +46 -0
  107. package/dist/terrain/sample-triangle-height.js.map +1 -0
  108. package/dist/terrain/tile-update-data.d.ts +14 -0
  109. package/dist/terrain/tile-update-data.d.ts.map +1 -0
  110. package/dist/terrain/tile-update-data.js +23 -0
  111. package/dist/terrain/tile-update-data.js.map +1 -0
  112. package/package.json +7 -7
  113. package/src/index.ts +59 -0
  114. package/src/terrain/bounds-regions.ts +106 -0
  115. package/src/terrain/bounds-update.ts +19 -0
  116. package/src/terrain/box-index.ts +47 -0
  117. package/src/terrain/contour-simplify.ts +10 -2
  118. package/src/terrain/contour-topology.ts +263 -0
  119. package/src/terrain/delatin-regions.ts +25 -0
  120. package/src/terrain/dirty-regions.ts +61 -0
  121. package/src/terrain/gradient-pyramid-regions.ts +140 -0
  122. package/src/terrain/gradient-pyramid-update.ts +25 -0
  123. package/src/terrain/index.ts +56 -0
  124. package/src/terrain/isobands.ts +348 -0
  125. package/src/terrain/lod-morph-evaluate.ts +36 -0
  126. package/src/terrain/lod-morph.ts +138 -0
  127. package/src/terrain/martini-regions.ts +38 -0
  128. package/src/terrain/mesh-error.ts +14 -1
  129. package/src/terrain/mesh-regions-data.ts +113 -0
  130. package/src/terrain/mesh-regions.ts +18 -0
  131. package/src/terrain/mesh-update.ts +15 -0
  132. package/src/terrain/mixed-gradient-update.ts +40 -0
  133. package/src/terrain/mixed-halo-update.ts +56 -0
  134. package/src/terrain/mixed-vertex-halos.ts +170 -0
  135. package/src/terrain/persistent-bounds.ts +95 -0
  136. package/src/terrain/persistent-gradients.ts +117 -0
  137. package/src/terrain/persistent-hierarchy-data.ts +196 -0
  138. package/src/terrain/sample-triangle-height.ts +50 -0
  139. package/src/terrain/tile-update-data.ts +32 -0
package/dist/index.cjs CHANGED
@@ -10,9 +10,9 @@ var __export = (target, all) => {
10
10
  };
11
11
  var __copyProps = (to, from, except, desc) => {
12
12
  if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key2 of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key2) && key2 !== except)
15
- __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
13
+ for (let key3 of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key3) && key3 !== except)
15
+ __defProp(to, key3, { get: () => from[key3], enumerable: !(desc = __getOwnPropDesc(from, key3)) || desc.enumerable });
16
16
  }
17
17
  return to;
18
18
  };
@@ -71,6 +71,7 @@ __export(index_exports, {
71
71
  RhumbPolygon: () => RhumbPolygon,
72
72
  TERRAIN_BUFFER_VERSION: () => TERRAIN_BUFFER_VERSION,
73
73
  TerrainContourBoundaryAxis: () => TerrainContourBoundaryAxis,
74
+ TerrainMorphStatus: () => TerrainMorphStatus,
74
75
  TerrainProfileViewStatus: () => TerrainProfileViewStatus,
75
76
  TerrainSampleStatus: () => TerrainSampleStatus,
76
77
  TerrainSurface: () => TerrainSurface,
@@ -99,7 +100,10 @@ __export(index_exports, {
99
100
  createTerrainFilteredPyramid: () => createTerrainFilteredPyramid,
100
101
  createTerrainGradientGrid: () => createTerrainGradientGrid,
101
102
  createTerrainGradientPyramid: () => createTerrainGradientPyramid,
103
+ createTerrainIsobands: () => createTerrainIsobands,
104
+ createTerrainLodMorph: () => createTerrainLodMorph,
102
105
  createTerrainMesh: () => createTerrainMesh,
106
+ createTerrainMixedVertexTileHalos: () => createTerrainMixedVertexTileHalos,
103
107
  createTerrainSkirt: () => createTerrainSkirt,
104
108
  createTerrainSlopeAspectGrid: () => createTerrainSlopeAspectGrid,
105
109
  createTerrainSurface: () => createTerrainSurface,
@@ -108,6 +112,7 @@ __export(index_exports, {
108
112
  eastNorthUpToFixedFrame: () => eastNorthUpToFixedFrame,
109
113
  encodePROJString: () => encodePROJString,
110
114
  encodeWKTCRS: () => encodeWKTCRS,
115
+ evaluateTerrainLodMorph: () => evaluateTerrainLodMorph,
111
116
  fitBounds: () => web_mercator_exports.fitBounds,
112
117
  flyToViewport: () => web_mercator_exports.flyToViewport,
113
118
  formatAngle: () => formatAngle,
@@ -127,6 +132,7 @@ __export(index_exports, {
127
132
  getMeterZoom: () => web_mercator_exports.getMeterZoom,
128
133
  getProjectionMatrix: () => web_mercator_exports.getProjectionMatrix,
129
134
  getProjectionParameters: () => web_mercator_exports.getProjectionParameters,
135
+ getTerrainHierarchyNode: () => getTerrainHierarchyNode,
130
136
  getTerrainMeshEdge: () => getTerrainMeshEdge,
131
137
  getTerrainProfileHorizon: () => getTerrainProfileHorizon,
132
138
  getTerrainProfileViewshed: () => getTerrainProfileViewshed,
@@ -165,6 +171,7 @@ __export(index_exports, {
165
171
  scaleToZoom: () => web_mercator_exports.scaleToZoom,
166
172
  selectTileMatrix: () => selectTileMatrix,
167
173
  simplifyTerrainContourPaths: () => simplifyTerrainContourPaths,
174
+ simplifyTerrainContourPathsTopology: () => simplifyTerrainContourPathsTopology,
168
175
  splitGeographicPolygon: () => splitGeographicPolygon,
169
176
  splitGeographicPolyline: () => splitGeographicPolyline,
170
177
  splitGlobeBounds: () => splitGlobeBounds,
@@ -180,6 +187,18 @@ __export(index_exports, {
180
187
  unitsPerMeter: () => web_mercator_exports.unitsPerMeter,
181
188
  unpackTerrainHeightField: () => unpackTerrainHeightField,
182
189
  unprojectGrid: () => unprojectGrid,
190
+ updateTerrainBounds: () => updateTerrainBounds,
191
+ updateTerrainBoundsRegions: () => updateTerrainBoundsRegions,
192
+ updateTerrainDelatinMeshRegions: () => updateTerrainDelatinMeshRegions,
193
+ updateTerrainGradientPyramidRegions: () => updateTerrainGradientPyramidRegions,
194
+ updateTerrainGradientPyramids: () => updateTerrainGradientPyramids,
195
+ updateTerrainMartiniMeshRegions: () => updateTerrainMartiniMeshRegions,
196
+ updateTerrainMeshRegions: () => updateTerrainMeshRegions,
197
+ updateTerrainMeshes: () => updateTerrainMeshes,
198
+ updateTerrainMixedGradientGrids: () => updateTerrainMixedGradientGrids,
199
+ updateTerrainMixedVertexTileHalos: () => updateTerrainMixedVertexTileHalos,
200
+ updateTerrainPersistentBounds: () => updateTerrainPersistentBounds,
201
+ updateTerrainPersistentGradients: () => updateTerrainPersistentGradients,
183
202
  updateTerrainVertexTileHalos: () => updateTerrainVertexTileHalos,
184
203
  validateTileMatrix: () => validateTileMatrix,
185
204
  validateTileMatrixLimits: () => validateTileMatrixLimits,
@@ -281,11 +300,11 @@ var import_core2 = require("@math.gl/core");
281
300
  function exactNearestSurface(x, y, z, a, b, c, result) {
282
301
  const values = [a, b, c, Math.abs(x), Math.abs(y), Math.abs(z)];
283
302
  const parts = values.map((value3) => {
284
- const bits = value3.toString(2);
285
- const dot4 = bits.indexOf(".");
303
+ const bits2 = value3.toString(2);
304
+ const dot4 = bits2.indexOf(".");
286
305
  return {
287
- integer: BigInt("0b" + bits.replace(".", "")),
288
- exponent: dot4 < 0 ? 0 : dot4 + 1 - bits.length
306
+ integer: BigInt("0b" + bits2.replace(".", "")),
307
+ exponent: dot4 < 0 ? 0 : dot4 + 1 - bits2.length
289
308
  };
290
309
  });
291
310
  const exponent = Math.min(...parts.filter((p) => p.integer !== 0n).map((p) => p.exponent));
@@ -326,10 +345,10 @@ function exactNearestSurface(x, y, z, a, b, c, result) {
326
345
  return false;
327
346
  const dx = d[0] + t, dy = d[1] + t, dz = d[2] + t;
328
347
  const xx = dx * dx, yy = dy * dy, zz = dz * dz;
329
- const sign = u2[0] * yy * zz + u2[1] * xx * zz + u2[2] * xx * yy - xx * yy * zz;
330
- if (sign === 0n)
348
+ const sign2 = u2[0] * yy * zz + u2[1] * xx * zz + u2[2] * xx * yy - xx * yy * zz;
349
+ if (sign2 === 0n)
331
350
  return commit(t, unit3);
332
- if (sign > 0n)
351
+ if (sign2 > 0n)
333
352
  lower = t;
334
353
  else
335
354
  upper = t;
@@ -2701,31 +2720,31 @@ var EllipsoidMetrics = class {
2701
2720
  return kind === "isometric" ? Math.sign(latitude) * Infinity : latitude;
2702
2721
  if (this.ratio === 1 && kind !== "isometric")
2703
2722
  return latitude;
2704
- const sign = Math.sign(latitude);
2723
+ const sign2 = Math.sign(latitude);
2705
2724
  const phi = Math.abs(latitude);
2706
2725
  const [s, c] = sincos(phi);
2707
2726
  switch (kind) {
2708
2727
  case "geocentric":
2709
- return sign * angle(this.ratio * this.ratio * s, c);
2728
+ return sign2 * angle(this.ratio * this.ratio * s, c);
2710
2729
  case "parametric":
2711
- return sign * angle(this.ratio * s, c);
2730
+ return sign2 * angle(this.ratio * s, c);
2712
2731
  case "rectifying":
2713
- return sign * (phi <= 45 ? this.meridian(phi) / this.quarter * 90 : 90 - integrate((t) => this.meridianIntegrand(Math.PI / 2 - t), 0, (90 - phi) * DEG) / this.quarter * 90);
2732
+ return sign2 * (phi <= 45 ? this.meridian(phi) / this.quarter * 90 : 90 - integrate((t) => this.meridianIntegrand(Math.PI / 2 - t), 0, (90 - phi) * DEG) / this.quarter * 90);
2714
2733
  case "authalic": {
2715
2734
  if (phi <= 45) {
2716
2735
  const q = this.ratio ** 2 * (s / (c * c + (this.ratio * s) ** 2) + this.eccentricIntegral(s));
2717
- return sign * Math.asin(q / this.qPole) / DEG;
2736
+ return sign2 * Math.asin(q / this.qPole) / DEG;
2718
2737
  }
2719
2738
  const cap = integrate((t) => {
2720
2739
  const st = Math.sin(t), ct = Math.cos(t);
2721
2740
  const d = st * st + (this.ratio * ct) ** 2;
2722
2741
  return 2 * this.ratio ** 2 * st / (d * d);
2723
2742
  }, 0, (90 - phi) * DEG);
2724
- return sign * (90 - 2 * Math.asin(Math.sqrt(cap / (2 * this.qPole))) / DEG);
2743
+ return sign2 * (90 - 2 * Math.asin(Math.sqrt(cap / (2 * this.qPole))) / DEG);
2725
2744
  }
2726
2745
  default: {
2727
2746
  const psi = Math.asinh(s / c) - this.e2 * this.eccentricIntegral(s);
2728
- return sign * (kind === "isometric" ? psi / DEG : psi < 1 ? Math.atan(Math.sinh(psi)) / DEG : 90 - 2 * Math.atan(Math.exp(-psi)) / DEG);
2747
+ return sign2 * (kind === "isometric" ? psi / DEG : psi < 1 ? Math.atan(Math.sinh(psi)) / DEG : 90 - 2 * Math.atan(Math.exp(-psi)) / DEG);
2729
2748
  }
2730
2749
  }
2731
2750
  }
@@ -2743,10 +2762,10 @@ var EllipsoidMetrics = class {
2743
2762
  return latitude;
2744
2763
  if (this.ratio === 1 && kind !== "isometric")
2745
2764
  return latitude;
2746
- const sign = Math.sign(latitude), target = Math.abs(latitude);
2765
+ const sign2 = Math.sign(latitude), target = Math.abs(latitude);
2747
2766
  if (kind === "geocentric" || kind === "parametric") {
2748
2767
  const [s, c] = sincos(target);
2749
- return sign * angle(s, c * (kind === "geocentric" ? this.ratio ** 2 : this.ratio));
2768
+ return sign2 * angle(s, c * (kind === "geocentric" ? this.ratio ** 2 : this.ratio));
2750
2769
  }
2751
2770
  let lo = 0, hi = 90;
2752
2771
  for (let i = 0; i < 64; ++i) {
@@ -2758,7 +2777,7 @@ var EllipsoidMetrics = class {
2758
2777
  else
2759
2778
  hi = mid;
2760
2779
  }
2761
- return sign * ((lo + hi) / 2);
2780
+ return sign2 * ((lo + hi) / 2);
2762
2781
  }
2763
2782
  eccentricIntegral(s) {
2764
2783
  const e = Math.sqrt(Math.abs(this.e2));
@@ -2954,11 +2973,11 @@ var div = (x, y) => x * Q / y;
2954
2973
  function exact(x) {
2955
2974
  const bytes = new DataView(new ArrayBuffer(8));
2956
2975
  bytes.setFloat64(0, x);
2957
- const bits = bytes.getBigUint64(0), exponent = Number(bits >> 52n & 2047n);
2958
- const mantissa = bits & (1n << 52n) - 1n | (exponent ? 1n << 52n : 0n);
2976
+ const bits2 = bytes.getBigUint64(0), exponent = Number(bits2 >> 52n & 2047n);
2977
+ const mantissa = bits2 & (1n << 52n) - 1n | (exponent ? 1n << 52n : 0n);
2959
2978
  const shift2 = exponent ? exponent - 1075 : -1074;
2960
2979
  const value3 = shift2 >= 0 ? mantissa * Q << BigInt(shift2) : mantissa * Q >> BigInt(-shift2);
2961
- return bits >> 63n ? -value3 : value3;
2980
+ return bits2 >> 63n ? -value3 : value3;
2962
2981
  }
2963
2982
  function sc(x) {
2964
2983
  let s = x, c = Q, ts = x, tc = Q;
@@ -2973,13 +2992,13 @@ function sc(x) {
2973
2992
  }
2974
2993
  return [s, c];
2975
2994
  }
2976
- function remainingPoleDistance(a, b, latitude, azimuth, distance, sign) {
2995
+ function remainingPoleDistance(a, b, latitude, azimuth, distance, sign2) {
2977
2996
  const unit3 = 2 ** Math.floor(Math.log2(a));
2978
2997
  a /= unit3;
2979
2998
  b /= unit3;
2980
2999
  distance /= unit3;
2981
3000
  const ratio2 = div(exact(b), exact(a));
2982
- const theta = mul(90n * Q - BigInt(sign) * exact(latitude), PI) / 180n;
3001
+ const theta = mul(90n * Q - BigInt(sign2) * exact(latitude), PI) / 180n;
2983
3002
  const [s, c] = sc(theta), prolate = ratio2 > Q;
2984
3003
  const square = mul(ratio2, ratio2);
2985
3004
  const k = prolate ? Q - div(Q, square) : Q - square;
@@ -2998,7 +3017,7 @@ function remainingPoleDistance(a, b, latitude, azimuth, distance, sign) {
2998
3017
  const gap = prolate ? div(total, ratio2) : mul(total, square);
2999
3018
  const angle3 = mul(exact(azimuth % 360), PI) / 180n;
3000
3019
  const north = mul(div(exact(distance), exact(a)), sc(angle3)[1]);
3001
- return Number(gap - BigInt(sign) * north) / Number(Q);
3020
+ return Number(gap - BigInt(sign2) * north) / Number(Q);
3002
3021
  }
3003
3022
 
3004
3023
  // dist/ellipsoid-rhumb.js
@@ -3118,10 +3137,10 @@ var EllipsoidRhumb = class {
3118
3137
  return this.metrics.latitudeToAuxiliary(latitude, "isometric") * DEG2;
3119
3138
  }
3120
3139
  polarEndpoint(latitude, north, poleDistance) {
3121
- const sign = Math.abs(latitude) > 80 && Math.abs(north) < Math.abs(this.meridianDelta(0, latitude)) ? Math.sign(latitude) : Math.sign(north), theta1 = (90 - sign * latitude) * DEG2, limit = 10 * DEG2;
3140
+ const sign2 = Math.abs(latitude) > 80 && Math.abs(north) < Math.abs(this.meridianDelta(0, latitude)) ? Math.sign(latitude) : Math.sign(north), theta1 = (90 - sign2 * latitude) * DEG2, limit = 10 * DEG2;
3122
3141
  const density = (theta2) => this.r ** 2 / Math.hypot(Math.sin(theta2), this.r * Math.cos(theta2)) ** 3;
3123
3142
  const gap = (theta2) => integrate(density, 0, theta2);
3124
- const target = sign === Math.sign(north) ? poleDistance : this.meridianDelta(sign > 0 ? latitude : -90, sign > 0 ? 90 : latitude) - sign * north;
3143
+ const target = sign2 === Math.sign(north) ? poleDistance : this.meridianDelta(sign2 > 0 ? latitude : -90, sign2 > 0 ? 90 : latitude) - sign2 * north;
3125
3144
  if (!(target > 0 && target < gap(limit)))
3126
3145
  return void 0;
3127
3146
  let lo = 0, hi = limit, theta = target * this.r;
@@ -3151,9 +3170,9 @@ var EllipsoidRhumb = class {
3151
3170
  return this.r ** 2 / (c * (c * c + (this.r * s) ** 2));
3152
3171
  }, -1, 1) / 2 : -(this.polarPsi(theta) - this.polarPsi(theta1)) / span;
3153
3172
  return {
3154
- latitude: sign * (90 - theta / DEG2),
3173
+ latitude: sign2 * (90 - theta / DEG2),
3155
3174
  means: [meanM, meanP],
3156
- psi: sign * this.polarPsi(theta)
3175
+ psi: sign2 * this.polarPsi(theta)
3157
3176
  };
3158
3177
  }
3159
3178
  polarPsi(theta) {
@@ -3508,9 +3527,9 @@ var GeodesicIntersections = class {
3508
3527
  ++search.failedSeeds;
3509
3528
  }
3510
3529
  } else {
3511
- for (const sign of [-1, 1]) {
3530
+ for (const sign2 of [-1, 1]) {
3512
3531
  try {
3513
- const s = this.bounds.conjugate(A3, sign * this.bounds.halfCircumference);
3532
+ const s = this.bounds.conjugate(A3, sign2 * this.bounds.halfCircumference);
3514
3533
  const point2 = this.coincidencePoint(a, b, {
3515
3534
  s: s * this.a,
3516
3535
  t: c.direction * s * this.a,
@@ -3605,8 +3624,8 @@ var GeodesicIntersections = class {
3605
3624
  for (let i = 0; i < 100; i++) {
3606
3625
  const a = A3.position(x), b = B2.position(y), v = this.solver.inverse(a.lat2, a.lon2, b.lat2, b.lon2);
3607
3626
  const X = math2.AngDiff(a.azi2, v.azi1), Y = math2.AngDiff(b.azi2, v.azi2), XY = math2.AngDiff(X.d, Y.d);
3608
- const orientation2 = XY.d + (XY.e + Y.e - X.e) < 0 ? -1 : 1;
3609
- const sx = math2.sincosde(orientation2 * X.d, orientation2 * X.e), sy = math2.sincosde(orientation2 * Y.d, orientation2 * Y.e);
3627
+ const orientation3 = XY.d + (XY.e + Y.e - X.e) < 0 ? -1 : 1;
3628
+ const sx = math2.sincosde(orientation3 * X.d, orientation3 * X.e), sy = math2.sincosde(orientation3 * Y.d, orientation3 * Y.e);
3610
3629
  let dx, dy, c = 0;
3611
3630
  if (v.s12 <= EPS * this.radius) {
3612
3631
  if (Math.abs(sx.s - sy.s) <= EPS && Math.abs(sx.c - sy.c) <= EPS)
@@ -3666,15 +3685,15 @@ var GeodesicIntersections = class {
3666
3685
  if (length > 0 && length < Math.sqrt(Number.EPSILON))
3667
3686
  return void 0;
3668
3687
  if (length <= EPS) {
3669
- const sign = dot(na, nb) >= 0 ? 1 : -1;
3688
+ const sign2 = dot(na, nb) >= 0 ? 1 : -1;
3670
3689
  const offset2 = Math.atan2(dot(pa, tb), dot(pa, pb));
3671
3690
  const coincidences = [];
3672
- for (let k = Math.ceil((y - sign * x - d - offset2) / (2 * Math.PI)); k <= Math.floor((y - sign * x + d - offset2) / (2 * Math.PI)); k++) {
3691
+ for (let k = Math.ceil((y - sign2 * x - d - offset2) / (2 * Math.PI)); k <= Math.floor((y - sign2 * x + d - offset2) / (2 * Math.PI)); k++) {
3673
3692
  const shift2 = offset2 + 2 * Math.PI * k;
3674
- const sx = (x + sign * (y - shift2)) / 2;
3675
- const sy = sign * sx + shift2;
3693
+ const sx = (x + sign2 * (y - shift2)) / 2;
3694
+ const sy = sign2 * sx + shift2;
3676
3695
  if (Math.abs(sx - x) + Math.abs(sy - y) <= d + this.tolerance)
3677
- coincidences.push({ s: sx * this.a, t: sy * this.a, direction: sign });
3696
+ coincidences.push({ s: sx * this.a, t: sy * this.a, direction: sign2 });
3678
3697
  }
3679
3698
  let failed2 = 0;
3680
3699
  const checked = coincidences.filter((c) => {
@@ -3698,8 +3717,8 @@ var GeodesicIntersections = class {
3698
3717
  }
3699
3718
  const result = [];
3700
3719
  let failed = 0;
3701
- for (const sign of [-1, 1]) {
3702
- const p = crossing.map((v) => sign * v / length);
3720
+ for (const sign2 of [-1, 1]) {
3721
+ const p = crossing.map((v) => sign2 * v / length);
3703
3722
  const s = Math.atan2(dot(p, ta), dot(p, pa)), t = Math.atan2(dot(p, tb), dot(p, pb));
3704
3723
  const k0 = Math.ceil((x - d - s) / (2 * Math.PI)), k1 = Math.floor((x + d - s) / (2 * Math.PI));
3705
3724
  const l0 = Math.ceil((y - d - t) / (2 * Math.PI)), l1 = Math.floor((y + d - t) / (2 * Math.PI));
@@ -4007,18 +4026,18 @@ function localFrameToFixedFrame(ellipsoid, firstAxis, secondAxis, thirdAxis, car
4007
4026
  return result;
4008
4027
  }
4009
4028
  if (atPole) {
4010
- const sign = Math.sign(origin.z);
4029
+ const sign2 = Math.sign(origin.z);
4011
4030
  firstAxisVector = scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);
4012
4031
  if (firstAxis !== "east" && firstAxis !== "west") {
4013
- firstAxisVector.scale(sign);
4032
+ firstAxisVector.scale(sign2);
4014
4033
  }
4015
4034
  secondAxisVector = scratchVector22.fromArray(degeneratePositionLocalFrame[secondAxis]);
4016
4035
  if (secondAxis !== "east" && secondAxis !== "west") {
4017
- secondAxisVector.scale(sign);
4036
+ secondAxisVector.scale(sign2);
4018
4037
  }
4019
4038
  thirdAxisVector = scratchVector3.fromArray(degeneratePositionLocalFrame[thirdAxis]);
4020
4039
  if (thirdAxis !== "east" && thirdAxis !== "west") {
4021
- thirdAxisVector.scale(sign);
4040
+ thirdAxisVector.scale(sign2);
4022
4041
  }
4023
4042
  } else {
4024
4043
  const { up, east, north } = scratchAxisVectors;
@@ -5091,8 +5110,8 @@ function interior(edges, context) {
5091
5110
  }
5092
5111
  throw new GeographicSeamError("topology", "No resolvable polygon interior");
5093
5112
  }
5094
- function output(edges, sign, context) {
5095
- if (interior(edges, context).sign !== sign)
5113
+ function output(edges, sign2, context) {
5114
+ if (interior(edges, context).sign !== sign2)
5096
5115
  edges = edges.slice().reverse().map(reverse);
5097
5116
  context.addVertices(edges.length + 1);
5098
5117
  return {
@@ -5113,7 +5132,7 @@ function processPolygon(inputs, options, latitudeRange) {
5113
5132
  context.tick(inputs.length);
5114
5133
  const rings = inputs.map((ring, i) => prepare(ring, i, context));
5115
5134
  const graph = [], nodes = /* @__PURE__ */ new Map();
5116
- const key2 = (p) => `${p[0]},${p[1]}`;
5135
+ const key3 = (p) => `${p[0]},${p[1]}`;
5117
5136
  const add3 = (edge) => {
5118
5137
  context.tick();
5119
5138
  if (edge.a[0] === edge.b[0] && edge.a[1] === edge.b[1])
@@ -5121,7 +5140,7 @@ function processPolygon(inputs, options, latitudeRange) {
5121
5140
  const id = graph.length;
5122
5141
  graph.push(edge);
5123
5142
  for (const p of [edge.a, edge.b]) {
5124
- const k = key2(p), node = nodes.get(k);
5143
+ const k = key3(p), node = nodes.get(k);
5125
5144
  if (node) {
5126
5145
  if (!same(node.p, p))
5127
5146
  throw new GeographicSeamError("topology", "Touching boundaries have inconsistent attributes");
@@ -5263,16 +5282,16 @@ function processPolygon(inputs, options, latitudeRange) {
5263
5282
  for (let seed = 0; seed < graph.length; seed++) {
5264
5283
  if (used.has(seed))
5265
5284
  continue;
5266
- const cycle = [], start = key2(graph[seed].a);
5285
+ const cycle = [], start = key3(graph[seed].a);
5267
5286
  let id = seed, current = start;
5268
5287
  do {
5269
5288
  context.tick();
5270
5289
  if (used.has(id))
5271
5290
  throw new GeographicSeamError("topology", "Non-simple boundary graph");
5272
5291
  used.add(id);
5273
- const edge = key2(graph[id].a) === current ? graph[id] : reverse(graph[id]);
5292
+ const edge = key3(graph[id].a) === current ? graph[id] : reverse(graph[id]);
5274
5293
  cycle.push(edge);
5275
- current = key2(edge.b);
5294
+ current = key3(edge.b);
5276
5295
  const adjacent = nodes.get(current).edges;
5277
5296
  id = adjacent[0] === id ? adjacent[1] : adjacent[0];
5278
5297
  } while (current !== start);
@@ -5294,13 +5313,13 @@ function processPolygon(inputs, options, latitudeRange) {
5294
5313
  throw new GeographicSeamError("topology", "Nested holes or overlapping polygon components");
5295
5314
  return containers[0];
5296
5315
  });
5297
- const sign = interior(rings[0].membership, context).sign;
5316
+ const sign2 = interior(rings[0].membership, context).sign;
5298
5317
  const result = [], groups = /* @__PURE__ */ new Map();
5299
5318
  for (let i = 0; i < cycles.length; i++)
5300
5319
  if (parents[i] === void 0) {
5301
5320
  if (cycles[i].every((e) => e.source && e.source.ringIndex !== 0))
5302
5321
  throw new GeographicSeamError("topology", "Hole is outside the outer ring");
5303
- const polygon = { rings: [output(cycles[i], sign, context)] };
5322
+ const polygon = { rings: [output(cycles[i], sign2, context)] };
5304
5323
  result.push(polygon);
5305
5324
  groups.set(i, polygon);
5306
5325
  }
@@ -5309,7 +5328,7 @@ function processPolygon(inputs, options, latitudeRange) {
5309
5328
  const group = groups.get(parents[i]);
5310
5329
  if (!group)
5311
5330
  throw new GeographicSeamError("topology", "Nested polygon rings");
5312
- group.rings.push(output(cycles[i], -sign, context));
5331
+ group.rings.push(output(cycles[i], -sign2, context));
5313
5332
  }
5314
5333
  return result;
5315
5334
  }
@@ -5713,7 +5732,7 @@ function cloneAndFreezeJsonValue(value3) {
5713
5732
  return Object.freeze(value3.map((item) => cloneAndFreezeJsonValue(item)));
5714
5733
  }
5715
5734
  if (value3 && typeof value3 === "object") {
5716
- return Object.freeze(Object.fromEntries(Object.entries(value3).map(([key2, item]) => [key2, cloneAndFreezeJsonValue(item)])));
5735
+ return Object.freeze(Object.fromEntries(Object.entries(value3).map(([key3, item]) => [key3, cloneAndFreezeJsonValue(item)])));
5717
5736
  }
5718
5737
  return value3;
5719
5738
  }
@@ -6572,7 +6591,7 @@ function getCRSSignature(crs) {
6572
6591
  return JSON.stringify([
6573
6592
  crs.coordinateFrame,
6574
6593
  crs.projection,
6575
- Object.keys(crs.parameters).sort().map((key2) => [key2, crs.parameters[key2]]),
6594
+ Object.keys(crs.parameters).sort().map((key3) => [key3, crs.parameters[key3]]),
6576
6595
  [crs.ellipsoid.semiMajorAxis, crs.ellipsoid.semiMinorAxis],
6577
6596
  crs.axis,
6578
6597
  [crs.xUnit.name, crs.xUnit.metersPerUnit, crs.xUnit.degreesPerUnit],
@@ -6593,7 +6612,7 @@ var CRSResolutionError = class extends Error {
6593
6612
  }
6594
6613
  };
6595
6614
  function createCRSDictionaryProvider(definitions, options = {}) {
6596
- const entries = new Map(Object.entries(definitions).map(([key2, value3]) => [key2, snapshot(value3)]));
6615
+ const entries = new Map(Object.entries(definitions).map(([key3, value3]) => [key3, snapshot(value3)]));
6597
6616
  return Object.freeze({
6598
6617
  id: options.id ?? "dictionary",
6599
6618
  version: options.version,
@@ -6703,7 +6722,7 @@ function snapshot(value3) {
6703
6722
  if (Array.isArray(value3))
6704
6723
  return Object.freeze(value3.map((item) => snapshot(item)));
6705
6724
  if (value3 && typeof value3 === "object") {
6706
- return Object.freeze(Object.fromEntries(Object.entries(value3).map(([key2, item]) => [key2, snapshot(item)])));
6725
+ return Object.freeze(Object.fromEntries(Object.entries(value3).map(([key3, item]) => [key3, snapshot(item)])));
6707
6726
  }
6708
6727
  return value3;
6709
6728
  }
@@ -6800,16 +6819,16 @@ function copyRecord(value3, stringsOnly) {
6800
6819
  if (!value3 || typeof value3 !== "object" || Array.isArray(value3) || ![Object.prototype, null].includes(Object.getPrototypeOf(value3)))
6801
6820
  throw new TypeError("Invalid execution identity record");
6802
6821
  const result = /* @__PURE__ */ Object.create(null);
6803
- for (const key2 of Object.keys(value3).sort()) {
6804
- nonempty(key2);
6805
- const item = value3[key2];
6822
+ for (const key3 of Object.keys(value3).sort()) {
6823
+ nonempty(key3);
6824
+ const item = value3[key3];
6806
6825
  if (stringsOnly)
6807
6826
  nonempty(item);
6808
6827
  else if (!(item === null || typeof item === "string" || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)))
6809
6828
  throw new TypeError("Invalid execution parameter");
6810
6829
  if (Object.is(item, -0))
6811
6830
  throw new TypeError("Execution parameters cannot contain negative zero");
6812
- result[key2] = item;
6831
+ result[key3] = item;
6813
6832
  }
6814
6833
  return Object.freeze(result);
6815
6834
  }
@@ -6858,10 +6877,10 @@ function createCRSDescriptor(options) {
6858
6877
  } : copyScale(suppliedScale);
6859
6878
  requireValue(Object.prototype.hasOwnProperty.call(options.converter, "WGS84"), "converter.WGS84");
6860
6879
  const converter = /* @__PURE__ */ Object.create(null);
6861
- for (const key2 of Object.getOwnPropertyNames(options.converter)) {
6862
- const operations = options.converter[key2];
6863
- requireValue(Boolean(key2.trim()), "converter key");
6864
- converter[key2] = Object.freeze({
6880
+ for (const key3 of Object.getOwnPropertyNames(options.converter)) {
6881
+ const operations = options.converter[key3];
6882
+ requireValue(Boolean(key3.trim()), "converter key");
6883
+ converter[key3] = Object.freeze({
6865
6884
  from: bindConversion(operations, "from"),
6866
6885
  to: bindConversion(operations, "to"),
6867
6886
  normalize: bindConversion(operations, "normalize")
@@ -6878,9 +6897,9 @@ function createCRSDescriptor(options) {
6878
6897
  converter: Object.freeze(converter)
6879
6898
  });
6880
6899
  }
6881
- function bindConversion(owner, key2) {
6882
- const operation = owner == null ? void 0 : owner[key2];
6883
- requireValue(typeof operation === "function", `converter.${key2}`);
6900
+ function bindConversion(owner, key3) {
6901
+ const operation = owner == null ? void 0 : owner[key3];
6902
+ requireValue(typeof operation === "function", `converter.${key3}`);
6884
6903
  function convert(coordinate, output2) {
6885
6904
  const result = operation.call(owner, coordinate, output2);
6886
6905
  requireSynchronous(result);
@@ -7025,8 +7044,8 @@ function value(c, n) {
7025
7044
  }
7026
7045
  function valueError(c, n) {
7027
7046
  if (Math.abs(c.offset) > 0.5) {
7028
- const sign = c.offset > 0 ? 1 : -1;
7029
- return ROUND * (1 - Math.abs(c.offset) + Math.hypot(...n.map((x, i) => x - sign * c.normal[i])));
7047
+ const sign2 = c.offset > 0 ? 1 : -1;
7048
+ return ROUND * (1 - Math.abs(c.offset) + Math.hypot(...n.map((x, i) => x - sign2 * c.normal[i])));
7030
7049
  }
7031
7050
  return ROUND * (Math.abs(c.offset) + n.reduce((sum, x, i) => sum + Math.abs(x * c.normal[i]), 0));
7032
7051
  }
@@ -7368,7 +7387,7 @@ function orientation(edges, frame2, context) {
7368
7387
  }
7369
7388
  throw new GeographicSeamError("precision", "No resolvable chart-ring interior");
7370
7389
  }
7371
- function polygons(arcs, frame2, chart, sign, context) {
7390
+ function polygons(arcs, frame2, chart, sign2, context) {
7372
7391
  const outgoing = /* @__PURE__ */ new Map(), incoming = /* @__PURE__ */ new Map();
7373
7392
  for (let i = 0; i < arcs.length; i++) {
7374
7393
  context.tick();
@@ -7380,8 +7399,8 @@ function polygons(arcs, frame2, chart, sign, context) {
7380
7399
  outgoing.set(e.a.id, i);
7381
7400
  incoming.set(e.b.id, i);
7382
7401
  }
7383
- for (const key2 of outgoing.keys())
7384
- if (!incoming.has(key2))
7402
+ for (const key3 of outgoing.keys())
7403
+ if (!incoming.has(key3))
7385
7404
  throw new GeographicSeamError("topology", "Open atlas boundary");
7386
7405
  const cycles = [], used = /* @__PURE__ */ new Set();
7387
7406
  for (let i = 0; i < arcs.length; i++)
@@ -7425,7 +7444,7 @@ function polygons(arcs, frame2, chart, sign, context) {
7425
7444
  if (orientation(cycles[i], frame2, context) !== expected)
7426
7445
  throw new GeographicSeamError("topology", "Inconsistent nested atlas winding");
7427
7446
  if (expected === 1) {
7428
- const p = { chart, rings: [output2(cycles[i], sign)] };
7447
+ const p = { chart, rings: [output2(cycles[i], sign2)] };
7429
7448
  result.push(p);
7430
7449
  groups.set(i, p);
7431
7450
  }
@@ -7435,7 +7454,7 @@ function polygons(arcs, frame2, chart, sign, context) {
7435
7454
  const immediate = parents[i].filter((j) => depths[j] === depths[i] - 1);
7436
7455
  if (immediate.length !== 1 || !groups.has(immediate[0]))
7437
7456
  throw new GeographicSeamError("topology", "Unresolved atlas ring hierarchy");
7438
- groups.get(immediate[0]).rings.push(output2(cycles[i], -sign));
7457
+ groups.get(immediate[0]).rings.push(output2(cycles[i], -sign2));
7439
7458
  }
7440
7459
  return result;
7441
7460
  }
@@ -7650,9 +7669,9 @@ var GeographicCutAtlas = class {
7650
7669
  const rings = snapshots.map((r, i) => prepare(r, i, context));
7651
7670
  if (!rings.length)
7652
7671
  return { sources: [], rings, sign: 1 };
7653
- const sign = interior(rings[0].membership, context).sign, sources = [];
7672
+ const sign2 = interior(rings[0].membership, context).sign, sources = [];
7654
7673
  for (let i = 0; i < rings.length; i++) {
7655
- const orientation2 = interior(rings[i].membership, context).sign, reversed = orientation2 !== (i ? -1 : 1), points = originals[i];
7674
+ const orientation3 = interior(rings[i].membership, context).sign, reversed = orientation3 !== (i ? -1 : 1), points = originals[i];
7656
7675
  if (points.length > 1 && points[0][0] === points[points.length - 1][0] && points[0][1] === points[points.length - 1][1])
7657
7676
  points.pop();
7658
7677
  for (const edge of mergeEdges(rings[i].edges)) {
@@ -7664,14 +7683,14 @@ var GeographicCutAtlas = class {
7664
7683
  });
7665
7684
  }
7666
7685
  }
7667
- return { sources, rings, sign };
7686
+ return { sources, rings, sign: sign2 };
7668
7687
  }
7669
7688
  /** Clip simple original outer+hole rings to every chart. Shared events are computed once. */
7670
7689
  clipPolygon(inputs) {
7671
- const context = new Context(this.config.options), { sources, rings, sign } = this.sources(inputs, context);
7690
+ const context = new Context(this.config.options), { sources, rings, sign: sign2 } = this.sources(inputs, context);
7672
7691
  if (!rings.length)
7673
7692
  return [];
7674
- return this.clip(sources, context, (n) => filled(rings, position(n), context), sign);
7693
+ return this.clip(sources, context, (n) => filled(rings, position(n), context), sign2);
7675
7694
  }
7676
7695
  clipPolyline(input, options = {}) {
7677
7696
  const context = new Context(this.config.options), points = context.read(input), turns = options.longitudeTurns ? Array.from(options.longitudeTurns) : new Array(Math.max(0, points.length - 1)).fill(0);
@@ -7705,7 +7724,7 @@ var GeographicCutAtlas = class {
7705
7724
  }
7706
7725
  return this.clip(sources, context);
7707
7726
  }
7708
- clip(sources, context, contains2, sign = 1) {
7727
+ clip(sources, context, contains2, sign2 = 1) {
7709
7728
  const registry = /* @__PURE__ */ new Map(), events = new Map(this.boundaries.map((c) => [c.id, /* @__PURE__ */ new Set()]));
7710
7729
  let serial = 0;
7711
7730
  const node = (n, attributes, source = false) => {
@@ -7730,7 +7749,7 @@ var GeographicCutAtlas = class {
7730
7749
  registry.set(k, p);
7731
7750
  return p;
7732
7751
  };
7733
- const on = (n, b) => {
7752
+ const on2 = (n, b) => {
7734
7753
  n.cuts.add(b.id);
7735
7754
  events.get(b.id).add(n);
7736
7755
  };
@@ -7750,8 +7769,8 @@ var GeographicCutAtlas = class {
7750
7769
  if (!relevant([this.boundaries[i].id, this.boundaries[j].id], n))
7751
7770
  continue;
7752
7771
  const v = node(n, this.attributes);
7753
- on(v, this.boundaries[i]);
7754
- on(v, this.boundaries[j]);
7772
+ on2(v, this.boundaries[i]);
7773
+ on2(v, this.boundaries[j]);
7755
7774
  }
7756
7775
  }
7757
7776
  const sourceArcs = [];
@@ -7767,8 +7786,8 @@ var GeographicCutAtlas = class {
7767
7786
  const hit = roots(curve, b, context);
7768
7787
  if (hit.coincident) {
7769
7788
  coincident.add(b.id);
7770
- on(endpoints[0], b);
7771
- on(endpoints[1], b);
7789
+ on2(endpoints[0], b);
7790
+ on2(endpoints[1], b);
7772
7791
  continue;
7773
7792
  }
7774
7793
  for (const t of hit.fractions) {
@@ -7780,11 +7799,11 @@ var GeographicCutAtlas = class {
7780
7799
  v = node(n, p.slice(2), true);
7781
7800
  at.set(t, v);
7782
7801
  }
7783
- on(v, b);
7802
+ on2(v, b);
7784
7803
  }
7785
7804
  for (const v of endpoints)
7786
7805
  if (value(b, v.n) === 0)
7787
- on(v, b);
7806
+ on2(v, b);
7788
7807
  }
7789
7808
  if (!contains2 && Math.hypot(...endpoints[0].n.map((x, i) => x - endpoints[1].n[i])) === 0 && curve.speed > ANGULAR) {
7790
7809
  const steps = Math.max(4, Math.ceil(curve.speed / (Math.PI / 2)));
@@ -7830,7 +7849,7 @@ var GeographicCutAtlas = class {
7830
7849
  if (Array.from(events.get(b.id)).some((v2) => Math.hypot(...v2.n.map((x, j) => x - n[j])) < ANGULAR))
7831
7850
  continue;
7832
7851
  const v = node(n, this.attributes);
7833
- on(v, b);
7852
+ on2(v, b);
7834
7853
  }
7835
7854
  const accepts = (cell, n, known) => {
7836
7855
  const values = cell.cuts.filter((r) => !(known == null ? void 0 : known.has(r.circle.id))).map((r) => {
@@ -7926,7 +7945,7 @@ var GeographicCutAtlas = class {
7926
7945
  arcs.push(arc);
7927
7946
  }
7928
7947
  }
7929
- result.push(...polygons(arcs, cell, cell.id, sign, context));
7948
+ result.push(...polygons(arcs, cell, cell.id, sign2, context));
7930
7949
  }
7931
7950
  return result;
7932
7951
  }
@@ -8278,7 +8297,7 @@ var EllipsoidGeodesicExact = class {
8278
8297
  c1 /= sigmaNorm;
8279
8298
  const sig1 = Math.atan2(s1, c1);
8280
8299
  const k2 = ca0 * ca0 * ep2, I = ellipticIntegrals(k2, ep2), dn1 = Math.sqrt(1 + k2 * s1 * s1);
8281
- const sign = sa0 < 0 || Object.is(sa0, -0) ? -1 : 1;
8300
+ const sign2 = sa0 < 0 || Object.is(sa0, -0) ? -1 : 1;
8282
8301
  const includeArea = Boolean(options.area);
8283
8302
  const unroll = Boolean(options.unrollLongitude), azi1 = angleMath.AngNormalize(azimuth);
8284
8303
  const distanceLimit = b * I.E(sig1, 4 * Math.PI);
@@ -8286,13 +8305,13 @@ var EllipsoidGeodesicExact = class {
8286
8305
  const phase = arcDegrees === void 0 ? { s: Math.sin(delta), c: Math.cos(delta) } : angleMath.sincosd(arcDegrees);
8287
8306
  const s2 = s1 * phase.c + c1 * phase.s, c2 = c1 * phase.c - s1 * phase.s;
8288
8307
  const dn2 = Math.sqrt(1 + k2 * s2 * s2), J = I.J(sig1, delta);
8289
- const chi2 = Math.atan2(sign * sa0 * s2, f1 * dn2 * c2), signedChi1 = Math.atan2(sign * sa0 * s1, f1 * dn1 * c1);
8308
+ const chi2 = Math.atan2(sign2 * sa0 * s2, f1 * dn2 * c2), signedChi1 = Math.atan2(sign2 * sa0 * s1, f1 * dn1 * c1);
8290
8309
  const t = k2 * (s2 - s1) * (s2 + s1) / (dn1 + dn2);
8291
8310
  const turns = Math.trunc(arcDegrees === void 0 ? delta / Math.PI : arcDegrees / 180), remainder = arcDegrees === void 0 ? delta - turns * Math.PI : arcDegrees - turns * 180;
8292
8311
  const parity = Math.abs(turns % 2) === 1 ? -1 : 1;
8293
8312
  const sr = phase.s * parity;
8294
8313
  const endS = s2 * parity, endC = c2 * parity;
8295
- const chi = sa0 === 0 ? Math.round(sign * (delta - (Math.atan2(s2, c2) - Math.atan2(s1, c1)) + (chi2 - signedChi1)) / Math.PI) * Math.PI : sign * (turns * Math.PI + (remainder === 0 ? 0 : Math.atan2(sign * sa0 * f1 * (dn1 * sr - t * s1 * endC), f1 * f1 * dn1 * dn2 * c1 * endC + sa0 * sa0 * s1 * endS)));
8314
+ const chi = sa0 === 0 ? Math.round(sign2 * (delta - (Math.atan2(s2, c2) - Math.atan2(s1, c1)) + (chi2 - signedChi1)) / Math.PI) * Math.PI : sign2 * (turns * Math.PI + (remainder === 0 ? 0 : Math.atan2(sign2 * sa0 * f1 * (dn1 * sr - t * s1 * endC), f1 * f1 * dn1 * dn2 * c1 * endC + sa0 * sa0 * s1 * endS)));
8296
8315
  const longitude = (unroll ? lon : angleMath.AngNormalize(lon)) + (chi - e2 / f1 * sa0 * I.H(sig1, delta)) / DEG4;
8297
8316
  const cosine = phase.c;
8298
8317
  return {
@@ -8593,8 +8612,8 @@ function parseAngle(text, axis = "angle") {
8593
8612
  const degrees2 = Number(parts[2]), minutes = Number(parts[3] ?? 0), seconds = Number(parts[4] ?? 0);
8594
8613
  if (minutes >= 60 || seconds >= 60 || parts[3] !== void 0 && !Number.isInteger(degrees2) || parts[4] !== void 0 && !Number.isInteger(minutes))
8595
8614
  throw new RangeError("Invalid DMS components");
8596
- const sign = parts[1] === "-" || /[SW]/.test(hemisphere) ? -1 : 1;
8597
- const result = sign * (degrees2 + minutes / 60 + seconds / 3600);
8615
+ const sign2 = parts[1] === "-" || /[SW]/.test(hemisphere) ? -1 : 1;
8616
+ const result = sign2 * (degrees2 + minutes / 60 + seconds / 3600);
8598
8617
  validate(result, axis);
8599
8618
  return result;
8600
8619
  }
@@ -9643,8 +9662,8 @@ function sphericalExtremum(vector2, parameters, domain, maximize = true) {
9643
9662
  length = 1;
9644
9663
  }
9645
9664
  if (length > 1e-14) {
9646
- for (const sign of [-1, 1]) {
9647
- const position2 = axis.map((value3, index) => value3 * limit + sign * tangent[index] * Math.sin(domain.distance) / length);
9665
+ for (const sign2 of [-1, 1]) {
9666
+ const position2 = axis.map((value3, index) => value3 * limit + sign2 * tangent[index] * Math.sin(domain.distance) / length);
9648
9667
  consider(Math.atan2(position2[1], position2[0]), Math.atan2(position2[2], Math.hypot(position2[0], position2[1])));
9649
9668
  }
9650
9669
  }
@@ -9845,10 +9864,10 @@ function forward3(state, p) {
9845
9864
  return p;
9846
9865
  }
9847
9866
  if (state.sphere && Math.abs(state.coslat0) <= EPSLN) {
9848
- const sign = state.lat0 > 0 ? 1 : -1;
9849
- const radius = 2 * state.a * state.k0 * Math.tan(Math.PI / 4 - sign * lat / 2);
9867
+ const sign2 = state.lat0 > 0 ? 1 : -1;
9868
+ const radius = 2 * state.a * state.k0 * Math.tan(Math.PI / 4 - sign2 * lat / 2);
9850
9869
  p.x = state.x0 + radius * Math.sin(dlon);
9851
- p.y = state.y0 - sign * radius * Math.cos(dlon);
9870
+ p.y = state.y0 - sign2 * radius * Math.cos(dlon);
9852
9871
  return p;
9853
9872
  }
9854
9873
  if (state.sphere) {
@@ -9989,7 +10008,7 @@ var prepared = /* @__PURE__ */ new Map();
9989
10008
  function projection(zone, north) {
9990
10009
  if (!Number.isInteger(zone) || zone < 0 || zone > 60 || typeof north !== "boolean")
9991
10010
  throw new RangeError("Invalid UTM/UPS zone or hemisphere");
9992
- const key2 = 2 * zone + Number(north), cached = prepared.get(key2);
10011
+ const key3 = 2 * zone + Number(north), cached = prepared.get(key3);
9993
10012
  if (cached)
9994
10013
  return cached;
9995
10014
  const parameters = zone ? { zone: String(zone), ...north ? {} : { south: void 0 } } : {
@@ -10003,7 +10022,7 @@ function projection(zone, north) {
10003
10022
  eccentricitySquared: F * (2 - F),
10004
10023
  parameters
10005
10024
  });
10006
- prepared.set(key2, result);
10025
+ prepared.set(key3, result);
10007
10026
  return result;
10008
10027
  }
10009
10028
  function projectGrid(latitude, longitude, options = {}) {
@@ -10282,8 +10301,8 @@ function subdivideGeographicCutRing(inputs, ring, options) {
10282
10301
  const s = descriptor.source, p = points[s.ringIndex];
10283
10302
  if (!Number.isInteger(s.ringIndex) || !p || !Number.isInteger(s.edgeIndex) || s.edgeIndex < 0 || s.edgeIndex >= p.length || ![s.startFraction, s.endFraction, s.longitudeShift].every(Number.isFinite) || Math.min(s.startFraction, s.endFraction) < 0 || Math.max(s.startFraction, s.endFraction) > 1 || !Number.isSafeInteger(s.longitudeShift / 360))
10284
10303
  throw new GeographicSeamError("input", "Invalid cut source interval");
10285
- const key2 = s.ringIndex + ":" + s.edgeIndex;
10286
- let path = sources.get(key2);
10304
+ const key3 = s.ringIndex + ":" + s.edgeIndex;
10305
+ let path = sources.get(key3);
10287
10306
  if (!path) {
10288
10307
  const first = p[s.edgeIndex], last = p[(s.edgeIndex + 1) % p.length], edgeTurns = ((_a = turns[s.ringIndex]) == null ? void 0 : _a[s.edgeIndex]) ?? 0;
10289
10308
  if (settings.edgeModel === "geodesic")
@@ -10297,7 +10316,7 @@ function subdivideGeographicCutRing(inputs, ring, options) {
10297
10316
  sample: edge.sample
10298
10317
  };
10299
10318
  }
10300
- sources.set(key2, path);
10319
+ sources.set(key3, path);
10301
10320
  }
10302
10321
  const curve = path;
10303
10322
  return {
@@ -10704,19 +10723,19 @@ function validateBatch(positions, output2) {
10704
10723
  }
10705
10724
  const count = positions.length / 2;
10706
10725
  const buffers = [positions];
10707
- for (const [key2, size] of [
10726
+ for (const [key3, size] of [
10708
10727
  ["heights", 1],
10709
10728
  ["statuses", 1],
10710
10729
  ["gradients", 2],
10711
10730
  ["normals", 3],
10712
10731
  ["gradientStatuses", 1]
10713
10732
  ]) {
10714
- const buffer = output2[key2];
10715
- if (buffer === void 0 && key2 !== "heights" && key2 !== "statuses")
10733
+ const buffer = output2[key3];
10734
+ if (buffer === void 0 && key3 !== "heights" && key3 !== "statuses")
10716
10735
  continue;
10717
- const byte = key2 === "statuses" || key2 === "gradientStatuses";
10736
+ const byte = key3 === "statuses" || key3 === "gradientStatuses";
10718
10737
  if ((byte ? !(buffer instanceof Uint8Array) : !isTerrainArray(buffer)) || buffer.length < count * size) {
10719
- throw new Error(`Terrain batch ${key2} has an invalid type or insufficient length`);
10738
+ throw new Error(`Terrain batch ${key3} has an invalid type or insufficient length`);
10720
10739
  }
10721
10740
  for (const other of buffers) {
10722
10741
  if (buffer.buffer === other.buffer && buffer.byteOffset < other.byteOffset + other.byteLength && other.byteOffset < buffer.byteOffset + buffer.byteLength) {
@@ -10751,9 +10770,9 @@ function createTerrainSkirt(mesh, options) {
10751
10770
  if (!Number.isFinite(area) || area <= 0)
10752
10771
  throw new Error("Terrain skirt requires upward nondegenerate XY triangles");
10753
10772
  for (let j = 0; j < 3; j++) {
10754
- const u = ids[j], v = ids[(j + 1) % 3], key2 = edgeKey(u, v), prior = boundary.get(key2);
10773
+ const u = ids[j], v = ids[(j + 1) % 3], key3 = edgeKey(u, v), prior = boundary.get(key3);
10755
10774
  if (!prior)
10756
- boundary.set(key2, { a: u, b: v, count: 1 });
10775
+ boundary.set(key3, { a: u, b: v, count: 1 });
10757
10776
  else {
10758
10777
  if (prior.count !== 1 || prior.a !== v || prior.b !== u)
10759
10778
  throw new Error("Terrain skirt mesh has nonmanifold or inconsistent edges");
@@ -10766,10 +10785,10 @@ function createTerrainSkirt(mesh, options) {
10766
10785
  selected = [];
10767
10786
  const used = /* @__PURE__ */ new Set();
10768
10787
  for (let i = 0; i < edges.length; i += 2) {
10769
- const key2 = edgeKey(edges[i], edges[i + 1]), edge = boundary.get(key2);
10770
- if (!edge || edge.count !== 1 || used.has(key2))
10788
+ const key3 = edgeKey(edges[i], edges[i + 1]), edge = boundary.get(key3);
10789
+ if (!edge || edge.count !== 1 || used.has(key3))
10771
10790
  throw new Error("Terrain skirt selection must contain unique boundary edges");
10772
- used.add(key2);
10791
+ used.add(key3);
10773
10792
  selected.push(edge);
10774
10793
  }
10775
10794
  } else
@@ -11023,10 +11042,10 @@ var TiledHeightField = class _TiledHeightField {
11023
11042
  throw new Error("Terrain requires unique matrix identifiers");
11024
11043
  for (const tile of props.tiles) {
11025
11044
  const matrix = this.validateTileId(tile);
11026
- const key2 = tileKey(tile.matrixId, tile.column, tile.row);
11027
- if (this.tiles.has(key2))
11045
+ const key3 = tileKey(tile.matrixId, tile.column, tile.row);
11046
+ if (this.tiles.has(key3))
11028
11047
  throw new Error("Duplicate terrain tile");
11029
- this.tiles.set(key2, copyTileData(tile, matrix));
11048
+ this.tiles.set(key3, copyTileData(tile, matrix));
11030
11049
  }
11031
11050
  for (const tile of props.tiles)
11032
11051
  this.buildHalo(this.getMatrix(tile.matrixId), tile.column, tile.row, props.diagonal);
@@ -11055,10 +11074,10 @@ var TiledHeightField = class _TiledHeightField {
11055
11074
  const touched = /* @__PURE__ */ new Map();
11056
11075
  for (const tile of [...update.tiles ?? [], ...update.remove ?? []]) {
11057
11076
  this.validateTileId(tile);
11058
- const key2 = tileKey(tile.matrixId, tile.column, tile.row);
11059
- if (touched.has(key2))
11077
+ const key3 = tileKey(tile.matrixId, tile.column, tile.row);
11078
+ if (touched.has(key3))
11060
11079
  throw new Error("Terrain update contains duplicate or conflicting tile identifiers");
11061
- touched.set(key2, tile);
11080
+ touched.set(key3, tile);
11062
11081
  }
11063
11082
  for (const tile of update.tiles ?? [])
11064
11083
  replacements.set(tileKey(tile.matrixId, tile.column, tile.row), copyTileData(tile, this.getMatrix(tile.matrixId)));
@@ -11069,18 +11088,18 @@ var TiledHeightField = class _TiledHeightField {
11069
11088
  diagonal: this.diagonal,
11070
11089
  heightReference: this.heightReference
11071
11090
  });
11072
- for (const [key2, tile] of this.tiles)
11073
- next.tiles.set(key2, tile);
11074
- for (const [key2, halo] of this.halos)
11075
- next.halos.set(key2, halo);
11091
+ for (const [key3, tile] of this.tiles)
11092
+ next.tiles.set(key3, tile);
11093
+ for (const [key3, halo] of this.halos)
11094
+ next.halos.set(key3, halo);
11076
11095
  const affected = /* @__PURE__ */ new Map();
11077
- for (const [key2, tile] of touched) {
11078
- if (replacements.has(key2))
11079
- next.tiles.set(key2, replacements.get(key2));
11096
+ for (const [key3, tile] of touched) {
11097
+ if (replacements.has(key3))
11098
+ next.tiles.set(key3, replacements.get(key3));
11080
11099
  else {
11081
- if (!next.tiles.delete(key2))
11100
+ if (!next.tiles.delete(key3))
11082
11101
  continue;
11083
- next.halos.delete(key2);
11102
+ next.halos.delete(key3);
11084
11103
  }
11085
11104
  for (let row = tile.row - 1; row <= tile.row + 1; row++)
11086
11105
  for (let column = tile.column - 1; column <= tile.column + 1; column++) {
@@ -11093,11 +11112,11 @@ var TiledHeightField = class _TiledHeightField {
11093
11112
  }
11094
11113
  }
11095
11114
  const changes = [];
11096
- for (const [key2, tile] of affected) {
11097
- if (next.tiles.has(key2)) {
11115
+ for (const [key3, tile] of affected) {
11116
+ if (next.tiles.has(key3)) {
11098
11117
  next.buildHalo(next.getMatrix(tile.matrixId), tile.column, tile.row, this.diagonal);
11099
11118
  changes.push({ ...tile, resident: true });
11100
- } else if (this.tiles.has(key2))
11119
+ } else if (this.tiles.has(key3))
11101
11120
  changes.push(tile);
11102
11121
  }
11103
11122
  next.changes = freezeChanges(changes);
@@ -11820,10 +11839,10 @@ function buildTopology(indices, validity) {
11820
11839
  if (!validity[triangle])
11821
11840
  continue;
11822
11841
  const a = indices[i], b = indices[triangle * 3 + (i % 3 + 1) % 3];
11823
- const key2 = a < b ? `${a}/${b}` : `${b}/${a}`;
11824
- const opposite = edges.get(key2);
11842
+ const key3 = a < b ? `${a}/${b}` : `${b}/${a}`;
11843
+ const opposite = edges.get(key3);
11825
11844
  if (opposite === void 0)
11826
- edges.set(key2, i);
11845
+ edges.set(key3, i);
11827
11846
  else {
11828
11847
  if (halfedges[opposite] !== -1)
11829
11848
  throw new Error("Nonmanifold terrain edge");
@@ -11993,7 +12012,8 @@ function measureTerrainMeshError(field, mesh, options = {}) {
11993
12012
  const x = mesh.gridCoordinates[i * 2] + shift2, y = mesh.gridCoordinates[i * 2 + 1] + shift2;
11994
12013
  for (let axis = 0; axis < 2; axis++) {
11995
12014
  const expected = field.origin[axis] - mesh.origin[axis] + x * field.columnStep[axis] + y * field.rowStep[axis];
11996
- if (!Number.isFinite(expected) || mesh.positions[i * 3 + axis] !== expected)
12015
+ const tolerance = Math.min(16 * Number.EPSILON * (Math.abs(field.origin[axis] - mesh.origin[axis]) + Math.abs(x * field.columnStep[axis]) + Math.abs(y * field.rowStep[axis])), 1e-9 * Math.max(Math.abs(field.columnStep[axis]), Math.abs(field.rowStep[axis])));
12016
+ if (!Number.isFinite(expected) || Math.abs(mesh.positions[i * 3 + axis] - expected) > tolerance)
11997
12017
  throw new Error("Terrain mesh XY does not match the source grid frame");
11998
12018
  }
11999
12019
  }
@@ -12028,9 +12048,9 @@ function measureTerrainMeshError(field, mesh, options = {}) {
12028
12048
  throw new Error("Terrain mesh sample-test budget exceeded");
12029
12049
  const dx = baseX + (column + shift2) * columnX + (row + shift2) * rowX - px;
12030
12050
  const dy = baseY + (column + shift2) * columnY + (row + shift2) * rowY - py;
12031
- const sign = Math.sign(xyArea), area = Math.abs(xyArea);
12032
- const nu = (dx * vy - dy * vx) * sign;
12033
- const nv = (ux * dy - uy * dx) * sign;
12051
+ const sign2 = Math.sign(xyArea), area = Math.abs(xyArea);
12052
+ const nu = (dx * vy - dy * vx) * sign2;
12053
+ const nv = (ux * dy - uy * dx) * sign2;
12034
12054
  const tolerance = 16 * Number.EPSILON * (Math.abs(dx * vy) + Math.abs(dy * vx) + Math.abs(ux * dy) + Math.abs(uy * dx) + area);
12035
12055
  if (nu < -tolerance || nv < -tolerance || nu + nv > area + tolerance)
12036
12056
  continue;
@@ -12739,8 +12759,8 @@ function createTerrainContours(field, levels, options = {}) {
12739
12759
  const exact2 = height(a) === level ? a : height(b) === level ? b : void 0;
12740
12760
  return exact2 === void 0 ? { a, b, key: `e${a}/${b}` } : { a: exact2, b: exact2, key: `v${exact2}` };
12741
12761
  };
12742
- const vertex = ({ a, b, key: key2 }) => {
12743
- const existing = vertices.get(key2);
12762
+ const vertex = ({ a, b, key: key3 }) => {
12763
+ const existing = vertices.get(key3);
12744
12764
  if (existing !== void 0)
12745
12765
  return existing;
12746
12766
  if (positions.length / 3 >= maxVertices)
@@ -12767,7 +12787,7 @@ function createTerrainContours(field, levels, options = {}) {
12767
12787
  const index = positions.length / 3;
12768
12788
  positions.push(px, py, pz);
12769
12789
  coordinates.push(x, y);
12770
- vertices.set(key2, index);
12790
+ vertices.set(key3, index);
12771
12791
  return index;
12772
12792
  };
12773
12793
  const triangle = (a, b, c) => {
@@ -12784,14 +12804,14 @@ function createTerrainContours(field, levels, options = {}) {
12784
12804
  if (hits.length !== 2 || hits[0].key === hits[1].key)
12785
12805
  return;
12786
12806
  const va = vertex(hits[0]), vb = vertex(hits[1]);
12787
- const key2 = va < vb ? `${va}/${vb}` : `${vb}/${va}`;
12788
- if (edges.has(key2))
12807
+ const key3 = va < vb ? `${va}/${vb}` : `${vb}/${va}`;
12808
+ if (edges.has(key3))
12789
12809
  return;
12790
12810
  if (segments.length / 2 >= maxSegments)
12791
12811
  throw new Error("Terrain contour segment capacity exceeded");
12792
12812
  if (positions[3 * va] === positions[3 * vb] && positions[3 * va + 1] === positions[3 * vb + 1])
12793
12813
  throw new Error("Terrain contour segment collapses; use a local origin");
12794
- edges.add(key2);
12814
+ edges.add(key3);
12795
12815
  segments.push(va, vb);
12796
12816
  levelIndices.push(levelIndex);
12797
12817
  };
@@ -12878,10 +12898,10 @@ function stitchTerrainContours(contours, options = {}) {
12878
12898
  validateContourVertex(contours, b, level, assignments);
12879
12899
  if (a === b || contours.positions[3 * a] === contours.positions[3 * b] && contours.positions[3 * a + 1] === contours.positions[3 * b + 1])
12880
12900
  throw new Error("Degenerate terrain contour segment");
12881
- const key2 = a < b ? `${a}/${b}` : `${b}/${a}`;
12882
- if (unique.has(key2))
12901
+ const key3 = a < b ? `${a}/${b}` : `${b}/${a}`;
12902
+ if (unique.has(key3))
12883
12903
  throw new Error("Duplicate terrain contour segment");
12884
- unique.add(key2);
12904
+ unique.add(key3);
12885
12905
  degrees2[a]++;
12886
12906
  degrees2[b]++;
12887
12907
  }
@@ -13069,10 +13089,10 @@ function diagnoseTerrainContourBoundaries(contours, options) {
13069
13089
  validateContourVertex(contours, b, level, assignments);
13070
13090
  if (a === b || contours.positions[3 * a] === contours.positions[3 * b] && contours.positions[3 * a + 1] === contours.positions[3 * b + 1])
13071
13091
  throw new Error("Degenerate terrain contour segment");
13072
- const key2 = a < b ? `${a}/${b}` : `${b}/${a}`;
13073
- if (seen.has(key2))
13092
+ const key3 = a < b ? `${a}/${b}` : `${b}/${a}`;
13093
+ if (seen.has(key3))
13074
13094
  throw new Error("Duplicate terrain contour segment");
13075
- seen.add(key2);
13095
+ seen.add(key3);
13076
13096
  degrees2[a]++;
13077
13097
  degrees2[b]++;
13078
13098
  }
@@ -13208,6 +13228,10 @@ function simplifyTerrainContourPaths(paths, options) {
13208
13228
  uses[vertex]++;
13209
13229
  }
13210
13230
  }
13231
+ const protectedIds = new Set(options.protectedVertexIndices);
13232
+ for (const id of protectedIds)
13233
+ if (id >= count)
13234
+ throw new Error("Invalid protected contour vertex");
13211
13235
  const keep = new Uint8Array(paths.indices.length);
13212
13236
  let distanceTests = 0, maxDeviation = 0;
13213
13237
  for (let p = 0; p < pathCount; p++) {
@@ -13218,7 +13242,7 @@ function simplifyTerrainContourPaths(paths, options) {
13218
13242
  keep[start + Math.floor(2 * (end - start) / 3)] = 1;
13219
13243
  }
13220
13244
  for (let i = start; i <= end; i++)
13221
- if (uses[paths.indices[i]] > 1)
13245
+ if (uses[paths.indices[i]] > 1 || protectedIds.has(paths.indices[i]))
13222
13246
  keep[i] = 1;
13223
13247
  const stack = [];
13224
13248
  let previous = start;
@@ -13439,9 +13463,9 @@ function compareTerrainSlopes(a, ad, b, bd) {
13439
13463
  const bytes = new DataView(new ArrayBuffer(8));
13440
13464
  const parts = (value3) => {
13441
13465
  bytes.setFloat64(0, Math.abs(value3));
13442
- const bits = bytes.getBigUint64(0);
13443
- const exponent = Number(bits >> 52n & 0x7ffn);
13444
- const fraction = bits & 0xfffffffffffffn;
13466
+ const bits2 = bytes.getBigUint64(0);
13467
+ const exponent = Number(bits2 >> 52n & 0x7ffn);
13468
+ const fraction = bits2 & 0xfffffffffffffn;
13445
13469
  return exponent ? [fraction | 0x10000000000000n, exponent - 1075] : [fraction, -1074];
13446
13470
  };
13447
13471
  const [am, ae] = parts(a), [bdm, bde] = parts(bd);
@@ -13558,10 +13582,10 @@ function reconcileTerrainVertexTiles(tiles, options) {
13558
13582
  const shared2 = /* @__PURE__ */ new Map();
13559
13583
  const result = [];
13560
13584
  for (const tile of sorted) {
13561
- const key2 = `${tile.column},${tile.row}`;
13562
- if (!Number.isSafeInteger(tile.column) || !Number.isSafeInteger(tile.row) || seen.has(key2))
13585
+ const key3 = `${tile.column},${tile.row}`;
13586
+ if (!Number.isSafeInteger(tile.column) || !Number.isSafeInteger(tile.row) || seen.has(key3))
13563
13587
  throw new Error("Invalid or duplicate vertex tile address");
13564
- seen.add(key2);
13588
+ seen.add(key3);
13565
13589
  const x = tile.column * (width - 1), y = tile.row * (height - 1);
13566
13590
  if (![x, y, x + width - 1, y + height - 1].every(Number.isSafeInteger))
13567
13591
  throw new Error("Vertex tile lattice overflow");
@@ -13712,20 +13736,20 @@ function getTerrainVertexHaloAffectedTiles(resident, changed, options) {
13712
13736
  if (!Number.isSafeInteger(limit) || limit < 0 || resident.length > limit || changed.length > limit || !Number.isSafeInteger(options.width) || options.width < 2 || !Number.isSafeInteger(options.height) || options.height < 2)
13713
13737
  throw new Error("Invalid vertex halo tile capacity");
13714
13738
  const addresses = /* @__PURE__ */ new Map();
13715
- const key2 = (tile) => {
13739
+ const key3 = (tile) => {
13716
13740
  if (!Number.isSafeInteger(tile.column) || !Number.isSafeInteger(tile.row))
13717
13741
  throw new Error("Invalid vertex tile address");
13718
13742
  return `${tile.column},${tile.row}`;
13719
13743
  };
13720
13744
  for (const tile of resident) {
13721
- const id = key2(tile);
13745
+ const id = key3(tile);
13722
13746
  if (addresses.has(id))
13723
13747
  throw new Error("Duplicate resident vertex tile address");
13724
13748
  addresses.set(id, { column: tile.column, row: tile.row });
13725
13749
  }
13726
13750
  const affected = /* @__PURE__ */ new Map();
13727
13751
  for (const tile of changed) {
13728
- key2(tile);
13752
+ key3(tile);
13729
13753
  const rx = options.width === 2 ? 2 : 1, ry = options.height === 2 ? 2 : 1;
13730
13754
  for (let x = -rx; x <= rx; x++)
13731
13755
  for (let y = -ry; y <= ry; y++) {
@@ -13752,26 +13776,26 @@ function updateTerrainVertexTileHalos(previous, resident, changed, options) {
13752
13776
  const equalPair = (a, b) => a[0] === b[0] && a[1] === b[1];
13753
13777
  if (prior.width !== options.width || prior.height !== options.height || !equalPair(prior.origin ?? [0, 0], options.origin ?? [0, 0]) || !equalPair(prior.columnStep ?? [1, 0], options.columnStep ?? [1, 0]) || !equalPair(prior.rowStep ?? [0, 1], options.rowStep ?? [0, 1]) || (prior.heightReference ?? "unknown") !== (options.heightReference ?? "unknown") || (prior.maxHeightDifference ?? 0) !== (options.maxHeightDifference ?? 0))
13754
13778
  throw new Error("Vertex tile options changed; rebuild the full snapshot");
13755
- const key2 = (t) => `${t.column},${t.row}`;
13779
+ const key3 = (t) => `${t.column},${t.row}`;
13756
13780
  const affected = getTerrainVertexHaloAffectedTiles(resident, changed, options);
13757
13781
  getTerrainVertexHaloAffectedTiles(previous, [], options);
13758
- const previousMap = new Map(previous.map((tile) => [key2(tile), tile]));
13759
- const currentKeys = new Set(resident.map(key2));
13760
- const changedKeys = new Set(changed.map(key2));
13782
+ const previousMap = new Map(previous.map((tile) => [key3(tile), tile]));
13783
+ const currentKeys = new Set(resident.map(key3));
13784
+ const changedKeys = new Set(changed.map(key3));
13761
13785
  for (const tile of resident) {
13762
- if (!previousMap.has(key2(tile)) && !changedKeys.has(key2(tile)))
13786
+ if (!previousMap.has(key3(tile)) && !changedKeys.has(key3(tile)))
13763
13787
  throw new Error("Unreported vertex tile arrival");
13764
13788
  }
13765
13789
  const removed = [];
13766
13790
  for (const tile of previous) {
13767
- if (!currentKeys.has(key2(tile))) {
13768
- if (!changedKeys.has(key2(tile)))
13791
+ if (!currentKeys.has(key3(tile))) {
13792
+ if (!changedKeys.has(key3(tile)))
13769
13793
  throw new Error("Unreported vertex tile eviction");
13770
13794
  removed.push({ column: tile.column, row: tile.row });
13771
13795
  }
13772
13796
  }
13773
13797
  removed.sort((a, b) => a.column - b.column || a.row - b.row);
13774
- const affectedKeys = new Set(affected.map(key2));
13798
+ const affectedKeys = new Set(affected.map(key3));
13775
13799
  const rx = options.width === 2 ? 2 : 1;
13776
13800
  const ry = options.height === 2 ? 2 : 1;
13777
13801
  const needed = /* @__PURE__ */ new Set();
@@ -13782,12 +13806,12 @@ function updateTerrainVertexTileHalos(previous, resident, changed, options) {
13782
13806
  if (Number.isSafeInteger(column) && Number.isSafeInteger(row))
13783
13807
  needed.add(`${column},${row}`);
13784
13808
  }
13785
- const source = resident.filter((tile) => needed.has(key2(tile)));
13809
+ const source = resident.filter((tile) => needed.has(key3(tile)));
13786
13810
  const rebuilt = createTerrainVertexTileHalos(source, options).tiles;
13787
- const results = new Map(previous.filter((tile) => currentKeys.has(key2(tile)) && !affectedKeys.has(key2(tile))).map((tile) => [key2(tile), tile]));
13811
+ const results = new Map(previous.filter((tile) => currentKeys.has(key3(tile)) && !affectedKeys.has(key3(tile))).map((tile) => [key3(tile), tile]));
13788
13812
  for (const tile of rebuilt)
13789
- if (affectedKeys.has(key2(tile)))
13790
- results.set(key2(tile), tile);
13813
+ if (affectedKeys.has(key3(tile)))
13814
+ results.set(key3(tile), tile);
13791
13815
  if (results.size !== resident.length)
13792
13816
  throw new Error("Incomplete vertex halo update");
13793
13817
  return {
@@ -13898,9 +13922,9 @@ function stitchTerrainMeshEdges(a, edgeA, b, edgeB, options = {}) {
13898
13922
  let direction = 0;
13899
13923
  for (let i = 0; i < mesh.indices.length; i += 3)
13900
13924
  for (let j = 0; j < 3; j++) {
13901
- const u = mesh.indices[i + j], v = mesh.indices[i + (j + 1) % 3], key2 = pair(u, v);
13902
- if (pairs.has(key2)) {
13903
- pairs.set(key2, pairs.get(key2) + 1);
13925
+ const u = mesh.indices[i + j], v = mesh.indices[i + (j + 1) % 3], key3 = pair(u, v);
13926
+ if (pairs.has(key3)) {
13927
+ pairs.set(key3, pairs.get(key3) + 1);
13904
13928
  const nextDirection = Math.sign(mesh.gridCoordinates[2 * v + 1 - axis] - mesh.gridCoordinates[2 * u + 1 - axis]);
13905
13929
  if (direction && direction !== nextDirection)
13906
13930
  throw new Error("Inconsistent stitching boundary orientation");
@@ -14139,19 +14163,19 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
14139
14163
  throw new Error("Mixed contour frame overflow");
14140
14164
  const onEdge = x === 0 || y === 0 || x === tile.width - 1 || y === tile.height - 1;
14141
14165
  const xi = Math.floor(sx), yi = Math.floor(sy);
14142
- const key2 = `${level}/${tile.column + xi}/${sx - xi}/${tile.row + yi}/${sy - yi}`;
14166
+ const key3 = `${level}/${tile.column + xi}/${sx - xi}/${tile.row + yi}/${sy - yi}`;
14143
14167
  if (onEdge) {
14144
14168
  const rounded = `${level}/${gx}/${gy}`;
14145
14169
  const identity2 = roundedBoundary.get(rounded);
14146
- if (identity2 !== void 0 && identity2 !== key2)
14170
+ if (identity2 !== void 0 && identity2 !== key3)
14147
14171
  throw new Error("Mixed contour lattice loses precision");
14148
- roundedBoundary.set(rounded, key2);
14172
+ roundedBoundary.set(rounded, key3);
14149
14173
  }
14150
- if (onEdge && local.has(key2))
14174
+ if (onEdge && local.has(key3))
14151
14175
  throw new Error("Duplicate mixed contour boundary vertex");
14152
14176
  if (onEdge)
14153
- local.add(key2);
14154
- let id = onEdge ? shared2.get(key2) : void 0;
14177
+ local.add(key3);
14178
+ let id = onEdge ? shared2.get(key3) : void 0;
14155
14179
  if (id !== void 0) {
14156
14180
  if (Math.hypot(px - positions[3 * id], py - positions[3 * id + 1]) > tolerance)
14157
14181
  throw new Error("Mixed contour boundary positions disagree");
@@ -14163,7 +14187,7 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
14163
14187
  grid.push(gx, gy);
14164
14188
  vertexLevels.push(level);
14165
14189
  if (onEdge) {
14166
- shared2.set(key2, id);
14190
+ shared2.set(key3, id);
14167
14191
  boundary.add(id);
14168
14192
  }
14169
14193
  }
@@ -14175,10 +14199,10 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
14175
14199
  const level = data.levelIndices[i], a = vertex(data.segments[2 * i], level), b = vertex(data.segments[2 * i + 1], level);
14176
14200
  if (a === b || positions[3 * a] === positions[3 * b] && positions[3 * a + 1] === positions[3 * b + 1])
14177
14201
  throw new Error("Degenerate mixed contour segment");
14178
- const key2 = a < b ? `${a}/${b}` : `${b}/${a}`;
14179
- if (localEdges.has(key2))
14202
+ const key3 = a < b ? `${a}/${b}` : `${b}/${a}`;
14203
+ if (localEdges.has(key3))
14180
14204
  throw new Error("Duplicate mixed contour segment");
14181
- localEdges.add(key2);
14205
+ localEdges.add(key3);
14182
14206
  const box = bounds[ti];
14183
14207
  const seam = grid[2 * a] === grid[2 * b] && (grid[2 * a] === box[0] || grid[2 * a] === box[2]) || grid[2 * a + 1] === grid[2 * b + 1] && (grid[2 * a + 1] === box[1] || grid[2 * a + 1] === box[3]);
14184
14208
  edges.push({ a, b, level, tile: ti, seam });
@@ -14205,8 +14229,8 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
14205
14229
  }
14206
14230
  cuts.sort((u, v) => grid[2 * u + axis] - grid[2 * v + axis]);
14207
14231
  for (let i = 1; i < cuts.length; i++) {
14208
- const u = cuts[i - 1], v = cuts[i], key2 = u < v ? `${u}/${v}` : `${v}/${u}`;
14209
- const prior = emitted.get(key2);
14232
+ const u = cuts[i - 1], v = cuts[i], key3 = u < v ? `${u}/${v}` : `${v}/${u}`;
14233
+ const prior = emitted.get(key3);
14210
14234
  if (prior !== void 0) {
14211
14235
  if (prior === edge.tile)
14212
14236
  throw new Error("Overlapping mixed contour segments within tile");
@@ -14214,7 +14238,7 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
14214
14238
  }
14215
14239
  if (levels.length >= limits.maxSegments)
14216
14240
  throw new Error("Mixed contour output segment capacity exceeded");
14217
- emitted.set(key2, edge.tile);
14241
+ emitted.set(key3, edge.tile);
14218
14242
  segments.push(u, v);
14219
14243
  levels.push(level);
14220
14244
  }
@@ -14229,4 +14253,1314 @@ function weldTerrainMixedContourTiles(tiles, options = {}) {
14229
14253
  heightReference: first.heightReference
14230
14254
  };
14231
14255
  }
14256
+
14257
+ // dist/terrain/sample-triangle-height.js
14258
+ function sampleTerrainTriangleHeight(field, x, y) {
14259
+ if (Number.isInteger(x) && Number.isInteger(y))
14260
+ return field.getHeight(x, y);
14261
+ const column = Math.min(Math.floor(x), field.width - 2);
14262
+ const row = Math.min(Math.floor(y), field.height - 2);
14263
+ const u = x - column, v = y - row;
14264
+ let a, b, c, d;
14265
+ if (field.diagonal === "00-11") {
14266
+ if (v <= u) {
14267
+ a = 1 - u;
14268
+ b = u - v;
14269
+ c = 0;
14270
+ d = v;
14271
+ } else {
14272
+ a = 1 - v;
14273
+ b = 0;
14274
+ c = v - u;
14275
+ d = u;
14276
+ }
14277
+ } else if (u + v <= 1) {
14278
+ a = 1 - u - v;
14279
+ b = u;
14280
+ c = v;
14281
+ d = 0;
14282
+ } else {
14283
+ a = 0;
14284
+ b = 1 - v;
14285
+ c = 1 - u;
14286
+ d = u + v - 1;
14287
+ }
14288
+ const za = a ? field.getHeight(column, row) : 0;
14289
+ const zb = b ? field.getHeight(column + 1, row) : 0;
14290
+ const zc = c ? field.getHeight(column, row + 1) : 0;
14291
+ const zd = d ? field.getHeight(column + 1, row + 1) : 0;
14292
+ if (za === void 0 || zb === void 0 || zc === void 0 || zd === void 0)
14293
+ return void 0;
14294
+ const height = a * za + b * zb + c * zc + d * zd;
14295
+ if (!Number.isFinite(height))
14296
+ throw new Error("Terrain triangle numeric sampling failure");
14297
+ return height;
14298
+ }
14299
+
14300
+ // dist/terrain/mixed-vertex-halos.js
14301
+ function createTerrainMixedVertexTileHalos(tiles, options = {}) {
14302
+ return buildMixedVertexTileHalos(tiles, options);
14303
+ }
14304
+ function buildMixedVertexTileHalos(tiles, options = {}, targets) {
14305
+ const maxSamples = options.maxSamples ?? 4e6, maxTests = options.maxTileTests ?? 1e7;
14306
+ if (![maxSamples, maxTests].every((v) => Number.isSafeInteger(v) && v >= 0))
14307
+ throw new Error("Invalid mixed halo capacity");
14308
+ let count = 0;
14309
+ const addresses = /* @__PURE__ */ new Set();
14310
+ let frame2;
14311
+ const sources = [...tiles].sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row).map((tile) => {
14312
+ if (![tile.column, tile.row, tile.spacing].every(Number.isSafeInteger) || tile.spacing < 1 || 2 ** Math.round(Math.log2(tile.spacing)) !== tile.spacing)
14313
+ throw new Error("Invalid mixed halo lattice");
14314
+ const key3 = `${tile.spacing}/${tile.column}/${tile.row}`;
14315
+ if (addresses.has(key3))
14316
+ throw new Error("Duplicate mixed halo tile");
14317
+ addresses.add(key3);
14318
+ count += (tile.field.width + 2) * (tile.field.height + 2);
14319
+ if (!Number.isSafeInteger(count) || count > maxSamples)
14320
+ throw new Error("Mixed halo sample capacity exceeded");
14321
+ const field = new HeightField(tile.field);
14322
+ if (field.registration !== "vertex")
14323
+ throw new Error("Mixed halos require vertex registration");
14324
+ const column = field.columnStep.map((v) => v / tile.spacing);
14325
+ const row = field.rowStep.map((v) => v / tile.spacing);
14326
+ const origin = field.origin.map((v, axis) => v - tile.column * column[axis] - tile.row * row[axis]);
14327
+ 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])));
14328
+ if (!origin.every(Number.isFinite))
14329
+ throw new Error("Mixed halo coordinate overflow");
14330
+ 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]))))))
14331
+ throw new Error("Mixed halo frames or height references differ");
14332
+ frame2 ?? (frame2 = { origin, column, row, reference: field.heightReference, scale: scale3 });
14333
+ return { ...tile, source: field };
14334
+ });
14335
+ for (const axis of ["column", "row"]) {
14336
+ let min = Infinity, max = -Infinity;
14337
+ for (const tile of sources) {
14338
+ const size = axis === "column" ? tile.source.width : tile.source.height;
14339
+ const low = tile[axis] - tile.spacing, high = tile[axis] + size * tile.spacing;
14340
+ if (![low, high].every(Number.isSafeInteger))
14341
+ throw new Error("Mixed halo lattice overflow");
14342
+ min = Math.min(min, low);
14343
+ max = Math.max(max, high);
14344
+ }
14345
+ if (sources.length && !Number.isSafeInteger(max - min))
14346
+ throw new Error("Mixed halo lattice span overflow");
14347
+ }
14348
+ let tests = 0;
14349
+ return {
14350
+ tiles: sources.filter((tile) => !targets || targets.has(`${tile.spacing}/${tile.column}/${tile.row}`)).map((tile) => {
14351
+ const source = tile.source, width = source.width + 2, height = source.height + 2;
14352
+ const heights = new Float64Array(width * height), validity = new Uint8Array(heights.length), statuses = new Uint8Array(heights.length);
14353
+ for (let y = 0; y < height; y++)
14354
+ for (let x = 0; x < width; x++) {
14355
+ const gx = tile.column + (x - 1) * tile.spacing, gy = tile.row + (y - 1) * tile.spacing;
14356
+ if (![gx, gy].every(Number.isSafeInteger))
14357
+ throw new Error("Mixed halo lattice overflow");
14358
+ for (const candidate of sources) {
14359
+ if (++tests > maxTests)
14360
+ throw new Error("Mixed halo tile-test budget exceeded");
14361
+ const cx = (gx - candidate.column) / candidate.spacing, cy = (gy - candidate.row) / candidate.spacing;
14362
+ const f = candidate.source;
14363
+ if (cx < 0 || cy < 0 || cx > f.width - 1 || cy > f.height - 1)
14364
+ continue;
14365
+ const value3 = sampleTerrainTriangleHeight(f, cx, cy);
14366
+ const i = y * width + x;
14367
+ statuses[i] = value3 === void 0 ? 1 : 2;
14368
+ if (value3 !== void 0) {
14369
+ heights[i] = value3;
14370
+ validity[i] = 1;
14371
+ }
14372
+ break;
14373
+ }
14374
+ }
14375
+ const origin = [
14376
+ source.origin[0] - source.columnStep[0] - source.rowStep[0],
14377
+ source.origin[1] - source.columnStep[1] - source.rowStep[1]
14378
+ ];
14379
+ if (!origin.every(Number.isFinite))
14380
+ throw new Error("Mixed halo coordinate overflow");
14381
+ return {
14382
+ column: tile.column,
14383
+ row: tile.row,
14384
+ spacing: tile.spacing,
14385
+ statuses,
14386
+ field: {
14387
+ ...tile.field,
14388
+ width,
14389
+ height,
14390
+ heights,
14391
+ validity,
14392
+ offset: 0,
14393
+ stride: width,
14394
+ origin,
14395
+ columnStep: [...source.columnStep],
14396
+ rowStep: [...source.rowStep]
14397
+ }
14398
+ };
14399
+ })
14400
+ };
14401
+ }
14402
+
14403
+ // dist/terrain/mixed-halo-update.js
14404
+ var key2 = (t) => `${t.spacing}/${t.column}/${t.row}`;
14405
+ function updateTerrainMixedVertexTileHalos(previous, resident, options = {}) {
14406
+ const budget = options.maxDependencyTests ?? 1e7;
14407
+ if (!Number.isSafeInteger(budget) || budget < 0)
14408
+ throw new Error("Invalid mixed halo dependency budget");
14409
+ const old = new Map(previous == null ? void 0 : previous.sources.map((t) => [key2(t), t]));
14410
+ const current = new Map(resident.map((t) => [key2(t), t]));
14411
+ const changed = [...old.values()].filter((t) => current.get(key2(t)) !== t).concat(resident.filter((t) => old.get(key2(t)) !== t));
14412
+ const cached = new Map(previous == null ? void 0 : previous.tiles.map((t) => [key2(t), t]));
14413
+ const targets = /* @__PURE__ */ new Set();
14414
+ let tests = 0;
14415
+ for (const tile of resident) {
14416
+ if (!cached.has(key2(tile)))
14417
+ targets.add(key2(tile));
14418
+ for (const source of changed) {
14419
+ if (++tests > budget)
14420
+ throw new Error("Mixed halo dependency budget exceeded");
14421
+ if (tile.column - tile.spacing <= source.column + (source.field.width - 1) * source.spacing && tile.column + tile.field.width * tile.spacing >= source.column && tile.row - tile.spacing <= source.row + (source.field.height - 1) * source.spacing && tile.row + tile.field.height * tile.spacing >= source.row)
14422
+ targets.add(key2(tile));
14423
+ }
14424
+ }
14425
+ const built = buildMixedVertexTileHalos(resident, options, targets).tiles;
14426
+ for (const tile of built)
14427
+ cached.set(key2(tile), tile);
14428
+ const tiles = resident.map((t) => cached.get(key2(t))).sort((a, b) => a.spacing - b.spacing || a.column - b.column || a.row - b.row);
14429
+ return {
14430
+ sources: resident.slice(),
14431
+ tiles,
14432
+ rebuilt: built.map(key2),
14433
+ removed: [...old.keys()].filter((k) => !current.has(k)).sort()
14434
+ };
14435
+ }
14436
+
14437
+ // dist/terrain/mixed-gradient-update.js
14438
+ function updateTerrainMixedGradientGrids(previous, halos, options = {}) {
14439
+ const method = options.method ?? "horn";
14440
+ if (method !== "horn" && method !== "zevenbergen-thorne")
14441
+ throw new Error("Unknown terrain gradient method");
14442
+ const limit = options.maxSamples ?? 4e6;
14443
+ const count = halos.tiles.reduce((n, t) => n + t.field.width * t.field.height, 0);
14444
+ if (!Number.isSafeInteger(limit) || limit < 0 || !Number.isSafeInteger(count) || count > limit)
14445
+ throw new Error("Mixed gradient sample capacity exceeded");
14446
+ const cache = new Map((previous == null ? void 0 : previous.method) === method ? previous.tiles.map((t) => [t.halo, t]) : []);
14447
+ return {
14448
+ method,
14449
+ tiles: halos.tiles.map((halo) => cache.get(halo) ?? {
14450
+ halo,
14451
+ grid: createTerrainGradientGrid(new HeightField(halo.field), { method, maxSamples: limit })
14452
+ })
14453
+ };
14454
+ }
14455
+
14456
+ // dist/terrain/box-index.js
14457
+ var overlaps = (a, b) => a.minX <= b.maxX && b.minX <= a.maxX && a.minY <= b.maxY && b.minY <= a.maxY;
14458
+ function createTerrainBoxIndex(boxes) {
14459
+ const build = (ids) => {
14460
+ const box = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
14461
+ for (const id of ids) {
14462
+ const b = boxes[id];
14463
+ box.minX = Math.min(box.minX, b.minX);
14464
+ box.minY = Math.min(box.minY, b.minY);
14465
+ box.maxX = Math.max(box.maxX, b.maxX);
14466
+ box.maxY = Math.max(box.maxY, b.maxY);
14467
+ }
14468
+ if (ids.length <= 8)
14469
+ return { ...box, ids };
14470
+ const axis = box.maxX - box.minX >= box.maxY - box.minY ? "X" : "Y";
14471
+ ids.sort((a, b) => boxes[a][`min${axis}`] / 2 + boxes[a][`max${axis}`] / 2 - (boxes[b][`min${axis}`] / 2 + boxes[b][`max${axis}`] / 2) || a - b);
14472
+ const mid = ids.length >>> 1;
14473
+ return { ...box, left: build(ids.slice(0, mid)), right: build(ids.slice(mid)) };
14474
+ };
14475
+ const root2 = build(boxes.map((_, i) => i));
14476
+ return (query, charge) => {
14477
+ const found = [], stack = [root2];
14478
+ while (stack.length) {
14479
+ charge();
14480
+ const node = stack.pop();
14481
+ if (!overlaps(node, query))
14482
+ continue;
14483
+ if (node.ids) {
14484
+ for (const id of node.ids) {
14485
+ charge();
14486
+ if (overlaps(boxes[id], query))
14487
+ found.push(id);
14488
+ }
14489
+ } else
14490
+ stack.push(node.right, node.left);
14491
+ }
14492
+ return found.sort((a, b) => a - b);
14493
+ };
14494
+ }
14495
+
14496
+ // dist/terrain/contour-topology.js
14497
+ var bits = new DataView(new ArrayBuffer(8));
14498
+ function integer(x) {
14499
+ bits.setFloat64(0, x);
14500
+ const high = bits.getUint32(0), low = bits.getUint32(4);
14501
+ const exponent = high >>> 20 & 2047;
14502
+ const mantissa = BigInt(high & 1048575) << 32n | BigInt(low);
14503
+ const value3 = exponent ? (1n << 52n | mantissa) << BigInt(exponent - 1) : mantissa;
14504
+ return high >>> 31 ? -value3 : value3;
14505
+ }
14506
+ var orientation2 = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
14507
+ var sign = (v) => v < 0n ? -1 : v > 0n ? 1 : 0;
14508
+ var between = (a, b, p) => p >= (a < b ? a : b) && p <= (a > b ? a : b);
14509
+ var on = (a, b, p) => orientation2(a, b, p) === 0n && between(a.x, b.x, p.x) && between(a.y, b.y, p.y);
14510
+ function intersects(a, b, c, d) {
14511
+ return on(a, b, c) || on(a, b, d) || on(c, d, a) || on(c, d, b) || sign(orientation2(a, b, c)) * sign(orientation2(a, b, d)) < 0 && sign(orientation2(c, d, a)) * sign(orientation2(c, d, b)) < 0;
14512
+ }
14513
+ function simplifyTerrainContourPathsTopology(paths, options) {
14514
+ if (options.rejection !== void 0 && options.rejection !== "batch" && options.rejection !== "path")
14515
+ throw new Error("Invalid contour rejection policy");
14516
+ const candidate = simplifyTerrainContourPaths(paths, options);
14517
+ const budget = options.maxTopologyTests ?? 1e6;
14518
+ if (!Number.isSafeInteger(budget) || budget < 0)
14519
+ throw new Error("Invalid contour topology budget");
14520
+ let topologyTests = 0;
14521
+ const charge = () => {
14522
+ if (++topologyTests > budget)
14523
+ throw new Error("Contour topology work budget exceeded");
14524
+ };
14525
+ const points = new Array(paths.positions.length / 3);
14526
+ for (const i of new Set(paths.indices))
14527
+ points[i] = { x: integer(paths.positions[3 * i]), y: integer(paths.positions[3 * i + 1]) };
14528
+ const edges = [];
14529
+ for (let p = 0; p < paths.closed.length; p++)
14530
+ for (let i = paths.offsets[p]; i + 1 < paths.offsets[p + 1]; i++)
14531
+ edges.push({ a: paths.indices[i], b: paths.indices[i + 1], p, i });
14532
+ const box = (a, b) => ({
14533
+ minX: Math.min(paths.positions[3 * a], paths.positions[3 * b]),
14534
+ maxX: Math.max(paths.positions[3 * a], paths.positions[3 * b]),
14535
+ minY: Math.min(paths.positions[3 * a + 1], paths.positions[3 * b + 1]),
14536
+ maxY: Math.max(paths.positions[3 * a + 1], paths.positions[3 * b + 1])
14537
+ });
14538
+ const edgeBoxes = edges.map((e) => box(e.a, e.b)), edgeIndex = createTerrainBoxIndex(edgeBoxes);
14539
+ const vertexIds = [...new Set(paths.indices)], vertexIndex = createTerrainBoxIndex(vertexIds.map((v) => box(v, v)));
14540
+ for (let i = 0; i < edges.length; i++)
14541
+ for (const j of edgeIndex(edgeBoxes[i], charge)) {
14542
+ if (j <= i)
14543
+ continue;
14544
+ charge();
14545
+ const a = edges[i], b = edges[j];
14546
+ const common = [a.a, a.b].filter((v) => v === b.a || v === b.b);
14547
+ if (common.length === 1) {
14548
+ const v = common[0], x = a.a === v ? a.b : a.a, y = b.a === v ? b.b : b.a;
14549
+ if (on(points[v], points[x], points[y]) || on(points[v], points[y], points[x]))
14550
+ throw new Error("Overlapping contour edges");
14551
+ } else if (intersects(points[a.a], points[a.b], points[b.a], points[b.b]))
14552
+ throw new Error("Contour input has crossings or unshared touches");
14553
+ }
14554
+ let rejected = false;
14555
+ const rejectedPaths = /* @__PURE__ */ new Set();
14556
+ for (let p = 0; p < paths.closed.length; p++) {
14557
+ let start = paths.offsets[p];
14558
+ for (let k = candidate.offsets[p] + 1; k < candidate.offsets[p + 1]; k++) {
14559
+ const endId = candidate.sourceVertexIndices[candidate.indices[k]];
14560
+ let end = start + 1;
14561
+ while (paths.indices[end] !== endId)
14562
+ end++;
14563
+ if (end > start + 1) {
14564
+ const a = paths.indices[start], b = paths.indices[end];
14565
+ const pa = points[a], pb = points[b];
14566
+ const axis = pa.x !== pb.x ? "x" : "y";
14567
+ const direction = sign(pb[axis] - pa[axis]);
14568
+ let straight2 = true;
14569
+ for (let i = start + 1; i <= end; i++) {
14570
+ charge();
14571
+ const q = points[paths.indices[i]], prior = points[paths.indices[i - 1]];
14572
+ if (!on(pa, pb, q) || sign(q[axis] - prior[axis]) !== direction)
14573
+ straight2 = false;
14574
+ }
14575
+ const interior2 = new Set(Array.from(paths.indices.subarray(start + 1, end)));
14576
+ let unsafe = false;
14577
+ for (const edgeId of edgeIndex(box(a, b), charge)) {
14578
+ const edge = edges[edgeId];
14579
+ if (edge.p === p && edge.i >= start && edge.i < end) {
14580
+ if (straight2)
14581
+ continue;
14582
+ charge();
14583
+ const others2 = [edge.a, edge.b].filter((v) => v !== a && v !== b);
14584
+ if (others2.some((v) => on(points[a], points[b], points[v])) || others2.length === 2 && intersects(points[a], points[b], points[edge.a], points[edge.b]))
14585
+ unsafe = true;
14586
+ continue;
14587
+ }
14588
+ charge();
14589
+ const others = [edge.a, edge.b].filter((v) => v !== a && v !== b);
14590
+ if (others.some((v) => on(points[a], points[b], points[v])) || others.length === 2 && intersects(points[a], points[b], points[edge.a], points[edge.b]))
14591
+ unsafe = true;
14592
+ }
14593
+ const swept = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
14594
+ for (let i = start; i <= end; i++) {
14595
+ const v = paths.indices[i];
14596
+ swept.minX = Math.min(swept.minX, paths.positions[3 * v]);
14597
+ swept.maxX = Math.max(swept.maxX, paths.positions[3 * v]);
14598
+ swept.minY = Math.min(swept.minY, paths.positions[3 * v + 1]);
14599
+ swept.maxY = Math.max(swept.maxY, paths.positions[3 * v + 1]);
14600
+ }
14601
+ for (const vertexId of vertexIndex(swept, charge)) {
14602
+ const vertex = vertexIds[vertexId];
14603
+ if (vertex === a || vertex === b || interior2.has(vertex))
14604
+ continue;
14605
+ let inside = false;
14606
+ for (let i = start, j = end; i <= end; j = i++) {
14607
+ charge();
14608
+ const u = points[paths.indices[i]], v = points[paths.indices[j]], q = points[vertex];
14609
+ if (on(u, v, q)) {
14610
+ unsafe = true;
14611
+ break;
14612
+ }
14613
+ if (u.y > q.y !== v.y > q.y && orientation2(u, v, q) > 0n === v.y > u.y)
14614
+ inside = !inside;
14615
+ }
14616
+ if (inside)
14617
+ unsafe = true;
14618
+ }
14619
+ if (unsafe) {
14620
+ rejected = true;
14621
+ rejectedPaths.add(p);
14622
+ }
14623
+ }
14624
+ start = end;
14625
+ }
14626
+ }
14627
+ const outputEdges = [];
14628
+ for (let p = 0; p < candidate.closed.length; p++)
14629
+ for (let i = candidate.offsets[p]; i + 1 < candidate.offsets[p + 1]; i++)
14630
+ outputEdges.push({
14631
+ p,
14632
+ a: candidate.sourceVertexIndices[candidate.indices[i]],
14633
+ b: candidate.sourceVertexIndices[candidate.indices[i + 1]]
14634
+ });
14635
+ const outputBoxes = outputEdges.map((e) => box(e.a, e.b)), outputIndex = createTerrainBoxIndex(outputBoxes);
14636
+ for (let i = 0; i < outputEdges.length; i++)
14637
+ for (const j of outputIndex(outputBoxes[i], charge)) {
14638
+ if (j <= i)
14639
+ continue;
14640
+ charge();
14641
+ const a = outputEdges[i], b = outputEdges[j];
14642
+ const common = [a.a, a.b].filter((v) => v === b.a || v === b.b);
14643
+ if (common.length === 1) {
14644
+ const v = common[0], x = a.a === v ? a.b : a.a, y = b.a === v ? b.b : b.a;
14645
+ if (on(points[v], points[x], points[y]) || on(points[v], points[y], points[x])) {
14646
+ rejected = true;
14647
+ rejectedPaths.add(a.p);
14648
+ rejectedPaths.add(b.p);
14649
+ }
14650
+ } else if (intersects(points[a.a], points[a.b], points[b.a], points[b.b])) {
14651
+ rejected = true;
14652
+ rejectedPaths.add(a.p);
14653
+ rejectedPaths.add(b.p);
14654
+ }
14655
+ }
14656
+ if (rejected && options.rejection === "path") {
14657
+ const indices = [], offsets = [0];
14658
+ for (let p = 0; p < paths.closed.length; p++) {
14659
+ if (rejectedPaths.has(p))
14660
+ for (let i = paths.offsets[p]; i < paths.offsets[p + 1]; i++)
14661
+ indices.push(paths.indices[i]);
14662
+ else
14663
+ for (let i = candidate.offsets[p]; i < candidate.offsets[p + 1]; i++)
14664
+ indices.push(candidate.sourceVertexIndices[candidate.indices[i]]);
14665
+ offsets.push(indices.length);
14666
+ }
14667
+ return {
14668
+ ...paths,
14669
+ positions: paths.positions.slice(),
14670
+ gridCoordinates: paths.gridCoordinates.slice(),
14671
+ indices: Uint32Array.from(indices),
14672
+ offsets: Uint32Array.from(offsets),
14673
+ closed: paths.closed.slice(),
14674
+ levelIndices: paths.levelIndices.slice(),
14675
+ levels: paths.levels.slice(),
14676
+ origin: Object.freeze([...paths.origin]),
14677
+ sourceVertexIndices: Uint32Array.from({ length: points.length }, (_, i) => i),
14678
+ maxDeviation: candidate.maxDeviation,
14679
+ requestedMaxError: options.maxError,
14680
+ distanceTests: candidate.distanceTests,
14681
+ topologyTests,
14682
+ rejected: true
14683
+ };
14684
+ }
14685
+ if (!rejected)
14686
+ return { ...candidate, topologyTests, rejected: false };
14687
+ return {
14688
+ ...paths,
14689
+ positions: paths.positions.slice(),
14690
+ gridCoordinates: paths.gridCoordinates.slice(),
14691
+ indices: paths.indices.slice(),
14692
+ offsets: paths.offsets.slice(),
14693
+ levelIndices: paths.levelIndices.slice(),
14694
+ closed: paths.closed.slice(),
14695
+ levels: paths.levels.slice(),
14696
+ origin: Object.freeze([...paths.origin]),
14697
+ sourceVertexIndices: Uint32Array.from({ length: points.length }, (_, i) => i),
14698
+ maxDeviation: 0,
14699
+ requestedMaxError: options.maxError,
14700
+ distanceTests: candidate.distanceTests,
14701
+ topologyTests,
14702
+ rejected: true
14703
+ };
14704
+ }
14705
+
14706
+ // dist/terrain/isobands.js
14707
+ function createTerrainIsobands(fields, levels, options = {}) {
14708
+ const maxLevels = options.maxLevels ?? 256;
14709
+ if (!Number.isSafeInteger(maxLevels) || maxLevels < 2 || levels.length > maxLevels)
14710
+ throw new Error("Isoband level capacity exceeded");
14711
+ if (levels.length < 2 || levels.some((v, i) => !Number.isFinite(v) || i > 0 && v <= levels[i - 1]))
14712
+ throw new Error("Invalid isoband levels");
14713
+ const maxTriangles = options.maxTriangles ?? 2e6, maxVertices = options.maxVertices ?? 2e6, maxEdges = options.maxEdges ?? 6 * maxTriangles, maxTests = options.maxTests ?? 32 * maxTriangles;
14714
+ if (![maxTriangles, maxVertices, maxEdges, maxTests].every((n) => Number.isSafeInteger(n) && n >= 0))
14715
+ throw new Error("Invalid isoband capacity");
14716
+ const count = fields.reduce((n, f) => n + 2 * (f.width - 1) * (f.height - 1), 0);
14717
+ if (!Number.isSafeInteger(count) || count > maxTriangles)
14718
+ throw new Error("Isoband triangle capacity exceeded");
14719
+ const originals = /* @__PURE__ */ new Map(), vertices = /* @__PURE__ */ new Map();
14720
+ const frame2 = fields[0];
14721
+ for (const f of fields)
14722
+ if (f.heightReference !== frame2.heightReference)
14723
+ throw new Error("Isoband height references differ");
14724
+ let tests = 0, edgeCount = 0;
14725
+ const charge = () => {
14726
+ if (++tests > maxTests)
14727
+ throw new Error("Isoband work budget exceeded");
14728
+ };
14729
+ const rectangles = fields.map((f) => {
14730
+ if (f.registration !== frame2.registration || f.columnStep.some((v, i) => v !== frame2.columnStep[i]) || f.rowStep.some((v, i) => v !== frame2.rowStep[i]))
14731
+ throw new Error("Isoband tiles require a conforming common frame");
14732
+ const dx = f.origin[0] - frame2.origin[0], dy = f.origin[1] - frame2.origin[1];
14733
+ const determinant = frame2.columnStep[0] * frame2.rowStep[1] - frame2.columnStep[1] * frame2.rowStep[0];
14734
+ const x = Math.round((dx * frame2.rowStep[1] - dy * frame2.rowStep[0]) / determinant), y = Math.round((dy * frame2.columnStep[0] - dx * frame2.columnStep[1]) / determinant);
14735
+ if (!Number.isSafeInteger(x) || !Number.isSafeInteger(y))
14736
+ throw new Error("Isoband tiles require integral lattice origins");
14737
+ for (let axis = 0; axis < 2; axis++) {
14738
+ const a = x * frame2.columnStep[axis], b = y * frame2.rowStep[axis];
14739
+ const expected = frame2.origin[axis] + a + b;
14740
+ const tolerance = Math.min(16 * Number.EPSILON * Math.max(1, Math.abs(f.origin[axis]), Math.abs(frame2.origin[axis]), Math.abs(a), Math.abs(b)), 1e-9 * Math.max(Math.abs(frame2.columnStep[axis]), Math.abs(frame2.rowStep[axis])));
14741
+ if (!Number.isFinite(expected) || Math.abs(f.origin[axis] - expected) > tolerance)
14742
+ throw new Error("Isoband tiles require integral lattice origins");
14743
+ }
14744
+ return { x, y, right: x + f.width - 1, top: y + f.height - 1 };
14745
+ });
14746
+ const rectangleBoxes = rectangles.map((r) => ({ minX: r.x, minY: r.y, maxX: r.right, maxY: r.top })), rectangleIndex = createTerrainBoxIndex(rectangleBoxes);
14747
+ const rangeIndex = createTerrainBoxIndex(fields.map((f) => {
14748
+ var _a, _b;
14749
+ return {
14750
+ minX: ((_a = f.heightRange) == null ? void 0 : _a[0]) ?? Infinity,
14751
+ maxX: ((_b = f.heightRange) == null ? void 0 : _b[1]) ?? -Infinity,
14752
+ minY: 0,
14753
+ maxY: 0
14754
+ };
14755
+ }));
14756
+ for (let i = 0; i < rectangles.length; i++)
14757
+ for (const j of rectangleIndex(rectangleBoxes[i], charge)) {
14758
+ if (j <= i)
14759
+ continue;
14760
+ charge();
14761
+ const a = rectangles[i], b = rectangles[j];
14762
+ if (a.x < b.right && b.x < a.right && a.y < b.top && b.y < a.top)
14763
+ throw new Error("Overlapping isoband tiles");
14764
+ for (let y = Math.max(a.y, b.y); y <= Math.min(a.top, b.top); y++)
14765
+ for (let x = Math.max(a.x, b.x); x <= Math.min(a.right, b.right); x++) {
14766
+ charge();
14767
+ const u = fields[i].getHeight(x - a.x, y - a.y), v = fields[j].getHeight(x - b.x, y - b.y);
14768
+ if (u !== void 0 && v !== void 0 && u !== v)
14769
+ throw new Error("Isoband shared heights differ");
14770
+ }
14771
+ }
14772
+ const rings = [], bands = [];
14773
+ const register = (v) => {
14774
+ if (!vertices.has(v.key)) {
14775
+ if (vertices.size >= maxVertices)
14776
+ throw new Error("Isoband vertex capacity exceeded");
14777
+ vertices.set(v.key, v);
14778
+ }
14779
+ return vertices.get(v.key);
14780
+ };
14781
+ const clip = (poly, level, above) => {
14782
+ const out = [];
14783
+ for (let i = 0; i < poly.length; i++) {
14784
+ charge();
14785
+ const a = poly[i], b = poly[(i + 1) % poly.length], ia = above ? a.z >= level : a.z <= level, ib = above ? b.z >= level : b.z <= level;
14786
+ if (ia)
14787
+ out.push(a);
14788
+ if (ia !== ib) {
14789
+ if (a.z === level) {
14790
+ out.push(a);
14791
+ continue;
14792
+ }
14793
+ if (b.z === level) {
14794
+ out.push(b);
14795
+ continue;
14796
+ }
14797
+ const support = [.../* @__PURE__ */ new Set([...a.support, ...b.support])].sort();
14798
+ if (support.length !== 2)
14799
+ throw new Error("Invalid isoband intersection support");
14800
+ const u = originals.get(support[0]), v = originals.get(support[1]);
14801
+ const scale3 = Math.max(Math.abs(u.z), Math.abs(v.z), Math.abs(level), 1);
14802
+ const t = (level / scale3 - u.z / scale3) / (v.z / scale3 - u.z / scale3);
14803
+ const point2 = {
14804
+ x: u.x * (1 - t) + v.x * t,
14805
+ y: u.y * (1 - t) + v.y * t,
14806
+ z: level,
14807
+ key: `e:${support.join("|")}:${level}`,
14808
+ support
14809
+ };
14810
+ if (![point2.x, point2.y, t].every(Number.isFinite))
14811
+ throw new Error("Isoband arithmetic overflow");
14812
+ out.push(register(point2));
14813
+ }
14814
+ }
14815
+ return out.filter((v, i) => v.key !== out[(i + 1) % out.length].key);
14816
+ };
14817
+ for (let band = 0; band + 1 < levels.length; band++) {
14818
+ const edges = /* @__PURE__ */ new Map();
14819
+ for (const fieldId of rangeIndex({ minX: levels[band], maxX: levels[band + 1], minY: 0, maxY: 0 }, charge))
14820
+ for (let y = 0; y < fields[fieldId].height - 1; y++)
14821
+ for (let x = 0; x < fields[fieldId].width - 1; x++) {
14822
+ const f = fields[fieldId];
14823
+ const nodes = [
14824
+ [x, y],
14825
+ [x + 1, y],
14826
+ [x, y + 1],
14827
+ [x + 1, y + 1]
14828
+ ].map(([c, r]) => {
14829
+ const z = f.getHeight(c, r);
14830
+ if (z === void 0)
14831
+ return void 0;
14832
+ const shift2 = f.registration === "cell" ? 0.5 : 0;
14833
+ const px = frame2.origin[0] + (rectangles[fieldId].x + c + shift2) * frame2.columnStep[0] + (rectangles[fieldId].y + r + shift2) * frame2.rowStep[0], py = frame2.origin[1] + (rectangles[fieldId].x + c + shift2) * frame2.columnStep[1] + (rectangles[fieldId].y + r + shift2) * frame2.rowStep[1];
14834
+ if (![px, py].every(Number.isFinite))
14835
+ throw new Error("Isoband coordinate overflow");
14836
+ const key3 = `v:${px},${py}`, v = { x: px, y: py, z, key: key3, support: [key3] };
14837
+ const old = originals.get(key3);
14838
+ if (old && old.z !== z)
14839
+ throw new Error("Isoband shared heights differ");
14840
+ originals.set(key3, v);
14841
+ return v;
14842
+ });
14843
+ for (const ids of f.diagonal === "00-11" ? [
14844
+ [0, 1, 3],
14845
+ [0, 3, 2]
14846
+ ] : [
14847
+ [0, 1, 2],
14848
+ [1, 3, 2]
14849
+ ]) {
14850
+ charge();
14851
+ if (ids.some((i) => !nodes[i]))
14852
+ continue;
14853
+ let poly = ids.map((i) => nodes[i]);
14854
+ if (poly.every((v) => v.z === levels[band + 1]) && band + 2 < levels.length)
14855
+ continue;
14856
+ if ((poly[1].x - poly[0].x) * (poly[2].y - poly[0].y) - (poly[1].y - poly[0].y) * (poly[2].x - poly[0].x) < 0)
14857
+ poly.reverse();
14858
+ poly = clip(clip(poly, levels[band], true), levels[band + 1], false);
14859
+ if (poly.length < 3)
14860
+ continue;
14861
+ const area2 = poly.reduce((n, a, i) => {
14862
+ const b = poly[(i + 1) % poly.length], o = poly[0];
14863
+ return n + (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y);
14864
+ }, 0);
14865
+ if (!Number.isFinite(area2))
14866
+ throw new Error("Isoband area arithmetic overflow");
14867
+ if (area2 === 0)
14868
+ continue;
14869
+ for (let i = 0; i < poly.length; i++) {
14870
+ const a = register(poly[i]), b = register(poly[(i + 1) % poly.length]);
14871
+ if (++edgeCount > maxEdges)
14872
+ throw new Error("Isoband edge capacity exceeded");
14873
+ const key3 = `${a.key}>${b.key}`, reverse2 = `${b.key}>${a.key}`;
14874
+ if (edges.has(reverse2))
14875
+ edges.delete(reverse2);
14876
+ else {
14877
+ if (edges.has(key3))
14878
+ throw new Error("Overlapping isoband tiles");
14879
+ edges.set(key3, { a, b });
14880
+ }
14881
+ }
14882
+ }
14883
+ }
14884
+ const outgoing = /* @__PURE__ */ new Map();
14885
+ for (const [key3, e] of edges) {
14886
+ if (!outgoing.has(e.a.key))
14887
+ outgoing.set(e.a.key, /* @__PURE__ */ new Set());
14888
+ outgoing.get(e.a.key).add(key3);
14889
+ }
14890
+ while (edges.size) {
14891
+ const first = edges.values().next().value, ring = [];
14892
+ let edge = first;
14893
+ for (; ; ) {
14894
+ charge();
14895
+ ring.push(edge.a);
14896
+ edges.delete(`${edge.a.key}>${edge.b.key}`);
14897
+ outgoing.get(edge.a.key).delete(`${edge.a.key}>${edge.b.key}`);
14898
+ if (edge.b.key === first.a.key)
14899
+ break;
14900
+ const choices = [...outgoing.get(edge.b.key) ?? []].map((k) => edges.get(k));
14901
+ if (!choices.length)
14902
+ throw new Error("Open isoband boundary");
14903
+ const angle3 = (e) => Math.atan2((edge.b.x - edge.a.x) * (e.b.y - e.a.y) - (edge.b.y - edge.a.y) * (e.b.x - e.a.x), (edge.b.x - edge.a.x) * (e.b.x - e.a.x) + (edge.b.y - edge.a.y) * (e.b.y - e.a.y));
14904
+ choices.sort((a, b) => angle3(b) - angle3(a) || a.b.key.localeCompare(b.b.key));
14905
+ edge = choices[0];
14906
+ }
14907
+ rings.push(ring);
14908
+ bands.push(band);
14909
+ }
14910
+ }
14911
+ const area = (ring) => ring.reduce((n, a, i) => {
14912
+ const b = ring[(i + 1) % ring.length], o = ring[0];
14913
+ return n + (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y);
14914
+ }, 0);
14915
+ const areas = rings.map(area), parents = new Int32Array(rings.length).fill(-1);
14916
+ const ringBoxes = rings.map((r) => r.reduce((b, v) => ({
14917
+ minX: Math.min(b.minX, v.x),
14918
+ minY: Math.min(b.minY, v.y),
14919
+ maxX: Math.max(b.maxX, v.x),
14920
+ maxY: Math.max(b.maxY, v.y)
14921
+ }), { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity }));
14922
+ const ringIndex = createTerrainBoxIndex(ringBoxes);
14923
+ for (let i = 0; i < rings.length; i++)
14924
+ if (areas[i] < 0) {
14925
+ let best = Infinity;
14926
+ const q = rings[i][0];
14927
+ for (const j of ringIndex({ minX: q.x, maxX: q.x, minY: q.y, maxY: q.y }, charge))
14928
+ if (bands[j] === bands[i] && areas[j] > 0) {
14929
+ let inside = false;
14930
+ const ring = rings[j];
14931
+ for (let k = 0, l = ring.length - 1; k < ring.length; l = k++) {
14932
+ charge();
14933
+ const a = ring[k], b = ring[l];
14934
+ if (a.y > q.y !== b.y > q.y && q.x < (b.x - a.x) * (q.y - a.y) / (b.y - a.y) + a.x)
14935
+ inside = !inside;
14936
+ }
14937
+ if (inside && areas[j] < best) {
14938
+ parents[i] = j;
14939
+ best = areas[j];
14940
+ }
14941
+ }
14942
+ if (parents[i] < 0)
14943
+ throw new Error("Uncontained isoband hole");
14944
+ }
14945
+ const used = /* @__PURE__ */ new Map(), positions = [], indices = [], offsets = [0];
14946
+ for (const ring of rings) {
14947
+ for (const v of [...ring, ring[0]]) {
14948
+ if (!used.has(v.key)) {
14949
+ used.set(v.key, used.size);
14950
+ positions.push(v.x, v.y);
14951
+ }
14952
+ indices.push(used.get(v.key));
14953
+ }
14954
+ offsets.push(indices.length);
14955
+ }
14956
+ return {
14957
+ positions: Float64Array.from(positions),
14958
+ indices: Uint32Array.from(indices),
14959
+ offsets: Uint32Array.from(offsets),
14960
+ bandIndices: Uint32Array.from(bands),
14961
+ parents,
14962
+ levels: Float64Array.from(levels),
14963
+ heightReference: (frame2 == null ? void 0 : frame2.heightReference) ?? "unknown"
14964
+ };
14965
+ }
14966
+
14967
+ // dist/terrain/tile-update-data.js
14968
+ function updateTerrainTileData(previous, resident, create, maxSamples = 4e6) {
14969
+ if (!Number.isSafeInteger(maxSamples) || maxSamples < 0)
14970
+ throw new Error("Invalid terrain update sample capacity");
14971
+ let count = 0;
14972
+ const ids = /* @__PURE__ */ new Set();
14973
+ for (const tile of resident) {
14974
+ if (typeof tile.id !== "string" || ids.has(tile.id))
14975
+ throw new Error("Invalid or duplicate terrain update tile");
14976
+ ids.add(tile.id);
14977
+ count += tile.field.width * tile.field.height;
14978
+ if (!Number.isSafeInteger(count) || count > maxSamples)
14979
+ throw new Error("Terrain update sample capacity exceeded");
14980
+ }
14981
+ const cached = new Map(previous == null ? void 0 : previous.map((t) => [t.source.id, t]));
14982
+ return resident.map((source) => {
14983
+ const old = cached.get(source.id);
14984
+ return (old == null ? void 0 : old.source.field) === source.field ? { source, data: old.data } : { source, data: create(source.field) };
14985
+ });
14986
+ }
14987
+
14988
+ // dist/terrain/mesh-update.js
14989
+ function updateTerrainMeshes(previous, resident, options = {}) {
14990
+ return updateTerrainTileData(previous, resident, createTerrainMesh, options.maxSamples);
14991
+ }
14992
+
14993
+ // dist/terrain/bounds-update.js
14994
+ function updateTerrainBounds(previous, resident, options = {}) {
14995
+ return updateTerrainTileData(previous, resident, (f) => new HeightFieldMinMax(f), options.maxSamples);
14996
+ }
14997
+
14998
+ // dist/terrain/gradient-pyramid-update.js
14999
+ function updateTerrainGradientPyramids(previous, gradients, options = {}) {
15000
+ const limit = options.maxSamples ?? 4e6;
15001
+ const count = gradients.tiles.reduce((n, t) => n + t.grid.width * t.grid.height, 0);
15002
+ if (!Number.isSafeInteger(limit) || limit < 0 || !Number.isSafeInteger(count) || count > limit)
15003
+ throw new Error("Gradient pyramid update sample capacity exceeded");
15004
+ const cached = new Map(previous == null ? void 0 : previous.map((t) => [t.source.grid, t.data]));
15005
+ return gradients.tiles.map((source) => ({
15006
+ source,
15007
+ data: cached.get(source.grid) ?? createTerrainGradientPyramid(source.grid, { maxSamples: limit })
15008
+ }));
15009
+ }
15010
+
15011
+ // dist/terrain/dirty-regions.js
15012
+ function validateTerrainDirtyWindows(windows, width, height, maxWindows = 1e5) {
15013
+ if (windows.length > maxWindows)
15014
+ throw new Error("Terrain dirty window capacity exceeded");
15015
+ for (const w of windows)
15016
+ if (![w.minColumn, w.minRow, w.maxColumn, w.maxRow].every(Number.isSafeInteger) || w.minColumn < 0 || w.minRow < 0 || w.maxColumn >= width || w.maxRow >= height || w.minColumn > w.maxColumn || w.minRow > w.maxRow)
15017
+ throw new Error("Invalid terrain dirty sample window");
15018
+ }
15019
+ function sameTerrainFrame(a, b) {
15020
+ return a.width === b.width && a.height === b.height && a.registration === b.registration && a.diagonal === b.diagonal && a.heightReference === b.heightReference && a.origin.every((v, i) => v === b.origin[i]) && a.columnStep.every((v, i) => v === b.columnStep[i]) && a.rowStep.every((v, i) => v === b.rowStep[i]);
15021
+ }
15022
+ function terrainDirtyIndices(windows, width, height, expand, charge) {
15023
+ const ids = /* @__PURE__ */ new Set();
15024
+ for (const w of windows)
15025
+ for (let y = Math.max(0, w.minRow - expand); y <= Math.min(height - 1, w.maxRow + expand); y++)
15026
+ for (let x = Math.max(0, w.minColumn - expand); x <= Math.min(width - 1, w.maxColumn + expand); x++) {
15027
+ charge();
15028
+ ids.add(y * width + x);
15029
+ }
15030
+ return ids;
15031
+ }
15032
+
15033
+ // dist/terrain/mesh-regions-data.js
15034
+ function updateMeshRegions(previous, field, dirty, options, configuration, create) {
15035
+ const cells = options.cellsPerRegion ?? 32, limit = options.maxSamples ?? 4e6, budget = options.maxTests ?? 1e7;
15036
+ if (![cells, limit, budget].every(Number.isSafeInteger) || cells < 1 || limit < 0 || budget < 0)
15037
+ throw new Error("Invalid terrain mesh region capacity");
15038
+ validateTerrainDirtyWindows(dirty, field.width, field.height);
15039
+ let count = 0, tests = 0;
15040
+ const regions = [], rebuilt = [];
15041
+ const reusable = previous && sameTerrainFrame(previous.field, field) && previous.cellsPerRegion === cells && previous.configuration === configuration;
15042
+ const cache = new Map(previous == null ? void 0 : previous.regions.map((r) => [`${r.column},${r.row}`, r]));
15043
+ for (let row = 0; row < field.height - 1; row += cells)
15044
+ for (let column = 0; column < field.width - 1; column += cells) {
15045
+ const width = Math.min(cells, field.width - 1 - column) + 1, height = Math.min(cells, field.height - 1 - row) + 1;
15046
+ count += width * height;
15047
+ if (!Number.isSafeInteger(count) || count > limit)
15048
+ throw new Error("Terrain mesh region sample capacity exceeded");
15049
+ let affected = !reusable;
15050
+ for (const w of reusable ? dirty : []) {
15051
+ if (++tests > budget)
15052
+ throw new Error("Terrain mesh region work budget exceeded");
15053
+ if (w.minColumn <= column + width - 1 && w.maxColumn >= column && w.minRow <= row + height - 1 && w.maxRow >= row)
15054
+ affected = true;
15055
+ }
15056
+ const old = cache.get(`${column},${row}`);
15057
+ if (!affected && old) {
15058
+ regions.push(old);
15059
+ continue;
15060
+ }
15061
+ const heights = Float64Array.from({ length: width * height }, (_, i) => field.getHeight(column + i % width, row + Math.floor(i / width)) ?? NaN);
15062
+ const source = new HeightField({
15063
+ width,
15064
+ height,
15065
+ heights,
15066
+ origin: [
15067
+ column * field.columnStep[0] + row * field.rowStep[0],
15068
+ column * field.columnStep[1] + row * field.rowStep[1]
15069
+ ],
15070
+ columnStep: field.columnStep,
15071
+ rowStep: field.rowStep,
15072
+ registration: field.registration,
15073
+ diagonal: field.diagonal,
15074
+ heightReference: field.heightReference
15075
+ });
15076
+ rebuilt.push(regions.length);
15077
+ let data = create(source);
15078
+ if (data) {
15079
+ const mesh = data;
15080
+ const positions = mesh.positions.map((value3, i) => {
15081
+ const axis = i % 3;
15082
+ if (axis === 2)
15083
+ return value3;
15084
+ const vertex = Math.floor(i / 3), shift2 = field.registration === "cell" ? 0.5 : 0;
15085
+ const c = column + mesh.gridCoordinates[2 * vertex] + shift2, r = row + mesh.gridCoordinates[2 * vertex + 1] + shift2;
15086
+ const coordinate = c * field.columnStep[axis] + r * field.rowStep[axis];
15087
+ if (!Number.isFinite(coordinate))
15088
+ throw new Error("Terrain region coordinate overflow");
15089
+ return coordinate;
15090
+ });
15091
+ data = { ...mesh, origin: [0, 0, 0], positions };
15092
+ }
15093
+ regions.push({ column, row, field: source, data });
15094
+ }
15095
+ return {
15096
+ field,
15097
+ origin: [field.origin[0], field.origin[1], 0],
15098
+ cellsPerRegion: cells,
15099
+ configuration,
15100
+ regions,
15101
+ rebuilt: Uint32Array.from(rebuilt)
15102
+ };
15103
+ }
15104
+
15105
+ // dist/terrain/mesh-regions.js
15106
+ function updateTerrainMeshRegions(previous, field, dirty, options = {}) {
15107
+ return updateMeshRegions(previous, field, dirty, options, "regular", createTerrainMesh);
15108
+ }
15109
+
15110
+ // dist/terrain/martini-regions.js
15111
+ function updateTerrainMartiniMeshRegions(previous, field, dirty, options) {
15112
+ const cells = options.cellsPerRegion ?? 32;
15113
+ if (!Number.isSafeInteger(cells) || cells < 1 || cells > 32768 || (cells & cells - 1) !== 0 || (field.width - 1) % cells || (field.height - 1) % cells || !Number.isFinite(options.maxError) || options.maxError < 0)
15114
+ throw new Error("Invalid MARTINI region dimensions or error");
15115
+ return updateMeshRegions(previous, field, dirty, options, `martini:${options.maxError}`, (f) => f.validCount !== f.width * f.height ? null : createMartiniTerrainMesh(f, {
15116
+ maxError: options.maxError,
15117
+ fullEdges: ["minColumn", "maxColumn", "minRow", "maxRow"]
15118
+ }));
15119
+ }
15120
+
15121
+ // dist/terrain/delatin-regions.js
15122
+ function updateTerrainDelatinMeshRegions(previous, field, dirty, options) {
15123
+ if (!Number.isFinite(options.maxError) || options.maxError < 0)
15124
+ throw new Error("Invalid Delatin region error");
15125
+ return updateMeshRegions(previous, field, dirty, options, `delatin:${options.maxError}`, (f) => f.validCount !== f.width * f.height ? null : createDelatinTerrainMesh(f, { maxError: options.maxError }));
15126
+ }
15127
+
15128
+ // dist/terrain/bounds-regions.js
15129
+ function updateTerrainBoundsRegions(previous, field, dirty, options = {}) {
15130
+ const limit = options.maxSamples ?? 4e6, budget = options.maxTests ?? 1e7;
15131
+ if (![limit, budget].every(Number.isSafeInteger) || limit < 0 || budget < 0 || field.width * field.height > limit)
15132
+ throw new Error("Invalid bounds region capacity");
15133
+ validateTerrainDirtyWindows(dirty, field.width, field.height);
15134
+ if (!previous || !sameTerrainFrame(previous.field, field)) {
15135
+ const bounds = new HeightFieldMinMax(field), levels2 = Array.from({ length: bounds.levelCount }, (_, i) => bounds.copyLevel(i));
15136
+ return { field, levels: levels2, updatedCounts: Uint32Array.from(levels2, (l) => l.width * l.height) };
15137
+ }
15138
+ let tests = 0;
15139
+ const charge = () => {
15140
+ if (++tests > budget)
15141
+ throw new Error("Bounds region work budget exceeded");
15142
+ };
15143
+ let ids = terrainDirtyIndices(dirty, field.width - 1, field.height - 1, 1, charge);
15144
+ const counts = [], levels = previous.levels.slice();
15145
+ for (let l = 0; l < levels.length; l++) {
15146
+ counts.push(ids.size);
15147
+ if (!ids.size)
15148
+ continue;
15149
+ const old = levels[l], next = {
15150
+ ...old,
15151
+ minimums: old.minimums.slice(),
15152
+ maximums: old.maximums.slice(),
15153
+ populatedCellCounts: old.populatedCellCounts.slice(),
15154
+ completeCellCounts: old.completeCellCounts.slice()
15155
+ };
15156
+ const parents = /* @__PURE__ */ new Set();
15157
+ for (const id of ids) {
15158
+ charge();
15159
+ const x = id % next.width, y = Math.floor(id / next.width);
15160
+ let min = Infinity, max = -Infinity, populated = 0, complete = 0;
15161
+ if (l === 0) {
15162
+ let valid = 0;
15163
+ for (let dy = 0; dy < 2; dy++)
15164
+ for (let dx = 0; dx < 2; dx++) {
15165
+ const h = field.getHeight(x + dx, y + dy);
15166
+ if (h !== void 0) {
15167
+ valid++;
15168
+ min = Math.min(min, h);
15169
+ max = Math.max(max, h);
15170
+ }
15171
+ }
15172
+ populated = valid ? 1 : 0;
15173
+ complete = valid === 4 ? 1 : 0;
15174
+ } else {
15175
+ const child = levels[l - 1];
15176
+ for (let dy = 0; dy < 2; dy++)
15177
+ for (let dx = 0; dx < 2; dx++) {
15178
+ const cx = x * 2 + dx, cy = y * 2 + dy;
15179
+ if (cx >= child.width || cy >= child.height)
15180
+ continue;
15181
+ const i = cy * child.width + cx;
15182
+ if (child.populatedCellCounts[i]) {
15183
+ min = Math.min(min, child.minimums[i]);
15184
+ max = Math.max(max, child.maximums[i]);
15185
+ }
15186
+ populated += child.populatedCellCounts[i];
15187
+ complete += child.completeCellCounts[i];
15188
+ }
15189
+ }
15190
+ next.minimums[id] = populated ? min : 0;
15191
+ next.maximums[id] = populated ? max : 0;
15192
+ next.populatedCellCounts[id] = populated;
15193
+ next.completeCellCounts[id] = complete;
15194
+ parents.add(Math.floor(y / 2) * Math.ceil(next.width / 2) + Math.floor(x / 2));
15195
+ }
15196
+ levels[l] = next;
15197
+ ids = parents;
15198
+ }
15199
+ return { field, levels, updatedCounts: Uint32Array.from(counts) };
15200
+ }
15201
+
15202
+ // dist/terrain/gradient-pyramid-regions.js
15203
+ function updateTerrainGradientPyramidRegions(previous, grid, dirty, options = {}) {
15204
+ const limit = options.maxSamples ?? 4e6, budget = options.maxTests ?? 1e7;
15205
+ if (![limit, budget].every(Number.isSafeInteger) || limit < 0 || budget < 0 || !Number.isSafeInteger(grid.width) || grid.width < 1 || !Number.isSafeInteger(grid.height) || grid.height < 1 || grid.width * grid.height > limit)
15206
+ throw new Error("Invalid gradient region capacity");
15207
+ if (grid.method !== "horn" && grid.method !== "zevenbergen-thorne" || grid.registration !== "vertex" && grid.registration !== "cell" || typeof grid.heightReference !== "string" || ![grid.origin, grid.columnStep, grid.rowStep].every((v) => v.length === 2 && v.every(Number.isFinite)))
15208
+ throw new Error("Invalid gradient region metadata");
15209
+ validateTerrainDirtyWindows(dirty, grid.width, grid.height);
15210
+ const old = previous == null ? void 0 : previous.source;
15211
+ if (!old || old.width !== grid.width || old.height !== grid.height || old.method !== grid.method || old.registration !== grid.registration || old.heightReference !== grid.heightReference || !old.origin.every((v, i) => v === grid.origin[i]) || !old.columnStep.every((v, i) => v === grid.columnStep[i]) || !old.rowStep.every((v, i) => v === grid.rowStep[i])) {
15212
+ const pyramid = createTerrainGradientPyramid(grid, { maxSamples: limit });
15213
+ return {
15214
+ source: grid,
15215
+ pyramid,
15216
+ updatedCounts: Uint32Array.from(pyramid.levels, (l) => l.width * l.height)
15217
+ };
15218
+ }
15219
+ if (!(grid.gradients instanceof Float64Array) || grid.gradients.length !== 2 * grid.width * grid.height || !(grid.statuses instanceof Uint8Array) || grid.statuses.length !== grid.width * grid.height)
15220
+ throw new Error("Invalid gradient region buffers");
15221
+ const levels = previous.pyramid.levels.slice();
15222
+ let tests = 0;
15223
+ const charge = () => {
15224
+ if (++tests > budget)
15225
+ throw new Error("Gradient region work budget exceeded");
15226
+ };
15227
+ let ids = terrainDirtyIndices(dirty, grid.width, grid.height, 0, charge);
15228
+ const counts = [];
15229
+ for (let l = 0; l < levels.length; l++) {
15230
+ counts.push(ids.size);
15231
+ if (!ids.size)
15232
+ continue;
15233
+ const oldLevel = levels[l], next = {
15234
+ ...oldLevel,
15235
+ gradients: oldLevel.gradients.slice(),
15236
+ validCounts: oldLevel.validCounts.slice(),
15237
+ sampleCounts: oldLevel.sampleCounts
15238
+ };
15239
+ const parents = /* @__PURE__ */ new Set();
15240
+ for (const id of ids) {
15241
+ charge();
15242
+ const x = id % next.width, y = Math.floor(id / next.width);
15243
+ next.validCounts[id] = 0;
15244
+ next.gradients[2 * id] = next.gradients[2 * id + 1] = 0;
15245
+ if (l === 0) {
15246
+ if (grid.statuses[id] > 6)
15247
+ throw new Error("Invalid terrain gradient status");
15248
+ if (grid.statuses[id] === 0) {
15249
+ if (!Number.isFinite(grid.gradients[2 * id]) || !Number.isFinite(grid.gradients[2 * id + 1]))
15250
+ throw new Error("Invalid terrain gradient value");
15251
+ next.validCounts[id] = 1;
15252
+ next.gradients[2 * id] = grid.gradients[2 * id];
15253
+ next.gradients[2 * id + 1] = grid.gradients[2 * id + 1];
15254
+ }
15255
+ } else {
15256
+ const child = levels[l - 1];
15257
+ for (let dy = 0; dy < 2; dy++)
15258
+ for (let dx = 0; dx < 2; dx++) {
15259
+ const cx = x * 2 + dx, cy = y * 2 + dy;
15260
+ if (cx >= child.width || cy >= child.height)
15261
+ continue;
15262
+ const i = cy * child.width + cx, n = child.validCounts[i], count = next.validCounts[id];
15263
+ if (n) {
15264
+ const total = count + n;
15265
+ for (let axis = 0; axis < 2; axis++) {
15266
+ const a = next.gradients[2 * id + axis], b = child.gradients[2 * i + axis];
15267
+ next.gradients[2 * id + axis] = count ? a * (count / total) + b * (n / total) : b;
15268
+ }
15269
+ next.validCounts[id] = total;
15270
+ }
15271
+ }
15272
+ }
15273
+ parents.add(Math.floor(y / 2) * Math.ceil(next.width / 2) + Math.floor(x / 2));
15274
+ }
15275
+ levels[l] = next;
15276
+ ids = parents;
15277
+ }
15278
+ return {
15279
+ source: grid,
15280
+ pyramid: { ...previous.pyramid, levels },
15281
+ updatedCounts: Uint32Array.from(counts)
15282
+ };
15283
+ }
15284
+
15285
+ // dist/terrain/persistent-hierarchy-data.js
15286
+ function getTerrainHierarchyNode(level, column, row) {
15287
+ if (!Number.isSafeInteger(level.width) || level.width < 1 || !Number.isSafeInteger(level.height) || level.height < 1 || !Number.isSafeInteger(level.nodesPerBlock) || level.nodesPerBlock < 1 || !Array.isArray(level.blocks))
15288
+ throw new Error("Invalid persistent hierarchy level");
15289
+ if (!Number.isSafeInteger(column) || !Number.isSafeInteger(row) || column < 0 || row < 0 || column >= level.width || row >= level.height)
15290
+ throw new Error("Invalid persistent hierarchy node");
15291
+ const id = row * level.width + column, block = level.blocks[Math.floor(id / level.nodesPerBlock)], i = block ? 2 * (id - block.offset) : -1;
15292
+ const expectedOffset = Math.floor(id / level.nodesPerBlock) * level.nodesPerBlock;
15293
+ if (!block || block.offset !== expectedOffset || block.count !== Math.min(level.nodesPerBlock, level.width * level.height - expectedOffset) || !(block.values instanceof Float64Array) || !(block.counts instanceof Uint32Array) || block.values.length !== 2 * block.count || block.counts.length !== 2 * block.count)
15294
+ throw new Error("Invalid persistent hierarchy block");
15295
+ return {
15296
+ values: [block.values[i], block.values[i + 1]],
15297
+ counts: [block.counts[i], block.counts[i + 1]]
15298
+ };
15299
+ }
15300
+ function packTerrainHierarchyLevel(width, height, blockSize, values, counts, nodesPerBlock) {
15301
+ if (values.length !== 2 * width * height || counts.length !== values.length || !values.every(Number.isFinite))
15302
+ throw new Error("Invalid persistent hierarchy buffers");
15303
+ const blocks = [];
15304
+ for (let offset2 = 0; offset2 < width * height; offset2 += nodesPerBlock) {
15305
+ const count = Math.min(nodesPerBlock, width * height - offset2);
15306
+ blocks.push({
15307
+ offset: offset2,
15308
+ count,
15309
+ values: values.slice(2 * offset2, 2 * (offset2 + count)),
15310
+ counts: counts.slice(2 * offset2, 2 * (offset2 + count))
15311
+ });
15312
+ }
15313
+ return { width, height, blockSize, nodesPerBlock, blocks };
15314
+ }
15315
+ function persistentHierarchyOptions(options, count) {
15316
+ const nodesPerBlock = options.nodesPerBlock ?? 256, maxSamples = options.maxSamples ?? 4e6, maxTests = options.maxTests ?? 1e7;
15317
+ if (![nodesPerBlock, maxSamples, maxTests, count].every(Number.isSafeInteger) || nodesPerBlock < 1 || maxSamples < 0 || maxTests < 0 || count < 1 || count > maxSamples)
15318
+ throw new Error("Invalid persistent terrain hierarchy capacity");
15319
+ let tests = 0;
15320
+ return {
15321
+ nodesPerBlock,
15322
+ maxSamples,
15323
+ charge: () => {
15324
+ if (++tests > maxTests)
15325
+ throw new Error("Persistent hierarchy work budget exceeded");
15326
+ }
15327
+ };
15328
+ }
15329
+ function updatePersistentHierarchy(previous, ids, mode, base, charge) {
15330
+ const levels = previous.slice(), updatedNodes = [];
15331
+ let copiedBlocks = 0, copiedBytes = 0;
15332
+ for (let l = 0; l < levels.length; l++) {
15333
+ updatedNodes.push(ids.size);
15334
+ if (!ids.size)
15335
+ continue;
15336
+ const old = levels[l], blocks = old.blocks.slice(), cloned = /* @__PURE__ */ new Set(), parents = /* @__PURE__ */ new Set();
15337
+ const node = (level, x, y) => getTerrainHierarchyNode(level, x, y);
15338
+ for (const id of ids) {
15339
+ charge();
15340
+ const x = id % old.width, y = Math.floor(id / old.width);
15341
+ let value3;
15342
+ if (l === 0)
15343
+ value3 = base(x, y);
15344
+ else {
15345
+ const child = levels[l - 1];
15346
+ let a = mode === "bounds" ? Infinity : 0, b = mode === "bounds" ? -Infinity : 0, c = 0, d = 0;
15347
+ for (let dy = 0; dy < 2; dy++)
15348
+ for (let dx = 0; dx < 2; dx++) {
15349
+ const cx = x * 2 + dx, cy = y * 2 + dy;
15350
+ if (cx >= child.width || cy >= child.height)
15351
+ continue;
15352
+ const v = node(child, cx, cy), n = v.counts[0];
15353
+ d += v.counts[1];
15354
+ if (n) {
15355
+ if (mode === "bounds") {
15356
+ a = Math.min(a, v.values[0]);
15357
+ b = Math.max(b, v.values[1]);
15358
+ } else {
15359
+ const total = c + n;
15360
+ a = c ? a * (c / total) + v.values[0] * (n / total) : v.values[0];
15361
+ b = c ? b * (c / total) + v.values[1] * (n / total) : v.values[1];
15362
+ }
15363
+ c += n;
15364
+ }
15365
+ }
15366
+ if (c && (!Number.isFinite(a) || !Number.isFinite(b)))
15367
+ throw new Error("Persistent hierarchy arithmetic overflow");
15368
+ value3 = { values: c ? [a, b] : [0, 0], counts: [c, d] };
15369
+ }
15370
+ const blockId = Math.floor(id / old.nodesPerBlock);
15371
+ if (!cloned.has(blockId)) {
15372
+ const source = blocks[blockId];
15373
+ blocks[blockId] = { ...source, values: source.values.slice(), counts: source.counts.slice() };
15374
+ cloned.add(blockId);
15375
+ copiedBlocks++;
15376
+ copiedBytes += blocks[blockId].values.byteLength + blocks[blockId].counts.byteLength;
15377
+ }
15378
+ const block = blocks[blockId], i = 2 * (id - block.offset);
15379
+ block.values[i] = value3.values[0];
15380
+ block.values[i + 1] = value3.values[1];
15381
+ block.counts[i] = value3.counts[0];
15382
+ block.counts[i + 1] = value3.counts[1];
15383
+ parents.add(Math.floor(y / 2) * Math.ceil(old.width / 2) + Math.floor(x / 2));
15384
+ }
15385
+ levels[l] = { ...old, blocks };
15386
+ ids = parents;
15387
+ }
15388
+ return { levels, stats: { copiedBlocks, copiedBytes, updatedNodes: Uint32Array.from(updatedNodes) } };
15389
+ }
15390
+
15391
+ // dist/terrain/persistent-bounds.js
15392
+ function updateTerrainPersistentBounds(previous, field, dirty, options = {}) {
15393
+ const { nodesPerBlock, charge } = persistentHierarchyOptions(options, field.width * field.height);
15394
+ validateTerrainDirtyWindows(dirty, field.width, field.height);
15395
+ if (!previous || !sameTerrainFrame(previous.field, field) || previous.levels[0].nodesPerBlock !== nodesPerBlock) {
15396
+ const bounds = new HeightFieldMinMax(field), levels = Array.from({ length: bounds.levelCount }, (_, i) => {
15397
+ const l = bounds.copyLevel(i), values = new Float64Array(2 * l.width * l.height), counts = new Uint32Array(values.length);
15398
+ for (let j = 0; j < l.width * l.height; j++) {
15399
+ values[2 * j] = l.minimums[j];
15400
+ values[2 * j + 1] = l.maximums[j];
15401
+ counts[2 * j] = l.populatedCellCounts[j];
15402
+ counts[2 * j + 1] = l.completeCellCounts[j];
15403
+ }
15404
+ return packTerrainHierarchyLevel(l.width, l.height, l.blockSize, values, counts, nodesPerBlock);
15405
+ });
15406
+ return {
15407
+ field,
15408
+ levels,
15409
+ stats: {
15410
+ copiedBlocks: levels.reduce((n, l) => n + l.blocks.length, 0),
15411
+ copiedBytes: levels.reduce((n, l) => n + l.blocks.reduce((s, b) => s + b.values.byteLength + b.counts.byteLength, 0), 0),
15412
+ updatedNodes: Uint32Array.from(levels, (l) => l.width * l.height)
15413
+ }
15414
+ };
15415
+ }
15416
+ const ids = terrainDirtyIndices(dirty, field.width - 1, field.height - 1, 1, charge);
15417
+ const result = updatePersistentHierarchy(previous.levels, ids, "bounds", (x, y) => {
15418
+ let min = Infinity, max = -Infinity, n = 0;
15419
+ for (let dy = 0; dy < 2; dy++)
15420
+ for (let dx = 0; dx < 2; dx++) {
15421
+ const z = field.getHeight(x + dx, y + dy);
15422
+ if (z !== void 0) {
15423
+ min = Math.min(min, z);
15424
+ max = Math.max(max, z);
15425
+ n++;
15426
+ }
15427
+ }
15428
+ return { values: n ? [min, max] : [0, 0], counts: [n ? 1 : 0, n === 4 ? 1 : 0] };
15429
+ }, charge);
15430
+ return { field, ...result };
15431
+ }
15432
+
15433
+ // dist/terrain/persistent-gradients.js
15434
+ function updateTerrainPersistentGradients(previous, grid, dirty, options = {}) {
15435
+ const { nodesPerBlock, maxSamples, charge } = persistentHierarchyOptions(options, grid.width * grid.height);
15436
+ if (!Number.isSafeInteger(grid.width) || grid.width < 1 || !Number.isSafeInteger(grid.height) || grid.height < 1 || !(grid.gradients instanceof Float64Array) || grid.gradients.length !== 2 * grid.width * grid.height || !(grid.statuses instanceof Uint8Array) || grid.statuses.length !== grid.width * grid.height || grid.method !== "horn" && grid.method !== "zevenbergen-thorne" || grid.registration !== "vertex" && grid.registration !== "cell" || typeof grid.heightReference !== "string" || ![grid.origin, grid.columnStep, grid.rowStep].every((v) => v.length === 2 && v.every(Number.isFinite)))
15437
+ throw new Error("Invalid persistent gradient grid");
15438
+ validateTerrainDirtyWindows(dirty, grid.width, grid.height);
15439
+ const old = previous == null ? void 0 : previous.source;
15440
+ if (!old || old.width !== grid.width || old.height !== grid.height || old.method !== grid.method || old.registration !== grid.registration || old.heightReference !== grid.heightReference || !old.origin.every((v, i) => v === grid.origin[i]) || !old.columnStep.every((v, i) => v === grid.columnStep[i]) || !old.rowStep.every((v, i) => v === grid.rowStep[i]) || previous.levels[0].nodesPerBlock !== nodesPerBlock) {
15441
+ const pyramid = createTerrainGradientPyramid(grid, { maxSamples }), levels = pyramid.levels.map((l) => {
15442
+ const counts = new Uint32Array(2 * l.width * l.height);
15443
+ for (let i = 0; i < l.width * l.height; i++) {
15444
+ counts[2 * i] = l.validCounts[i];
15445
+ counts[2 * i + 1] = l.sampleCounts[i];
15446
+ }
15447
+ return packTerrainHierarchyLevel(l.width, l.height, l.blockSize, l.gradients, counts, nodesPerBlock);
15448
+ });
15449
+ return {
15450
+ source: grid,
15451
+ levels,
15452
+ stats: {
15453
+ copiedBlocks: levels.reduce((n, l) => n + l.blocks.length, 0),
15454
+ copiedBytes: levels.reduce((n, l) => n + l.blocks.reduce((s, b) => s + b.values.byteLength + b.counts.byteLength, 0), 0),
15455
+ updatedNodes: Uint32Array.from(levels, (l) => l.width * l.height)
15456
+ }
15457
+ };
15458
+ }
15459
+ const ids = terrainDirtyIndices(dirty, grid.width, grid.height, 0, charge);
15460
+ const result = updatePersistentHierarchy(previous.levels, ids, "gradient", (x, y) => {
15461
+ const i = y * grid.width + x, s = grid.statuses[i];
15462
+ if (s > 6)
15463
+ throw new Error("Invalid terrain gradient status");
15464
+ if (s === 0 && (!Number.isFinite(grid.gradients[2 * i]) || !Number.isFinite(grid.gradients[2 * i + 1])))
15465
+ throw new Error("Invalid terrain gradient value");
15466
+ return {
15467
+ values: s === 0 ? [grid.gradients[2 * i], grid.gradients[2 * i + 1]] : [0, 0],
15468
+ counts: [s === 0 ? 1 : 0, 1]
15469
+ };
15470
+ }, charge);
15471
+ return { source: grid, ...result };
15472
+ }
15473
+
15474
+ // dist/terrain/lod-morph.js
15475
+ var TerrainMorphStatus = {
15476
+ VALID: 0,
15477
+ FINE_NO_DATA: 1,
15478
+ COARSE_NO_DATA: 2,
15479
+ OUTSIDE_COARSE: 3
15480
+ };
15481
+ function createTerrainLodMorph(fine, coarse, options) {
15482
+ const { ratio: ratio2 } = options, offset2 = options.coarseOrigin ?? [0, 0], limit = options.maxSamples ?? 4e6, count = fine.width * fine.height;
15483
+ if (!Number.isSafeInteger(ratio2) || ratio2 < 2 || 2 ** Math.round(Math.log2(ratio2)) !== ratio2 || offset2.length !== 2 || !offset2.every(Number.isSafeInteger) || !Number.isSafeInteger(limit) || limit < 0 || count > limit)
15484
+ throw new Error("Invalid terrain LOD ratio, origin or sample capacity");
15485
+ if (fine.registration !== "vertex" || coarse.registration !== "vertex" || fine.diagonal !== coarse.diagonal || fine.heightReference !== coarse.heightReference)
15486
+ throw new Error("Incompatible terrain LOD registration, diagonal or height reference");
15487
+ for (let axis = 0; axis < 2; axis++) {
15488
+ if (fine.columnStep[axis] * ratio2 !== coarse.columnStep[axis] || fine.rowStep[axis] * ratio2 !== coarse.rowStep[axis])
15489
+ throw new Error("Terrain LOD steps differ");
15490
+ const a = offset2[0] * fine.columnStep[axis], b = offset2[1] * fine.rowStep[axis], expected = fine.origin[axis] + a + b;
15491
+ const tolerance = Math.min(16 * Number.EPSILON * Math.max(1, Math.abs(fine.origin[axis]), Math.abs(coarse.origin[axis]), Math.abs(a), Math.abs(b)), 1e-9 * Math.max(Math.abs(fine.columnStep[axis]), Math.abs(fine.rowStep[axis])));
15492
+ if (!Number.isFinite(expected) || Math.abs(coarse.origin[axis] - expected) > tolerance)
15493
+ throw new Error("Terrain LOD origins differ");
15494
+ }
15495
+ const fineHeights = new Float64Array(count), coarseHeights = new Float64Array(count), deltas = new Float64Array(count), statuses = new Uint8Array(count), coarseCoordinates = new Float64Array(2 * count);
15496
+ let maxNodalDisplacement = 0;
15497
+ for (let y = 0; y < fine.height; y++)
15498
+ for (let x = 0; x < fine.width; x++) {
15499
+ const i = y * fine.width + x, u = (x - offset2[0]) / ratio2, v = (y - offset2[1]) / ratio2;
15500
+ if (!Number.isSafeInteger(x - offset2[0]) || !Number.isSafeInteger(y - offset2[1]))
15501
+ throw new Error("Terrain LOD lattice overflow");
15502
+ coarseCoordinates[2 * i] = u;
15503
+ coarseCoordinates[2 * i + 1] = v;
15504
+ const source = fine.getHeight(x, y);
15505
+ if (source === void 0) {
15506
+ statuses[i] = TerrainMorphStatus.FINE_NO_DATA;
15507
+ continue;
15508
+ }
15509
+ fineHeights[i] = source;
15510
+ if (u < 0 || v < 0 || u > coarse.width - 1 || v > coarse.height - 1) {
15511
+ statuses[i] = TerrainMorphStatus.OUTSIDE_COARSE;
15512
+ continue;
15513
+ }
15514
+ const target = sampleTerrainTriangleHeight(coarse, u, v);
15515
+ if (target === void 0) {
15516
+ statuses[i] = TerrainMorphStatus.COARSE_NO_DATA;
15517
+ continue;
15518
+ }
15519
+ const delta = target - source;
15520
+ if (!Number.isFinite(delta))
15521
+ throw new Error("Terrain LOD displacement overflow");
15522
+ coarseHeights[i] = target;
15523
+ deltas[i] = delta;
15524
+ maxNodalDisplacement = Math.max(maxNodalDisplacement, Math.abs(delta));
15525
+ }
15526
+ return {
15527
+ width: fine.width,
15528
+ height: fine.height,
15529
+ origin: [...fine.origin],
15530
+ columnStep: [...fine.columnStep],
15531
+ rowStep: [...fine.rowStep],
15532
+ heightReference: fine.heightReference,
15533
+ fineHeights,
15534
+ coarseHeights,
15535
+ deltas,
15536
+ statuses,
15537
+ coarseCoordinates,
15538
+ maxNodalDisplacement,
15539
+ ratio: ratio2,
15540
+ coarseOrigin: [...offset2],
15541
+ diagonal: fine.diagonal
15542
+ };
15543
+ }
15544
+
15545
+ // dist/terrain/lod-morph-evaluate.js
15546
+ function evaluateTerrainLodMorph(morph, factor) {
15547
+ const count = morph.width * morph.height;
15548
+ if (!Number.isFinite(factor) || factor < 0 || factor > 1 || !Number.isSafeInteger(count) || count < 1 || morph.fineHeights.length !== count || morph.coarseHeights.length !== count || morph.statuses.length !== count)
15549
+ throw new Error("Invalid terrain morph evaluation");
15550
+ const heights = new Float64Array(count), validity = new Uint8Array(count);
15551
+ for (let i = 0; i < count; i++) {
15552
+ if (morph.statuses[i] > 3)
15553
+ throw new Error("Invalid terrain morph status");
15554
+ if (morph.statuses[i] !== 0)
15555
+ continue;
15556
+ const a = morph.fineHeights[i], b = morph.coarseHeights[i];
15557
+ if (!Number.isFinite(a) || !Number.isFinite(b))
15558
+ throw new Error("Invalid terrain morph height");
15559
+ heights[i] = factor === 0 ? a : factor === 1 ? b : a * (1 - factor) + b * factor;
15560
+ if (!Number.isFinite(heights[i]))
15561
+ throw new Error("Terrain morph arithmetic overflow");
15562
+ validity[i] = 1;
15563
+ }
15564
+ return { heights, validity };
15565
+ }
14232
15566
  //# sourceMappingURL=index.cjs.map