@vizhub/quadstream 0.0.0-stage → 0.3.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 (57) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +21 -0
  3. package/README.md +718 -2
  4. package/bin/quadstream.mjs +240 -0
  5. package/dist/adapters.d.ts +26 -0
  6. package/dist/adapters.js +229 -0
  7. package/dist/blg.d.ts +17 -0
  8. package/dist/blg.js +83 -0
  9. package/dist/dataset.d.ts +16 -0
  10. package/dist/dataset.js +61 -0
  11. package/dist/geometry-wire.d.ts +8 -0
  12. package/dist/geometry-wire.js +76 -0
  13. package/dist/geometry.d.ts +15 -0
  14. package/dist/geometry.js +236 -0
  15. package/dist/index.d.ts +36 -0
  16. package/dist/index.js +22 -0
  17. package/dist/loader.d.ts +34 -0
  18. package/dist/loader.js +138 -0
  19. package/dist/lod-scheduler.d.ts +15 -0
  20. package/dist/lod-scheduler.js +85 -0
  21. package/dist/manifest-schema.d.ts +4 -0
  22. package/dist/manifest-schema.js +141 -0
  23. package/dist/maplibre-adapter.d.ts +30 -0
  24. package/dist/maplibre-adapter.js +84 -0
  25. package/dist/partition.d.ts +13 -0
  26. package/dist/partition.js +124 -0
  27. package/dist/progressive-map.d.ts +28 -0
  28. package/dist/progressive-map.js +112 -0
  29. package/dist/quadtree.d.ts +8 -0
  30. package/dist/quadtree.js +50 -0
  31. package/dist/reconstruct.d.ts +27 -0
  32. package/dist/reconstruct.js +145 -0
  33. package/dist/session.d.ts +24 -0
  34. package/dist/session.js +116 -0
  35. package/dist/spatial-index.d.ts +9 -0
  36. package/dist/spatial-index.js +63 -0
  37. package/dist/spherical-clip.d.ts +95 -0
  38. package/dist/spherical-clip.js +557 -0
  39. package/dist/spherical-cull.d.ts +25 -0
  40. package/dist/spherical-cull.js +93 -0
  41. package/dist/spherical-dataset.d.ts +55 -0
  42. package/dist/spherical-dataset.js +305 -0
  43. package/dist/spherical-geometry.d.ts +39 -0
  44. package/dist/spherical-geometry.js +229 -0
  45. package/dist/spherical-preprocess.d.ts +19 -0
  46. package/dist/spherical-preprocess.js +144 -0
  47. package/dist/spherical-repair.d.ts +17 -0
  48. package/dist/spherical-repair.js +100 -0
  49. package/dist/spherical-robust-dataset.d.ts +27 -0
  50. package/dist/spherical-robust-dataset.js +89 -0
  51. package/dist/spherical-view-clipper.d.ts +22 -0
  52. package/dist/spherical-view-clipper.js +85 -0
  53. package/dist/topology.d.ts +11 -0
  54. package/dist/topology.js +229 -0
  55. package/dist/types.d.ts +123 -0
  56. package/dist/types.js +1 -0
  57. package/package.json +79 -4
