@math.gl/geospatial 5.0.0-beta.10 → 5.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/crs/index.cjs +54 -0
  2. package/dist/crs/index.cjs.map +2 -2
  3. package/dist/crs/index.d.ts +1 -0
  4. package/dist/crs/index.d.ts.map +1 -1
  5. package/dist/crs/index.js +1 -0
  6. package/dist/crs/index.js.map +1 -1
  7. package/dist/crs/spatial-reference-metadata.d.ts +20 -0
  8. package/dist/crs/spatial-reference-metadata.d.ts.map +1 -0
  9. package/dist/crs/spatial-reference-metadata.js +86 -0
  10. package/dist/crs/spatial-reference-metadata.js.map +1 -0
  11. package/dist/expressions.d.ts +1 -1
  12. package/dist/expressions.d.ts.map +1 -1
  13. package/dist/index.cjs +1030 -104
  14. package/dist/index.cjs.map +3 -3
  15. package/dist/index.d.ts +9 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +8 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/tasks/index.cjs +181 -84
  20. package/dist/tasks/index.cjs.map +2 -2
  21. package/dist/tasks/terrain-residency.d.ts.map +1 -1
  22. package/dist/tasks/terrain-residency.js +80 -18
  23. package/dist/tasks/terrain-residency.js.map +1 -1
  24. package/dist/terrain/cutout-skirts.d.ts +34 -0
  25. package/dist/terrain/cutout-skirts.d.ts.map +1 -0
  26. package/dist/terrain/cutout-skirts.js +29 -0
  27. package/dist/terrain/cutout-skirts.js.map +1 -0
  28. package/dist/terrain/depression-fill.d.ts +25 -0
  29. package/dist/terrain/depression-fill.d.ts.map +1 -0
  30. package/dist/terrain/depression-fill.js +106 -0
  31. package/dist/terrain/depression-fill.js.map +1 -0
  32. package/dist/terrain/hydrology.d.ts +42 -0
  33. package/dist/terrain/hydrology.d.ts.map +1 -0
  34. package/dist/terrain/hydrology.js +112 -0
  35. package/dist/terrain/hydrology.js.map +1 -0
  36. package/dist/terrain/index.cjs +1014 -88
  37. package/dist/terrain/index.cjs.map +3 -3
  38. package/dist/terrain/index.d.ts +10 -1
  39. package/dist/terrain/index.d.ts.map +1 -1
  40. package/dist/terrain/index.js +9 -0
  41. package/dist/terrain/index.js.map +1 -1
  42. package/dist/terrain/lod-screen-error.d.ts +28 -0
  43. package/dist/terrain/lod-screen-error.d.ts.map +1 -0
  44. package/dist/terrain/lod-screen-error.js +95 -0
  45. package/dist/terrain/lod-screen-error.js.map +1 -0
  46. package/dist/terrain/lod-select.d.ts +26 -10
  47. package/dist/terrain/lod-select.d.ts.map +1 -1
  48. package/dist/terrain/lod-select.js +27 -14
  49. package/dist/terrain/lod-select.js.map +1 -1
  50. package/dist/terrain/mesh-cutout.d.ts +40 -0
  51. package/dist/terrain/mesh-cutout.d.ts.map +1 -0
  52. package/dist/terrain/mesh-cutout.js +294 -0
  53. package/dist/terrain/mesh-cutout.js.map +1 -0
  54. package/dist/terrain/mesh-skirts.d.ts +8 -2
  55. package/dist/terrain/mesh-skirts.d.ts.map +1 -1
  56. package/dist/terrain/mesh-skirts.js +5 -4
  57. package/dist/terrain/mesh-skirts.js.map +1 -1
  58. package/dist/terrain/mixed-halo-update.d.ts.map +1 -1
  59. package/dist/terrain/mixed-halo-update.js +58 -23
  60. package/dist/terrain/mixed-halo-update.js.map +1 -1
  61. package/dist/terrain/mixed-vertex-halos.d.ts +24 -1
  62. package/dist/terrain/mixed-vertex-halos.d.ts.map +1 -1
  63. package/dist/terrain/mixed-vertex-halos.js +75 -58
  64. package/dist/terrain/mixed-vertex-halos.js.map +1 -1
  65. package/dist/terrain/regional-viewshed.d.ts +55 -0
  66. package/dist/terrain/regional-viewshed.d.ts.map +1 -0
  67. package/dist/terrain/regional-viewshed.js +119 -0
  68. package/dist/terrain/regional-viewshed.js.map +1 -0
  69. package/dist/terrain/sweep-polytope.d.ts +4 -0
  70. package/dist/terrain/sweep-polytope.d.ts.map +1 -1
  71. package/dist/terrain/sweep-polytope.js +15 -5
  72. package/dist/terrain/sweep-polytope.js.map +1 -1
  73. package/dist/terrain/sweep-rotating-capsule.d.ts +17 -0
  74. package/dist/terrain/sweep-rotating-capsule.d.ts.map +1 -0
  75. package/dist/terrain/sweep-rotating-capsule.js +118 -0
  76. package/dist/terrain/sweep-rotating-capsule.js.map +1 -0
  77. package/dist/terrain/sweep-rotation.d.ts +35 -0
  78. package/dist/terrain/sweep-rotation.d.ts.map +1 -0
  79. package/dist/terrain/sweep-rotation.js +114 -0
  80. package/dist/terrain/sweep-rotation.js.map +1 -0
  81. package/dist/terrain/watershed-accumulation.d.ts +20 -0
  82. package/dist/terrain/watershed-accumulation.d.ts.map +1 -0
  83. package/dist/terrain/watershed-accumulation.js +53 -0
  84. package/dist/terrain/watershed-accumulation.js.map +1 -0
  85. package/dist/turf/expressions.d.ts +1 -1
  86. package/dist/turf/expressions.d.ts.map +1 -1
  87. package/package.json +8 -8
  88. package/src/crs/index.ts +7 -0
  89. package/src/crs/spatial-reference-metadata.ts +118 -0
  90. package/src/expressions.ts +1 -1
  91. package/src/index.ts +57 -0
  92. package/src/tasks/terrain-residency.ts +86 -21
  93. package/src/terrain/cutout-skirts.ts +52 -0
  94. package/src/terrain/depression-fill.ts +125 -0
  95. package/src/terrain/hydrology.ts +149 -0
  96. package/src/terrain/index.ts +61 -1
  97. package/src/terrain/lod-screen-error.ts +128 -0
  98. package/src/terrain/lod-select.ts +65 -31
  99. package/src/terrain/mesh-cutout.ts +358 -0
  100. package/src/terrain/mesh-skirts.ts +10 -7
  101. package/src/terrain/mixed-halo-update.ts +54 -20
  102. package/src/terrain/mixed-vertex-halos.ts +94 -78
  103. package/src/terrain/regional-viewshed.ts +177 -0
  104. package/src/terrain/sweep-polytope.ts +49 -25
  105. package/src/terrain/sweep-rotating-capsule.ts +139 -0
  106. package/src/terrain/sweep-rotation.ts +149 -0
  107. package/src/terrain/watershed-accumulation.ts +67 -0
  108. package/src/turf/expressions.ts +1 -1
