@math.gl/geospatial 5.0.0-beta.8 → 5.0.0-beta.9

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 (102) hide show
  1. package/dist/index.cjs +1354 -383
  2. package/dist/index.cjs.map +3 -3
  3. package/dist/index.d.ts +10 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +9 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/tasks/index.cjs +1135 -142
  8. package/dist/tasks/index.cjs.map +3 -3
  9. package/dist/tasks/index.d.ts +12 -0
  10. package/dist/tasks/index.d.ts.map +1 -1
  11. package/dist/tasks/index.js +26 -0
  12. package/dist/tasks/index.js.map +1 -1
  13. package/dist/tasks/terrain-coverage-worker.d.ts +2 -0
  14. package/dist/tasks/terrain-coverage-worker.d.ts.map +1 -0
  15. package/dist/tasks/terrain-coverage-worker.js +7 -0
  16. package/dist/tasks/terrain-coverage-worker.js.map +1 -0
  17. package/dist/tasks/terrain-coverage.d.ts +25 -0
  18. package/dist/tasks/terrain-coverage.d.ts.map +1 -0
  19. package/dist/tasks/terrain-coverage.js +15 -0
  20. package/dist/tasks/terrain-coverage.js.map +1 -0
  21. package/dist/tasks/terrain-residency-worker.d.ts +2 -0
  22. package/dist/tasks/terrain-residency-worker.d.ts.map +1 -0
  23. package/dist/tasks/terrain-residency-worker.js +7 -0
  24. package/dist/tasks/terrain-residency-worker.js.map +1 -0
  25. package/dist/tasks/terrain-residency.d.ts +64 -0
  26. package/dist/tasks/terrain-residency.d.ts.map +1 -0
  27. package/dist/tasks/terrain-residency.js +124 -0
  28. package/dist/tasks/terrain-residency.js.map +1 -0
  29. package/dist/terrain/breakline-mesh.d.ts +18 -0
  30. package/dist/terrain/breakline-mesh.d.ts.map +1 -0
  31. package/dist/terrain/breakline-mesh.js +126 -0
  32. package/dist/terrain/breakline-mesh.js.map +1 -0
  33. package/dist/terrain/breakline-preprocess.d.ts +11 -0
  34. package/dist/terrain/breakline-preprocess.d.ts.map +1 -0
  35. package/dist/terrain/breakline-preprocess.js +94 -0
  36. package/dist/terrain/breakline-preprocess.js.map +1 -0
  37. package/dist/terrain/continuous-mesh-error.d.ts +34 -0
  38. package/dist/terrain/continuous-mesh-error.d.ts.map +1 -0
  39. package/dist/terrain/continuous-mesh-error.js +221 -0
  40. package/dist/terrain/continuous-mesh-error.js.map +1 -0
  41. package/dist/terrain/geographic-seam.d.ts +21 -0
  42. package/dist/terrain/geographic-seam.d.ts.map +1 -0
  43. package/dist/terrain/geographic-seam.js +52 -0
  44. package/dist/terrain/geographic-seam.js.map +1 -0
  45. package/dist/terrain/index.cjs +1104 -133
  46. package/dist/terrain/index.cjs.map +3 -3
  47. package/dist/terrain/index.d.ts +10 -0
  48. package/dist/terrain/index.d.ts.map +1 -1
  49. package/dist/terrain/index.js +9 -0
  50. package/dist/terrain/index.js.map +1 -1
  51. package/dist/terrain/lod-select.d.ts +32 -0
  52. package/dist/terrain/lod-select.d.ts.map +1 -0
  53. package/dist/terrain/lod-select.js +60 -0
  54. package/dist/terrain/lod-select.js.map +1 -0
  55. package/dist/terrain/lod-stitch.d.ts +13 -0
  56. package/dist/terrain/lod-stitch.d.ts.map +1 -0
  57. package/dist/terrain/lod-stitch.js +49 -0
  58. package/dist/terrain/lod-stitch.js.map +1 -0
  59. package/dist/terrain/mesh-coverage.d.ts +35 -0
  60. package/dist/terrain/mesh-coverage.d.ts.map +1 -0
  61. package/dist/terrain/mesh-coverage.js +186 -0
  62. package/dist/terrain/mesh-coverage.js.map +1 -0
  63. package/dist/terrain/mesh-regions-data.d.ts +2 -2
  64. package/dist/terrain/mesh-regions-data.d.ts.map +1 -1
  65. package/dist/terrain/mesh-regions-data.js +20 -10
  66. package/dist/terrain/mesh-regions-data.js.map +1 -1
  67. package/dist/terrain/mixed-halo-update.d.ts.map +1 -1
  68. package/dist/terrain/mixed-halo-update.js +93 -16
  69. package/dist/terrain/mixed-halo-update.js.map +1 -1
  70. package/dist/terrain/mixed-vertex-halos.d.ts +11 -1
  71. package/dist/terrain/mixed-vertex-halos.d.ts.map +1 -1
  72. package/dist/terrain/mixed-vertex-halos.js +43 -5
  73. package/dist/terrain/mixed-vertex-halos.js.map +1 -1
  74. package/dist/terrain/valid-domain-mesh.d.ts +29 -0
  75. package/dist/terrain/valid-domain-mesh.d.ts.map +1 -0
  76. package/dist/terrain/valid-domain-mesh.js +183 -0
  77. package/dist/terrain/valid-domain-mesh.js.map +1 -0
  78. package/dist/terrain/valid-domain-regions.d.ts +16 -0
  79. package/dist/terrain/valid-domain-regions.d.ts.map +1 -0
  80. package/dist/terrain/valid-domain-regions.js +19 -0
  81. package/dist/terrain/valid-domain-regions.js.map +1 -0
  82. package/package.json +9 -8
  83. package/src/index.ts +43 -0
  84. package/src/tasks/index.ts +34 -0
  85. package/src/tasks/terrain-coverage-worker.ts +6 -0
  86. package/src/tasks/terrain-coverage.ts +25 -0
  87. package/src/tasks/terrain-residency-worker.ts +6 -0
  88. package/src/tasks/terrain-residency.ts +154 -0
  89. package/src/terrain/breakline-mesh.ts +164 -0
  90. package/src/terrain/breakline-preprocess.ts +106 -0
  91. package/src/terrain/cdt2d.d.ts +10 -0
  92. package/src/terrain/continuous-mesh-error.ts +321 -0
  93. package/src/terrain/geographic-seam.ts +73 -0
  94. package/src/terrain/index.ts +39 -0
  95. package/src/terrain/lod-select.ts +95 -0
  96. package/src/terrain/lod-stitch.ts +70 -0
  97. package/src/terrain/mesh-coverage.ts +215 -0
  98. package/src/terrain/mesh-regions-data.ts +21 -13
  99. package/src/terrain/mixed-halo-update.ts +105 -17
  100. package/src/terrain/mixed-vertex-halos.ts +58 -4
  101. package/src/terrain/valid-domain-mesh.ts +221 -0
  102. package/src/terrain/valid-domain-regions.ts +41 -0
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },
9
- "version": "5.0.0-beta.8",
9
+ "version": "5.0.0-beta.9",
10
10
  "keywords": [
11
11
  "webgl",
12
12
  "javascript",
@@ -1062,12 +1062,13 @@
1062
1062
  ],
