@vizhub/quadstream 0.2.0 → 1.0.0

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 (49) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +49 -323
  3. package/bin/quadstream.mjs +8 -6
  4. package/dist/blg.d.ts +3 -0
  5. package/dist/blg.js +14 -1
  6. package/dist/cooperative.d.ts +21 -0
  7. package/dist/cooperative.js +33 -0
  8. package/dist/dataset.d.ts +8 -4
  9. package/dist/dataset.js +51 -14
  10. package/dist/geometry-wire.d.ts +8 -0
  11. package/dist/geometry-wire.js +76 -0
  12. package/dist/geometry.d.ts +3 -1
  13. package/dist/geometry.js +115 -5
  14. package/dist/index.d.ts +20 -2
  15. package/dist/index.js +9 -1
  16. package/dist/loader.d.ts +1 -1
  17. package/dist/loader.js +1 -1
  18. package/dist/lod-scheduler.d.ts +15 -0
  19. package/dist/lod-scheduler.js +85 -0
  20. package/dist/progressive-map.d.ts +1 -1
  21. package/dist/progressive-map.js +12 -8
  22. package/dist/quadtree.d.ts +2 -0
  23. package/dist/quadtree.js +12 -0
  24. package/dist/reconstruct.d.ts +18 -1
  25. package/dist/reconstruct.js +94 -32
  26. package/dist/session.d.ts +12 -9
  27. package/dist/session.js +24 -7
  28. package/dist/spherical-clip.d.ts +95 -0
  29. package/dist/spherical-clip.js +557 -0
  30. package/dist/spherical-cull.d.ts +25 -0
  31. package/dist/spherical-cull.js +102 -0
  32. package/dist/spherical-dataset.d.ts +41 -9
  33. package/dist/spherical-dataset.js +221 -122
  34. package/dist/spherical-geometry.d.ts +2 -0
  35. package/dist/spherical-geometry.js +87 -44
  36. package/dist/spherical-line.d.ts +29 -0
  37. package/dist/spherical-line.js +221 -0
  38. package/dist/spherical-preprocess.d.ts +23 -0
  39. package/dist/spherical-preprocess.js +160 -0
  40. package/dist/spherical-repair.d.ts +17 -0
  41. package/dist/spherical-repair.js +100 -0
  42. package/dist/spherical-robust-dataset.d.ts +27 -0
  43. package/dist/spherical-robust-dataset.js +89 -0
  44. package/dist/spherical-view-clipper.d.ts +22 -0
  45. package/dist/spherical-view-clipper.js +85 -0
  46. package/dist/topology.d.ts +3 -0
  47. package/dist/topology.js +40 -9
  48. package/dist/types.d.ts +5 -1
  49. package/package.json +12 -7
package/dist/dataset.js CHANGED
@@ -1,21 +1,46 @@
1
+ import { runSync, runCooperative, } from "./cooperative.js";
1
2
  import { assertBounds } from "./geometry.js";
2
- import { buildTopology } from "./topology.js";
3
- import { buildSparseQuadtree } from "./quadtree.js";
3
+ import { buildPlanarTopologySteps } from "./topology.js";
4
+ import { buildSparseQuadtreeSteps } from "./quadtree.js";
4
5
  import { createSpatialIndex } from "./spatial-index.js";
