@math.gl/geospatial 5.0.1 → 5.0.3

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 (88) 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/linear-referencing.d.ts +2 -12
  24. package/dist/linear-referencing.d.ts.map +1 -1
  25. package/dist/linear-referencing.js +17 -49
  26. package/dist/linear-referencing.js.map +1 -1
  27. package/dist/polygon-simplification.d.ts.map +1 -1
  28. package/dist/polygon-simplification.js +3 -33
  29. package/dist/polygon-simplification.js.map +1 -1
  30. package/dist/route-editing.d.ts +10 -0
  31. package/dist/route-editing.d.ts.map +1 -0
  32. package/dist/route-editing.js +58 -0
  33. package/dist/route-editing.js.map +1 -0
  34. package/dist/spatial-line-polygon-intersection.d.ts.map +1 -1
  35. package/dist/spatial-line-polygon-intersection.js +2 -2
  36. package/dist/spatial-line-polygon-intersection.js.map +1 -1
  37. package/dist/spatial-planar-intersects.d.ts +1 -11
  38. package/dist/spatial-planar-intersects.d.ts.map +1 -1
  39. package/dist/spatial-planar-intersects.js +2 -42
  40. package/dist/spatial-planar-intersects.js.map +1 -1
  41. package/dist/spatial-sql.d.ts +6 -4
  42. package/dist/spatial-sql.d.ts.map +1 -1
  43. package/dist/spatial-sql.js +38 -4
  44. package/dist/spatial-sql.js.map +1 -1
  45. package/dist/spatial-touches.d.ts +0 -2
  46. package/dist/spatial-touches.d.ts.map +1 -1
  47. package/dist/spatial-touches.js +1 -15
  48. package/dist/spatial-touches.js.map +1 -1
  49. package/dist/st-coverage-functions.d.ts +11 -0
  50. package/dist/st-coverage-functions.d.ts.map +1 -0
  51. package/dist/st-coverage-functions.js +57 -0
  52. package/dist/st-coverage-functions.js.map +1 -0
  53. package/dist/st-functions.cjs +1201 -775
  54. package/dist/st-functions.cjs.map +3 -3
  55. package/dist/st-functions.d.ts +36 -3
  56. package/dist/st-functions.d.ts.map +1 -1
  57. package/dist/st-functions.js +53 -19
  58. package/dist/st-functions.js.map +1 -1
  59. package/dist/st-geodesic-functions.d.ts +10 -2
  60. package/dist/st-geodesic-functions.d.ts.map +1 -1
  61. package/dist/st-geodesic-functions.js +179 -25
  62. package/dist/st-geodesic-functions.js.map +1 -1
  63. package/dist/st-hull-functions.cjs.map +1 -1
  64. package/dist/st-overlay-functions.cjs +114 -67
  65. package/dist/st-overlay-functions.cjs.map +2 -2
  66. package/dist/st-overlay-functions.d.ts +11 -1
  67. package/dist/st-overlay-functions.d.ts.map +1 -1
  68. package/dist/st-overlay-functions.js +74 -9
  69. package/dist/st-overlay-functions.js.map +1 -1
  70. package/dist/st-viewport-functions.cjs.map +1 -1
  71. package/dist/turf-functions.cjs.map +1 -1
  72. package/package.json +12 -6
  73. package/src/coverage-simplification.ts +215 -0
  74. package/src/line-network/build-line-network.ts +990 -0
  75. package/src/line-network/line-network-routes.ts +213 -0
  76. package/src/line-network/line-network-weights.ts +40 -0
  77. package/src/line-network.ts +29 -0
  78. package/src/linear-referencing.ts +23 -64
  79. package/src/polygon-simplification.ts +3 -42
  80. package/src/route-editing.ts +107 -0
  81. package/src/spatial-line-polygon-intersection.ts +7 -2
  82. package/src/spatial-planar-intersects.ts +7 -54
  83. package/src/spatial-sql.ts +54 -5
  84. package/src/spatial-touches.ts +1 -15
  85. package/src/st-coverage-functions.ts +88 -0
  86. package/src/st-functions.ts +70 -19
  87. package/src/st-geodesic-functions.ts +218 -26
  88. package/src/st-overlay-functions.ts +79 -10
@@ -6,19 +6,26 @@ import {Bool, Float64} from 'apache-arrow';
6
6
  import type {WellKnownGeometry} from '@math.gl/core/arrow';
7
7
  import {WGS84_RADIUS_X, WGS84_RADIUS_Z} from './constants';
8
8
  import {normalizeCRSIdentifier} from './crs/crs-identifier';
9
- import {EllipsoidGeodesic} from './ellipsoid-geodesic';
10
- import {lineKinds, pointKinds, spatialFunction} from './spatial-sql';
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';
11
13
 
12
14
  /** Ellipsoidal kernel with axes expressed in meters, initialized when first used. */
13
15
  let kernel: EllipsoidGeodesic | undefined;
14
16
 