1063
1063
  "dependencies": {
1064
1064
  "@mapbox/martini": "0.2.0",
1065
- "@math.gl/arrow": "5.0.0-beta.8",
1066
- "@math.gl/core": "5.0.0-beta.8",
1067
- "@math.gl/expressions": "5.0.0-beta.8",
1068
- "@math.gl/geometry": "5.0.0-beta.8",
1069
- "@math.gl/tasks": "5.0.0-beta.8",
1070
- "@math.gl/web-mercator": "5.0.0-beta.8",
1065
+ "@math.gl/arrow": "5.0.0-beta.9",
1066
+ "@math.gl/core": "5.0.0-beta.9",
1067
+ "@math.gl/expressions": "5.0.0-beta.9",
1068
+ "@math.gl/geometry": "5.0.0-beta.9",
1069
+ "@math.gl/tasks": "5.0.0-beta.9",
1070
+ "@math.gl/web-mercator": "5.0.0-beta.9",
1071
+ "cdt2d": "1.0.0",
1071
1072
  "polygon-clipping": "0.15.7"
1072
1073
  },
1073
1074
  "devDependencies": {
@@ -1079,5 +1080,5 @@
1079
1080
  "proj4": "2.22.0"
1080
1081
  },
1081
1082
  "sideEffects": false,
1082
- "gitHead": "9fa9ea96be8c49acbf16f31d0072f1d5357dddb0"
1083
+ "gitHead": "7d423f219d2971bb94a8d721690f837e92f4fe5e"
1083
1084
  }
package/src/index.ts CHANGED
@@ -363,3 +363,46 @@ export {coordinateTerrainLodMorphs} from './terrain/lod-coordinate';
363
363
  export {createTerrainMixedIsobands} from './terrain/isobands-mixed';