5
- import { buildArcTrees, reconstructFeature } from "./reconstruct.js";
6
+ import { buildArcTreeSteps, reconstructFeatureSteps } from "./reconstruct.js";
7
+ function* preparePlanar(input, maxLevel) {
8
+ yield { stage: "Construct topology" };
9
+ const topology = yield* buildPlanarTopologySteps(input);
10
+ const quadtree = yield* buildSparseQuadtreeSteps(topology.vertices, topology.bounds, maxLevel);
11
+ const arcTrees = yield* buildArcTreeSteps(topology.arcs, quadtree.levelByVertexId, topology.vertices.map((v) => v.critical));
12
+ return { topology, quadtree, arcTrees };
13
+ }
6
14
  export class QuadstreamDataset {
7
15
  topology;
8
16
  quadtree;
9
17
  arcTrees;
10
18
  featureIndex;
11
19
  validityCache = new Map();
12
- constructor(input, { maxLevel = 20 } = {}) {
13
- this.topology = buildTopology(input);
14
- this.quadtree = buildSparseQuadtree(this.topology.vertices, this.topology.bounds, maxLevel);
15
- this.arcTrees = buildArcTrees(this.topology.arcs, this.quadtree.levelByVertexId, this.topology.vertices.map((v) => v.critical));
20
+ constructor(input, { maxLevel = 20 } = {}, prepared) {
21
+ const state = prepared ?? runSync(preparePlanar(input, maxLevel));
22
+ this.topology = state.topology;
23
+ this.quadtree = state.quadtree;
24
+ this.arcTrees = state.arcTrees;
16
25
  this.featureIndex = createSpatialIndex(this.topology.features.map((f, i) => ({ bounds: f.bounds, value: i })));
17
26
  }
27
+ static async create(input, options = {}) {
28
+ const prepared = await runCooperative(preparePlanar(input, options.maxLevel ?? 20), options);
29
+ options.signal?.throwIfAborted();
30
+ return new QuadstreamDataset(input, options, prepared);
31
+ }
32
+ /** @internal Synchronous reference for algorithm parity tests. */
33
+ static createSync(input, options) {
34
+ return new QuadstreamDataset(input, options);
35
+ }
36
+ /** @internal Synchronous reference for algorithm parity tests. */
37
+ querySync(options = {}) {
38
+ return runSync(this.querySteps(options));
39
+ }
18
40
  query(options = {}) {
41
+ return runCooperative(this.querySteps(options), options);
42
+ }
43
+ *querySteps(options) {
19
44
  const level = options.level ?? this.quadtree.maxLevel - 1;
20
45
  if (!Number.isFinite(level) || level < 0 || level >= this.quadtree.maxLevel)
21
46
  throw new Error("Invalid query level");
@@ -36,16 +61,23 @@ export class QuadstreamDataset {
36
61
  else {
37
62
  // Viewport-independent decision: shared boundaries must render consistently
38
63
  // even when two viewports select different subsets of features.
39
- globallyInvalid = this.topology.features.some((f) => !reconstructFeature(f, this.topology.arcs, this.arcTrees, level, coords).valid);
64
+ for (const f of this.topology.features) {
65
+ const result = yield* reconstructFeatureSteps(f, this.topology.arcs, this.arcTrees, level, coords);
66
+ if (!result.valid) {
67
+ globallyInvalid = true;
68
+ break;
69
+ }
70
+ }
40
71
  this.validityCache.set(level, !globallyInvalid);
41
72
  }
42
73
  }
43
74
  let total = 0;
44
- const results = selected.map((i) => {
45
- const r = reconstructFeature(this.topology.features[i], this.topology.arcs, this.arcTrees, globallyInvalid ? Infinity : level, coords);
75
+ const results = [];
76
+ for (const i of selected) {
77
+ const r = yield* reconstructFeatureSteps(this.topology.features[i], this.topology.arcs, this.arcTrees, globallyInvalid ? Infinity : level, coords);
46
78
  total += r.selectedVertices;
47
- return r.feature;
48
- });
79
+ results.push(r.feature);
80
+ }
49
81
  return {
50
82
  geojson: { type: "FeatureCollection", features: results },
51
83
  level,
@@ -56,6 +88,11 @@ export class QuadstreamDataset {
56
88
  };
57
89
  }
58
90
  }
59
- export function buildQuadstream(input, options) {
60
- return new QuadstreamDataset(input, options);
91
+ /** @internal Synchronous reference for algorithm parity tests. */
92
+ export function buildQuadstreamSync(input, options) {
93
+ return QuadstreamDataset.createSync(input, options);
94
+ }
95
+ /** Cooperative construction using the same topology and priority algorithms. */
96
+ export async function buildQuadstream(input, options = {}) {
97
+ return QuadstreamDataset.create(input, options);
61
98
  }
@@ -0,0 +1,8 @@
1
+ import type { FeatureCollection } from "./types.js";
2
+ export interface PackedGeometry {
3
+ coords: Float64Array;
4
+ meta: Int32Array;
5
+ }
6
+ /** Transferable geometry only; feature order and metadata are supplied by the original. */
7
+ export declare function packGeometry(geojson: FeatureCollection): PackedGeometry;
8
+ export declare function unpackGeometry(original: FeatureCollection, coords: Float64Array, meta: Int32Array): FeatureCollection;
@@ -0,0 +1,76 @@
1
+ function polygons(g) {
2
+ if (g.type === "Polygon")
3
+ return [g.coordinates];
4
+ if (g.type === "MultiPolygon")
5
+ return g.coordinates;
6
+ throw new Error("Packed geometry supports only Polygon and MultiPolygon");
7
+ }
8
+ /** Transferable geometry only; feature order and metadata are supplied by the original. */
9
+ export function packGeometry(geojson) {
10
+ let metaLen = 0, coordCount = 0;
11
+ for (const f of geojson.features) {
12
+ const polys = polygons(f.geometry);
13
+ metaLen++;
14
+ for (const rings of polys) {
15
+ metaLen += 1 + rings.length;
16
+ for (const ring of rings)
17
+ coordCount += ring.length * 2;
18
+ }
19
+ }
20
+ const meta = new Int32Array(metaLen), coords = new Float64Array(coordCount);
21
+ let mi = 0, ci = 0;
22
+ for (const f of geojson.features) {
23
+ const polys = polygons(f.geometry);
24
+ meta[mi++] = polys.length;
25
+ for (const rings of polys) {
26
+ meta[mi++] = rings.length;
27
+ for (const ring of rings) {
28
+ meta[mi++] = ring.length;
29
+ for (const [x, y] of ring) {
30
+ if (!Number.isFinite(x) || !Number.isFinite(y))
31
+ throw new Error("Non-finite coordinate");
32
+ coords[ci++] = x;
33
+ coords[ci++] = y;
34
+ }
35
+ }
36
+ }
37
+ }
38
+ return { coords, meta };
39
+ }
40
+ export function unpackGeometry(original, coords, meta) {
41
+ let mi = 0, ci = 0;
42
+ const next = (limit) => {
43
+ const n = meta[mi++];
44
+ if (n === undefined || n < 0 || n > limit)
45
+ throw new Error("Malformed geometry metadata");
46
+ return n;
47
+ };
48
+ const features = original.features.map((f) => {
49
+ polygons(f.geometry);
50
+ const count = next(meta.length - mi - 1);
51
+ if (f.geometry.type === "Polygon" && count !== 1)
52
+ throw new Error("Malformed polygon");
53
+ const polys = [];
54
+ for (let p = 0; p < count; p++) {
55
+ const rings = [], nr = next(meta.length - mi - 1);
56
+ for (let r = 0; r < nr; r++) {
57
+ const ring = [], np = next(Math.floor((coords.length - ci) / 2));
58
+ for (let k = 0; k < np; k++) {
59
+ const x = coords[ci++], y = coords[ci++];
60
+ if (!Number.isFinite(x) || !Number.isFinite(y))
61
+ throw new Error("Non-finite coordinate");
62
+ ring.push([x, y]);
63
+ }
64
+ rings.push(ring);
65
+ }
66
+ polys.push(rings);
67
+ }
68
+ const geometry = f.geometry.type === "Polygon"
69
+ ? { type: "Polygon", coordinates: polys[0] }
70
+ : { type: "MultiPolygon", coordinates: polys };
71
+ return { ...f, geometry };
72
+ });
73
+ if (mi !== meta.length || ci !== coords.length)
74
+ throw new Error("Trailing geometry data");
75
+ return { type: "FeatureCollection", features };
76
+ }
@@ -7,7 +7,9 @@ export declare function assertBounds(b: Bounds): Bounds;
7
7
  export declare function signedArea(ring: readonly Position[]): number;
8
8
  /** Includes touching endpoints; callers skip adjacent polygon edges. */
9
9
  export declare function segmentsIntersect(a: Position, b: Position, c: Position, d: Position): boolean;
10
- /** O(n^2) reference predicate; safe but not intended as the final large-data validator. */
10
+ /** O(n^2) reference predicate; retained as the oracle for the indexed validator. */
11
+ export declare function simpleClosedRingReference(ring: readonly Position[]): boolean;
12
+ /** Sweep-and-prune over segment boxes; exact predicates only on overlapping candidates. */
11
13
  export declare function simpleClosedRing(ring: readonly Position[]): boolean;
12
14
  export declare function pointInRing(p: Position, ring: readonly Position[]): boolean;
13
15
  export declare function validPolygon(rings: readonly Position[][]): boolean;
package/dist/geometry.js CHANGED
@@ -60,6 +60,12 @@ function within(a, b, p) {
60
60
  }
61
61
  /** Includes touching endpoints; callers skip adjacent polygon edges. */
62
62
  export function segmentsIntersect(a, b, c, d) {
63
+ // Inclusive AABB rejection: disjoint boxes cannot touch or cross.
64
+ if (Math.max(a[0], b[0]) < Math.min(c[0], d[0]) ||
65
+ Math.max(c[0], d[0]) < Math.min(a[0], b[0]) ||
66
+ Math.max(a[1], b[1]) < Math.min(c[1], d[1]) ||
67
+ Math.max(c[1], d[1]) < Math.min(a[1], b[1]))
68
+ return false;
63
69
  const abC = orientation(a, b, c), abD = orientation(a, b, d), cdA = orientation(c, d, a), cdB = orientation(c, d, b);
64
70
  if (((abC > 0 && abD < 0) || (abC < 0 && abD > 0)) &&
65
71
  ((cdA > 0 && cdB < 0) || (cdA < 0 && cdB > 0)))
@@ -72,8 +78,8 @@ export function segmentsIntersect(a, b, c, d) {
72
78
  function same(a, b) {
73
79
  return a[0] === b[0] && a[1] === b[1];
74
80
  }
75
- /** O(n^2) reference predicate; safe but not intended as the final large-data validator. */
76
- export function simpleClosedRing(ring) {
81
+ /** O(n^2) reference predicate; retained as the oracle for the indexed validator. */
82
+ export function simpleClosedRingReference(ring) {
77
83
  const n = ring.length - 1;
78
84
  if (n < 3 || !same(ring[0], ring[n]) || signedArea(ring) === 0)
79
85
  return false;
@@ -89,6 +95,95 @@ export function simpleClosedRing(ring) {
89
95
  }
90
96
  return true;
91
97
  }
98
+ /** Rings below this many segments use the quadratic loops directly. */
99
+ const INDEX_MIN_SEGMENTS = 24;
100
+ function segmentBoxes(ring) {
101
+ const count = ring.length - 1, minX = new Float64Array(count), maxX = new Float64Array(count), minY = new Float64Array(count), maxY = new Float64Array(count);
102
+ for (let i = 0; i < count; i++) {
103
+ const a = ring[i], b = ring[i + 1];
104
+ if (!Number.isFinite(a[0] + a[1] + b[0] + b[1]) ||
105
+ a.length !== 2 ||
106
+ b.length !== 2)
107
+ return null;
108
+ minX[i] = Math.min(a[0], b[0]);
109
+ maxX[i] = Math.max(a[0], b[0]);
110
+ minY[i] = Math.min(a[1], b[1]);
111
+ maxY[i] = Math.max(a[1], b[1]);
112
+ }
113
+ const order = new Uint32Array(count);
114
+ for (let i = 0; i < count; i++)
115
+ order[i] = i;
116
+ order.sort((p, q) => minX[p] - minX[q] || p - q);
117
+ return { count, minX, maxX, minY, maxY, order };
118
+ }
119
+ /** Each unordered segment pair with overlapping boxes is visited once; true stops. */
120
+ function sweepSelf(s, visit) {
121
+ const { count, minX, maxX, minY, maxY, order } = s;
122
+ for (let a = 0; a < count; a++) {
123
+ const i = order[a], reach = maxX[i];
124
+ for (let b = a + 1; b < count; b++) {
125
+ const j = order[b];
126
+ if (minX[j] > reach)
127
+ break;
128
+ if (minY[j] > maxY[i] || maxY[j] < minY[i])
129
+ continue;
130
+ if (visit(i, j))
131
+ return true;
132
+ }
133
+ }
134
+ return false;
135
+ }
136
+ function sweepBetween(A, B, visit) {
137
+ let ia = 0, ib = 0;
138
+ while (ia < A.count && ib < B.count) {
139
+ const i = A.order[ia], j = B.order[ib];
140
+ if (A.minX[i] <= B.minX[j]) {
141
+ for (let k = ib; k < B.count; k++) {
142
+ const m = B.order[k];
143
+ if (B.minX[m] > A.maxX[i])
144
+ break;
145
+ if (B.minY[m] > A.maxY[i] || B.maxY[m] < A.minY[i])
146
+ continue;
147
+ if (visit(i, m))
148
+ return true;
149
+ }
150
+ ia++;
151
+ }
152
+ else {
153
+ for (let k = ia; k < A.count; k++) {
154
+ const m = A.order[k];
155
+ if (A.minX[m] > B.maxX[j])
156
+ break;
157
+ if (A.minY[m] > B.maxY[j] || A.maxY[m] < B.minY[j])
158
+ continue;
159
+ if (visit(m, j))
160
+ return true;
161
+ }
162
+ ib++;
163
+ }
164
+ }
165
+ return false;
166
+ }
167
+ /** Sweep-and-prune over segment boxes; exact predicates only on overlapping candidates. */
168
+ export function simpleClosedRing(ring) {
169
+ const n = ring.length - 1;
170
+ if (n < INDEX_MIN_SEGMENTS)
171
+ return simpleClosedRingReference(ring);
172
+ if (!same(ring[0], ring[n]) || signedArea(ring) === 0)
173
+ return false;
174
+ for (let i = 0; i < n; i++)
175
+ if (same(ring[i], ring[i + 1]))
176
+ return false;
177
+ const boxes = segmentBoxes(ring);
178
+ if (!boxes)
179
+ return simpleClosedRingReference(ring);
180
+ return !sweepSelf(boxes, (p, q) => {
181
+ const i = Math.min(p, q), j = Math.max(p, q);
182
+ if (j === i + 1 || (i === 0 && j === n - 1))
183
+ return false;
184
+ return segmentsIntersect(ring[i], ring[i + 1], ring[j], ring[j + 1]);
185
+ });
186
+ }
92
187
  export function pointInRing(p, ring) {
93
188
  let inside = false;
94
189
  for (let i = 0, j = ring.length - 2; i < ring.length - 1; j = i++) {
@@ -101,22 +196,37 @@ export function pointInRing(p, ring) {
101
196
  }
102
197
  return inside;
103
198
  }
104
- function ringsIntersect(a, b) {
199
+ function ringsIntersectReference(a, b) {
105
200
  for (let i = 0; i < a.length - 1; i++)
106
201
  for (let j = 0; j < b.length - 1; j++)
107
202
  if (segmentsIntersect(a[i], a[i + 1], b[j], b[j + 1]))
108
203
  return true;
109
204
  return false;
110
205
  }
206
+ /** Touching counts as intersecting. Boxes are cached per validPolygon call. */
207
+ function ringsIntersect(a, b, cache) {
208
+ if (a.length - 1 < INDEX_MIN_SEGMENTS && b.length - 1 < INDEX_MIN_SEGMENTS)
209
+ return ringsIntersectReference(a, b);
210
+ const boxesOf = (r) => {
211
+ if (!cache.has(r))
212
+ cache.set(r, segmentBoxes(r));
213
+ return cache.get(r);
214
+ };
215
+ const A = boxesOf(a), B = boxesOf(b);
216
+ if (!A || !B)
217
+ return ringsIntersectReference(a, b);
218
+ return sweepBetween(A, B, (i, j) => segmentsIntersect(a[i], a[i + 1], b[j], b[j + 1]));
219
+ }
111
220
  export function validPolygon(rings) {
112
221
  if (!rings.length || rings.some((r) => !simpleClosedRing(r)))
113
222
  return false;
223
+ const cache = new Map();
114
224
  for (let i = 1; i < rings.length; i++) {
115
225
  if (!pointInRing(rings[i][0], rings[0]) ||
116
- ringsIntersect(rings[0], rings[i]))
226
+ ringsIntersect(rings[0], rings[i], cache))
117
227
  return false;
118
228
  for (let j = 1; j < i; j++) {
119
- if (ringsIntersect(rings[j], rings[i]) ||
229
+ if (ringsIntersect(rings[j], rings[i], cache) ||
120
230
  pointInRing(rings[i][0], rings[j]) ||
121
231
  pointInRing(rings[j][0], rings[i]))
122
232
  return false;
package/dist/index.d.ts CHANGED
@@ -5,9 +5,10 @@ export { buildBlgTree, selectBlgPositions, stableBlgRandom, assertBlgInvariants,
5
5
  export { createSpatialIndex } from "./spatial-index.js";
6
6
  export { exportPartitions, encodePartition, decodePartition, checksum, requiredPartitionKeys, partitionsWithVerticesInBounds, } from "./partition.js";
7
7
  export { QuadstreamSession } from "./session.js";
8
+ export type { SessionQueryResult } from "./session.js";
8
9
  export { QuadstreamLoader, fetchFromBundle } from "./loader.js";
9
10
  export type { PartitionFetcher, LoaderOptions } from "./loader.js";
10
- export { validPolygon, simpleClosedRing, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
11
+ export { validPolygon, simpleClosedRing, simpleClosedRingReference, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
11
12
  export type * from "./types.js";
12
13
  export { importGeoJSON, exportGeoJSON, importTopoJSON, exportTopoJSON, } from "./adapters.js";
13
14
  export type { TopoJSONTopology } from "./adapters.js";
@@ -19,4 +20,21 @@ export type { MapLibreLike, MapLibreAdapterOptions, } from "./maplibre-adapter.j
19
20
  export { canonicalLonLat, lonLatVector, angularDistance, validGreatCirclePath, sphericalCellAddress, buildSphericalPriorities, sphericalChart, projectSpherical, sphericalPolygonSignature, validSphericalPolygon, } from "./spherical-geometry.js";
20
21
  export type { UnitVector, CubeFace, SphericalCell, SphericalPriorities, SphericalChart, SphericalPolygonSignature, } from "./spherical-geometry.js";
21
22
  export { SphericalQuadstreamDataset, buildSphericalQuadstream, importSphericalTopoJSON, } from "./spherical-dataset.js";
22
- export type { SphericalQueryOptions } from "./spherical-dataset.js";
23
+ export type { SphericalBuildOptions, SphericalQueryOptions, } from "./spherical-dataset.js";
24
+ export { computeFeatureCap, computeFeatureCaps, isCapVisible, filterSphericalFeatures, } from "./spherical-cull.js";
25
+ export type { SphericalCap, SphericalViewCone } from "./spherical-cull.js";
26
+ export { clipWindow, clipToWindow } from "./spherical-clip.js";
27
+ export type { SphericalClipWindow, SphericalClipStats, SphericalClipResult, } from "./spherical-clip.js";
28
+ export { repairRing, repairGeometry } from "./spherical-repair.js";
29
+ export type { SphericalRepairOptions } from "./spherical-repair.js";
30
+ export { createLatestGeometry, improvesLod } from "./lod-scheduler.js";
31
+ export type { LatestGeometryOptions } from "./lod-scheduler.js";
32
+ export { sphericalConnectedComponents, buildRobustSphericalGroups, } from "./spherical-robust-dataset.js";
33
+ export type { SphericalBuildGroup, RobustSphericalOptions, } from "./spherical-robust-dataset.js";
34
+ export { packGeometry, unpackGeometry } from "./geometry-wire.js";
35
+ export type { PackedGeometry } from "./geometry-wire.js";
36
+ export { createSphericalViewClipper } from "./spherical-view-clipper.js";
37
+ export type { SphericalViewClipperOptions, CachedSphericalClipResult, } from "./spherical-view-clipper.js";
38
+ export { createSphericalLineClipper, clipLineToCone, edgeIntersectsCone, } from "./spherical-line.js";
39
+ export type { SphericalLineStats, SphericalLineResult, } from "./spherical-line.js";
40
+ export type { CooperativeOptions, WorkProgress } from "./cooperative.js";
package/dist/index.js CHANGED
@@ -6,10 +6,18 @@ export { createSpatialIndex } from "./spatial-index.js";
6
6
  export { exportPartitions, encodePartition, decodePartition, checksum, requiredPartitionKeys, partitionsWithVerticesInBounds, } from "./partition.js";
7
7
  export { QuadstreamSession } from "./session.js";
8
8
  export { QuadstreamLoader, fetchFromBundle } from "./loader.js";
9
- export { validPolygon, simpleClosedRing, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
9
+ export { validPolygon, simpleClosedRing, simpleClosedRingReference, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
10
10
  export { importGeoJSON, exportGeoJSON, importTopoJSON, exportTopoJSON, } from "./adapters.js";
11
11
  export { validateManifest, MANIFEST_VERSION } from "./manifest-schema.js";
12
12
  export { ProgressiveMap } from "./progressive-map.js";
13
13
  export { attachMapLibre, mapLibreBounds } from "./maplibre-adapter.js";
14
14
  export { canonicalLonLat, lonLatVector, angularDistance, validGreatCirclePath, sphericalCellAddress, buildSphericalPriorities, sphericalChart, projectSpherical, sphericalPolygonSignature, validSphericalPolygon, } from "./spherical-geometry.js";
15
15
  export { SphericalQuadstreamDataset, buildSphericalQuadstream, importSphericalTopoJSON, } from "./spherical-dataset.js";
16
+ export { computeFeatureCap, computeFeatureCaps, isCapVisible, filterSphericalFeatures, } from "./spherical-cull.js";
17
+ export { clipWindow, clipToWindow } from "./spherical-clip.js";
18
+ export { repairRing, repairGeometry } from "./spherical-repair.js";
19
+ export { createLatestGeometry, improvesLod } from "./lod-scheduler.js";
20
+ export { sphericalConnectedComponents, buildRobustSphericalGroups, } from "./spherical-robust-dataset.js";
21
+ export { packGeometry, unpackGeometry } from "./geometry-wire.js";
22
+ export { createSphericalViewClipper } from "./spherical-view-clipper.js";
23
+ export { createSphericalLineClipper, clipLineToCone, edgeIntersectsCone, } from "./spherical-line.js";
package/dist/loader.d.ts CHANGED
@@ -27,7 +27,7 @@ export declare class QuadstreamLoader {
27
27
  signal?: AbortSignal;
28
28
  }): Promise<void>;
29
29
  /** Supersede the preceding latest-view request without clearing valid stored geometry. */
30
- loadLatest(query?: QueryOptions): Promise<ReturnType<QuadstreamSession["query"]>>;
30
+ loadLatest(query?: QueryOptions): Promise<Awaited<ReturnType<QuadstreamSession["query"]>>>;
31
31
  cancelLatest(): void;
32
32
  }
33
33
  /** In-memory adapter for examples and deterministic end-to-end tests. */
package/dist/loader.js CHANGED
@@ -116,7 +116,7 @@ export class QuadstreamLoader {
116
116
  await this.ensureLevel(query.level ?? this.session.manifest.maxLevel - 1, { signal: controller.signal });
117
117
  if (controller.signal.aborted)
118
118
  throw abortError();
119
- return this.session.query(query);
119
+ return await this.session.query({ ...query, signal: controller.signal });
120
120
  }
121
121
  finally {
122
122
  if (this.latestRequest === controller)
@@ -0,0 +1,15 @@
1
+ export interface LatestGeometryOptions<T> {
2
+ request: (level: number) => Promise<T>;
3
+ onFrame: (frame: T) => void;
4
+ onError?: (error: unknown) => void;
5
+ cacheCapacity?: number;
6
+ }
7
+ export declare function improvesLod(level: number, rendered: number | null, target: number | null): boolean;
8
+ export declare function createLatestGeometry<T extends {
9
+ seq?: number;
10
+ }>({ request, onFrame, onError, cacheCapacity, }: LatestGeometryOptions<T>): {
11
+ select(level: number): Promise<void>;
12
+ invalidate: () => void;
13
+ dispose(): void;
14
+ readonly target: number | null;
15
+ };
@@ -0,0 +1,85 @@
1
+ // Compare against the current target, not the target at dispatch time.
2
+ // A first frame is useful; subsequent frames must strictly reduce LOD error.
3
+ export function improvesLod(level, rendered, target) {
4
+ return (target != null &&
5
+ (rendered == null || Math.abs(level - target) < Math.abs(rendered - target)));
6
+ }
7
+ // Completion-driven throttle: one active query, one replaceable desired level.
8
+ // Completed obsolete frames remain cached but cannot regress visible detail.
9
+ export function createLatestGeometry({ request, onFrame, onError = () => { }, cacheCapacity = 4, }) {
10
+ if (!Number.isInteger(cacheCapacity) || cacheCapacity < 0)
11
+ throw new Error("Invalid cache capacity");
12
+ let generation = 0, lastSeq = 0, desired = null, rendered = null, running = false, disposed = false;
13
+ const cache = new Map();
14
+ async function drain() {
15
+ if (running || disposed)
16
+ return;
17
+ running = true;
18
+ try {
19
+ while (!disposed && desired !== null && desired !== rendered) {
20
+ const level = desired, id = generation;
21
+ try {
22
+ let frame = cache.get(level);
23
+ if (!frame) {
24
+ frame = await request(level);
25
+ if (disposed || id !== generation)
26
+ continue;
27
+ const seq = frame?.seq;
28
+ if (seq != null) {
29
+ if (seq < lastSeq)
30
+ throw new Error("Out-of-order geometry frame");
31
+ lastSeq = seq;
32
+ }
33
+ cache.set(level, frame);
34
+ if (cache.size > cacheCapacity)
35
+ cache.delete(cache.keys().next().value);
36
+ }
37
+ if (improvesLod(level, rendered, desired)) {
38
+ rendered = level;
39
+ onFrame(frame);
40
+ }
41
+ }
42
+ catch (e) {
43
+ if (disposed || id !== generation)
44
+ continue;
45
+ // An obsolete failure must not block the newest target. A failure
46
+ // of the current target may be retried by a subsequent selection.
47
+ if (desired === level) {
48
+ desired = null;
49
+ onError(e);
50
+ }
51
+ }
52
+ }
53
+ }
54
+ finally {
55
+ running = false;
56
+ }
57
+ }
58
+ function invalidate() {
59
+ generation++;
60
+ lastSeq = 0;
61
+ desired = null;
62
+ rendered = null;
63
+ cache.clear();
64
+ }
65
+ return {
66
+ async select(level) {
67
+ if (!Number.isFinite(level))
68
+ throw new Error("Invalid LOD");
69
+ if (disposed)
70
+ return;
71
+ desired = level;
72
+ // While busy this records intent only; the existing drain owns the
73
+ // query and will consume the latest target when that query completes.
74
+ await drain();
75
+ },
76
+ invalidate,
77
+ dispose() {
78
+ disposed = true;
79
+ invalidate();
80
+ },
81
+ get target() {
82
+ return desired;
83
+ },
84
+ };
85
+ }
@@ -3,7 +3,7 @@ import type { QuadstreamSession } from "./session.js";
3
3
  import type { QueryOptions } from "./types.js";
4
4
  export type MapQuery = Omit<QueryOptions, "validate">;
5
5
  export interface MapFrame {
6
- result: ReturnType<QuadstreamSession["query"]>;
6
+ result: Awaited<ReturnType<QuadstreamSession["query"]>>;
7
7
  targetLevel: number;
8
8
  final: boolean;
9
9
  loadedPartitions: number;
@@ -1,3 +1,4 @@
1
+ import { assertBounds } from "./geometry.js";
1
2
  function aborted() {
2
3
  const e = new Error("Map request cancelled");
3
4
  e.name = "AbortError";
@@ -71,9 +72,10 @@ export class ProgressiveMap {
71
72
  }
72
73
  }
73
74
  };
74
- const emit = (level, final) => {
75
+ const emit = async (level, final) => {
76
+ check();
77
+ const result = await session.query({ level, bounds, signal });
75
78
  check();
76
- const result = session.query({ level, bounds });
77
79
  if (final && !result.complete)
78
80
  throw new Error("Incomplete final geometry");
79
81
  onFrame({
@@ -87,21 +89,23 @@ export class ProgressiveMap {
87
89
  };
88
90
  try {
89
91
  session.missingKeys(target);
90
- session.query({ level: target, bounds }); // validate bounds before fetching
92
+ if (bounds)
93
+ assertBounds(bounds); // validate bounds before fetching
91
94
  for (const level of [...new Set([0, Math.floor(target / 2), target])]) {
92
95
  await ensure(level);
93
- const global = session.query({ level });
96
+ const global = await session.query({ level, signal });
97
+ check();
94
98
  if (level === target) {
95
99
  if (!global.complete) {
96
- emit(level, false);
100
+ await emit(level, false);
97
101
  await ensure(session.manifest.maxLevel - 1);
98
- if (!session.query({ level }).complete)
102
+ if (!(await session.query({ level, signal })).complete)
99
103
  throw new Error("Incomplete global geometry");
100
104
  }
101
- emit(level, true);
105
+ await emit(level, true);
102
106
  }
103
107
  else
104
- emit(level, false);
108
+ await emit(level, false);
105
109
  }
106
110
  }
107
111
  finally {
@@ -1,3 +1,4 @@
1
+ import { type Work } from "./cooperative.js";
1
2
  import type { Bounds, SparseQuadtree, Vertex } from "./types.js";
2
3
  export declare function cellKey(level: number, i: number, j: number): string;
3
4
  export declare function cellAddress(x: number, y: number, bounds: Bounds, level: number): {
@@ -6,3 +7,4 @@ export declare function cellAddress(x: number, y: number, bounds: Bounds, level:
6
7
  };
7
8
  /** Assign each distinct vertex to the first unoccupied quadtree cell, coarse to fine. */
8
9
  export declare function buildSparseQuadtree(vertices: readonly Vertex[], bounds: Bounds, maxLevel?: number): SparseQuadtree;
10
+ export declare function buildSparseQuadtreeSteps(vertices: readonly Vertex[], bounds: Bounds, maxLevel?: number): Work<SparseQuadtree>;
package/dist/quadtree.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { runSync } from "./cooperative.js";
1
2
  import { assertBounds } from "./geometry.js";
2
3
  export function cellKey(level, i, j) {
3
4
  return `${level}_${i}_${j}`;
@@ -22,6 +23,9 @@ export function cellAddress(x, y, bounds, level) {
22
23
  }
23
24
  /** Assign each distinct vertex to the first unoccupied quadtree cell, coarse to fine. */
24
25
  export function buildSparseQuadtree(vertices, bounds, maxLevel = 20) {
26
+ return runSync(buildSparseQuadtreeSteps(vertices, bounds, maxLevel));
27
+ }
28
+ export function* buildSparseQuadtreeSteps(vertices, bounds, maxLevel = 20) {
25
29
  assertBounds(bounds);
26
30
  if (!Number.isInteger(maxLevel) || maxLevel < 1 || maxLevel > 26)
27
31
  throw new Error("maxLevel must be 1..26");
@@ -30,7 +34,15 @@ export function buildSparseQuadtree(vertices, bounds, maxLevel = 20) {
30
34
  a.y - b.y ||
31
35
  a.id - b.id);
32
36
  const occupied = new Set(), cells = [], levelByVertexId = [];
37
+ let processed = 0;
33
38
  for (const v of sorted) {
39
+ if (processed % 512 === 0)
40
+ yield {
41
+ stage: "Planar priorities",
42
+ completed: processed,
43
+ total: sorted.length,
44
+ };
45
+ processed++;
34
46
  let inserted = false;
35
47
  for (let level = 0; level < maxLevel; level++) {
36
48
  const { i, j } = cellAddress(v.x, v.y, bounds, level), key = cellKey(level, i, j);