@math.gl/geospatial 5.0.0 → 5.0.2

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 (164) hide show
  1. package/dist/coverage-simplification.d.ts +9 -0
  2. package/dist/coverage-simplification.d.ts.map +1 -0
  3. package/dist/coverage-simplification.js +167 -0
  4. package/dist/coverage-simplification.js.map +1 -0
  5. package/dist/line-network/build-line-network.d.ts +100 -0
  6. package/dist/line-network/build-line-network.d.ts.map +1 -0
  7. package/dist/line-network/build-line-network.js +766 -0
  8. package/dist/line-network/build-line-network.js.map +1 -0
  9. package/dist/line-network/line-network-routes.d.ts +53 -0
  10. package/dist/line-network/line-network-routes.d.ts.map +1 -0
  11. package/dist/line-network/line-network-routes.js +146 -0
  12. package/dist/line-network/line-network-routes.js.map +1 -0
  13. package/dist/line-network/line-network-weights.d.ts +11 -0
  14. package/dist/line-network/line-network-weights.d.ts.map +1 -0
  15. package/dist/line-network/line-network-weights.js +25 -0
  16. package/dist/line-network/line-network-weights.js.map +1 -0
  17. package/dist/line-network.cjs +850 -0
  18. package/dist/line-network.cjs.map +6 -0
  19. package/dist/line-network.d.ts +7 -0
  20. package/dist/line-network.d.ts.map +1 -0
  21. package/dist/line-network.js +7 -0
  22. package/dist/line-network.js.map +1 -0
  23. package/dist/line-simplification.d.ts +7 -0
  24. package/dist/line-simplification.d.ts.map +1 -1
  25. package/dist/line-simplification.js +4 -13
  26. package/dist/line-simplification.js.map +1 -1
  27. package/dist/linear-referencing.d.ts +3 -1
  28. package/dist/linear-referencing.d.ts.map +1 -1
  29. package/dist/linear-referencing.js +21 -33
  30. package/dist/linear-referencing.js.map +1 -1
  31. package/dist/measure-referencing.d.ts +16 -0
  32. package/dist/measure-referencing.d.ts.map +1 -0
  33. package/dist/measure-referencing.js +143 -0
  34. package/dist/measure-referencing.js.map +1 -0
  35. package/dist/polygon-simplification.d.ts +6 -0
  36. package/dist/polygon-simplification.d.ts.map +1 -0
  37. package/dist/polygon-simplification.js +111 -0
  38. package/dist/polygon-simplification.js.map +1 -0
  39. package/dist/route-editing.d.ts +10 -0
  40. package/dist/route-editing.d.ts.map +1 -0
  41. package/dist/route-editing.js +58 -0
  42. package/dist/route-editing.js.map +1 -0
  43. package/dist/spatial-box-clipping.d.ts +9 -0
  44. package/dist/spatial-box-clipping.d.ts.map +1 -0
  45. package/dist/spatial-box-clipping.js +123 -0
  46. package/dist/spatial-box-clipping.js.map +1 -0
  47. package/dist/spatial-dwithin.d.ts +19 -0
  48. package/dist/spatial-dwithin.d.ts.map +1 -0
  49. package/dist/spatial-dwithin.js +107 -0
  50. package/dist/spatial-dwithin.js.map +1 -0
  51. package/dist/spatial-hulls.d.ts +6 -0
  52. package/dist/spatial-hulls.d.ts.map +1 -0
  53. package/dist/spatial-hulls.js +176 -0
  54. package/dist/spatial-hulls.js.map +1 -0
  55. package/dist/spatial-line-intersection-result.d.ts +4 -0
  56. package/dist/spatial-line-intersection-result.d.ts.map +1 -0
  57. package/dist/spatial-line-intersection-result.js +79 -0
  58. package/dist/spatial-line-intersection-result.js.map +1 -0
  59. package/dist/spatial-line-polygon-intersection.d.ts +4 -0
  60. package/dist/spatial-line-polygon-intersection.d.ts.map +1 -0
  61. package/dist/spatial-line-polygon-intersection.js +130 -0
  62. package/dist/spatial-line-polygon-intersection.js.map +1 -0
  63. package/dist/spatial-planar-intersects.d.ts +1 -0
  64. package/dist/spatial-planar-intersects.d.ts.map +1 -1
  65. package/dist/spatial-planar-intersects.js +5 -37
  66. package/dist/spatial-planar-intersects.js.map +1 -1
  67. package/dist/spatial-planar.d.ts +9 -0
  68. package/dist/spatial-planar.d.ts.map +1 -1
  69. package/dist/spatial-planar.js +13 -1
  70. package/dist/spatial-planar.js.map +1 -1
  71. package/dist/spatial-polygon-overlay.d.ts +5 -0
  72. package/dist/spatial-polygon-overlay.d.ts.map +1 -0
  73. package/dist/spatial-polygon-overlay.js +23 -0
  74. package/dist/spatial-polygon-overlay.js.map +1 -0
  75. package/dist/spatial-sql.d.ts +15 -2
  76. package/dist/spatial-sql.d.ts.map +1 -1
  77. package/dist/spatial-sql.js +65 -13
  78. package/dist/spatial-sql.js.map +1 -1
  79. package/dist/spatial-subdivision.d.ts +9 -0
  80. package/dist/spatial-subdivision.d.ts.map +1 -0
  81. package/dist/spatial-subdivision.js +61 -0
  82. package/dist/spatial-subdivision.js.map +1 -0
  83. package/dist/spatial-touches.d.ts +11 -0
  84. package/dist/spatial-touches.d.ts.map +1 -0
  85. package/dist/spatial-touches.js +178 -0
  86. package/dist/spatial-touches.js.map +1 -0
  87. package/dist/st-coverage-functions.d.ts +11 -0
  88. package/dist/st-coverage-functions.d.ts.map +1 -0
  89. package/dist/st-coverage-functions.js +57 -0
  90. package/dist/st-coverage-functions.js.map +1 -0
  91. package/dist/st-functions.cjs +3279 -554
  92. package/dist/st-functions.cjs.map +3 -3
  93. package/dist/st-functions.d.ts +100 -2
  94. package/dist/st-functions.d.ts.map +1 -1
  95. package/dist/st-functions.js +239 -22
  96. package/dist/st-functions.js.map +1 -1
  97. package/dist/st-geodesic-functions.d.ts +41 -0
  98. package/dist/st-geodesic-functions.d.ts.map +1 -0
  99. package/dist/st-geodesic-functions.js +238 -0
  100. package/dist/st-geodesic-functions.js.map +1 -0
  101. package/dist/st-hull-functions.cjs +386 -0
  102. package/dist/st-hull-functions.cjs.map +6 -0
  103. package/dist/st-hull-functions.d.ts +17 -0
  104. package/dist/st-hull-functions.d.ts.map +1 -0
  105. package/dist/st-hull-functions.js +14 -0
  106. package/dist/st-hull-functions.js.map +1 -0
  107. package/dist/st-overlay-functions.cjs +668 -0
  108. package/dist/st-overlay-functions.cjs.map +6 -0
  109. package/dist/st-overlay-functions.d.ts +46 -0
  110. package/dist/st-overlay-functions.d.ts.map +1 -0
  111. package/dist/st-overlay-functions.js +248 -0
  112. package/dist/st-overlay-functions.js.map +1 -0
  113. package/dist/st-viewport-functions.cjs +481 -0
  114. package/dist/st-viewport-functions.cjs.map +6 -0
  115. package/dist/st-viewport-functions.d.ts +13 -0
  116. package/dist/st-viewport-functions.d.ts.map +1 -0
  117. package/dist/st-viewport-functions.js +81 -0
  118. package/dist/st-viewport-functions.js.map +1 -0
  119. package/dist/terrain/index.cjs +93 -20
  120. package/dist/terrain/index.cjs.map +3 -3
  121. package/dist/terrain/index.d.ts +1 -0
  122. package/dist/terrain/index.d.ts.map +1 -1
  123. package/dist/terrain/index.js +1 -0
  124. package/dist/terrain/index.js.map +1 -1
  125. package/dist/terrain/regional-watersheds.d.ts +44 -0
  126. package/dist/terrain/regional-watersheds.d.ts.map +1 -0
  127. package/dist/terrain/regional-watersheds.js +108 -0
  128. package/dist/terrain/regional-watersheds.js.map +1 -0
  129. package/dist/terrain/tile-cutout-update.d.ts.map +1 -1
  130. package/dist/terrain/tile-cutout-update.js +28 -22
  131. package/dist/terrain/tile-cutout-update.js.map +1 -1
  132. package/dist/turf-functions.cjs +16 -9
  133. package/dist/turf-functions.cjs.map +1 -1
  134. package/package.json +27 -6
  135. package/src/coverage-simplification.ts +215 -0
  136. package/src/line-network/build-line-network.ts +990 -0
  137. package/src/line-network/line-network-routes.ts +213 -0
  138. package/src/line-network/line-network-weights.ts +40 -0
  139. package/src/line-network.ts +29 -0
  140. package/src/line-simplification.ts +4 -16
  141. package/src/linear-referencing.ts +27 -40
  142. package/src/measure-referencing.ts +165 -0
  143. package/src/polygon-simplification.ts +146 -0
  144. package/src/route-editing.ts +107 -0
  145. package/src/spatial-box-clipping.ts +140 -0
  146. package/src/spatial-dwithin.ts +135 -0
  147. package/src/spatial-hulls.ts +203 -0
  148. package/src/spatial-line-intersection-result.ts +93 -0
  149. package/src/spatial-line-polygon-intersection.ts +152 -0
  150. package/src/spatial-planar-intersects.ts +10 -51
  151. package/src/spatial-planar.ts +20 -1
  152. package/src/spatial-polygon-overlay.ts +30 -0
  153. package/src/spatial-sql.ts +97 -13
  154. package/src/spatial-subdivision.ts +75 -0
  155. package/src/spatial-touches.ts +204 -0
  156. package/src/st-coverage-functions.ts +88 -0
  157. package/src/st-functions.ts +345 -26
  158. package/src/st-geodesic-functions.ts +313 -0
  159. package/src/st-hull-functions.ts +25 -0
  160. package/src/st-overlay-functions.ts +313 -0
  161. package/src/st-viewport-functions.ts +98 -0
  162. package/src/terrain/index.ts +7 -0
  163. package/src/terrain/regional-watersheds.ts +153 -0
  164. package/src/terrain/tile-cutout-update.ts +32 -26