364
364
  export type {TerrainLodTile} from './terrain/lod-coordinate';
365
365
  export type {TerrainMixedSurface, TerrainMixedSurfaceOptions} from './terrain/mixed-surface';
366
+
367
+ export {
368
+ createValidDomainTerrainMesh,
369
+ type ValidDomainTerrainMesh,
370
+ type ValidDomainMeshOptions
371
+ } from './terrain/valid-domain-mesh';
372
+
373
+ export {
374
+ createBreaklineTerrainMesh,
375
+ type TerrainBreaklinePoint,
376
+ type TerrainBreakline,
377
+ type BreaklineTerrainMesh,
378
+ type BreaklineMeshOptions
379
+ } from './terrain/breakline-mesh';
380
+
381
+ export {
382
+ boundTerrainMeshError,
383
+ type TerrainContinuousMesh,
384
+ type TerrainContinuousError
385
+ } from './terrain/continuous-mesh-error';
386
+
387
+ export {
388
+ wrapTerrainLongitude,
389
+ measureGeographicTerrainSeam,
390
+ type TerrainGeographicProbe
391
+ } from './terrain/geographic-seam';
392
+ export {
393
+ selectTerrainLod,
394
+ type TerrainLodCandidate,
395
+ type TerrainLodView
396
+ } from './terrain/lod-select';
397
+ export {stitchTerrainLodCut, type TerrainLodSeam} from './terrain/lod-stitch';
398
+
399
+ export {splitTerrainBreaklines} from './terrain/breakline-preprocess';
400
+
401
+ export {
402
+ updateTerrainValidDomainMeshRegions,
403
+ type TerrainValidDomainMeshRegions,
404
+ type TerrainValidDomainRegionOptions
405
+ } from './terrain/valid-domain-regions';
406
+
407
+ export {certifyTerrainMeshCoverage} from './terrain/mesh-coverage';
408
+ export type {TerrainCoverageMesh, TerrainMeshCoverage} from './terrain/mesh-coverage';
@@ -2,6 +2,8 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
4
  import type {TaskWorker} from '@math.gl/tasks';
5
+ import {TerrainResidencyTask as residencyTask} from './terrain-residency';
6
+ import {CertifyTerrainCoverageTask as coverageTask} from './terrain-coverage';
5
7
  import {ProjectCoordinatesTask as projectionTask, PrepareMapTask as mapTask} from './definitions';
6
8
  export type {ProjectCoordinatesTypes, PrepareMapTypes} from './definitions';
7
9
  declare const __filename: string;
@@ -37,3 +39,35 @@ export const PrepareMapTask: typeof mapTask & {worker: TaskWorker} = {
37
39
  capabilities: {atomic: true, streaming: false}
38
40
  }
39
41
  };