@@ -5,6 +5,7 @@
5
5
  import type {Task} from '@math.gl/tasks';
6
6
  import type {TerrainMixedHaloSnapshot} from '../terrain/mixed-halo-update';
7
7
  import type {TerrainMixedVertexTile} from '../terrain/mixed-vertex-halos';
8
+ import type {HeightFieldProps, TerrainArray} from '../terrain/types';
8
9
 
9
10
  type TileAddress = Pick<TerrainMixedVertexTile, 'column' | 'row' | 'spacing'>;
10
11
  type TerrainResidencyTimings = {
@@ -43,6 +44,9 @@ export type TerrainResidencyTypes = {
43
44
  };
44
45
  };
45
46
 
47
+ /** Address lookup retained with an immutable source layout, not rebuilt per sample batch. */
48
+ const sourceIndexes = new WeakMap<TerrainMixedHaloSnapshot, Map<string, number>>();
49
+
46
50
  const addressKey = ({spacing, column, row}: TileAddress) => `${spacing}/${column}/${row}`;
47
51
 
48
52
  function sameArray(a: ArrayLike<number>, b: ArrayLike<number>): boolean {
@@ -68,6 +72,50 @@ function sameHalo(a: ResidentHalo, b: ResidentHalo): boolean {
68
72
  );
69
73
  }