@@ -0,0 +1,213 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import {visitPolylineSpan} from '@math.gl/geometry/polygon';
6
+ import type {LineNetwork, LineNetworkLines} from './build-line-network';
7
+
8
+ /** Predecessor of a source node or an unreachable node (the luma.gl shortest-path sentinel). */
9
+ export const NO_PREDECESSOR = 0xffffffff;
10
+
11
+ /** Compressed sparse row (CSR) adjacency of a line network. */
12
+ export type LineNetworkAdjacency = {
13
+ /** True when each edge is listed only from its source node. */
14
+ directed: boolean;
15
+ /** First slot of each node, followed by the slot count (`nodeCount + 1` values). */
16
+ offsets: Uint32Array;
17
+ /** Node at the other end of the edge in each slot. */
18
+ neighbors: Uint32Array;
19
+ /** Edge of each slot. */
20
+ edges: Uint32Array;
21
+ };
22
+
23
+ /** Options of `buildLineNetworkAdjacency`. */
24
+ export type LineNetworkAdjacencyOptions = {
25
+ /** List each edge from its source only. Default: false. */
26
+ directed?: boolean;
27
+ };
28
+
29
+ /**
30
+ * Builds a CSR adjacency. An undirected adjacency lists each edge from both end nodes; a
31
+ * directed adjacency lists it from its source node only. Slots of a node keep edge order.
32
+ */
33
+ export function buildLineNetworkAdjacency(
34
+ network: Pick<LineNetwork, 'nodeCount' | 'edgeCount' | 'edgeSource' | 'edgeTarget'>,
35
+ options: LineNetworkAdjacencyOptions = {}
36
+ ): LineNetworkAdjacency {
37
+ const directed = options.directed ?? false;
38
+ const {nodeCount, edgeCount, edgeSource, edgeTarget} = network;
39
+ const offsets = new Uint32Array(nodeCount + 1);
40
+ for (let e = 0; e < edgeCount; e++) {
41
+ offsets[edgeSource[e] + 1]++;
42
+ if (!directed) offsets[edgeTarget[e] + 1]++;
43
+ }
44
+ for (let n = 0; n < nodeCount; n++) offsets[n + 1] += offsets[n];
45
+ const cursor = offsets.slice(0, nodeCount);
46
+ const slotCount = directed ? edgeCount : edgeCount * 2;
47
+ const neighbors = new Uint32Array(slotCount);
48
+ const edges = new Uint32Array(slotCount);
49
+ for (let e = 0; e < edgeCount; e++) {
50
+ const s = edgeSource[e];
51
+ const t = edgeTarget[e];
52
+ neighbors[cursor[s]] = t;
53
+ edges[cursor[s]++] = e;
54
+ if (directed) continue;
55
+ neighbors[cursor[t]] = s;
56
+ edges[cursor[t]++] = e;
57
+ }
58
+ return {directed, offsets, neighbors, edges};
59
+ }
60
+
61
+ /** Optional predecessor conventions supplied by the solver. */
62
+ export type RoutePredecessorOptions = {
63
+ /** Sentinel for unreachable nodes. Defaults to the luma.gl sentinel. */
64
+ unreachable?: number;
65
+ /** Selected incoming edge ID per node, in the adjacency's edge numbering. */
66
+ predecessorEdges?: ArrayLike<number>;
67
+ };
68
+
69
+ /**
70
+ * Walks a predecessor array from `target` back to `source`. Returns the edges in travel order,
71
+ * an empty array when the target is the source, or null when the target is unreachable.
72
+ * Between a node and its predecessor it takes the edge of lowest weight (lowest id on a tie),
73
+ * which is the edge that a shortest-path search relaxes.
74
+ */
75
+ export function getRouteEdges(
76
+ adjacency: LineNetworkAdjacency,
77
+ edgeWeight: ArrayLike<number> | undefined,
78
+ predecessors: ArrayLike<number>,
79
+ source: number,
80
+ target: number,
81
+ options: RoutePredecessorOptions = {}
82
+ ): Uint32Array | null {
83
+ const unreachable = options.unreachable ?? NO_PREDECESSOR;
84
+ if (target === source) return new Uint32Array(0);
85
+ if (predecessors[target] === unreachable) return null;
86
+ const route: number[] = [];
87
+ const selectedEdges = options.predecessorEdges;
88
+ let node = target;
89
+ while (node !== source) {
90
+ const previous = predecessors[node];
91
+ if (
92
+ !Number.isInteger(previous) ||
93
+ previous === unreachable ||
94
+ previous < 0 ||
95
+ previous >= predecessors.length ||
96
+ route.length >= predecessors.length
97
+ )
98
+ return null;
99
+ let best = NO_PREDECESSOR;
100
+ // The slots of the predecessor list its out-edges in both a directed and an undirected adjacency.
101
+ for (let slot = adjacency.offsets[previous]; slot < adjacency.offsets[previous + 1]; slot++) {
102
+ if (adjacency.neighbors[slot] !== node) continue;
103
+ const edge = adjacency.edges[slot];
104
+ if (selectedEdges) {
105
+ if (edge !== selectedEdges[node]) continue;
106
+ best = edge;
107
+ break;
108
+ }
109
+ if (
110
+ best === NO_PREDECESSOR ||
111
+ (edgeWeight?.[edge] ?? 1) < (edgeWeight?.[best] ?? 1) ||
112
+ ((edgeWeight?.[edge] ?? 1) === (edgeWeight?.[best] ?? 1) && edge < best)
113
+ ) {
114
+ best = edge;
115
+ }
116
+ }
117
+ if (best === NO_PREDECESSOR) return null;
118
+ route.push(best);
119
+ node = previous;
120
+ }
121
+ return Uint32Array.from(route.reverse());
122
+ }
123
+
124
+ /** Number of points in the geometry of an edge. The first and last can be split points. */
125
+ export function getEdgePointCount(network: LineNetwork, edge: number): number {
126
+ const vertices = network.edgeVertexEnd[edge] - network.edgeVertexStart[edge] + 1;
127
+ return Math.max(
128
+ 1,
129
+ vertices -
130
+ Number(network.edgeStartFraction[edge] === 1) -
131
+ Number(network.edgeEndFraction[edge] === 0)
132
+ );
133
+ }
134
+
135
+ /**
136
+ * Writes the longitude, latitude geometry of an edge, in path direction, into `target` from
137
+ * value index `offset`. The first and last points follow the split fractions.
138
+ * @returns `target`, or a new array of `2 * getEdgePointCount(network, edge)` values.
139
+ */
140
+ export function getEdgeGeometry(
141
+ network: LineNetwork,
142
+ lines: LineNetworkLines,
143
+ edge: number,
144
+ target: Float64Array = new Float64Array(2 * getEdgePointCount(network, edge)),
145
+ offset: number = 0
146
+ ): Float64Array {
147
+ visitEdge(network, lines, edge, false, (x, y) => {
148
+ target[offset++] = x;
149
+ target[offset++] = y;
150
+ });
151
+ return target;
152
+ }
153
+
154
+ /**
155
+ * Concatenates the geometry of route edges into one flat longitude, latitude path from `source`.
156
+ * Each edge is reversed as needed. Where two edges meet at the same point, the point appears
157
+ * once. A joined dangling end gives a straight step to the split point of the next edge.
158
+ */
159
+ export function getRouteGeometry(
160
+ network: LineNetwork,
161
+ lines: LineNetworkLines,
162
+ route: ArrayLike<number>,
163
+ source: number
164
+ ): Float64Array {
165
+ let pointTotal = 0;
166
+ for (let i = 0; i < route.length; i++) pointTotal += getEdgePointCount(network, route[i]);
167
+ const path = new Float64Array(pointTotal * 2);
168
+ let at = 0;
169
+ let node = source;
170
+ for (let i = 0; i < route.length; i++) {
171
+ const e = route[i];
172
+ const forward = network.edgeSource[e] === node;
173
+ let first = true;
174
+ visitEdge(network, lines, e, !forward, (x, y) => {
175
+ if (!(first && at > 0 && x === path[at - 2] && y === path[at - 1])) {
176
+ path[at++] = x;
177
+ path[at++] = y;
178
+ }
179
+ first = false;
180
+ });
181
+ node = forward ? network.edgeTarget[e] : network.edgeSource[e];
182
+ }
183
+ return at === path.length ? path : path.slice(0, at);
184
+ }
185
+
186
+ /** Visits one edge span in travel order. */
187
+ function visitEdge(
188
+ network: LineNetwork,
189
+ lines: LineNetworkLines,
190
+ edge: number,
191
+ reverse: boolean,
192
+ visit: (x: number, y: number) => void
193
+ ): void {
194
+ const {value, size} = lines.positions;
195
+ const startFraction = network.edgeStartFraction[edge];
196
+ const endFraction = network.edgeEndFraction[edge];
197
+ const firstSegment = network.edgeVertexStart[edge] + Number(startFraction === 1);
198
+ const lastSegment = network.edgeVertexEnd[edge] - 1 - Number(endFraction === 0);
199
+ // A split coincident with a vertex is represented on its interior-facing segment.
200
+ if (firstSegment > lastSegment) {
201
+ visit(value[size * firstSegment], value[size * firstSegment + 1]);
202
+ return;
203
+ }
204
+ visitPolylineSpan(
205
+ (vertex, ordinate) => value[size * vertex + ordinate],
206
+ firstSegment,
207
+ startFraction === 1 ? 0 : startFraction,
208
+ lastSegment,
209
+ endFraction === 0 ? 1 : endFraction,
210
+ visit,
211
+ reverse
212
+ );
213
+ }
@@ -0,0 +1,40 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {LineNetwork, LineNetworkEdgeWeight} from './build-line-network';
6
+
7
+ /** Routing cost policy for a network whose topology has already been built. */
8
+ export type LineNetworkWeightOptions = {
9
+ /** Multiplier for each source path's physical edge lengths. */
10
+ pathWeightFactors?: ArrayLike<number>;
11
+ /** Computes the cost of each edge. Requires includePathFractions at build time. */
12
+ edgeWeight?: LineNetworkEdgeWeight;
13
+ };
14
+
15
+ /** Creates Float32 weights indexed by edge ID. Defaults to physical edge length. */
16
+ export function createLineNetworkWeights(
17
+ network: Pick<
18
+ LineNetwork,
19
+ 'edgePath' | 'edgeLength' | 'edgePathStartFraction' | 'edgePathEndFraction'
20
+ >,
21
+ {pathWeightFactors, edgeWeight}: LineNetworkWeightOptions = {}
22
+ ): Float32Array {
23
+ const {edgePath, edgeLength, edgePathStartFraction, edgePathEndFraction} = network;
24
+ if (pathWeightFactors && edgeWeight)
25
+ throw new Error('Specify pathWeightFactors or edgeWeight, not both');
26
+ if (edgeWeight && (!edgePathStartFraction || !edgePathEndFraction)) {
27
+ throw new Error('A custom edgeWeight requires includePathFractions');
28
+ }
29
+ const weights = new Float32Array(edgeLength.length);
30
+ for (let edge = 0; edge < weights.length; edge++) {
31
+ const path = edgePath[edge]!;
32
+ const length = edgeLength[edge]!;
33
+ const weight = edgeWeight
34
+ ? edgeWeight(path, edgePathStartFraction![edge]!, edgePathEndFraction![edge]!, length)
35
+ : length * (pathWeightFactors ? pathWeightFactors[path]! : 1);
36
+ if (!(weight >= 0)) throw new RangeError('Edge weights must be zero or positive');
37
+ weights[edge] = weight;
38
+ }
39
+ return weights;
40
+ }
@@ -0,0 +1,29 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ export {buildLineNetwork} from './line-network/build-line-network';
6
+ export type {
7
+ BuildLineNetworkOptions,
8
+ LineNetwork,
9
+ LineNetworkDistance,
10
+ LineNetworkEdgeWeight,
11
+ LineNetworkFixedSizeList,
12
+ LineNetworkLines
13
+ } from './line-network/build-line-network';
14
+ export {
15
+ NO_PREDECESSOR,
16
+ buildLineNetworkAdjacency,
17
+ getEdgeGeometry,
18
+ getEdgePointCount,
19
+ getRouteEdges,
20
+ getRouteGeometry
21
+ } from './line-network/line-network-routes';
22
+ export type {
23
+ LineNetworkAdjacency,
24
+ LineNetworkAdjacencyOptions,
25
+ RoutePredecessorOptions
26
+ } from './line-network/line-network-routes';
27
+
28
+ export {createLineNetworkWeights} from './line-network/line-network-weights';
29
+ export type {LineNetworkWeightOptions} from './line-network/line-network-weights';
@@ -3,6 +3,7 @@
3
3
  // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