42
+
43
+ export type {CertifyTerrainCoverageTypes} from './terrain-coverage';
44
+
45
+ /** Certify horizontal terrain coverage in an atomic task. */
46
+ export const CertifyTerrainCoverageTask: typeof coverageTask & {worker: TaskWorker} = {
47
+ ...coverageTask,
48
+ worker: {
49
+ ...(!isBrowser
50
+ ? {url: /* @__PURE__ */ (() => new URL('./terrain-coverage-worker.js', moduleUrl).href)()}
51
+ : {
52
+ create: () =>
53
+ new Worker(new URL('./terrain-coverage-worker.js', import.meta.url), {type: 'module'})
54
+ }),
55
+ capabilities: {atomic: true, streaming: false}
56
+ }
57
+ };
58
+
59
+ export type {TerrainResidencyEdit, TerrainResidencyTypes} from './terrain-residency';
60
+
61
+ /** Apply revisioned edit batches to one resident mixed halo snapshot per initialized worker. */
62
+ export const TerrainResidencyTask: typeof residencyTask & {worker: TaskWorker} = {
63
+ ...residencyTask,
64
+ worker: {
65
+ ...(!isBrowser
66
+ ? {url: /* @__PURE__ */ (() => new URL('./terrain-residency-worker.js', moduleUrl).href)()}
67
+ : {
68
+ create: () =>
69
+ new Worker(new URL('./terrain-residency-worker.js', import.meta.url), {type: 'module'})
70
+ }),
71
+ capabilities: {atomic: true, streaming: false}
72
+ }
73
+ };
@@ -0,0 +1,6 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import {initializeTaskWorker} from '@math.gl/tasks';
5
+ import {CertifyTerrainCoverageTask} from './terrain-coverage';
6
+ void initializeTaskWorker(CertifyTerrainCoverageTask);
@@ -0,0 +1,25 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {Task} from '@math.gl/tasks';
6
+ import type {HeightFieldProps} from '../terrain/types';
7
+ import type {TerrainCoverageMesh, TerrainMeshCoverage} from '../terrain/mesh-coverage';
8
+
9
+ export type CertifyTerrainCoverageTypes = {
10
+ input: {field: HeightFieldProps; mesh: TerrainCoverageMesh};
11
+ output: TerrainMeshCoverage;
12
+ options: {reference?: 'triangle' | 'bilinear' | TerrainCoverageMesh; maxTriangles?: number};
13
+ };
14
+
15
+ /** Certify coverage from serializable field and triangle buffers. */
16
+ export const CertifyTerrainCoverageTask = {
17
+ id: 'certify-terrain-coverage',
18
+ async process({field, mesh}, options) {
19
+ const [{HeightField}, {certifyTerrainMeshCoverage}] = await Promise.all([
20
+ import('../terrain/height-field'),
21
+ import('../terrain/mesh-coverage')
22
+ ]);
23
+ return certifyTerrainMeshCoverage(new HeightField(field), mesh, options);
24
+ }
25
+ } satisfies Task<CertifyTerrainCoverageTypes>;
@@ -0,0 +1,6 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import {initializeTaskWorker} from '@math.gl/tasks';
5
+ import {TerrainResidencyTask} from './terrain-residency';
6
+ void initializeTaskWorker(TerrainResidencyTask);
@@ -0,0 +1,154 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {Task} from '@math.gl/tasks';
6
+ import type {TerrainMixedHaloSnapshot} from '../terrain/mixed-halo-update';
7
+ import type {TerrainMixedVertexTile} from '../terrain/mixed-vertex-halos';
8
+
9
+ type TileAddress = Pick<TerrainMixedVertexTile, 'column' | 'row' | 'spacing'>;
10
+ type ResidentHalo = TerrainMixedHaloSnapshot['tiles'][number];
11
+ export type TerrainResidencyEdit =
12
+ | {type: 'upsert'; tile: TerrainMixedVertexTile}
13
+ | {type: 'remove'; address: TileAddress}
14
+ | {
15
+ type: 'samples';
16
+ address: TileAddress;
17
+ /** Row-major sample indices. Null marks nodata. */
18
+ samples: readonly {index: number; height: number | null}[];
19
+ };
20
+
21
+ export type TerrainResidencyTypes = {
22
+ initialization: {maxSamples?: number; maxTileTests?: number; maxDependencyTests?: number};
23
+ state: {
24
+ limits: TerrainResidencyTypes['initialization'];
25
+ snapshot: TerrainMixedHaloSnapshot | null;
26
+ revision: number;
27
+ };
28
+ input: {revision: number; edits: readonly TerrainResidencyEdit[]} | {type: 'snapshot'};
29
+ output: {revision: number; tiles: ResidentHalo[]; removed: string[]; error?: string};
30
+ };
31
+
32
+ const addressKey = ({spacing, column, row}: TileAddress) => `${spacing}/${column}/${row}`;
33
+
34
+ function sameArray(a: ArrayLike<number>, b: ArrayLike<number>): boolean {
35
+ if (a.length !== b.length) return false;
36
+ for (let i = 0; i < a.length; i++) if (!Object.is(a[i], b[i])) return false;
37
+ return true;
38
+ }
39
+
40
+ function sameHalo(a: ResidentHalo, b: ResidentHalo): boolean {
41
+ if (a === b) return true;
42
+ const af = a.field;
43
+ const bf = b.field;
44
+ const keys = Object.keys(af) as (keyof typeof af)[];
45
+ return (
46
+ keys.length === Object.keys(bf).length &&
47
+ keys.every(key => {
48
+ const left = af[key];
49
+ const right = bf[key];
50
+ if (typeof left === 'object' && typeof right === 'object') return sameArray(left, right);
51
+ return Object.prototype.hasOwnProperty.call(bf, key) && Object.is(left, right);
52
+ }) &&
53
+ sameArray(a.statuses, b.statuses)
54
+ );
55
+ }
56
+
57
+ /** Keep mixed halo sources and outputs resident across serialized edit batches. */
58
+ export const TerrainResidencyTask = {
59
+ id: 'terrain-residency',
60
+ initialize(limits): TerrainResidencyTypes['state'] {
61
+ return {limits: {...limits}, snapshot: null, revision: 0};
62
+ },
63
+ async process(input, _options, context): Promise<TerrainResidencyTypes['output']> {
64
+ const state = context.state;
65
+ if ('type' in input) {
66
+ if (input.type !== 'snapshot') throw new Error('Unknown terrain residency request');
67
+ return {
68
+ revision: state.revision,
69
+ tiles: structuredClone(state.snapshot?.tiles ?? []),
70
+ removed: []
71
+ };
72
+ }
73
+ try {
74
+ if (input.revision !== state.revision) throw new Error('Stale terrain residency revision');
75
+
76
+ const [{updateTerrainMixedVertexTileHalos}, {HeightField}] = await Promise.all([
77
+ import('../terrain/mixed-halo-update'),
78
+ import('../terrain/height-field')
79
+ ]);
80
+ context.throwIfAborted();
81
+ const sources = new Map(state.snapshot?.sources.map(tile => [addressKey(tile), tile]));
82
+ // Several edits to a tile in one batch share one private copy.
83
+ const writable = new Map<string, ReturnType<InstanceType<typeof HeightField>['copyData']>>();
84
+ for (const edit of input.edits) {
85
+ if (edit.type === 'upsert') {
86
+ const key = addressKey(edit.tile);
87
+ sources.set(key, structuredClone(edit.tile));
88
+ writable.delete(key);
89
+ continue;
90
+ }
91
+ const key = addressKey(edit.address);
92
+ if (edit.type === 'remove') {
93
+ sources.delete(key);
94
+ writable.delete(key);
95
+ continue;
96
+ }
97
+ if (edit.type !== 'samples') throw new Error('Unknown terrain residency edit');
98
+ const source = sources.get(key);
99
+ if (!source) throw new Error('Terrain sample edit requires a resident tile');
100
+ if (!edit.samples.length) continue;
101
+ let data = writable.get(key);
102
+ if (!data) {
103
+ const copied = new HeightField(source.field).copyData();
104
+ data = {heights: copied.heights, validity: copied.validity};
105
+ writable.set(key, data);
106
+ sources.set(key, {
107
+ ...source,
108
+ field: {...source.field, ...data, offset: 0, stride: source.field.width}
109
+ });
110
+ }
111
+ for (const {index, height} of edit.samples) {
112
+ if (
113
+ !Number.isSafeInteger(index) ||
114
+ index < 0 ||
115
+ index >= data.heights.length ||
116
+ (height !== null && !Number.isFinite(height))
117
+ ) {
118
+ throw new Error('Invalid terrain sample edit');
119
+ }
120
+ data.heights[index] = height ?? 0;
121
+ if (!Number.isFinite(data.heights[index]))
122
+ throw new Error('Terrain sample edit overflow');
123
+ data.validity[index] = height === null ? 0 : 1;
124
+ }
125
+ }
126
+ const next = updateTerrainMixedVertexTileHalos(
127
+ state.snapshot,
128
+ [...sources.values()],
129
+ state.limits
130
+ );
131
+ const old = new Map(state.snapshot?.tiles.map(tile => [addressKey(tile), tile]));
132
+ // Copy outgoing buffers so transfer cannot detach the resident snapshot.
133
+ const tiles = structuredClone(
134
+ next.tiles.filter(tile => {
135
+ const prior = old.get(addressKey(tile));
136
+ return !prior || !sameHalo(prior, tile);
137
+ })
138
+ );
139
+ context.throwIfAborted();
140
+ state.snapshot = next;
141
+ state.revision++;
142
+ return {revision: state.revision, tiles, removed: next.removed};
143
+ } catch (error) {
144
+ context.throwIfAborted();
145
+ // A rejected transaction preserves the initialized handle on both task transports.
146
+ return {
147
+ revision: state.revision,
148
+ tiles: [],
149
+ removed: [],
150
+ error: error instanceof Error ? error.message : String(error)
151
+ };
152
+ }
153
+ }
154
+ } satisfies Task<TerrainResidencyTypes>;
@@ -0,0 +1,164 @@
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
+ import {
7
+ meshValidDomain,
8
+ type Edge,
9
+ type ValidDomainMeshOptions,
10
+ type ValidDomainTerrainMesh
11
+ } from './valid-domain-mesh';
12
+
13
+ /** X and Y are fractional sample indices. Z is in the field's vertical reference. */
14
+ export type TerrainBreaklinePoint = readonly [number, number, number];
15
+ export type TerrainBreakline = readonly [TerrainBreaklinePoint, TerrainBreaklinePoint];
16
+
17
+ export type BreaklineMeshOptions = ValidDomainMeshOptions & {
18
+ breaklines: readonly TerrainBreakline[];
19
+ /** Let a line override source samples that lie exactly on it. Defaults to false. */
20
+ breaklinesOverrideSamples?: boolean;
21
+ };
22
+
23
+ export type BreaklineTerrainMesh = ValidDomainTerrainMesh & {
24
+ /** Packed vertex pairs, one pair per input segment in input order. */
25
+ breaklineEdges: Uint32Array;
26
+ overriddenSamples: number;
27
+ };
28
+
29
+ type XY = readonly [number, number];
30
+ const cross = (a: XY, b: XY, c: XY) =>
31
+ (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
32
+ const onSegment = (a: XY, b: XY, p: XY) =>
33
+ Math.abs(cross(a, b, p)) <=
34
+ 8 *
35
+ Number.EPSILON *
36
+ (Math.abs((b[0] - a[0]) * (p[1] - a[1])) + Math.abs((b[1] - a[1]) * (p[0] - a[0]))) &&
37
+ p[0] >= Math.min(a[0], b[0]) &&
38
+ p[0] <= Math.max(a[0], b[0]) &&
39
+ p[1] >= Math.min(a[1], b[1]) &&
40
+ p[1] <= Math.max(a[1], b[1]);
41
+
42
+ /** Mesh a valid raster domain with noncrossing, piecewise-linear XYZ constraints. */
43
+ export function createBreaklineTerrainMesh(
44
+ field: HeightField,
45
+ options: BreaklineMeshOptions
46
+ ): BreaklineTerrainMesh {
47
+ const breaklineEdges: Edge[] = [];
48
+ let overriddenSamples = 0;
49
+ const mesh = meshValidDomain(field, options, (points, heights, boundary, selected, originZ) => {
50
+ const ids = new Map(points.map(([x, y], i) => [`${x},${y}`, i]));
51
+ const fixed = new Map<number, number>();
52
+ const excluded = new Set<number>();
53
+ const fixedSamples = new Set<number>();
54
+
55
+ const add = ([x, y, z]: TerrainBreaklinePoint): number => {
56
+ if (
57
+ ![x, y, z, z - originZ].every(Number.isFinite) ||
58
+ x < 0 ||
59
+ y < 0 ||
60
+ x > field.width - 1 ||
61
+ y > field.height - 1
62
+ ) {
63
+ throw new Error('Breakline endpoint is outside the sample rectangle or nonfinite');
64
+ }
65
+ const key = `${x},${y}`;
66
+ const id = ids.get(key) ?? points.length;
67
+ if (fixed.has(id) && fixed.get(id) !== z) throw new Error('Conflicting breakline heights');
68
+ if (!ids.has(key)) {
69
+ points.push([x, y]);
70
+ ids.set(key, id);
71
+ }
72
+ fixed.set(id, z);
73
+ heights[id] = z - originZ;
74
+ if (Number.isInteger(x) && Number.isInteger(y)) selected[y * field.width + x] = id;
75
+ return id;
76
+ };
77
+ if (options.breaklines.length > 2048) throw new Error('Breakline limit exceeded');
78
+ for (const [a, b] of options.breaklines) {
79
+ const p = add(a),
80
+ q = add(b);
81
+ if (p === q) throw new Error('Zero-length breakline');
82
+ breaklineEdges.push([p, q]);
83
+ }
84
+ const edges: Edge[] = [];
85
+ for (const [a, b] of boundary) {
86
+ const split = [
87
+ a,
88
+ ...Array.from(fixed.keys()).filter(
89
+ id => id !== a && id !== b && onSegment(points[a], points[b], points[id])
90
+ ),
91
+ b
92
+ ];
93
+ const [x, y] = points[a];
94
+ split.sort(
95
+ (i, j) =>
96
+ Math.hypot(points[i][0] - x, points[i][1] - y) -
97
+ Math.hypot(points[j][0] - x, points[j][1] - y)
98
+ );
99
+ for (let i = 1; i < split.length; i++) edges.push([split[i - 1], split[i]]);
100
+ }
101
+ const seen = new Set<string>();
102
+ for (const [a, b] of breaklineEdges) {
103
+ const key = `${Math.min(a, b)},${Math.max(a, b)}`;
104
+ if (seen.has(key)) throw new Error('Duplicate breakline');
105
+ seen.add(key);
106
+ const p = points[a],
107
+ q = points[b];
108
+ let coincident = false;
109
+ for (const [c, d] of edges) {
110
+ if ((a === c && b === d) || (a === d && b === c)) {
111
+ coincident = true;
112
+ continue;
113
+ }
114
+ const r = points[c],
115
+ s = points[d];
116
+ const intersects =
117
+ Math.sign(cross(p, q, r)) * Math.sign(cross(p, q, s)) < 0 &&
118
+ Math.sign(cross(r, s, p)) * Math.sign(cross(r, s, q)) < 0;
119
+ if (
120
+ intersects ||
121
+ (c !== a && c !== b && onSegment(p, q, r)) ||
122
+ (d !== a && d !== b && onSegment(p, q, s)) ||
123
+ (a !== c && a !== d && onSegment(r, s, p)) ||
124
+ (b !== c && b !== d && onSegment(r, s, q))
125
+ ) {
126
+ throw new Error('Breaklines and domain edges must meet only at shared endpoints');
127
+ }
128
+ }
129
+ if (!coincident) edges.push([a, b]);
130
+ for (let y = Math.ceil(Math.min(p[1], q[1])); y <= Math.floor(Math.max(p[1], q[1])); y++) {
131
+ for (let x = Math.ceil(Math.min(p[0], q[0])); x <= Math.floor(Math.max(p[0], q[0])); x++) {
132
+ const source = field.getHeight(x, y);
133
+ if (source === undefined || !onSegment(p, q, [x, y])) continue;
134
+ fixedSamples.add(y * field.width + x);
135
+
136
+ const dx = q[0] - p[0],
137
+ dy = q[1] - p[1];
138
+ const f = Math.abs(dx) >= Math.abs(dy) ? (x - p[0]) / dx : (y - p[1]) / dy;
139
+ const z = (1 - f) * heights[a] + f * heights[b] + originZ;
140
+ if (Math.abs(source - z) <= options.maxError) continue;
141
+ if (!options.breaklinesOverrideSamples)
142
+ throw new Error('Breakline conflicts with source tolerance');
143
+ excluded.add(y * field.width + x);
144
+ }
145
+ }
146
+ }
147
+ // Samples on constraints are already represented by the linear constraint.
148
+ // Prevent refinement from introducing T-junctions through roundoff.
149
+ overriddenSamples = excluded.size;
150
+ return {edges, excluded, fixedSamples};
151
+ });
152
+ const edges = new Set<string>();
153
+ for (let i = 0; i < mesh.indices.length; i += 3) {
154
+ for (let j = 0; j < 3; j++) {
155
+ const a = mesh.indices[i + j],
156
+ b = mesh.indices[i + ((j + 1) % 3)];
157
+ edges.add(`${Math.min(a, b)},${Math.max(a, b)}`);
158
+ }
159
+ }
160
+ if (breaklineEdges.some(([a, b]) => !edges.has(`${Math.min(a, b)},${Math.max(a, b)}`))) {
161
+ throw new Error('Breakline was not preserved inside the valid terrain domain');
162
+ }
163
+ return {...mesh, breaklineEdges: Uint32Array.from(breaklineEdges.flat()), overriddenSamples};
164
+ }
@@ -0,0 +1,106 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {TerrainBreakline, TerrainBreaklinePoint} from './breakline-mesh';
5
+
6
+ /** Split a set of XYZ constraints at crossings and T-junctions. */
7
+ export function splitTerrainBreaklines(
8
+ input: readonly TerrainBreakline[],
9
+ options: {heightTolerance?: number; maxPairTests?: number; maxSegments?: number} = {}
10
+ ): {segments: TerrainBreakline[]; sourceSegments: Uint32Array} {
11
+ const {heightTolerance = 1e-8, maxPairTests = 2_100_000, maxSegments = 2048} = options;
12
+ if (
13
+ !Number.isFinite(heightTolerance) ||
14
+ heightTolerance < 0 ||
15
+ ![maxPairTests, maxSegments].every(n => Number.isSafeInteger(n) && n >= 0 && n <= 0xffffffff)
16
+ )
17
+ throw new Error('Invalid breakline split limits');
18
+ if (input.length > maxSegments || (input.length * (input.length - 1)) / 2 > maxPairTests)
19
+ throw new Error('Breakline preprocessing work limit exceeded');
20
+ type Knot = {t: number; point: TerrainBreaklinePoint};
21
+ const vertices = new Map<string, TerrainBreaklinePoint>();
22
+ const canonical = (p: TerrainBreaklinePoint): TerrainBreaklinePoint => {
23
+ if (!p.every(Number.isFinite)) throw new Error('Invalid breakline vertex');
24
+ const key = `${p[0]},${p[1]}`;
25
+ const prior = vertices.get(key);
26
+ if (prior) {
27
+ if (Math.abs(prior[2] - p[2]) > heightTolerance)
28
+ throw new Error('Conflicting breakline heights');
29
+ return prior;
30
+ }
31
+ const point: TerrainBreaklinePoint = [...p];
32
+ vertices.set(key, point);
33
+ return point;
34
+ };
35
+ const lines = input.map(([a, b]) => {
36
+ const p = canonical(a),
37
+ q = canonical(b);
38
+ if (p === q) throw new Error('Zero-length breakline');
39
+ const knots: Knot[] = [
40
+ {t: 0, point: p},
41
+ {t: 1, point: q}
42
+ ];
43
+ return {p, q, dx: q[0] - p[0], dy: q[1] - p[1], knots};
44
+ });
45
+ let count = input.length;
46
+ const add = (knots: Knot[], t: number, point: TerrainBreaklinePoint) => {
47
+ if (knots.some(k => k.point === point)) return;
48
+ if (knots.some(k => k.t === t))
49
+ throw new Error('Unresolved coincident breakline intersections');
50
+ if (++count > maxSegments) throw new Error('Breakline output limit exceeded');
51
+ knots.push({t, point});
52
+ };
53
+ const cross = (ax: number, ay: number, bx: number, by: number) => ax * by - ay * bx;
54
+ for (let i = 0; i < lines.length; i++) {
55
+ const a = lines[i];
56
+ for (let j = i + 1; j < lines.length; j++) {
57
+ const b = lines[j];
58
+ const x = b.p[0] - a.p[0],
59
+ y = b.p[1] - a.p[1];
60
+ const det = cross(a.dx, a.dy, b.dx, b.dy);
61
+ const u = cross(x, y, a.dx, a.dy),
62
+ t = cross(x, y, b.dx, b.dy);
63
+ if (![det, u, t].every(Number.isFinite)) throw new Error('Breakline intersection overflow');
64
+ if (det === 0) {
65
+ if (u !== 0 || t !== 0) continue;
66
+ const axis = Math.abs(a.dx) >= Math.abs(a.dy) ? 0 : 1;
67
+ if (
68
+ Math.max(Math.min(a.p[axis], a.q[axis]), Math.min(b.p[axis], b.q[axis])) <
69
+ Math.min(Math.max(a.p[axis], a.q[axis]), Math.max(b.p[axis], b.q[axis]))
70
+ )
71
+ throw new Error('Overlapping collinear breaklines');
72
+ continue;
73
+ }
74
+ const fa = t / det,
75
+ fb = u / det;
76
+ if (fa < 0 || fa > 1 || fb < 0 || fb > 1) continue;
77
+ const za = (1 - fa) * a.p[2] + fa * a.q[2],
78
+ zb = (1 - fb) * b.p[2] + fb * b.q[2];
79
+ if (!Number.isFinite(za) || !Number.isFinite(zb) || Math.abs(za - zb) > heightTolerance)
80
+ throw new Error('Conflicting breakline heights at intersection');
81
+ const point = canonical(
82
+ fa === 0
83
+ ? a.p
84
+ : fa === 1
85
+ ? a.q
86
+ : fb === 0
87
+ ? b.p
88
+ : fb === 1
89
+ ? b.q
90
+ : [a.p[0] + fa * a.dx, a.p[1] + fa * a.dy, za]
91
+ );
92
+ add(a.knots, fa, point);
93
+ add(b.knots, fb, point);
94
+ }
95
+ }
96
+ const segments: TerrainBreakline[] = [];
97
+ const sourceSegments = new Uint32Array(count);
98
+ for (let i = 0; i < lines.length; i++) {
99
+ const knots = lines[i].knots.sort((a, b) => a.t - b.t);
100
+ for (let j = 1; j < knots.length; j++) {
101
+ sourceSegments[segments.length] = i;
102
+ segments.push([knots[j - 1].point, knots[j].point]);
103
+ }
104
+ }
105
+ return {segments, sourceSegments};
106
+ }
@@ -0,0 +1,10 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ declare module 'cdt2d' {
5
+ export default function triangulate(
6
+ points: [number, number][],
7
+ edges: [number, number][],
8
+ options?: {exterior?: boolean; delaunay?: boolean}
9
+ ): [number, number, number][];
10
+ }