70
74
 
75
+ /** Copy already validated resident samples once, preserving precision and nodata normalization. */
76
+ function copyResidentSamples(field: HeightFieldProps): {
77
+ heights: TerrainArray;
78
+ validity: Uint8Array;
79
+ } {
80
+ const {width, height, offset = 0, stride = width} = field;
81
+ const heights =
82
+ field.heights instanceof Float64Array
83
+ ? new Float64Array(width * height)
84
+ : new Float32Array(width * height);
85
+ const validity = new Uint8Array(heights.length);
86
+ for (let y = 0; y < height; y++) {
87
+ for (let x = 0; x < width; x++) {
88
+ const input = offset + y * stride + x;
89
+ const output = y * width + x;
90
+ const value = field.heights[input];
91
+ if (Number.isFinite(value) && (!field.validity || field.validity[input] !== 0)) {
92
+ heights[output] = value;
93
+ validity[output] = 1;
94
+ }
95
+ }
96
+ }
97
+ return {heights, validity};
98
+ }
99
+
100
+ /** Compare halo addresses in the order used by the incremental builder. */
101
+ function compareAddress(a: TileAddress, b: TileAddress): number {
102
+ return a.spacing - b.spacing || a.column - b.column || a.row - b.row;
103
+ }
104
+
105
+ /** Compute changed outputs with a linear merge over sorted snapshots. */
106
+ function changedHalos(previous: readonly ResidentHalo[], next: readonly ResidentHalo[]) {
107
+ const changed: ResidentHalo[] = [];
108
+ let index = 0;
109
+ for (let i = 0; i < next.length; i++) {
110
+ const tile = next[i];
111
+ while (index < previous.length && compareAddress(previous[index], tile) < 0) index++;
112
+ const prior = previous[index];
113
+ if (!prior || (prior !== tile && (compareAddress(prior, tile) !== 0 || !sameHalo(prior, tile))))
114
+ changed.push(tile);
115
+ }
116
+ return changed;
117
+ }
118
+
71
119
  /** Keep mixed halo sources and outputs resident across serialized edit batches. */