package/README.md CHANGED
@@ -1,3 +1,719 @@
1
- # Temporary Holding Version
1
+ # Quadstream
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Progressive, topology-aware, multiresolution geometry for the web.**
4
+
5
+ Quadstream prepares geographic shapes at multiple levels of detail while
6
+ sharing exactly matching boundaries. Build once, query a simpler representation
7
+ for a map or globe, or serialize planar geometry into independently loadable
8
+ binary partitions. The TypeScript-first core is ESM with no runtime dependencies,
9
+ and requires no VizHub account, map framework or server.
10
+
11
+ > **Experimental 0.1.0.** Reference validation can be expensive; do not use it
12
+ > for safety-critical geometry.
13
+
14
+ ## Features
15
+
16
+ - Deterministic spatial vertex priorities and BLG-style ordered reconstruction.
17
+ - Exact shared arcs, reversible references and explicit validity fallback.
18
+ - Planar viewport queries, GeoJSON/TopoJSON adapters and versioned binary partitions.
19
+ - Transport-independent progressive loading with cancellation and a bounded raw-byte cache.
20
+ - Experimental spherical geometry for D3 globes, including seam and pole aliases.
21
+ - Standalone CLI and local Canvas, MapLibre and D3 globe demos.
22
+
23
+ ## Install
24
+
25
+ Install from npm when version 0.1.0 is available (Node.js 20+, ESM):
26
+
27
+ ```sh
28
+ npm install @vizhub/quadstream
29
+ ```
30
+
31
+ Alternatively, build from a checkout:
32
+
33
+ ```sh
34
+ git clone https://github.com/vizhub-studio/quadstream.git
35
+ cd quadstream
36
+ npm ci
37
+ npm run build
38
+ node examples/hello.mjs
39
+ npm pack
40
+ ```
41
+
42
+ The generated tarball can be installed into a separate project. The following
43
+ examples use the package's public import path. From a checkout, examples in
44
+ `examples/` instead import `../dist/index.js`.
45
+
46
+ ## Quick start: planar geometry
47
+
48
+ ```js
49
+ import { buildQuadstream } from "@vizhub/quadstream";
50
+
51
+ const source = {
52
+ type: "FeatureCollection",
53
+ features: [
54
+ {
55
+ type: "Feature",
56
+ id: "square",
57
+ properties: { value: 42 },
58
+ geometry: {
59
+ type: "Polygon",
60
+ coordinates: [
61
+ [
62
+ [0, 0],
63
+ [10, 0],
64
+ [10, 10],
65
+ [0, 10],
66
+ [0, 0],
67
+ ],
68
+ ],
69
+ },
70
+ },
71
+ ],
72
+ };
73
+
74
+ const dataset = buildQuadstream(source, { maxLevel: 12 });
75
+ const result = dataset.query({ level: 4, bounds: [0, 0, 10, 10] });
76
+ console.log(result.geojson, result.usedFallback);
77
+ ```
78
+
79
+ Detail levels run from 0 (coarsest) to `maxLevel - 1` (finest).
80
+ The returned feature collection can be rendered with your preferred renderer.
81
+ TypeScript users can annotate the source with the exported `FeatureCollection`
82
+ type.
83
+
84
+ The planar engine interprets coordinates as Cartesian numbers. Project or
85
+ split dateline-crossing geography upstream; use the spherical API for
86
+ great-circle globe geometry.
87
+
88
+ ## Progressive planar loading
89
+
90
+ ```js
91
+ import {
92
+ exportPartitions,
93
+ QuadstreamSession,
94
+ QuadstreamLoader,
95
+ fetchFromBundle,
96
+ } from "@vizhub/quadstream";
97
+
98
+ const bundle = exportPartitions(dataset, { fileDepth: 3 });
99
+ const session = new QuadstreamSession(bundle.manifest);
100
+ const loader = new QuadstreamLoader(session, fetchFromBundle(bundle), {
101
+ concurrency: 4,
102
+ cacheBytes: 1024 * 1024,
103
+ });
104
+
105
+ const frame = await loader.loadLatest({ level: 4 });
106
+ console.log(frame.geojson, frame.complete, frame.usedFallback);
107
+ ```
108
+
109
+ Replace `fetchFromBundle` with an async function accepting a partition key and
110
+ `{ signal }` to retrieve bytes from your own transport. The session validates
111
+ partition checksums, sizes and records before ingestion. A new latest-view
112
+ request cancels the preceding one. Partial session queries report incomplete
113
+ or omitted features until required partitions arrive.
114
+
115
+ The raw-byte cache does not evict parsed session vertices. The planner is
116
+ conservative: it may request partitions outside the viewport to reconstruct
117
+ segments that cross it. No production HTTP/CDN client is bundled.
118
+
119
+ ## Spherical geometry and D3
120
+
121
+ Use the distinct spherical engine for longitude/latitude coordinates in
122
+ degrees with D3 spherical winding (clockwise small polygon interiors).
123
+ The following example assumes a TopoJSON atlas is already loaded:
124
+
125
+ ```js
126
+ import {
127
+ buildSphericalQuadstream,
128
+ importSphericalTopoJSON,
129
+ } from "@vizhub/quadstream";
130
+
131
+ const countries = importSphericalTopoJSON(atlas, "countries");
132
+ const globe = buildSphericalQuadstream(countries, { maxLevel: 20 });
133
+ const { geojson, valid, promotedArcs } = globe.query({ level: 8.5 });
134
+ // Supply geojson to your D3 geoPath renderer.
135
+ ```
136
+
137
+ Spherical queries reconstruct global geometry in memory. Fractional detail uses
138
+ stable vertex-ID hashing for nominal priorities and topology-safe preprocessing
139
+ for corrected activation thresholds, without query-time promotion. They do not support
140
+ planar viewport bounds, v1 partition serialization or network streaming.
141
+ They may reject inputs that cannot be validated in the reference hemisphere
142
+ chart. See [spherical semantics](https://github.com/vizhub-studio/quadstream/blob/master/docs/SPHERICAL.md).
143
+
144
+ ### Spherical visibility and clipping
145
+
146
+ The geometry library also provides renderer-independent visibility helpers:
147
+
148
+ ```ts
149
+ import {
150
+ lonLatVector,
151
+ computeFeatureCaps,
152
+ filterSphericalFeatures,
153
+ clipWindow,
154
+ clipToWindow,
155
+ } from "@vizhub/quadstream";
156
+
157
+ const [x, y, z] = lonLatVector([10, 45]);
158
+ const window = clipWindow(x, y, z, Math.PI / 12);
159
+ const caps = computeFeatureCaps(countries);
160
+ const visible = filterSphericalFeatures(countries, window, caps);
161
+ const { geojson, stats } = clipToWindow(visible, window);
162
+ ```
163
+
164
+ Centers are unit vectors and angular radii are in radians. Clipping
165
+ windows support radii from zero up to (but excluding) a hemisphere;
166
+ nondegenerate polygon output requires a positive radius. The input uses
167
+ D3 spherical winding and minor great-circle arcs. Clipping accepts only
168
+ Polygon and MultiPolygon feature collections; culling conservatively
169
+ keeps line geometry. Supplied caps must correspond to the features in
170
+ order and conservatively bound their current geometry. Caps are based on
171
+ vertices with a fixed margin; they are not certified bounds for arbitrary
172
+ large-interior or malformed spherical polygons. Boundary walks approximate
173
+ small circles by great-circle segments, and the existing polygon
174
+ reconstruction is not a general-purpose topology-preserving intersection
175
+ operation. The functions do not mutate inputs, but can reuse input
176
+ features and rings by reference. Treat those as immutable. Statistics
177
+ report output features, vertices, ring outcomes and classified positions.
178
+
179
+ These are post-query rendering helpers, not viewport-aware spherical
180
+ reconstruction or network streaming. Camera projection, padded-window
181
+ caching and D3 rendering remain application concerns.
182
+
183
+ ## Interactive demos
184
+
185
+ The React/Vite globe is published via GitHub Pages at
186
+ <https://vizhub-studio.github.io/quadstream/> (after the first successful deployment).
187
+ See the [deployment and local development instructions](quadstream-globe/README.md).
188
+
189
+ From a checkout, install dependencies and build, then run either command:
190
+
191
+ | Demo | Command | What it demonstrates |
192
+ | ------------------ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
193
+ | Progressive map | `npm run demo:map` | Canvas/MapLibre, detail levels, shared arcs, simulated partition latency |
194
+ | Orthographic globe | `npm run demo:globe` | D3 Canvas, Visionscarto 110m/50m inputs, zoom-gated US state/county boundaries, pinch zoom, rotation, worker-based LOD and original/reconstructed comparison |
195
+
196
+ Open the local URL printed by the server (normally http://127.0.0.1:4173/).
197
+ The demos are not included in the npm artifact. The globe downloads the full
198
+ atlas up front; its LOD reduction is not a bandwidth-saving streaming protocol.
199
+ See [map demo](https://github.com/vizhub-studio/quadstream/blob/master/docs/PROGRESSIVE-MAP.md)
200
+ and [globe demo](https://github.com/vizhub-studio/quadstream/blob/master/docs/GLOBE.md).
201
+
202
+ ## CLI
203
+
204
+ After installing the package, run its executable with
205
+ `npx --no-install quadstream` (or use `node bin/quadstream.mjs` from a built checkout):
206
+
207
+ ```sh
208
+ npx --no-install quadstream build countries.geojson countries.bundle --max-level 20 --file-depth 4
209
+ npx --no-install quadstream inspect countries.bundle
210
+ npx --no-install quadstream validate countries.bundle
211
+ npx --no-install quadstream query countries.bundle --level 10 --output simplified.geojson
212
+ npx --no-install quadstream benchmark countries.geojson --iterations 3
213
+ ```
214
+
215
+ The CLI currently operates on planar coordinates. Query output and build
216
+ directories must not already exist. See [CLI and format policy](https://github.com/vizhub-studio/quadstream/blob/master/docs/CLI.md)
217
+ for input restrictions, bounds, exit codes and static staging.
218
+
219
+ ## Public API guide
220
+
221
+ | API | Purpose |
222
+ | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
223
+ | `buildQuadstream`, `QuadstreamDataset` | Build planar multiresolution geometry and query by detail/bounds |
224
+ | `buildSphericalQuadstream`, `SphericalQuadstreamDataset`, `importSphericalTopoJSON` | In-memory D3-style geographic reconstruction |
225
+ | `importGeoJSON`, `exportGeoJSON`, `importTopoJSON`, `exportTopoJSON` | Planar geographic interchange |
226
+ | `exportPartitions`, `validateManifest`, `MANIFEST_VERSION` | Versioned planar artifacts |
227
+ | `QuadstreamSession`, `QuadstreamLoader`, `fetchFromBundle` | Partial reconstruction and injected async delivery |
228
+ | `ProgressiveMap`, `attachMapLibre`, `mapLibreBounds` | Renderer-independent orchestration and MapLibre integration |
229
+ | `buildTopology`, `buildSparseQuadtree`, `buildBlgTree`, `createSpatialIndex` | Lower-level algorithm building blocks |
230
+
231
+ See the [export list](https://github.com/vizhub-studio/quadstream/blob/master/src/index.ts)
232
+ and included TypeScript declarations for complete signatures and utilities.
233
+
234
+ ## Detailed API reference
235
+
236
+ The package exports its public API from `src/index.ts` and ships declarations
237
+ with the build. The signatures below describe the stable development-preview
238
+ surface; TypeScript is the authoritative source for exact structural types.
239
+
240
+ ### Core planar dataset
241
+
242
+ ```ts
243
+ buildQuadstream(
244
+ input: FeatureCollection,
245
+ options?: { maxLevel?: number },
246
+ ): QuadstreamDataset
247
+
248
+ dataset.query(options?: {
249
+ level?: number;
250
+ bounds?: Bounds;
251
+ validate?: boolean;
252
+ }): QueryResult
253
+ ```
254
+
255
+ `QuadstreamDataset` exposes `topology`, `quadtree`, and `arcTrees` for
256
+ inspection. `QueryResult` contains `geojson`, the requested `level`, `valid`,
257
+ `usedFallback`, `selectedFeatures`, and `selectedVertices`. `level` ranges
258
+ from `0` through `maxLevel - 1`; the default is the finest level. `bounds`
259
+ selects features by intersecting feature bounds and does not clip geometry.
260
+ Set `validate: false` only when the caller accepts unvalidated reconstructed
261
+ geometry.
262
+
263
+ The public planar model includes `Position`, `Bounds`, `Geometry`, `Feature`,
264
+ `FeatureCollection`, `Topology`, `TopologyFeature`, `Arc`, `TopologyPath`,
265
+ `Vertex`, `SparseQuadtree`, `QueryOptions`, and `QueryResult`. Supported
266
+ geometries are `Polygon`, `MultiPolygon`, `LineString`, and
267
+ `MultiLineString`.
268
+
269
+ ### Topology, priorities, and geometry helpers
270
+
271
+ - `buildTopology(collection)` deduplicates exact coordinates, shared arcs, and
272
+ feature metadata.
273
+ - `buildSparseQuadtree(vertices, bounds, maxLevel)`, `cellKey(level, i, j)`,
274
+ and `cellAddress(key)` expose deterministic sparse spatial priorities.
275
+ - `buildBlgTree(levels)`, `selectBlgPositions(tree, maxLevel)`, and
276
+ `assertBlgInvariants(tree)` expose the ordered vertex-selection structure.
277
+ - `createSpatialIndex(items)` builds a packed bounds index whose `query(bounds)`
278
+ returns matching values.
279
+ - `boundsOf(points)`, `intersects(a, b)`, `simpleClosedRing(ring)`,
280
+ `segmentsIntersect(a, b, c, d)`, `pointInRing(point, ring)`, and
281
+ `validPolygon(rings)` provide the reference planar predicates.
282
+
283
+ These lower-level functions are useful for diagnostics, custom pipelines, and
284
+ tests. They enforce the same finite-coordinate and exact-coordinate policies as
285
+ the dataset builder.
286
+
287
+ ### GeoJSON and TopoJSON
288
+
289
+ - `importGeoJSON(input)` validates and normalizes a GeoJSON
290
+ `FeatureCollection` or `Feature`.
291
+ - `exportGeoJSON(collection)` returns a serializable GeoJSON collection.
292
+ - `importTopoJSON(input)` decodes unquantized or quantized TopoJSON into a
293
+ feature collection.
294
+ - `exportTopoJSON(collection)` writes unquantized TopoJSON with shared arcs.
295
+ - `decodeTopoJSON(input, objectName, position?)` decodes one named TopoJSON
296
+ object with an optional coordinate normalizer.
297
+
298
+ `TopoJSONTopology` is exported for typed adapter integration. TopoJSON arc
299
+ references use standard zero-based indices and bitwise-complement reversal.
300
+ Feature IDs and properties are preserved by the adapters; the core normalizes
301
+ missing IDs and null properties during topology construction.
302
+
303
+ ### Partitioned artifacts and progressive loading
304
+
305
+ ```ts
306
+ exportPartitions(dataset, options?: { fileDepth?: number }): PartitionBundle
307
+ encodePartition(records): Uint8Array
308
+ decodePartition(bytes, maxRecords?): PartitionRecord[]
309
+ validateManifest(input): QuadstreamManifest
310
+ ```
311
+
312
+ `exportPartitions` returns a manifest and `Map<string, Uint8Array>` containing
313
+ deterministic QSTR v1 partitions. `checksum(bytes)` computes the non-authenticating
314
+ FNV-1a corruption check. `requiredPartitionKeys(manifest, level)` returns all
315
+ partitions needed for a level, while `partitionsWithVerticesInBounds(manifest,
316
+ bounds)` is diagnostic vertex coverage and is not a safe request planner.
317
+ `MANIFEST_VERSION` is the current artifact version.
318
+
319
+ `QuadstreamSession` validates a manifest in its constructor, then accepts
320
+ partitions with `load(key, bytes)`. Its `loadedKeys`, `missingKeys(level)`, and
321
+ `query(options)` APIs report partial results through `complete`, `missingKeys`,
322
+ `omittedFeatures`, and `usedFallback`.
323
+
324
+ `QuadstreamLoader` wraps a session with an injected `PartitionFetcher`:
325
+
326
+ ```ts
327
+ type PartitionFetcher = (
328
+ key: string,
329
+ context: { signal: AbortSignal },
330
+ ) => Promise<Uint8Array>;
331
+
332
+ loader.ensureLevel(level, { signal? }): Promise<void>
333
+ loader.loadLatest(query?): Promise<SessionQueryResult>
334
+ loader.cancelLatest(): void
335
+ ```
336
+
337
+ `LoaderOptions` limits per-request concurrency (default `4`, maximum `32`) and
338
+ the optional raw-byte LRU cache (default 16 MiB). `fetchFromBundle(bundle)`
339
+ provides an in-memory fetcher for tests and demos. Fetching, HTTP, retries,
340
+ persistent caching, and authentication remain application responsibilities.
341
+
342
+ ### Progressive map client and MapLibre adapter
343
+
344
+ `ProgressiveMap` stages requests at coarse, intermediate, and target levels.
345
+ Implement `ProgressiveMapClient` with `request(query, onFrame)` and `cancel()`
346
+ when integrating another renderer. Each `MapFrame` reports the session result,
347
+ target level, whether it is final, and loaded/total partition counts.
348
+
349
+ `attachMapLibre(map, loader, options?)` connects the loader to a MapLibre-like
350
+ map interface, and `mapLibreBounds(bounds)` converts the current map bounds to
351
+ the planar query bounds. The adapter intentionally has no MapLibre runtime
352
+ dependency; `MapLibreLike` and `MapLibreAdapterOptions` describe the minimal
353
+ integration surface. See [the progressive map guide](docs/PROGRESSIVE-MAP.md).
354
+
355
+ ### Spherical geographic API
356
+
357
+ ```ts
358
+ importSphericalTopoJSON(input, objectName): FeatureCollection
359
+ buildSphericalQuadstream(
360
+ input: FeatureCollection,
361
+ options?: { maxLevel?: number },
362
+ ): SphericalQuadstreamDataset
363
+ dataset.query(options?: { level?: number }): QueryResult
364
+ ```
365
+
366
+ The spherical API uses longitude/latitude degrees, D3's clockwise-small-interior
367
+ winding convention, minor great-circle arcs, and six cube-face sparse
368
+ priorities. It is intentionally separate from planar partitions and viewport
369
+ culling. Exported helpers include `canonicalLonLat`, `lonLatVector`,
370
+ `angularDistance`, `validGreatCirclePath`, `sphericalCellAddress`,
371
+ `buildSphericalPriorities`, `sphericalChart`, `projectSpherical`,
372
+ `sphericalPolygonSignature`, and `validSphericalPolygon`. Supporting types are
373
+ `UnitVector`, `CubeFace`, `SphericalCell`, `SphericalPriorities`,
374
+ `SphericalChart`, `SphericalPolygonSignature`, and `SphericalQueryOptions`.
375
+ Spherical queries support fractional levels. Preprocessing validates descending
376
+ vertex-removal batches on a conservative tenth-level grid, retaining unsafe
377
+ vertices at level zero. `activationLevels` exposes the corrected thresholds;
378
+ `retainedVertices` counts rejected removals. The legacy `promotedArcs` query
379
+ field is always zero. `valid: false` indicates a reconstruction invariant
380
+ failure, not a request for a finer level. No global full-detail fallback is applied. See [spherical semantics](docs/SPHERICAL.md) for winding,
381
+ poles, seams, charts, and topology junctions.
382
+
383
+ Spherical reconstruction applies three additional safeguards:
384
+
385
+ - vertices shared by three or more feature IDs are critical, preserving
386
+ multi-shape junctions and shared topology;
387
+ - a vertex is promoted to critical when its removal would reverse a ring's
388
+ projected winding, collapse its area, or make a small ring fail the spherical
389
+ validity predicate;
390
+ - closed rings that would reconstruct with fewer than three distinct vertices
391
+ are restored from their source path rather than emitted as degenerate rings.
392
+
393
+ These safeguards and topology-safe preprocessing preserve shared-arc identity
394
+ without promoting the query to a finer level. The globe demo separately isolates malformed
395
+ source features, so one invalid atlas feature does not force its whole
396
+ coordinate-connected component to full detail.
397
+
398
+ ## How it works
399
+
400
+ Quadstream deduplicates exact shared vertices and arcs, assigns deterministic
401
+ spatial importance using a sparse hierarchy, and reconstructs source order
402
+ through Binary Line Generalization (BLG)-style priority trees. Planar geometry
403
+ uses a sparse quadtree, while spherical geometry uses hierarchical occupancy
404
+ on six cube faces. A packed planar spatial index selects viewport candidates.
405
+ The versioned planar binary format stores checksummed vertex batches separately
406
+ from topology metadata.
407
+
408
+ ## Algorithmic complexity and computational geometry
409
+
410
+ These are analytical bounds for the current implementation, not performance
411
+ measurements or guarantees about an idealized Quadstream algorithm. We count
412
+ fixed-width numeric operations and assume expected constant-time Map/Set
413
+ operations and conventional comparison sorting. Space bounds include working
414
+ data and results unless described as auxiliary. Add the size of feature
415
+ properties, identifiers and other metadata when these are not constant-sized.
416
+
417
+ ### Notation
418
+
419
+ - N: input coordinate occurrences, including repeated shared boundaries;
420
+ V: distinct vertices; F: features.
421
+ - A: distinct arcs; M: total vertex positions stored across distinct arcs
422
+ (including repeated endpoints); R: arc references across feature paths.
423
+ - For a query, T is the sum of the full arc lengths across the selected
424
+ references, K is the reconstructed coordinate count, and J is the number
425
+ of selected features. A subscript "all" denotes the whole dataset.
426
+ - L: number of detail levels (currently at most 26); P: partitions;
427
+ B: bytes processed; U: distinct cached query levels.
428
+ - Q: sum of squared vertex counts of individual polygon components being
429
+ validated, counting all rings of each component. For K coordinates,
430
+ Q is at most K². Line validation contributes linear work instead.
431
+
432
+ Shared boundaries make V, M and N different quantities. In particular,
433
+ repeated arc references may make T much larger than the number of distinct
434
+ vertices selected by BLG. For topology built from ordinary supported input,
435
+ V, M, R and F are O(N); a serialized manifest can describe a different
436
+ reference workload.
437
+
438
+ ### Geometry predicates and preprocessing
439
+
440
+ | Algorithm | Time | Space and explanation |
441
+ | ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
442
+ | Coordinate normalization, bounding boxes, signed area (shoelace), ray-cast point-in-ring, great-circle path checks | O(n) for n positions | O(1) auxiliary for scans; O(n) if materializing normalized coordinates |
443
+ | Orientation, segment intersection, bounds intersection/union, cell addressing, angular distance and individual spherical projections | O(1) | O(1); fixed-dimensional arithmetic |
444
+ | Simple-ring validation | O(n²) worst case | O(1) auxiliary; tests nonadjacent segment pairs |
445
+ | Polygon validation (shell and holes) | O(n²) worst case | O(1) auxiliary planar space; ring simplicity, edge-pair intersection and containment tests |
446
+ | Exact-coordinate topology and reversible shared-arc interning | O(N + sum(d_e log d_e) + Q) | O(N); hash interning and adjacency scans, sorting the owner set of each edge e with d_e distinct owning paths |
447
+ | Sparse planar quadtree and six-face spherical priorities | O(V log V + VL) | O(V); deterministic sorting, at most L probes per vertex, one stored occupied cell per vertex |
448
+ | BLG min-Cartesian tree construction | O(m) per arc of length m; O(M) overall | O(m) per arc; each node is pushed and popped at most once on the monotone stack |
449
+ | BLG invariant checking | O(m) | O(m) visited set and traversal |
450
+ | Packed static bounding-volume hierarchy | O(F log F) | O(F) for fixed bucket size; sorting and packing progressively smaller groups |
451
+ | Spherical hemisphere chart construction | O(n) | O(n) vector arrays; individual gnomonic projection is O(1) |
452
+ | Spherical polygon signature and validation | O(n²) | O(n) projected working arrays; minor great-circle edges map to straight segments within the supported open hemisphere |
453
+
454
+ The topology owner-set sorting term is bounded by O(N log N) in the
455
+ fixed-width model. Without source validity checking, topology construction
456
+ would be expected near-linear for ordinary bounded edge ownership. It is not
457
+ a planar arrangement or a general-purpose noding algorithm: crossings and
458
+ differently digitized edges are not split or snapped to infer shared borders.
459
+
460
+ The planar quadtree computes cell addresses directly at each level, rather
461
+ than materializing the complete 4^L grid or descending a pointer tree. The
462
+ spherical variant chooses the dominant Cartesian axis of a unit vector to
463
+ select a cube face, then uses the analogous sparse occupancy test. Neither
464
+ guarantees logarithmic insertion independent of the configured depth and
465
+ coordinate distribution. Dense clusters can exhaust the available levels.
466
+
467
+ Spherical preprocessing also tests whether removing a vertex would reverse
468
+ projected winding or collapse a ring. After a linear projection and area
469
+ pass, each signed-area update takes O(1). For rings with at most 32 stored
470
+ coordinates, it additionally validates the entire candidate polygon.
471
+ For polygon p with n_p coordinates and s_p candidates in these short rings,
472
+ this adds O(sum_p(s_p n_p²)) time in the worst case, with O(N) peak working
473
+ geometry. A polygon with many short holes can therefore incur superquadratic
474
+ preprocessing (a loose O(N³) dataset-wide bound); the short-ring threshold
475
+ does not bound the size of its containing polygon.
476
+
477
+ Combining the phases, planar build time is
478
+ O(N + sum(d_e log d_e) + Q + V log V + VL + M + F log F),
479
+ with O(N + V + M + F) geometry storage. The spherical build substitutes
480
+ spherical predicates, adds the short-ring candidate term above and retains
481
+ the canonical source and signatures, but does not build a planar spatial index.
482
+
483
+ ### Level-of-detail selection and query complexity
484
+
485
+ | Algorithm | Time | Space and explanation |
486
+ | ---------------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
487
+ | BLG threshold traversal | O(t + 1), with t nodes passing the traversal threshold; O(m) worst case | O(h + k) for tree height h and k emitted positions; h can be m |
488
+ | Fractional BLG selection | Same traversal bound | Stable vertex-ID hash is O(1); rejected fractional-level candidates are still visited |
489
+ | Viewport feature lookup | O(w + J log(J + 1)) | O(w + J) conservative auxiliary bound; w counts visited nodes and tested entries; O(F + J log(J + 1)) worst case |
490
+ | Arc/path reconstruction before polygon validation | O(T + K + J) | O(T + K + J) conservative bound for full-ID scans, reversed copies, temporary paths and output |
491
+ | Planar feature reconstruction with validity checking | O(T + K + J + Q) | Same linear working storage; quadratic time does not imply quadratic storage |
492
+ | Spherical topology-safe preprocessing | O(V (T_all + Q_full)) conservative worst-case time; validated batches normally reduce checks | O(V + T_all + A) working storage, plus source and trees |
493
+
494
+ BLG is a min-heap on detail priority and an inorder sequence on path
495
+ position. An entire subtree can be skipped when its root exceeds the
496
+ traversal threshold. For integer levels, t equals k; fractional levels
497
+ also visit next-level candidates that fail their stable hash threshold.
498
+ Selection does not require a balanced tree, and no O(log m) worst-case tree
499
+ height is promised. The iterative traversal avoids call-stack overflow.
500
+
501
+ Importantly, current feature reconstruction collects all original arc IDs
502
+ for potential collapsed-ring restoration, even when BLG emits very few
503
+ vertices. It also repeats selection for each arc reference rather than
504
+ memoizing a shared arc's selected sequence across features. Consequently,
505
+ end-to-end reconstruction is not yet an O(K)-only algorithm. Exact shared
506
+ arcs ensure that both traversal directions refer to the same priority
507
+ sequence; arc reversal and stitching preserve shared coordinate identity.
508
+
509
+ The packed spatial index prunes disjoint bounding volumes, tests candidates
510
+ in intersecting leaves, then sorts results by original ordinal. There is
511
+ no guaranteed O(log F + J) query bound for heavily overlapping boxes.
512
+ Viewport lookup selects whole features rather than clipping their edges.
513
+
514
+ A cold validated planar query first reconstructs features globally to
515
+ determine whether the level is valid (up to O(T_all + F + Q_level)), then
516
+ reconstructs the selected features, possibly at full detail. Its cost is
517
+ therefore the global check plus the index lookup and selected reconstruction
518
+ terms above. The global Boolean decision is cached by exact numeric level,
519
+ using O(U) storage; a warm query avoids that global check but still runs
520
+ per-feature polygon validation during reconstruction. Setting
521
+ `validate: false` bypasses the global decision, not the internal planar
522
+ polygon predicates. A global fallback can raise K and Q to their
523
+ full-resolution values. Fractional levels mean U is not generally bounded
524
+ by L in the in-memory planar engine.
525
+
526
+ Spherical queries always reconstruct the global collection directly from the
527
+ corrected BLG trees and perform one diagnostic validation pass. The descending
528
+ preprocessing pass groups candidate removals by affected polygon or line,
529
+ validates batches, and bisects rejected batches. A shared vertex has a single
530
+ activation threshold across all its arcs. Unrelated cross-feature intersections
531
+ are not checked by the reference validator.
532
+
533
+ ### Adapters, serialization and progressive loading
534
+
535
+ | Algorithm | Time | Space and explanation |
536
+ | ---------------------------------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
537
+ | GeoJSON normalization / export | O(N) plus planar topology validation | O(N); export validates nonempty results again |
538
+ | TopoJSON delta decode, signed arc reversal and stitching | O(D + T_all) | O(D + T_all); D counts positions in all encoded arcs, including unselected named objects |
539
+ | Planar TopoJSON import/export | Decode or encode linear work plus topology construction | O(N + M + R + D) as applicable; export rebuilds topology after GeoJSON validation |
540
+ | Spherical TopoJSON import | Decode plus spherical signatures and topology validation | Linear geometry storage; includes quadratic polygon checks |
541
+ | Partition assignment and export | O(V + P log P + sum_p(v_p log v_p)) | O(V + P) new records, metadata and binary bytes, sharing existing topology; v_p records in partition p |
542
+ | QSTR encoding/decoding and FNV-1a checksum | O(B) | O(B) output for encoding/decoding, O(1) auxiliary checksum space |
543
+ | Manifest schema and reference validation | O(V + M + R + F + P) | O(V + M + R + F + P) conservative working space for IDs, arc copies and path accounting |
544
+ | Required/missing partition planning and diagnostic bounds filter | O(P) | O(P) worst-case key output; loaded membership is expected O(1) |
545
+ | Session construction | O(V + M + P + F log F) | O(V + M + F + P), including global manifest/tree/index data |
546
+ | Session partition ingestion | O(B) | O(B) temporary records and sets, plus retained parsed vertices; repeat loads still checksum the bytes |
547
+ | Loader ensure-level | O(P + B + e) local work | O(P + C b_max + H + V_loaded) excluding manifest/tree data; e cache evictions, C concurrency, b_max max partition bytes, H raw-byte cache budget |
548
+ | Sorted loaded-key enumeration | O(P_loaded log(P_loaded + 1)) | O(P_loaded) output |
549
+
550
+ QSTR v1 stores 10 header bytes plus 22 bytes per vertex record, so total
551
+ binary payload is exactly 10P + 22V bytes, separate from JSON metadata.
552
+ Partition export sorts keys and the records within each partition, and does
553
+ not perform another geometric simplification. The manifest stores global
554
+ topology, arc sequences, partition membership and vertex priorities, so even
555
+ a coarse client starts with O(V + M + R + F + P) structural information
556
+ before fetching all coordinate bytes.
557
+
558
+ Session queries combine the O(P) missing-key scan with the planar index and
559
+ reconstruction bounds. They perform global validity checks only once all
560
+ partitions are loaded; incomplete or invalid features can be omitted.
561
+ The session constructor performs its own structural/accounting checks;
562
+ `validateManifest` is the separate full schema validator.
563
+
564
+ The loader uses expected O(1) Map operations for LRU bookkeeping, amortized
565
+ constant eviction work per insertion, and O(B) copying/checksumming/decoding.
566
+ Its raw-byte budget does not evict parsed vertices or global topology.
567
+ Concurrency bounds active workers per request, not network latency or all
568
+ overlapping transport activity; a fetcher ignoring cancellation can keep
569
+ external work alive. Network time depends on request latency, throughput
570
+ and application transport. A conservative planner scans all partitions by
571
+ minimum level, not only those inside the viewport.
572
+
573
+ ProgressiveMap has at most three distinct normal stages (coarse, intermediate,
574
+ target), a bounded retry loop and optional full-detail rescue. Its total work
575
+ is the sum of loader and session-query costs over those stages, including
576
+ global completeness queries and sorted loaded-key diagnostics. It can fetch
577
+ all V records even for a coarse viewport. The MapLibre adapter adds O(1)
578
+ bounds/zoom and generation bookkeeping per event, excluding user callbacks
579
+ and renderer-side processing. There is no production spherical partition
580
+ protocol yet.
581
+
582
+ The CLI parses/serializes JSON in O(B) time and O(B) memory in the usual
583
+ input-size model, then delegates to the above algorithms. Its chunked reader
584
+ still buffers entire input files. Bundle inspect validates the manifest and
585
+ scans partitions; bundle query/validate load every partition, and query
586
+ export can revalidate or rebuild topology. The benchmark repeats build,
587
+ partition export and coarse/full query for each requested iteration; it is
588
+ not a separate simplification algorithm.
589
+
590
+ ### Globe and map rendering algorithms
591
+
592
+ The demos add computational geometry and scheduling that are not part of the
593
+ dependency-free core. Let n be the number of input positions in a frame,
594
+ c the number of clipping pieces from an individual ring, z the number of
595
+ generated boundary samples, and s the number of minimap samples per edge.
596
+
597
+ | Algorithm | Time | Space and explanation |
598
+ | --------------------------------------------------------------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------- |
599
+ | Atlas cleanup and degenerate-ring filtering | O(n) | O(n) for cleaned paths |
600
+ | Exact-coordinate-connected feature groups | O((n + F)F) conservative worst-case bound | O(n + F); union-find with path halving but no rank/size balancing |
601
+ | D3 area/containment compatibility checks | O(n) coordinate visits for fixed probe count | Excludes D3 internals; compares source and candidate |
602
+ | Feature/ring spherical cap and unit-vector preprocessing | O(n) | O(F) for feature caps; O(n) for cached per-ring vectors |
603
+ | Cached feature-cap visibility filtering | O(F) | O(F) worst-case result; dot-product cone test is O(1) per cap |
604
+ | Minor-arc/cone crossings and winding scan | O(n) per ring | O(n) flags and retained pieces; crossing of one minor arc is O(1) |
605
+ | Ring clipping and boundary walk | O(n + c² + z) | O(n + c + z); each exit scans all entry azimuths |
606
+ | Padded-window clipping cache hit | O(1) | Reuses existing output; drawing still costs work |
607
+ | Geometry worker packing/unpacking | O(n + F) | O(n + F) typed buffers and reconstructed arrays |
608
+ | Zoom hysteresis, quantization, gesture updates and latest-generation checks | O(1) per ordinary update | O(active pointers) gesture state; worker queue coalescing scans pending messages linearly |
609
+ | Minimap viewport sampling | O(s) | O(s) projected boundary samples |
610
+ | Planar Canvas path/segment diagnostics | O(n) expected | O(n) shared-segment map; excludes Canvas rasterization |
611
+
612
+ Ring clipping scans original edges for crossings, then pairs each exit with
613
+ the next entry in the required winding direction by exhaustive search.
614
+ For a collection the quadratic term is the sum of c² across processed rings.
615
+ Each piece has at most a fixed number of boundary samples at the current
616
+ four-degree step, so z is O(n) at that setting. A finer configurable step
617
+ would increase the output term. The cached padded cone avoids recomputing
618
+ clipping on every small camera movement; it does not accelerate the global
619
+ spherical engine query or change the original topology.
620
+
621
+ The globe's fallback preprocessing can attempt a whole collection, individual
622
+ features, a valid subset, and connected components. A constant number of
623
+ dataset-wide build attempts (some divided into disjoint groups) plus
624
+ component grouping and compatibility checks bounds that path; it can still
625
+ be costly. The component algorithm's loose bound above does not claim the
626
+ inverse-Ackermann guarantee of union-by-rank plus path compression.
627
+
628
+ The demo caches up to 48 worker geometry frames and four client frames.
629
+ With K_max maximum frame size their geometry can occupy O((48 + 4)K_max)
630
+ space, in addition to source data, topology, in-flight messages and
631
+ per-frame clipping caches. Worker wire encoding stores two Float64 values
632
+ per coordinate plus Int32 counts for features/polygons/rings; transfer avoids
633
+ an extra buffer copy where supported but not packing/unpacking work.
634
+ Cancellation is cooperative, and one expensive feature can exceed a nominal
635
+ time slice.
636
+
637
+ D3 projection, adaptive resampling and clipping, Canvas rasterization,
638
+ MapLibre triangulation and GPU rendering are external to these bounds.
639
+ Geometry traversal is linear in supplied coordinates before adaptive
640
+ resampling; projected sample count, pixel area and renderer internals
641
+ determine actual rendering work. The minimap also draws full-globe context
642
+ even when the main view is culled.
643
+
644
+ ### What these bounds imply
645
+
646
+ - The principal asymptotic bottleneck is pairwise geometric validation, not
647
+ Cartesian-tree construction. Spherical preprocessing candidate checks can
648
+ multiply that cost, in exchange for direct query reconstruction.
649
+ - The sparse hierarchy reduces stored grid cells from a potential O(4^L)
650
+ per face to O(V), and shared topology stores each distinct arc once.
651
+ Neither fact makes all feature queries output-sensitive.
652
+ - Reducing validation complexity with robust sweep-line or spatially indexed
653
+ intersection tests is a candidate improvement, not an implemented
654
+ O(n log n) guarantee. Any replacement must preserve the required
655
+ intersection, containment, winding and shared-boundary semantics.
656
+ - Avoiding unconditional full-ID scans, memoizing shared-arc selections,
657
+ indexing arc-to-feature dependencies, and sorting clipping events instead
658
+ of pairing them exhaustively are possible future optimizations. They must
659
+ retain deterministic output and existing validity/fallback behavior.
660
+ - A fair benchmark should separately measure input topology, priority
661
+ construction, BLG, preprocessing validation, cold/warm queries,
662
+ partition metadata and payload bytes, peak memory, and rendering. Compare
663
+ datasets with different vertex counts, feature overlap, hole counts and
664
+ shared-boundary ratios; vertex count alone does not characterize cost.
665
+
666
+ These bounds do not establish topological equivalence for arbitrary
667
+ overlapping geographic features, a screen-space error bound, or a production
668
+ latency guarantee. See the implementation in [src/](src/), the
669
+ [globe demo](examples/globe/) and [roadmap](plans/PROJECT_ROADMAP.md).
670
+
671
+ ## Geometry semantics and limitations
672
+
673
+ - Supported shapes: Polygon, MultiPolygon, LineString and MultiLineString.
674
+ No points, nested geometry collections, 3D coordinates or nonfinite positions.
675
+ - Only exact coordinate matches establish shared borders; no approximate
676
+ snapping or differently digitized boundary reconciliation.
677
+ - Planar bounds filter whole features; they do not clip geometry. Planar IDs
678
+ are normalized to strings, and null properties become empty objects.
679
+ - Full-detail reconstruction retains coordinates and order subject to documented
680
+ normalization and cyclic ring starts. Coarse BLG subsets are nested, but
681
+ validated output may not be monotonic when a fallback occurs.
682
+ - By default, invalid planar simplified geometry triggers a global full-detail
683
+ fallback, not independent per-feature simplification. Partial results are
684
+ explicit; validation does not prove global cross-feature topology.
685
+ - Reference polygon validity checks are quadratic; large-scale performance,
686
+ measured screen-space error, robust global spherical predicates and
687
+ production resource hardening remain future work.
688
+ - Binary checksums detect accidental corruption, not malicious changes.
689
+
690
+ See the [architecture](https://github.com/vizhub-studio/quadstream/blob/master/docs/ARCHITECTURE.md)
691
+ and [roadmap](https://github.com/vizhub-studio/quadstream/blob/master/plans/PROJECT_ROADMAP.md)
692
+ for implementation details and planned work.
693
+
694
+ ## Development
695
+
696
+ ```sh
697
+ npm ci
698
+ npm run check
699
+ npm run lint
700
+ npm run test:package
701
+ npx playwright install --with-deps chromium webkit
702
+ npm run test:globe:browser
703
+ ```
704
+
705
+ Use `npm run prettier` to format maintained sources. CI retains Node 26 and Chromium/WebKit globe regression tests and adds
706
+ packed-package verification for Node 20 and 26. The real-atlas globe tests
707
+ compare original and full-resolution reconstruction across multiple views and
708
+ zoom levels. Physical mobile-device validation and production benchmarks remain
709
+ outstanding. See [contributing](https://github.com/vizhub-studio/quadstream/blob/master/CONTRIBUTING.md).
710
+
711
+ ## History and license
712
+
713
+ Quadstream revives research and prototypes from 2010–2012 in a self-contained
714
+ modern TypeScript implementation. See [historical provenance](https://github.com/vizhub-studio/quadstream/blob/master/docs/HISTORY.md).
715
+
716
+ Run `npm run build` and `npm run demo:globe`. This geometry-only D3 Canvas demo includes touch rotation and repeated pinch zoom, real atlas inputs, Quadstream/original comparison, and render-time view culling and spherical clipping (`?clip=0` to disable; the engine query itself is not viewport-aware). See [globe controls, provenance and limitations](docs/GLOBE.md).
717
+ The modern implementation is MIT-licensed. Historical Java/browser code
718
+ retains its existing license terms.
719
+ See [LICENSE](https://github.com/vizhub-studio/quadstream/blob/master/LICENSE).