@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,313 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import {Bool, Float64} from 'apache-arrow';
6
+ import type {WellKnownGeometry} from '@math.gl/core/arrow';
7
+ import {WGS84_RADIUS_X, WGS84_RADIUS_Z} from './constants';
8
+ import {normalizeCRSIdentifier} from './crs/crs-identifier';
9
+ import {EllipsoidGeodesic, type GeodesicLine} from './ellipsoid-geodesic';
10
+ import {lineKinds, spatialFunction} from './spatial-sql';
11
+ import type {PolylineSegment} from '@math.gl/geometry/polygon';
12
+ import {segmentizeFunction} from './route-editing';
13
+
14
+ /** Ellipsoidal kernel with axes expressed in meters, initialized when first used. */
15
+ let kernel: EllipsoidGeodesic | undefined;
16
+
17
+ /** Reuses one WGS84 ellipsoid for all rows and segments. */
18
+ function getKernel(): EllipsoidGeodesic {
19
+ kernel ??= new EllipsoidGeodesic({
20
+ semiMajorAxis: WGS84_RADIUS_X,
21
+ semiMinorAxis: WGS84_RADIUS_Z
22
+ });
23
+ return kernel;
24
+ }
25
+
26
+ /** Measures the shortest WGS84 geodesic between two longitude–latitude positions. */
27
+ function meters(a: readonly number[], b: readonly number[]): number {
28
+ return getKernel().inverse(a[1]!, a[0]!, b[1]!, b[0]!).s12;
29
+ }
30
+
31
+ /** Tests the coordinate representation of an empty point. */
32
+ function emptyPoint(coordinate: readonly number[]): boolean {
33
+ return !coordinate.length || coordinate.every(Number.isNaN);
34
+ }
35
+
36
+ /** Point families supported by the geodesic distance predicates. */
37
+ const pointSetKinds = ['Point', 'MultiPoint'] as const;
38
+
39
+ /** Returns the points in one geometry without copying its coordinate buffers. */
40
+ function pointSet(geometry: WellKnownGeometry): readonly (readonly number[])[] {
41
+ if (geometry.type === 'Point') return [geometry.coordinates];
42
+ if (geometry.type === 'MultiPoint') return geometry.coordinates;
43
+ throw new Error('Expected Point or MultiPoint');
44
+ }
45
+
46
+ /** Finds the minimum pair distance, stopping once a requested threshold is reached. */
47
+ function pointSetDistance(a: WellKnownGeometry, b: WellKnownGeometry, stopAt = 0): number | null {
48
+ const left = pointSet(a);
49
+ const points = pointSet(b);
50
+ const right = points.some(emptyPoint) ? points.filter(point => !emptyPoint(point)) : points;
51
+ let minimum = Infinity;
52
+ for (const x of left) {
53
+ if (emptyPoint(x)) continue;
54
+ for (const y of right) {
55
+ const distance = meters(x, y);
56
+ if (distance <= stopAt) return distance;
57
+ minimum = Math.min(minimum, distance);
58
+ }
59
+ }
60
+ return minimum === Infinity ? null : minimum;
61
+ }
62
+
63
+ /** Narrows the geometry to a point or MultiPoint. */
64
+ function isPointSet(geometry: WellKnownGeometry): boolean {
65
+ return geometry.type === 'Point' || geometry.type === 'MultiPoint';
66
+ }
67
+
68
+ /** Linear paths, with no implicit connecting segment between parts. */
69
+ function paths(geometry: WellKnownGeometry): readonly (readonly (readonly number[])[])[] {
70
+ if (geometry.type === 'LineString') return [geometry.coordinates];
71
+ if (geometry.type === 'MultiLineString') return geometry.coordinates;
72
+ throw new Error('Expected geodesic line geometry');
73
+ }
74
+
75
+ /** Measures linear components without adding a segment between components. */
76
+ function lineLength(geometry: WellKnownGeometry): number {
77
+ let length = 0;
78
+ for (const path of paths(geometry))
79
+ for (let index = 1; index < path.length; index++)
80
+ length += meters(path[index - 1]!, path[index]!);
81
+ return length;
82
+ }
83
+
84
+ /** Search the interiors of long geodesics in intervals of at most 1,000 km. */
85
+ const MAX_SEARCH_INTERVAL = 1_000_000;
86
+ /** Along-track termination tolerance, in meters. */
87
+ const SEARCH_TOLERANCE = 1e-7;
88
+ /** Interior sampling ratio for a golden-section search. */
89
+
90
+ const GOLDEN_RATIO = (Math.sqrt(5) - 1) / 2;
91
+
92
+ /** Takes one inverse measurement after evaluating a position on the cached geodesic. */
93
+ function distanceAt(line: GeodesicLine, offset: number, point: readonly number[]): number {
94
+ const position = line.position(offset);
95
+ return getKernel().inverse(position.lat2, position.lon2, point[1]!, point[0]!).s12;
96
+ }
97
+
98
+ /** Finds a local minimum without allocating a new geodesic line at each evaluation. */
99
+ function minimizeDistance(
100
+ line: GeodesicLine,
101
+ point: readonly number[],
102
+ lo: number,
103
+ hi: number,
104
+ threshold: number
105
+ ): number {
106
+ let a = hi - GOLDEN_RATIO * (hi - lo);
107
+ let b = lo + GOLDEN_RATIO * (hi - lo);
108
+ let da = distanceAt(line, a, point);
109
+ let db = distanceAt(line, b, point);
110
+ while (hi - lo > SEARCH_TOLERANCE && Math.min(da, db) > threshold) {
111
+ if (da <= db) {
112
+ hi = b;
113
+ b = a;
114
+ db = da;
115
+ a = hi - GOLDEN_RATIO * (hi - lo);
116
+ da = distanceAt(line, a, point);
117
+ } else {
118
+ lo = a;
119
+ a = b;
120
+ da = db;
121
+ b = lo + GOLDEN_RATIO * (hi - lo);
122
+ db = distanceAt(line, b, point);
123
+ }
124
+ }
125
+ return Math.min(da, db);
126
+ }
127
+
128
+ /** Lower bound from the triangle inequality using both interval endpoints. */
129
+ function intervalLowerBound(start: number, end: number, length: number): number {
130
+ return (start + end - length) / 2;
131
+ }
132
+
133
+ /** Measures one finite segment, avoiding refinement when the endpoint bound already decides it. */
134
+ function segmentDistance(
135
+ a: readonly number[],
136
+ b: readonly number[],
137
+ point: readonly number[],
138
+ startDistance: number,
139
+ endDistance: number,
140
+ best: number,
141
+ threshold: number
142
+ ): number {
143
+ const limit = threshold >= 0 ? threshold : best;
144
+ const solver = getKernel();
145
+ const {s12: length, azi1} = solver.inverse(a[1]!, a[0]!, b[1]!, b[0]!);
146
+ if (length === 0 || intervalLowerBound(startDistance, endDistance, length) > limit) return best;
147
+
148
+ const line = solver.line(a[1]!, a[0]!, azi1);
149
+ const count = Math.ceil(length / MAX_SEARCH_INTERVAL);
150
+ let start = 0;
151
+ for (let interval = 1; interval <= count; interval++) {
152
+ const end = (interval * length) / count;
153
+ const distance = interval === count ? endDistance : distanceAt(line, end, point);
154
+ best = Math.min(best, distance);
155
+ if (intervalLowerBound(startDistance, distance, end - start) <= Math.min(limit, best)) {
156
+ best = Math.min(best, minimizeDistance(line, point, start, end, threshold));
157
+ }
158
+ if (best <= threshold) break;
159
+ start = end;
160
+ startDistance = distance;
161
+ }
162
+ return best;
163
+ }
164
+
165
+ /** Measures a point to the nearest position on any route component. */
166
+ function routeDistance(
167
+ route: WellKnownGeometry,
168
+ point: readonly number[],
169
+ threshold: number
170
+ ): number | null {
171
+ let best = Infinity;
172
+ for (const path of paths(route)) {
173
+ if (!path.length) continue;
174
+ let previous = meters(path[0]!, point);
175
+ best = Math.min(previous, best);
176
+ if (best <= threshold) return best;
177
+ for (let vertex = 1; vertex < path.length; vertex++) {
178
+ const distance = meters(path[vertex]!, point);
179
+ best = Math.min(distance, best);
180
+ if (best <= threshold) return best;
181
+ best = segmentDistance(
182
+ path[vertex - 1]!,
183
+ path[vertex]!,
184
+ point,
185
+ previous,
186
+ distance,
187
+ best,
188
+ threshold
189
+ );
190
+ if (best <= threshold) return best;
191
+ previous = distance;
192
+ }
193
+ }
194
+ return Number.isFinite(best) ? best : null;
195
+ }
196
+
197
+ /** Accepts point/point and point/line in either order, keeping their existing empty semantics. */
198
+ function proximityDistance(
199
+ a: WellKnownGeometry,
200
+ b: WellKnownGeometry,
201
+ threshold = -1
202
+ ): number | null {
203
+ if (isPointSet(a) && isPointSet(b)) {
204
+ return pointSetDistance(a, b, Math.max(0, threshold));
205
+ }
206
+ const point = a.type === 'Point' ? a : b;
207
+ if (point.type !== 'Point') throw new Error('Geodesic proximity requires at least one Point');
208
+ const other = a.type === 'Point' ? b : a;
209
+ if (emptyPoint(point.coordinates)) return null;
210
+ if (other.type !== 'LineString' && other.type !== 'MultiLineString')
211
+ throw new Error('Expected a Point or MultiPoint pair, or a Point paired with a route');
212
+ return routeDistance(other, point.coordinates, threshold);
213
+ }
214
+
215
+ /** Recognizes the WGS84 geographic identifiers in GeoArrow field metadata. */
216
+ function isWGS84(crs: unknown): boolean {
217
+ if (typeof crs === 'string') {
218
+ const identifier = normalizeCRSIdentifier(crs);
219
+ return identifier === 'EPSG:4326' || identifier === 'OGC:CRS84';
220
+ }
221
+ if (!crs || typeof crs !== 'object' || !('id' in crs)) return false;
222
+ const {id} = crs;
223
+ return Boolean(
224
+ id &&
225
+ typeof id === 'object' &&
226
+ 'authority' in id &&
227
+ 'code' in id &&
228
+ isWGS84(String(id.authority) + ':' + String(id.code))
229
+ );
230
+ }
231
+
232
+ /** Validates the CRS only when a geodesic function is bound. */
233
+ function validateWGS84(crs: unknown, name: string): void {
234
+ if (!isWGS84(crs))
235
+ throw new Error(`${name} requires WGS84 CRS metadata (EPSG:4326 or OGC:CRS84)`);
236
+ }
237
+
238
+ /** Geometry kinds accepted by point-to-point and point-to-route proximity. */
239
+
240
+ const proximityKinds = [...pointSetKinds, ...lineKinds];
241
+
242
+ /** Returns WGS84 point-set or point-to-route distance in meters. */
243
+ export const ST_GEODESICDISTANCE = /* @__PURE__ */ spatialFunction(
244
+ 'ST_GeodesicDistance',
245
+ [proximityKinds, proximityKinds],
246
+ /* @__PURE__ */ new Float64(),
247
+ ([a, b]) => proximityDistance(a!, b!),
248
+ 0,
249
+ true,
250
+ false,
251
+ validateWGS84
252
+ );
253
+
254
+ /** Sums WGS84 geodesic segment lengths in meters. */
255
+ export const ST_GEODESICLENGTH = /* @__PURE__ */ spatialFunction(
256
+ 'ST_GeodesicLength',
257
+ [lineKinds],
258
+ /* @__PURE__ */ new Float64(),
259
+ ([line]) => lineLength(line!),
260
+ 0,
261
+ true,
262
+ false,
263
+ validateWGS84
264
+ );
265
+
266
+ /** Checks an inclusive WGS84 point-set or point-to-route threshold in meters. */
267
+ export const ST_GEODESICDWITHIN = /* @__PURE__ */ spatialFunction(
268
+ 'ST_GeodesicDWithin',
269
+ [proximityKinds, proximityKinds],
270
+ /* @__PURE__ */ new Bool(),
271
+ ([a, b], radius) => {
272
+ if (!Number.isFinite(radius) || radius! < 0)
273
+ throw new Error('ST_GeodesicDWithin requires a finite nonnegative radius in meters');
274
+ const limit = isPointSet(a!) && isPointSet(b!) ? radius! : radius! + SEARCH_TOLERANCE;
275
+ const distance = proximityDistance(a!, b!, limit);
276
+ return distance !== null && distance <= limit;
277
+ },
278
+ 1,
279
+ true,
280
+ false,
281
+ validateWGS84
282
+ );
283
+
284
+ /** Measures a WGS84 segment and creates its geodesic line only if it needs a split. */
285
+ function ellipsoidalRouteSegment(a: readonly number[], b: readonly number[]): PolylineSegment {
286
+ const solver = getKernel();
287
+ const {s12: length, azi1} = solver.inverse(a[1]!, a[0]!, b[1]!, b[0]!);
288
+ let line: GeodesicLine | undefined;
289
+ return {
290
+ length,
291
+ /** Samples the geodesic at a fraction of its total length. */
292
+ interpolate(fraction) {
293
+ line ??= solver.line(a[1]!, a[0]!, azi1);
294
+ const {lon2, lat2} = line.position(length * fraction);
295
+ return [lon2, lat2];
296
+ }
297
+ };
298
+ }
299
+
300
+ /** Densifies WGS84 routes with equal-length geodesic steps bounded in meters. */
301
+ export const ST_GEODESICSEGMENTIZE = /* @__PURE__ */ segmentizeFunction(
302
+ 'ST_GeodesicSegmentize',
303
+ ellipsoidalRouteSegment,
304
+ validateWGS84
305
+ );
306
+
307
+ /** Opt-in SQL package for ellipsoidal distance, length, and proximity. */
308
+ export const GEODESIC_SPATIAL_FUNCTIONS = /* @__PURE__ */ Object.freeze([
309
+ ST_GEODESICDISTANCE,
310
+ ST_GEODESICLENGTH,
311
+ ST_GEODESICDWITHIN,
312
+ ST_GEODESICSEGMENTIZE
313
+ ]);
@@ -0,0 +1,25 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import {Binary} from 'apache-arrow';
6
+ import {writeWKB} from '@math.gl/core/arrow';
7
+ import {concaveHull, convexHull} from './spatial-hulls';
8
+ import {geometryTypes, spatialFunction} from './spatial-sql';
9
+
10
+ /** Returns the smallest convex footprint enclosing the input vertices. */
11
+ export const ST_CONVEXHULL = /* @__PURE__ */ spatialFunction(
12
+ 'ST_ConvexHull',
13
+ [[...geometryTypes, 'GeometryCollection']],
14
+ /* @__PURE__ */ new Binary(),
15
+ ([geometry]) => writeWKB(convexHull(geometry!), 'xy')
16
+ );
17
+
18
+ /** Returns a hole-free concave footprint around a planar point cloud. */
19
+ export const ST_CONCAVEHULL = /* @__PURE__ */ spatialFunction(
20
+ 'ST_ConcaveHull',
21
+ [['Point', 'MultiPoint']],
22
+ /* @__PURE__ */ new Binary(),
23
+ ([geometry], ratio) => writeWKB(concaveHull(geometry!, ratio!), 'xy'),
24
+ 1
25
+ );
@@ -0,0 +1,313 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {WellKnownGeometry} from '@math.gl/core/arrow';
6
+ import {lineIntersectionResult} from './spatial-line-intersection-result';
7
+ import {intersectLinePolygon} from './spatial-line-polygon-intersection';
8
+ import type {AggregateFunction, ScalarFunction} from '@math.gl/sql/arrow';
9
+ import polygonClipping from 'polygon-clipping';
10
+ import {polygonSet} from './spatial-polygon-overlay';
11
+ import {
12
+ EXTENSION_METADATA,
13
+ EXTENSION_NAME,
14
+ lineKinds,
15
+ nativeGeometryResult,
16
+ planarGeometry,
17
+ pointCoordinates,
18
+ pointKinds,
19
+ polygonKinds,
20
+ readGeometryValue,
21
+ spatialFunction
22
+ } from './spatial-sql';
23
+
24
+ /** Eight unit directions per quadrant with exact cardinal axes. */
25
+ const unitCircle = /* @__PURE__ */ Array.from({length: 32}, (_, index) => {
26
+ const angle = ((index % 8) * Math.PI) / 16;
27
+ const x = Math.cos(angle);
28
+ const y = Math.sin(angle);
29
+ switch (index >>> 3) {
30
+ case 0:
31
+ return [x, y];
32
+ case 1:
33
+ return [-y, x];
34
+ case 2:
35
+ return [-x, -y];
36
+ default:
37
+ return [y, -x];
38
+ }
39
+ });
40
+
41
+ /** Bounds the number of pieces passed to one polygon union. */
42
+ const polygonUnionFanout = 64;
43
+
44
+ /** Checks the radius for point and line buffers. */
45
+ function checkBufferRadius(radius: number): void {
46
+ if (!Number.isFinite(radius)) throw new Error('ST_Buffer requires a finite radius');
47
+ }
48
+
49
+ /** Checks a generated ring before passing it to the polygon kernel. */
50
+ function checkedRing(ring: polygonClipping.Ring): polygonClipping.Ring {
51
+ if (ring.some(point => !point.every(Number.isFinite))) {
52
+ throw new Error('ST_Buffer produced a nonfinite coordinate');
53
+ }
54
+ return ring;
55
+ }
56
+
57
+ /** Returns a circle approximation with eight segments per quadrant. */
58
+ function circleRing(x: number, y: number, radius: number): polygonClipping.Ring {
59
+ const ring: polygonClipping.Ring = unitCircle.map(([dx, dy]) => [
60
+ x + radius * dx!,
61
+ y + radius * dy!
62
+ ]);
63
+ ring.push(ring[0]!);
64
+ return checkedRing(ring);
65
+ }
66
+
67
+ /** Buffers a point without changing its established output schema. */
68
+ function bufferPoint(point: WellKnownGeometry, radius: number): WellKnownGeometry {
69
+ checkBufferRadius(radius);
70
+ const location = pointCoordinates(point);
71
+ if (!location || radius <= 0) return {type: 'Polygon', coordinates: []};
72
+ return {type: 'Polygon', coordinates: [circleRing(location[0]!, location[1]!, radius)]};
73
+ }
74
+
75
+ /** Unions a bounded group of pieces at a time, then combines groups at each level. */
76
+ function unionPolygonPieces(pieces: polygonClipping.MultiPolygon[]): polygonClipping.MultiPolygon {
77
+ if (!pieces.length) return [];
78
+ while (pieces.length > 1) {
79
+ const groups: polygonClipping.MultiPolygon[] = [];
80
+ for (let first = 0; first < pieces.length; first += polygonUnionFanout) {
81
+ groups.push(
82
+ polygonClipping.union(
83
+ pieces[first]!,
84
+ ...pieces.slice(first + 1, first + polygonUnionFanout)
85
+ )
86
+ );
87
+ }
88
+ pieces = groups;
89
+ }
90
+ return pieces[0]!;
91
+ }
92
+
93
+ /** Buffers line segments with rectangles and adds disks for round joins and caps. */
94
+ function bufferLine(geometry: WellKnownGeometry, radius: number): WellKnownGeometry {
95
+ checkBufferRadius(radius);
96
+ if (radius <= 0) return {type: 'MultiPolygon', coordinates: []};
97
+ const lines =
98
+ geometry.type === 'MultiLineString'
99
+ ? geometry.coordinates
100
+ : geometry.type === 'LineString'
101
+ ? [geometry.coordinates]
102
+ : [];
103
+ const pieces: polygonClipping.MultiPolygon[] = [];
104
+ for (const line of lines) {
105
+ let previous: readonly number[] | undefined;
106
+ for (const coordinate of line) {
107
+ const [x, y] = coordinate as polygonClipping.Pair;
108
+ if (previous && x === previous[0] && y === previous[1]) continue;
109
+ pieces.push([[circleRing(x, y, radius)]]);
110
+ if (previous) {
111
+ const x0 = previous[0]!;
112
+ const y0 = previous[1]!;
113
+ const dx = x - x0;
114
+ const dy = y - y0;
115
+ const length = Math.hypot(dx, dy);
116
+ if (!Number.isFinite(length))
117
+ throw new Error('ST_Buffer produced a nonfinite segment length');
118
+ const nx = (-dy / length) * radius;
119
+ const ny = (dx / length) * radius;
120
+ pieces.push([
121
+ [
122
+ checkedRing([
123
+ [x0 + nx, y0 + ny],
124
+ [x + nx, y + ny],
125
+ [x - nx, y - ny],
126
+ [x0 - nx, y0 - ny],
127
+ [x0 + nx, y0 + ny]
128
+ ])
129
+ ]
130
+ ]);
131
+ }
132
+ previous = coordinate;
133
+ }
134
+ }
135
+ return {type: 'MultiPolygon', coordinates: unionPolygonPieces(pieces)};
136
+ }
137
+
138
+ /** Implements the existing planar point overload. */
139
+ const pointBuffer = /* @__PURE__ */ spatialFunction(
140
+ 'ST_Buffer',
141
+ [pointKinds],
142
+ /* @__PURE__ */ nativeGeometryResult('geoarrow.polygon'),
143
+ ([geometry], radius) => bufferPoint(geometry!, radius!),
144
+ 1
145
+ );
146
+
147
+ /** Implements native planar line and multiline buffers with multipart output. */
148
+ const lineBuffer = /* @__PURE__ */ spatialFunction(
149
+ 'ST_Buffer',
150
+ [lineKinds],
151
+ /* @__PURE__ */ nativeGeometryResult('geoarrow.multipolygon'),
152
+ ([geometry], radius) => bufferLine(geometry!, radius!),
153
+ 1
154
+ );
155
+
156
+ /** Buffers planar points and native lines with round caps and joins. */
157
+ export const ST_BUFFER: ScalarFunction = {
158
+ ...pointBuffer,
159
+ /** Selects the result schema from the input column's GeoArrow encoding. */
160
+ resolvePrototype(fields) {
161
+ const encoding = fields[0]?.metadata.get(EXTENSION_NAME);
162
+ const buffer =
163
+ encoding === 'geoarrow.linestring' || encoding === 'geoarrow.multilinestring'
164
+ ? lineBuffer
165
+ : pointBuffer;
166
+ return buffer.resolvePrototype!(fields);
167
+ }
168
+ };
169
+
170
+ /** Creates a row-preserving areal overlay with the first geometry's metadata. */
171
+ function polygonOverlay(name: string, operation: typeof polygonClipping.intersection) {
172
+ const spatial = spatialFunction(
173
+ name,
174
+ [polygonKinds, polygonKinds],
175
+ nativeGeometryResult('geoarrow.multipolygon'),
176
+ ([left, right]): WellKnownGeometry => {
177
+ const a = polygonSet(left!);
178
+ const b = polygonSet(right!);
179
+ return {type: 'MultiPolygon', coordinates: operation(a, b)};
180
+ }
181
+ );
182
+ return withFirstInputMetadata(spatial);
183
+ }
184
+
185
+ /** Keeps overlay metadata tied to the first argument in either operand order. */
186
+ function withFirstInputMetadata(spatial: ScalarFunction): ScalarFunction {
187
+ return {
188
+ ...spatial,
189
+ /** Preserves the first input's metadata. Overlay does not assign a missing CRS. */
190
+ resolvePrototype(fields: Parameters<NonNullable<typeof spatial.resolvePrototype>>[0]) {
191
+ const result = spatial.resolvePrototype!(fields);
192
+ if (!fields[0]?.metadata.has(EXTENSION_METADATA)) {
193
+ result?.result.metadata.delete(EXTENSION_METADATA);
194
+ }
195
+ return result;
196
+ }
197
+ };
198
+ }
199
+
200
+ /** Binds polygon overlays or mixed-dimensional line clipping from the Arrow schema. */
201
+ function intersection(): ScalarFunction {
202
+ const polygons = polygonOverlay('ST_Intersection', polygonClipping.intersection);
203
+ const output = lineIntersectionResult();
204
+ const linearFirst = spatialFunction(
205
+ 'ST_Intersection',
206
+ [lineKinds, polygonKinds],
207
+ output,
208
+ ([line, area]) => intersectLinePolygon(line!, area!)
209
+ );
210
+ const linearSecond = spatialFunction(
211
+ 'ST_Intersection',
212
+ [polygonKinds, lineKinds],
213
+ output,
214
+ ([area, line]) => intersectLinePolygon(line!, area!)
215
+ );
216
+ return withFirstInputMetadata({
217
+ ...polygons,
218
+ /** A specialized line argument selects a mixed native GeoArrow result before evaluation. */
219
+ resolvePrototype(fields) {
220
+ const a = fields[0]?.metadata.get(EXTENSION_NAME);
221
+ const b = fields[1]?.metadata.get(EXTENSION_NAME);
222
+ if (a === 'geoarrow.linestring' || a === 'geoarrow.multilinestring')
223
+ return linearFirst.resolvePrototype!(fields);
224
+ if (b === 'geoarrow.linestring' || b === 'geoarrow.multilinestring')
225
+ return linearSecond.resolvePrototype!(fields);
226
+ return polygons.resolvePrototype!(fields);
227
+ }
228
+ });
229
+ }
230
+
231
+ /** Intersects two areal geometries or clips a native line by a polygon. */
232
+ export const ST_INTERSECTION = /* @__PURE__ */ intersection();
233
+ /** Returns the portion of the first polygonal geometry outside the second. */
234
+ export const ST_DIFFERENCE = /* @__PURE__ */ polygonOverlay(
235
+ 'ST_Difference',
236
+ polygonClipping.difference
237
+ );
238
+
239
+ /** Returns the combined polygon area as a native GeoArrow MultiPolygon. */
240
+ export const ST_UNION = /* @__PURE__ */ polygonOverlay('ST_Union', polygonClipping.union);
241
+
242
+ /** Returns the area covered by exactly one input as a native GeoArrow MultiPolygon. */
243
+ export const ST_SYMDIFFERENCE = /* @__PURE__ */ polygonOverlay(
244
+ 'ST_SymDifference',
245
+ polygonClipping.xor
246
+ );
247
+
248
+ /** Dissolves the components of a polygonal geometry into native GeoArrow storage. */
249
+ export const ST_UNARYUNION = /* @__PURE__ */ spatialFunction(
250
+ 'ST_UnaryUnion',
251
+ [polygonKinds],
252
+ /* @__PURE__ */ nativeGeometryResult('geoarrow.multipolygon'),
253
+ ([geometry]): WellKnownGeometry => ({
254
+ type: 'MultiPolygon',
255
+ coordinates: polygonClipping.union(polygonSet(geometry!))
256
+ })
257
+ );
258
+
259
+ /** Dissolves polygonal rows per group, ignoring nulls and retaining the input CRS. */
260
+ export const ST_UNION_AGGREGATE: AggregateFunction = {
261
+ kind: 'aggregate',
262
+ name: 'ST_Union',
263
+ argumentCount: 1,
264
+ /** Binds one polygonal input and declares the native multipolygon output. */
265
+ bind({arguments: fields}) {
266
+ const prototype = ST_UNARYUNION.resolvePrototype!(fields);
267
+ if (!prototype) throw new Error('Aggregate ST_Union requires one polygonal geometry column');
268
+ const field = prototype.arguments[0]!;
269
+ return {
270
+ outputField: prototype.result.clone({name: 'ST_Union'}),
271
+ /** Keeps bounded groups of partial unions at increasing input sizes. */
272
+ createAccumulator() {
273
+ const levels: polygonClipping.MultiPolygon[][] = [];
274
+ let seen = false;
275
+
276
+ /** Compacts a full level before accumulating further inputs. */
277
+ function add(polygon: polygonClipping.MultiPolygon) {
278
+ for (let level = 0; ; level++) {
279
+ levels[level] ??= [];
280
+ const pieces = levels[level]!;
281
+ pieces.push(polygon);
282
+ if (pieces.length < polygonUnionFanout) return;
283
+ polygon = unionPolygonPieces(pieces);
284
+ pieces.length = 0;
285
+ }
286
+ }
287
+
288
+ return {
289
+ /** Reduces the non-null polygonal rows of one input batch. */
290
+ update([vector], {length, signal}) {
291
+ const active = Uint8Array.from({length}, (_, row) => Number(vector!.isValid(row)));
292
+ const read = readGeometryValue(vector!, field, active, planarGeometry);
293
+ for (let row = 0; row < length; row++) {
294
+ if ((row & 255) === 0) signal?.throwIfAborted();
295
+ if (!active[row]) continue;
296
+ seen = true;
297
+ const pieces = polygonSet(read(row));
298
+ if (pieces.length) add(pieces);
299
+ }
300
+ },
301
+ /** Combines partial unions and distinguishes all-empty from all-null groups. */
302
+ finalize() {
303
+ if (!seen) return null;
304
+ const pieces = levels.flat();
305
+ return pieces.length === 1
306
+ ? polygonClipping.union(pieces[0]!)
307
+ : unionPolygonPieces(pieces);
308
+ }
309
+ };
310
+ }
311
+ };
312
+ }
313
+ };