4
 
5
5
  import type {WellKnownGeometry} from '@math.gl/core/arrow';
6
+ import {distanceToPlanarSegment} from './spatial-planar';
6
7
 
7
8
  /** One vertex in planar XY coordinates. */
8
9
  type Position = readonly number[];
@@ -25,21 +26,8 @@ function removeRepeated(path: Path, tolerance: number): Path {
25
26
  return kept;
26
27
  }
27
28
 
28
- /** Measures the distance to a finite segment, including its endpoints. */
29
- function distanceToSegment(p: Position, a: Position, b: Position): number {
30
- const dx = b[0]! - a[0]!,
31
- dy = b[1]! - a[1]!;
32
- const length = Math.hypot(dx, dy);
33
- const px = p[0]! - a[0]!,
34
- py = p[1]! - a[1]!;
35
- const t = length
36
- ? Math.max(0, Math.min(1, (px * (dx / length) + py * (dy / length)) / length))
37
- : 0;
38
- return Math.hypot(px - t * dx, py - t * dy);
39
- }
40
-
41
29
  /** Iterative Douglas-Peucker simplification of a single planar line. */
42
- function simplify(path: Path, tolerance: number): Path {
30
+ export function simplifyLine(path: Path, tolerance: number): Path {
43
31
  if (!path.length) return path;
44
32
  const last = path.length - 1;
45
33
  const kept = new Uint8Array(path.length);
@@ -51,7 +39,7 @@ function simplify(path: Path, tolerance: number): Path {
51
39
  let split = start,
52
40
  maximum = tolerance;
53
41
  for (let i = start + 1; i < end; i++) {
54
- const distance = distanceToSegment(path[i]!, path[start]!, path[end]!);
42
+ const distance = distanceToPlanarSegment(path[i]!, path[start]!, path[end]!);
55
43
  if (distance > maximum) {
56
44
  maximum = distance;
57
45
  split = i;
@@ -82,7 +70,7 @@ export function reduceLineVertices(
82
70
  (geometry.type === 'MultiLineString' && geometry.coordinates.every(path => !path.length)))
83
71
  )
84
72
  return geometry;
85
- const reduce = mode === 'simplify' ? simplify : removeRepeated;
73
+ const reduce = mode === 'simplify' ? simplifyLine : removeRepeated;
86
74
  if (geometry.type === 'LineString') {
87
75
  const coordinates = reduce(geometry.coordinates, tolerance);
88
76
  return coordinates.length || mode === 'removeRepeated'
@@ -3,6 +3,7 @@
3
3
  // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
4
 
5
5
  import type {WellKnownGeometry} from '@math.gl/core/arrow';
6
+ import {projectPointToPolyline, visitPolylineSpan} from '@math.gl/geometry/polygon';
6
7
 
7
8
  /** Ordered planar XY coordinates of a route. */
8
9
 
@@ -47,48 +48,34 @@ export function lineSubstring(
47
48
  const total = distances[distances.length - 1]!;
48
49
  const from = start * total,
49
50
  to = end * total;
50
- const first = coordinateAt(path, distances, from);
51
- if (from === to) return {type: 'Point', coordinates: first};
52
- const coordinates = [first];
53
- for (let i = 1; i < path.length - 1; i++) {
54
- if (distances[i]! > from && distances[i]! < to && distances[i] !== distances[i - 1])
55
- coordinates.push(path[i]!);
56
- }
57
- coordinates.push(coordinateAt(path, distances, to));
51
+ if (from === to) return {type: 'Point', coordinates: coordinateAt(path, distances, from)};
52
+ const coordinates: number[][] = [];
53
+ let startSegment = 0;
54
+ while (distances[startSegment + 1]! <= from) startSegment++;
55
+ let endSegment = startSegment;
56
+ while (distances[endSegment + 1]! < to) endSegment++;
57
+ visitPolylineSpan(
58
+ (vertex, ordinate) => path[vertex]![ordinate]!,
59
+ startSegment,
60
+ (from - distances[startSegment]!) / (distances[startSegment + 1]! - distances[startSegment]!),
61
+ endSegment,
62
+ (to - distances[endSegment]!) / (distances[endSegment + 1]! - distances[endSegment]!),
63
+ (x, y, vertex) => {
64
+ if (vertex === undefined || distances[vertex] !== distances[vertex - 1])
65
+ coordinates.push([x, y]);
66
+ }
67
+ );
58
68
  return {type: 'LineString', coordinates};
59
69
  }
60
70
 
61
- /** Projects a point onto the nearest route segment and returns fractional planar distance. */
71
+ /** Projects a SQL point onto a planar route after checking geometry kinds. */
72
+ export function projectPointToLine(line: WellKnownGeometry, point: WellKnownGeometry) {
73
+ return line.type === 'LineString' && point.type === 'Point'
74
+ ? projectPointToPolyline(line.coordinates, point.coordinates)
75
+ : null;
76
+ }
77
+
78
+ /** Returns the fraction of the route length at the projected point. */
62
79
  export function lineLocatePoint(line: WellKnownGeometry, point: WellKnownGeometry): number | null {
63
- if (
64
- line.type !== 'LineString' ||
65
- !line.coordinates.length ||
66
- point.type !== 'Point' ||
67
- !Number.isFinite(point.coordinates[0]) ||
68
- !Number.isFinite(point.coordinates[1])
69
- )
70
- return null;
71
- const path = line.coordinates,
72
- [x, y] = point.coordinates;
73
- let total = 0,
74
- nearest = Infinity,
75
- position = 0;
76
- for (let i = 1; i < path.length; i++) {
77
- const a = path[i - 1]!,
78
- b = path[i]!;
79
- const dx = b[0]! - a[0]!,
80
- dy = b[1]! - a[1]!;
81
- const length = Math.hypot(dx, dy);
82
- if (!length) continue;
83
- const ux = dx / length,
84
- uy = dy / length;
85
- const along = Math.max(0, Math.min(length, (x! - a[0]!) * ux + (y! - a[1]!) * uy));
86
- const distance = Math.hypot(x! - (a[0]! + along * ux), y! - (a[1]! + along * uy));
87
- if (distance < nearest) {
88
- nearest = distance;
89
- position = total + along;
90
- }
91
- total += length;
92
- }
93
- return total ? position / total : 0;
80
+ return projectPointToLine(line, point)?.fraction ?? null;
94
81
  }
@@ -0,0 +1,165 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {WellKnownDimension, WellKnownGeometry} from '@math.gl/core/arrow';
6
+
7
+ /** Vertex coordinates in the input geometry's declared dimension. */
8
+ type Position = readonly number[];
9
+ /** Ordered coordinates for one independent route component. */
10
+ type Path = readonly Position[];
11
+ /** Dimensions with a semantic measure ordinate. */
12
+ type MeasuredDimension = 'xym' | 'xyzm';
13
+
14
+ /** Extracts the paths of a linear geometry without connecting multipart gaps. */
15
+ function pathsOf(geometry: WellKnownGeometry): readonly Path[] {
16
+ if (geometry.type === 'LineString') return [geometry.coordinates];
17
+ if (geometry.type === 'MultiLineString') return geometry.coordinates;
18
+ throw new Error('Measured routes require a LineString or MultiLineString');
19
+ }
20
+
21
+ /** Returns the measure dimension or rejects unmeasured linework. */
22
+ export function measuredDimension(dimension: WellKnownDimension): MeasuredDimension {
23
+ if (dimension === 'xym' || dimension === 'xyzm') return dimension;
24
+ throw new Error('Input geometry requires a measure (M) ordinate');
25
+ }
26
+
27
+ /** Assigns measures by accumulated XY path length, retaining any Z ordinate. */
28
+ export function addMeasure(
29
+ geometry: WellKnownGeometry,
30
+ dimension: WellKnownDimension,
31
+ start: number,
32
+ end: number
33
+ ): {geometry: WellKnownGeometry; dimension: MeasuredDimension} {
34
+ if (!Number.isFinite(start) || !Number.isFinite(end)) throw new Error('Expected finite measures');
35
+ const paths = pathsOf(geometry);
36
+ let total = 0;
37
+ const distances = paths.map(path =>
38
+ path.map((point, i) => {
39
+ if (i > 0) {
40
+ const previous = path[i - 1]!;
41
+ total += Math.hypot(point[0]! - previous[0]!, point[1]! - previous[1]!);
42
+ }
43
+ return total;
44
+ })
45
+ );
46
+ if (!Number.isFinite(total)) throw new Error('Expected finite route length');
47
+ const spatialSize = dimension.includes('z') ? 3 : 2;
48
+ const coordinates = paths.map((path, part) =>
49
+ path.map((point, i) => {
50
+ const fraction = total ? distances[part]![i]! / total : 0;
51
+ return [...point.slice(0, spatialSize), (1 - fraction) * start + fraction * end];
52
+ })
53
+ );
54
+ return {
55
+ geometry:
56
+ geometry.type === 'LineString'
57
+ ? {type: 'LineString', coordinates: coordinates[0]!}
58
+ : {type: 'MultiLineString', coordinates},
59
+ dimension: spatialSize === 3 ? 'xyzm' : 'xym'
60
+ };
61
+ }
62
+
63
+ /** Tests equality of every ordinate, including dimensions other than XY. */
64
+ function samePosition(a: Position, b: Position): boolean {
65
+ return a.every((value, i) => value === b[i]);
66
+ }
67
+
68
+ /** Interpolates XY and optional Z while setting M exactly to the requested value. */
69
+ function atMeasure(a: Position, b: Position, index: number, measure: number): Position {
70
+ const from = a[index]!;
71
+ const to = b[index]!;
72
+ if (from !== to) {
73
+ if (measure === from) return a;
74
+ if (measure === to) return b;
75
+ }
76
+ const span = to - from;
77
+ const fraction =
78
+ span === 0
79
+ ? 0.5
80
+ : Number.isFinite(span)
81
+ ? (measure - from) / span
82
+ : (measure / 2 - from / 2) / (to / 2 - from / 2);
83
+ return a.map((value, i) => (i === index ? measure : (1 - fraction) * value + fraction * b[i]!));
84
+ }
85
+
86
+ /** Reads the measure ordinate and rejects invalid measured vertices. */
87
+ function measureAt(position: Position, index: number): number {
88
+ const value = position[index]!;
89
+ if (!Number.isFinite(value)) throw new Error('Expected finite route measures');
90
+ return value;
91
+ }
92
+
93
+ /** Finds each matching location. Constant-measure segments contribute their midpoint. */
94
+ export function locateAlong(
95
+ geometry: WellKnownGeometry,
96
+ dimension: MeasuredDimension,
97
+ measure: number
98
+ ): WellKnownGeometry {
99
+ if (!Number.isFinite(measure)) throw new Error('Expected a finite measure');
100
+ const index = dimension.indexOf('m');
101
+ const coordinates: Position[] = [];
102
+ for (const path of pathsOf(geometry)) {
103
+ let previousEndsAtVertex = false;
104
+ for (let i = 1; i < path.length; i++) {
105
+ const a = path[i - 1]!;
106
+ const b = path[i]!;
107
+ const from = measureAt(a, index);
108
+ const to = measureAt(b, index);
109
+ if (measure < Math.min(from, to) || measure > Math.max(from, to)) {
110
+ previousEndsAtVertex = false;
111
+ continue;
112
+ }
113
+ const startsAtVertex = from !== to && measure === from;
114
+ if (!previousEndsAtVertex || !startsAtVertex) {
115
+ coordinates.push(atMeasure(a, b, index, measure));
116
+ }
117
+ previousEndsAtVertex = from !== to && measure === to;
118
+ }
119
+ }
120
+ return {type: 'MultiPoint', coordinates};
121
+ }
122
+
123
+ /** Appends a clipped point or line when a contiguous portion is complete. */
124
+ function appendPortion(parts: WellKnownGeometry[], path: Position[]): void {
125
+ if (path.length === 1) parts.push({type: 'Point', coordinates: path[0]!});
126
+ else if (path.length > 1) parts.push({type: 'LineString', coordinates: path});
127
+ }
128
+
129
+ /** Clips each component in measure space, preserving direction and disjoint visits. */
130
+ export function locateBetween(
131
+ geometry: WellKnownGeometry,
132
+ dimension: MeasuredDimension,
133
+ start: number,
134
+ end: number
135
+ ): WellKnownGeometry {
136
+ if (!Number.isFinite(start) || !Number.isFinite(end)) throw new Error('Expected finite measures');
137
+ const low = Math.min(start, end);
138
+ const high = Math.max(start, end);
139
+ const index = dimension.indexOf('m');
140
+ const parts: WellKnownGeometry[] = [];
141
+ for (const path of pathsOf(geometry)) {
142
+ let portion: Position[] = [];
143
+ for (let i = 1; i < path.length; i++) {
144
+ const a = path[i - 1]!;
145
+ const b = path[i]!;
146
+ const from = measureAt(a, index);
147
+ const to = measureAt(b, index);
148
+ const begin = Math.max(low, Math.min(from, to));
149
+ const finish = Math.min(high, Math.max(from, to));
150
+ if (begin > finish) continue;
151
+ const first = from === to ? a : atMeasure(a, b, index, from <= to ? begin : finish);
152
+ const last = from === to ? b : atMeasure(a, b, index, from <= to ? finish : begin);
153
+ if (!portion.length) portion.push(first);
154
+ if (!samePosition(portion[portion.length - 1]!, last)) portion.push(last);
155
+ if (to < low || to > high) {
156
+ appendPortion(parts, portion);
157
+ portion = [];
158
+ }
159
+ }
160
+ appendPortion(parts, portion);
161
+ }
162
+ return parts.every(part => part.type === 'LineString')
163
+ ? {type: 'MultiLineString', coordinates: parts.map(part => part.coordinates)}
164
+ : {type: 'GeometryCollection', geometries: parts};
165
+ }