15
- /** Measures the shortest WGS84 geodesic between two longitude–latitude positions. */
16
- function meters(a: readonly number[], b: readonly number[]): number {
17
+ /** Reuses one WGS84 ellipsoid for all rows and segments. */
18
+ function getKernel(): EllipsoidGeodesic {
17
19
  kernel ??= new EllipsoidGeodesic({
18
20
  semiMajorAxis: WGS84_RADIUS_X,
19
21
  semiMinorAxis: WGS84_RADIUS_Z
20
22
  });
21
- return kernel.inverse(a[1]!, a[0]!, b[1]!, b[0]!).s12;
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;
22
29
  }
23
30
 
24
31
  /** Tests the coordinate representation of an empty point. */
@@ -26,29 +33,185 @@ function emptyPoint(coordinate: readonly number[]): boolean {
26
33
  return !coordinate.length || coordinate.every(Number.isNaN);
27
34
  }
28
35
 
29
- /** Measures a point pair, with null for the empty set. */
30
- function pointDistance(a: WellKnownGeometry, b: WellKnownGeometry): number | null {
31
- if (a.type !== 'Point' || b.type !== 'Point') throw new Error('Expected geodesic point pair');
32
- return emptyPoint(a.coordinates) || emptyPoint(b.coordinates)
33
- ? null
34
- : meters(a.coordinates, b.coordinates);
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');
35
73
  }
36
74
 
37
75
  /** Measures linear components without adding a segment between components. */
38
76
  function lineLength(geometry: WellKnownGeometry): number {
39
- const lines =
40
- geometry.type === 'LineString'
41
- ? [geometry.coordinates]
42
- : geometry.type === 'MultiLineString'
43
- ? geometry.coordinates
44
- : [];
45
77
  let length = 0;
46
- for (const path of lines)
78
+ for (const path of paths(geometry))
47
79
  for (let index = 1; index < path.length; index++)
48
80
  length += meters(path[index - 1]!, path[index]!);
49
81
  return length;
50
82
  }
51
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
+
52
215
  /** Recognizes the WGS84 geographic identifiers in GeoArrow field metadata. */
53
216
  function isWGS84(crs: unknown): boolean {
54
217
  if (typeof crs === 'string') {
@@ -72,12 +235,16 @@ function validateWGS84(crs: unknown, name: string): void {
72
235
  throw new Error(`${name} requires WGS84 CRS metadata (EPSG:4326 or OGC:CRS84)`);
73
236
  }
74
237
 
75
- /** Returns WGS84 point-to-point distance in meters. */
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. */
76
243
  export const ST_GEODESICDISTANCE = /* @__PURE__ */ spatialFunction(
77
244
  'ST_GeodesicDistance',
78
- [pointKinds, pointKinds],
245
+ [proximityKinds, proximityKinds],
79
246
  /* @__PURE__ */ new Float64(),
80
- ([a, b]) => pointDistance(a!, b!),
247
+ ([a, b]) => proximityDistance(a!, b!),
81
248
  0,
82
249
  true,
83
250
  false,
@@ -96,16 +263,17 @@ export const ST_GEODESICLENGTH = /* @__PURE__ */ spatialFunction(
96
263
  validateWGS84
97
264
  );
98
265
 
99
- /** Checks an inclusive WGS84 point-to-point proximity threshold in meters. */
266
+ /** Checks an inclusive WGS84 point-set or point-to-route threshold in meters. */
100
267
  export const ST_GEODESICDWITHIN = /* @__PURE__ */ spatialFunction(
101
268
  'ST_GeodesicDWithin',
102
- [pointKinds, pointKinds],
269
+ [proximityKinds, proximityKinds],
103
270
  /* @__PURE__ */ new Bool(),
104
271
  ([a, b], radius) => {
105
272
  if (!Number.isFinite(radius) || radius! < 0)
106
273
  throw new Error('ST_GeodesicDWithin requires a finite nonnegative radius in meters');
107
- const distance = pointDistance(a!, b!);
108
- return distance !== null && distance <= radius!;
274
+ const limit = isPointSet(a!) && isPointSet(b!) ? radius! : radius! + SEARCH_TOLERANCE;
275
+ const distance = proximityDistance(a!, b!, limit);
276
+ return distance !== null && distance <= limit;
109
277
  },
110
278
  1,
111
279
  true,
@@ -113,9 +281,33 @@ export const ST_GEODESICDWITHIN = /* @__PURE__ */ spatialFunction(
113
281
  validateWGS84
114
282
  );
115
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
+
116
307
  /** Opt-in SQL package for ellipsoidal distance, length, and proximity. */
117
308
  export const GEODESIC_SPATIAL_FUNCTIONS = /* @__PURE__ */ Object.freeze([
118
309
  ST_GEODESICDISTANCE,
119
310
  ST_GEODESICLENGTH,
120
- ST_GEODESICDWITHIN
311
+ ST_GEODESICDWITHIN,
312
+ ST_GEODESICSEGMENTIZE
121
313
  ]);
@@ -3,19 +3,21 @@
3
3
  // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
4
 
5
5
  import type {WellKnownGeometry} from '@math.gl/core/arrow';
6
- import type {ScalarFunction} from '@math.gl/sql/arrow';
7
6
  import {lineIntersectionResult} from './spatial-line-intersection-result';
8
7
  import {intersectLinePolygon} from './spatial-line-polygon-intersection';
8
+ import type {AggregateFunction, ScalarFunction} from '@math.gl/sql/arrow';
9
9
  import polygonClipping from 'polygon-clipping';
10
10
  import {polygonSet} from './spatial-polygon-overlay';
11
11
  import {
12
12
  EXTENSION_METADATA,
13
13
  EXTENSION_NAME,
14
14
  lineKinds,
15
- nativePolygonResult,
15
+ nativeGeometryResult,
16
+ planarGeometry,
16
17
  pointCoordinates,
17
18
  pointKinds,
18
19
  polygonKinds,
20
+ readGeometryValue,
19
21
  spatialFunction
20
22
  } from './spatial-sql';
21
23
 
@@ -37,7 +39,7 @@ const unitCircle = /* @__PURE__ */ Array.from({length: 32}, (_, index) => {
37
39
  });
38
40
 
39
41
  /** Bounds the number of pieces passed to one polygon union. */
40
- const corridorUnionFanout = 64;
42
+ const polygonUnionFanout = 64;
41
43
 
42
44
  /** Checks the radius for point and line buffers. */
43
45
  function checkBufferRadius(radius: number): void {
@@ -71,15 +73,15 @@ function bufferPoint(point: WellKnownGeometry, radius: number): WellKnownGeometr
71
73
  }
72
74
 
73
75
  /** Unions a bounded group of pieces at a time, then combines groups at each level. */
74
- function unionCorridorPieces(pieces: polygonClipping.MultiPolygon[]): polygonClipping.MultiPolygon {
76
+ function unionPolygonPieces(pieces: polygonClipping.MultiPolygon[]): polygonClipping.MultiPolygon {
75
77
  if (!pieces.length) return [];
76
78
  while (pieces.length > 1) {
77
79
  const groups: polygonClipping.MultiPolygon[] = [];
78
- for (let first = 0; first < pieces.length; first += corridorUnionFanout) {
80
+ for (let first = 0; first < pieces.length; first += polygonUnionFanout) {
79
81
  groups.push(
80
82
  polygonClipping.union(
81
83
  pieces[first]!,
82
- ...pieces.slice(first + 1, first + corridorUnionFanout)
84
+ ...pieces.slice(first + 1, first + polygonUnionFanout)
83
85
  )
84
86
  );
85
87
  }
@@ -130,14 +132,14 @@ function bufferLine(geometry: WellKnownGeometry, radius: number): WellKnownGeome
130
132
  previous = coordinate;
131
133
  }
132
134
  }
133
- return {type: 'MultiPolygon', coordinates: unionCorridorPieces(pieces)};
135
+ return {type: 'MultiPolygon', coordinates: unionPolygonPieces(pieces)};
134
136
  }
135
137
 
136
138
  /** Implements the existing planar point overload. */
137
139
  const pointBuffer = /* @__PURE__ */ spatialFunction(
138
140
  'ST_Buffer',
139
141
  [pointKinds],
140
- /* @__PURE__ */ nativePolygonResult('geoarrow.polygon'),
142
+ /* @__PURE__ */ nativeGeometryResult('geoarrow.polygon'),
141
143
  ([geometry], radius) => bufferPoint(geometry!, radius!),
142
144
  1
143
145
  );
@@ -146,7 +148,7 @@ const pointBuffer = /* @__PURE__ */ spatialFunction(
146
148
  const lineBuffer = /* @__PURE__ */ spatialFunction(
147
149
  'ST_Buffer',
148
150
  [lineKinds],
149
- /* @__PURE__ */ nativePolygonResult('geoarrow.multipolygon'),
151
+ /* @__PURE__ */ nativeGeometryResult('geoarrow.multipolygon'),
150
152
  ([geometry], radius) => bufferLine(geometry!, radius!),
151
153
  1
152
154
  );
@@ -170,7 +172,7 @@ function polygonOverlay(name: string, operation: typeof polygonClipping.intersec
170
172
  const spatial = spatialFunction(
171
173
  name,
172
174
  [polygonKinds, polygonKinds],
173
- nativePolygonResult('geoarrow.multipolygon'),
175
+ nativeGeometryResult('geoarrow.multipolygon'),
174
176
  ([left, right]): WellKnownGeometry => {
175
177
  const a = polygonSet(left!);
176
178
  const b = polygonSet(right!);
@@ -242,3 +244,70 @@ export const ST_SYMDIFFERENCE = /* @__PURE__ */ polygonOverlay(
242
244
  'ST_SymDifference',
243
245
  polygonClipping.xor
244
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
+ };