72
120
  export const TerrainResidencyTask = {
73
121
  id: 'terrain-residency',
@@ -88,37 +136,59 @@ export const TerrainResidencyTask = {
88
136
  try {
89
137
  if (input.revision !== state.revision) throw new Error('Stale terrain residency revision');
90
138
 
91
- const [{updateTerrainMixedVertexTileHalos}, {HeightField}] = await Promise.all([
92
- import('../terrain/mixed-halo-update'),
93
- import('../terrain/height-field')
94
- ]);
139
+ const {updateTerrainMixedVertexTileHalos} = await import('../terrain/mixed-halo-update');
95
140
  context.throwIfAborted();
96
- const sources = new Map(state.snapshot?.sources.map(tile => [addressKey(tile), tile]));
141
+ const priorSources = state.snapshot?.sources ?? [];
142
+ let sourceIndex = state.snapshot && sourceIndexes.get(state.snapshot);
143
+ if (!sourceIndex) {
144
+ sourceIndex = new Map();
145
+ for (let i = 0; i < priorSources.length; i++)
146
+ sourceIndex.set(addressKey(priorSources[i]), i);
147
+ }
148
+ // Sample-only transactions copy one reference array. Structural edits lazily
149
+ // create a map; neither path mutates the committed snapshot on rejection.
150
+ const resident = priorSources.slice();
151
+ let structural: Map<string, TerrainMixedVertexTile> | undefined;
152
+ const getSource = (key: string) =>
153
+ structural ? structural.get(key) : resident[sourceIndex.get(key)!];
154
+ const setSource = (key: string, tile: TerrainMixedVertexTile) => {
155
+ if (structural) structural.set(key, tile);
156
+ else resident[sourceIndex.get(key)!] = tile;
157
+ };
158
+ const editLayout = () => {
159
+ if (!structural) {
160
+ structural = new Map();
161
+ for (const tile of resident) structural.set(addressKey(tile), tile);
162
+ }
163
+ return structural;
164
+ };
97
165
  // Several edits to a tile in one batch share one private copy.
98
- const writable = new Map<string, ReturnType<InstanceType<typeof HeightField>['copyData']>>();
166
+ const writable = new Map<string, ReturnType<typeof copyResidentSamples>>();
99
167
  for (const edit of input.edits) {
100
168
  if (edit.type === 'upsert') {
101
169
  const key = addressKey(edit.tile);
102
- sources.set(key, structuredClone(edit.tile));
170
+ editLayout().set(key, structuredClone(edit.tile));
103
171
  writable.delete(key);
104
172
  continue;
105
173
  }
106
174
  const key = addressKey(edit.address);
107
175
  if (edit.type === 'remove') {
108
- sources.delete(key);
176
+ editLayout().delete(key);
109
177
  writable.delete(key);
110
178
  continue;
111
179
  }
112
180
  if (edit.type !== 'samples') throw new Error('Unknown terrain residency edit');
113
- const source = sources.get(key);
181
+ const source = getSource(key);
114
182
  if (!source) throw new Error('Terrain sample edit requires a resident tile');
115
183
  if (!edit.samples.length) continue;
116
184
  let data = writable.get(key);
117
185
  if (!data) {
118
- const copied = new HeightField(source.field).copyData();
119
- data = {heights: copied.heights, validity: copied.validity};
186
+ // Upserts in this transaction have not passed halo validation yet.
187
+ data = structural
188
+ ? new (await import('../terrain/height-field')).HeightField(source.field).copyData()
189
+ : copyResidentSamples(source.field);
120
190
  writable.set(key, data);
121
- sources.set(key, {
191
+ setSource(key, {
122
192
  ...source,
123
193
  field: {...source.field, ...data, offset: 0, stride: source.field.width}
124
194
  });
@@ -141,19 +211,14 @@ export const TerrainResidencyTask = {
141
211
  const applied = input.measureStages ? performance.now() : 0;
142
212
  const next = updateTerrainMixedVertexTileHalos(
143
213
  state.snapshot,
144
- [...sources.values()],
214
+ structural ? [...structural.values()] : resident,
145
215
  state.limits
146
216
  );
147
217
  const updated = input.measureStages ? performance.now() : 0;
148
- const old = new Map(state.snapshot?.tiles.map(tile => [addressKey(tile), tile]));
149
- // Copy outgoing buffers so transfer cannot detach the resident snapshot.
150
- const tiles = structuredClone(
151
- next.tiles.filter(tile => {
152
- const prior = old.get(addressKey(tile));
153
- return !prior || !sameHalo(prior, tile);
154
- })
155
- );
218
+ // Both snapshots are in address order. Unchanged halos retain object identity.
219
+ const tiles = structuredClone(changedHalos(state.snapshot?.tiles ?? [], next.tiles));
156
220
  context.throwIfAborted();
221
+ if (!structural) sourceIndexes.set(next, sourceIndex);
157
222
  state.snapshot = next;
158
223
  state.revision++;
159
224
  const result: TerrainResidencyTypes['output'] = {
@@ -0,0 +1,52 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {TerrainCutout, TerrainCutoutPiece} from './mesh-cutout';
6
+ import {createTerrainSkirt, type TerrainSkirtMesh, type TerrainSkirtOptions} from './mesh-skirts';
7
+
8
+ /** Select wall height or a local base, without allowing arbitrary edge selection. */
9
+ type WallOptions = Pick<TerrainSkirtOptions, 'maxVertices' | 'maxTriangles'> &
10
+ ({height: number; baseZ?: never} | {baseZ: number; height?: never});
11
+
12
+ /** Lift and wall settings for a terrain split. */
13
+ export type TerrainCutoutSkirtOptions = {
14
+ /** Amount added to the patch's local Z coordinates. Defaults to zero. */
15
+ lift?: number;
16
+ /** Wall options for the lifted patch. */
17
+ patch: WallOptions;
18
+ /** Wall options for the unchanged remainder. */
19
+ remainder: WallOptions;
20
+ };
21
+
22
+ /** Raised and stationary surfaces with optional visual skirts. */
23
+ export type SkirtedTerrainCutout = {
24
+ patch: {surface: TerrainCutoutPiece; skirt?: TerrainSkirtMesh};
25
+ remainder: {surface: TerrainCutoutPiece; skirt?: TerrainSkirtMesh};
26
+ };
27
+
28
+ /** Translate the patch and build both walls from the paired cut edges only. */
29
+ export function createTerrainCutoutSkirts(
30
+ cutout: TerrainCutout,
31
+ {lift = 0, patch, remainder}: TerrainCutoutSkirtOptions
32
+ ): SkirtedTerrainCutout {
33
+ if (!Number.isFinite(lift)) throw new RangeError('Invalid terrain cutout lift');
34
+ const positions = cutout.patch.positions.slice();
35
+ for (let i = 2; i < positions.length; i += 3) {
36
+ positions[i] += lift;
37
+ if (!Number.isFinite(positions[i])) throw new RangeError('Terrain cutout lift overflow');
38
+ }
39
+ return {
40
+ patch: skirtPiece({...cutout.patch, positions}, patch),
41
+ remainder: skirtPiece(cutout.remainder, remainder)
42
+ };
43
+ }
44
+
45
+ /** Compose on a nonempty paired boundary only. */
46
+ function skirtPiece(surface: TerrainCutoutPiece, options: WallOptions) {
47
+ if (!surface.cutEdges.length) return {surface};
48
+ return {
49
+ surface,
50
+ skirt: createTerrainSkirt(surface, {...options, edges: surface.cutEdges})
51
+ };
52
+ }
@@ -0,0 +1,125 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import {HeightField} from './height-field';
6
+
7
+ /** Outlet and allocation policy for four-neighbor terrain conditioning. */
8
+ export type TerrainDepressionFillOptions = {
9
+ /** Valid row-major cell indices that can drain. Exterior and nodata are closed. */
10
+ outlets: readonly number[];
11
+ /** Maximum grid cells before allocating buffers. Defaults to 4,194,304. */
12
+ maxCells?: number;
13
+ };
14
+
15
+ /** Conditioned terrain and its outlet-connected drainage forest. */
16
+ export type TerrainDepressionFill = {
17
+ /** Derived field, including the original heights of outlet-disconnected cells. */
18
+ field: HeightField;
19
+ /** Next face neighbor toward an outlet, -1 at outlets, -2 for nodata or disconnected cells. */
20
+ receiver: Int32Array;
21
+ /** Number of valid cells with no face-connected path to an outlet. */
22
+ disconnectedCells: number;
23
+ };
24
+
25
+ /**
26
+ * Raise each outlet-connected cell to the lowest spill elevation needed to reach
27
+ * a declared outlet by face neighbors. The returned forest routes across flats.
28
+ * Nodata blocks flow and disconnected components retain their source heights.
29
+ * The source is immutable. Time is O(cells log cells) and storage is O(cells).
30
+ */
31
+ export function fillTerrainDepressions(
32
+ field: HeightField,
33
+ {outlets, maxCells = 4_194_304}: TerrainDepressionFillOptions
34
+ ): TerrainDepressionFill {
35
+ if (field.registration !== 'cell')
36
+ throw new Error('Terrain depression fill requires cell registration');
37
+ const {width, height} = field;
38
+ const count = width * height;
39
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 0x7fffffff)
40
+ throw new RangeError('Terrain depression fill exceeds its cell budget');
41
+ if (!outlets.length) throw new RangeError('Terrain depression fill requires an outlet');
42
+ for (const i of outlets) {
43
+ if (
44
+ !Number.isInteger(i) ||
45
+ i < 0 ||
46
+ i >= count ||
47
+ field.getHeight(i % width, Math.floor(i / width)) === undefined
48
+ )
49
+ throw new RangeError('Terrain outlet must identify a valid cell');
50
+ }
51
+
52
+ const {heights, validity} = field.copyData();
53
+ const receiver = new Int32Array(count).fill(-2);
54
+ const heap = new Int32Array(count);
55
+ let size = 0;
56
+ let disconnectedCells = field.validCount;
57
+
58
+ /** Sort by spill elevation, then by cell index for reproducible flat routing. */
59
+ const before = (a: number, b: number) =>
60
+ heights[a] < heights[b] || (heights[a] === heights[b] && a < b);
61
+
62
+ /** Insert a newly reached cell. Its finalized spill height never changes. */
63
+ function push(cell: number): void {
64
+ let slot = size++;
65
+ while (slot > 0) {
66
+ const parent = Math.floor((slot - 1) / 2);
67
+ if (!before(cell, heap[parent])) break;
68
+ heap[slot] = heap[parent];
69
+ slot = parent;
70
+ }
71
+ heap[slot] = cell;
72
+ }
73
+
74
+ /** Remove the cell with the lowest known spill elevation. */
75
+ function pop(): number {
76
+ const first = heap[0];
77
+ const tail = heap[--size];
78
+ let slot = 0;
79
+ let child = 1;
80
+ while (child < size) {
81
+ if (child + 1 < size && before(heap[child + 1], heap[child])) child++;
82
+ if (!before(heap[child], tail)) break;
83
+ heap[slot] = heap[child];
84
+ slot = child;
85
+ child = slot * 2 + 1;
86
+ }
87
+ if (size) heap[slot] = tail;
88
+ return first;
89
+ }
90
+
91
+ /** First discovery from the minimum frontier finalizes the minimax path cost. */
92
+ function visit(cell: number, parent: number): void {
93
+ if (!validity[cell] || receiver[cell] !== -2) return;
94
+ receiver[cell] = parent;
95
+ disconnectedCells--;
96
+ if (parent >= 0) heights[cell] = Math.max(heights[cell], heights[parent]);
97
+ push(cell);
98
+ }
99
+
100
+ for (const outlet of outlets) visit(outlet, -1);
101
+ while (size) {
102
+ const cell = pop();
103
+ const column = cell % width;
104
+ if (column > 0) visit(cell - 1, cell);
105
+ if (column + 1 < width) visit(cell + 1, cell);
106
+ if (cell >= width) visit(cell - width, cell);
107
+ if (cell < count - width) visit(cell + width, cell);
108
+ }
109
+ return {
110
+ field: new HeightField({
111
+ width,
112
+ height,
113
+ heights,
114
+ validity,
115
+ origin: field.origin,
116
+ columnStep: field.columnStep,
117
+ rowStep: field.rowStep,
118
+ registration: field.registration,
119
+ diagonal: field.diagonal,
120
+ heightReference: field.heightReference
121
+ }),
122
+ receiver,
123
+ disconnectedCells
124
+ };
125
+ }
@@ -0,0 +1,149 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {HeightField} from './height-field';
6
+
7
+ /** Uniform horizontal finite-volume metrics for an affine cell-centered grid. */
8
+ export type TerrainCellMetrics = {
9
+ /** Horizontal area of one cell, in square meters. */
10
+ area: number;
11
+ /** Face lengths ordered by negative column, positive column, negative row, positive row. */
12
+ faceLengths: readonly [number, number, number, number];
13
+ /** Outward horizontal unit normals in the same order as the face lengths. */
14
+ faceNormals: readonly [
15
+ readonly [number, number],
16
+ readonly [number, number],
17
+ readonly [number, number],
18
+ readonly [number, number]
19
+ ];
20
+ };
21
+
22
+ /** Derive projected cell area and face geometry, including shear and reflected grids. */
23
+ export function getTerrainCellMetrics(
24
+ field: Pick<HeightField, 'registration' | 'columnStep' | 'rowStep'>
25
+ ): TerrainCellMetrics {
26
+ if (field.registration !== 'cell')
27
+ throw new Error('Terrain cell metrics require cell registration');
28
+ const [cx, cy] = field.columnStep;
29
+ const [rx, ry] = field.rowStep;
30
+ const determinant = cx * ry - cy * rx;
31
+ const columnLength = Math.hypot(cx, cy);
32
+ const rowLength = Math.hypot(rx, ry);
33
+ const area = Math.abs(determinant);
34
+ if (!(area > 0 && Number.isFinite(area) && Number.isFinite(columnLength + rowLength)))
35
+ throw new RangeError('Invalid terrain cell geometry');
36
+ const sign = Math.sign(determinant);
37
+ const east = [(sign * ry) / rowLength, (-sign * rx) / rowLength] as const;
38
+ const south = [(-sign * cy) / columnLength, (sign * cx) / columnLength] as const;
39
+ return {
40
+ area,
41
+ faceLengths: [rowLength, rowLength, columnLength, columnLength],
42
+ faceNormals: [[-east[0], -east[1]], east, [-south[0], -south[1]], south]
43
+ };
44
+ }
45
+
46
+ /** Drainage options for the unconditioned cell grid. */
47
+ export type TerrainDrainageOptions = {
48
+ /** Valid row-major cell indices where flow terminates, even if lower neighbors exist. */
49
+ outlets?: readonly number[];
50
+ /** Maximum grid cells before allocating drainage buffers. Defaults to 4,194,304. */
51
+ maxCells?: number;
52
+ };
53
+
54
+ /** Row-major routing, catchments and accumulation for a single affine cell grid. */
55
+ export type TerrainDrainage = {
56
+ /** Receiver index, or -1 for nodata and terminal cells. */
57
+ receiver: Int32Array;
58
+ /** Terminal cell index for the catchment, or -1 for nodata. */
59
+ terminal: Int32Array;
60
+ /** Upstream cell count including the cell itself. Zero denotes nodata. */
61
+ contributingCells: Uint32Array;
62
+ /** Multiply by contributingCells to get contributing area in square meters. */
63
+ cellArea: number;
64
+ };
65
+
66
+ /** Route each valid cell to its steepest strictly lower neighbor in projected XY.
67
+ * Equal slopes select the lower row-major index. Diagonal flow requires both
68
+ * intervening side cells to be valid. The exterior and nodata block flow.
69
+ * Flats, pits and declared outlets terminate flow. Accumulation is O(cells).
70
+ */
71
+ export function createTerrainDrainage(
72
+ field: HeightField,
73
+ {outlets = [], maxCells = 4_194_304}: TerrainDrainageOptions = {}
74
+ ): TerrainDrainage {
75
+ const {width, height, columnStep, rowStep} = field;
76
+ const count = width * height;
77
+ if (!Number.isSafeInteger(maxCells) || maxCells < 0 || count > maxCells || count > 0x7fffffff)
78
+ throw new RangeError('Terrain drainage exceeds its cell budget');
79
+ const {area: cellArea} = getTerrainCellMetrics(field);
80
+ for (const i of outlets) {
81
+ if (
82
+ !Number.isInteger(i) ||
83
+ i < 0 ||
84
+ i >= count ||
85
+ field.getHeight(i % width, Math.floor(i / width)) === undefined
86
+ )
87
+ throw new RangeError('Terrain outlet must identify a valid cell');
88
+ }
89
+ const {heights, validity} = field.copyData();
90
+ const receiver = new Int32Array(count).fill(-1);
91
+ const terminal = new Int32Array(count).fill(-1);
92
+ const contributingCells = new Uint32Array(count);
93
+ const incoming = new Uint8Array(count);
94
+ const queue = new Int32Array(count);
95
+ const outletSet = new Set(outlets);
96
+ const offsets = [];
97
+ for (let dy = -1; dy <= 1; dy++) {
98
+ for (let dx = -1; dx <= 1; dx++) {
99
+ if (!dx && !dy) continue;
100
+ const distance = Math.hypot(
101
+ dx * columnStep[0] + dy * rowStep[0],
102
+ dx * columnStep[1] + dy * rowStep[1]
103
+ );
104
+ if (!(distance > 0 && Number.isFinite(distance)))
105
+ throw new RangeError('Invalid terrain neighbor distance');
106
+ offsets.push({dx, dy, distance});
107
+ }
108
+ }
109
+ for (let i = 0; i < count; i++) {
110
+ if (!validity[i]) continue;
111
+ contributingCells[i] = 1;
112
+ if (outletSet.has(i)) continue;
113
+ const col = i % width;
114
+ const row = Math.floor(i / width);
115
+ let steepest = 0;
116
+ for (const {dx, dy, distance} of offsets) {
117
+ if (col + dx < 0 || col + dx >= width || row + dy < 0 || row + dy >= height) continue;
118
+ const j = i + dx + dy * width;
119
+ if (!validity[j] || heights[j] >= heights[i]) continue;
120
+ if (dx && dy && (!validity[i + dx] || !validity[i + dy * width])) continue;
121
+ const slope = (heights[i] - heights[j]) / distance;
122
+ if (!Number.isFinite(slope) || slope === 0)
123
+ throw new RangeError('Terrain drainage slope is outside the representable range');
124
+ // Offsets visit neighbors in ascending row-major order.
125
+ if (slope > steepest) {
126
+ steepest = slope;
127
+ receiver[i] = j;
128
+ }
129
+ }
130
+ if (receiver[i] >= 0) incoming[receiver[i]]++;
131
+ }
132
+ let end = 0;
133
+ for (let i = 0; i < count; i++) if (validity[i] && !incoming[i]) queue[end++] = i;
134
+ // Strict descent makes the graph acyclic. Topological order permits one
135
+ // accumulation pass and one backward catchment pass without sorting heights.
136
+ for (let cursor = 0; cursor < end; cursor++) {
137
+ const i = queue[cursor];
138
+ const next = receiver[i];
139
+ if (next < 0) continue;
140
+ contributingCells[next] += contributingCells[i];
141
+ if (--incoming[next] === 0) queue[end++] = next;
142
+ }
143
+ for (let cursor = end - 1; cursor >= 0; cursor--) {
144
+ const i = queue[cursor];
145
+ const next = receiver[i];
146
+ terminal[i] = next < 0 ? i : terminal[next];
147
+ }
148
+ return {receiver, terminal, contributingCells, cellArea};
149
+ }
@@ -192,7 +192,12 @@ export {
192
192
  measureGeographicTerrainSeam,
193
193
  type TerrainGeographicProbe
194
194
  } from './geographic-seam';
195
- export {selectTerrainLod, type TerrainLodCandidate, type TerrainLodView} from './lod-select';
195
+ export {
196
+ selectTerrainLod,
197
+ type TerrainLodCandidate,
198
+ type TerrainLodCertifiedView,
199
+ type TerrainLodView
200
+ } from './lod-select';
196
201
  export {stitchTerrainLodCut, type TerrainLodSeam} from './lod-stitch';
197
202
 
198
203
  export {splitTerrainBreaklines} from './breakline-preprocess';
@@ -232,6 +237,7 @@ export {
232
237
  type TerrainPolytopeSweepResult
233
238
  } from './sweep-polytope';
234
239
 
240
+ export {sweepTerrainRotatingCapsule, sweepTerrainRotatingSphere} from './sweep-rotating-capsule';
235
241
  export {sweepTerrainCylinder} from './sweep-cylinder';
236
242
 
237
243
  export {sweepTerrainPlane} from './sweep-plane';
@@ -242,3 +248,57 @@ export {
242
248
  type TerrainPoleIncidence,
243
249
  type TerrainPoleCoverage
244
250
  } from './geographic-poles';
251
+
252
+ export {
253
+ sweepTerrainRotatingBox,
254
+ sweepTerrainRotatingPolytope,
255
+ type TerrainRigidMotion,
256
+ type TerrainRotationalSweepResult
257
+ } from './sweep-rotation';
258
+
259
+ export {
260
+ boundTerrainLodScreenError,
261
+ type TerrainLodErrorBounds,
262
+ type TerrainLodProjection
263
+ } from './lod-screen-error';
264
+
265
+ export {
266
+ createTerrainRegionalViewshed,
267
+ TerrainRegionalViewStatus,
268
+ type TerrainRegionalViewshed,
269
+ type TerrainRegionalViewshedOptions,
270
+ type TerrainViewshedGrid
271
+ } from './regional-viewshed';
272
+
273
+ export {
274
+ createTerrainDrainage,
275
+ getTerrainCellMetrics,
276
+ type TerrainCellMetrics,
277
+ type TerrainDrainage,
278
+ type TerrainDrainageOptions
279
+ } from './hydrology';
280
+
281
+ export {
282
+ fillTerrainDepressions,
283
+ type TerrainDepressionFill,
284
+ type TerrainDepressionFillOptions
285
+ } from './depression-fill';
286
+
287
+ export {
288
+ splitTerrainMesh,
289
+ type TerrainCutout,
290
+ type TerrainCutoutInput,
291
+ type TerrainCutoutOptions,
292
+ type TerrainCutoutPiece
293
+ } from './mesh-cutout';
294
+ export {
295
+ createTerrainCutoutSkirts,
296
+ type SkirtedTerrainCutout,
297
+ type TerrainCutoutSkirtOptions
298
+ } from './cutout-skirts';
299
+
300
+ export {
301
+ accumulateTerrainWatersheds,
302
+ type TerrainWatershedAccumulation,
303
+ type TerrainWatershedAccumulationOptions
304
+ } from './watershed-accumulation';