@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
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env node
2
+ import { createReadStream } from "node:fs";
3
+ import { mkdir, writeFile, lstat, rm } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { performance } from "node:perf_hooks";
6
+ import { TextDecoder } from "node:util";
7
+ import {
8
+ buildQuadstream,
9
+ exportPartitions,
10
+ QuadstreamSession,
11
+ importGeoJSON,
12
+ importTopoJSON,
13
+ exportGeoJSON,
14
+ exportTopoJSON,
15
+ validateManifest,
16
+ } from "../dist/index.js";
17
+
18
+ const usage = `Quadstream (development preview)
19
+ quadstream build INPUT OUTPUT_DIR [--max-level N] [--file-depth N] [--max-bytes N]
20
+ quadstream validate INPUT_OR_BUNDLE [--max-bytes N]
21
+ quadstream inspect BUNDLE [--max-bytes N]
22
+ quadstream query BUNDLE [--level N] [--bounds xmin,ymin,xmax,ymax] [--format geojson|topojson] [--output FILE] [--max-bytes N]
23
+ quadstream benchmark INPUT [--max-level N] [--iterations N] [--max-bytes N]
24
+ Inputs are GeoJSON or TopoJSON files; all coordinates are planar. Output paths must not exist.
25
+ Exit codes: 0 success, 1 data/IO failure, 2 usage error.
26
+ `;
27
+ class UsageError extends Error {}
28
+ function parse(args, allowed, n) {
29
+ const options = {},
30
+ positional = [];
31
+ for (let i = 0; i < args.length; i++) {
32
+ const token = args[i];
33
+ if (!token.startsWith("--")) {
34
+ positional.push(token);
35
+ continue;
36
+ }
37
+ const key = token.slice(2),
38
+ value = args[++i];
39
+ if (
40
+ !allowed.includes(key) ||
41
+ Object.hasOwn(options, key) ||
42
+ value === undefined ||
43
+ value.startsWith("--")
44
+ )
45
+ throw new UsageError("Invalid option: " + token);
46
+ options[key] = value;
47
+ }
48
+ if (positional.length !== n)
49
+ throw new UsageError("Wrong number of arguments");
50
+ return { options, positional };
51
+ }
52
+ function int(v, min, max, name) {
53
+ if (
54
+ !/^[0-9]+$/.test(String(v)) ||
55
+ !Number.isSafeInteger(Number(v)) ||
56
+ Number(v) < min ||
57
+ Number(v) > max
58
+ )
59
+ throw new UsageError("Invalid " + name);
60
+ return Number(v);
61
+ }
62
+ function budget(max) {
63
+ let remaining = max;
64
+ return async function read(path) {
65
+ const st = await lstat(path);
66
+ if (!st.isFile() || st.size > remaining)
67
+ throw new Error("Not a regular file or byte limit exceeded: " + path);
68
+ const chunks = [];
69
+ let size = 0;
70
+ for await (const chunk of createReadStream(path)) {
71
+ size += chunk.length;
72
+ if (size > remaining) throw new Error("Byte limit exceeded: " + path);
73
+ chunks.push(chunk);
74
+ }
75
+ remaining -= size;
76
+ return Buffer.concat(chunks, size);
77
+ };
78
+ }
79
+ const json = (bytes) =>
80
+ JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
81
+ const asSource = (v) =>
82
+ v?.type === "Topology" ? importTopoJSON(v) : importGeoJSON(v);
83
+ const print = (v) => process.stdout.write(JSON.stringify(v, null, 2) + "\n");
84
+ async function manifest(dir, read) {
85
+ return validateManifest(json(await read(join(dir, "manifest.json"))));
86
+ }
87
+ async function load(dir, read) {
88
+ const m = await manifest(dir, read),
89
+ session = new QuadstreamSession(m);
90
+ for (const p of m.partitions)
91
+ session.load(p.key, await read(join(dir, p.key + ".qstr")));
92
+ return { m, session };
93
+ }
94
+ function inspect(m) {
95
+ return {
96
+ format: m.format,
97
+ version: m.version,
98
+ maxLevel: m.maxLevel,
99
+ fileDepth: m.fileDepth,
100
+ bounds: m.bounds,
101
+ features: m.features.length,
102
+ arcs: m.arcs.length,
103
+ vertices: m.vertices.length,
104
+ partitions: m.partitions.length,
105
+ partitionBytes: m.partitions.reduce((n, p) => n + p.byteLength, 0),
106
+ };
107
+ }
108
+ function bbox(v) {
109
+ const parts = v.split(",");
110
+ if (
111
+ parts.length !== 4 ||
112
+ parts.some((x) => !x.trim() || !Number.isFinite(Number(x)))
113
+ )
114
+ throw new UsageError("Invalid bounds");
115
+ const b = parts.map(Number);
116
+ if (b[0] > b[2] || b[1] > b[3]) throw new UsageError("Invalid bounds order");
117
+ return b;
118
+ }
119
+ async function main() {
120
+ const [cmd, ...args] = process.argv.slice(2);
121
+ if (cmd === "--help" || cmd === "help" || args.includes("--help")) {
122
+ process.stdout.write(usage);
123
+ return;
124
+ }
125
+ const config = {
126
+ build: [["max-level", "file-depth"], 2],
127
+ validate: [[], 1],
128
+ inspect: [[], 1],
129
+ query: [["level", "bounds", "format", "output"], 1],
130
+ benchmark: [["max-level", "iterations"], 1],
131
+ };
132
+ if (!Object.hasOwn(config, cmd)) throw new UsageError("Unknown command");
133
+ const [allowed, n] = config[cmd],
134
+ {
135
+ options: o,
136
+ positional: [input, output],
137
+ } = parse(args, [...allowed, "max-bytes"], n);
138
+ const read = budget(
139
+ int(o["max-bytes"] ?? "67108864", 1, 1073741824, "max-bytes"),
140
+ );
141
+ const maxLevel = () => int(o["max-level"] ?? "20", 1, 26, "max-level");
142
+ if (cmd === "build") {
143
+ const level = maxLevel(),
144
+ depth = int(
145
+ o["file-depth"] ?? String(Math.min(4, level)),
146
+ 1,
147
+ level,
148
+ "file-depth",
149
+ );
150
+ const bundle = exportPartitions(
151
+ buildQuadstream(asSource(json(await read(input))), { maxLevel: level }),
152
+ { fileDepth: depth },
153
+ );
154
+ validateManifest(bundle.manifest);
155
+ await mkdir(output);
156
+ try {
157
+ for (const [key, bytes] of bundle.partitions)
158
+ await writeFile(join(output, key + ".qstr"), bytes, { flag: "wx" });
159
+ await writeFile(
160
+ join(output, "manifest.json"),
161
+ JSON.stringify(bundle.manifest) + "\n",
162
+ { flag: "wx" },
163
+ );
164
+ } catch (e) {
165
+ await rm(output, { recursive: true, force: true });
166
+ throw e;
167
+ }
168
+ print(inspect(bundle.manifest));
169
+ return;
170
+ }
171
+ if (cmd === "inspect") {
172
+ print(inspect(await manifest(input, read)));
173
+ return;
174
+ }
175
+ if (cmd === "validate") {
176
+ if ((await lstat(input)).isDirectory()) {
177
+ const { m, session } = await load(input, read),
178
+ result = session.query({ level: m.maxLevel - 1 });
179
+ if (!result.complete || result.omittedFeatures)
180
+ throw new Error("Incomplete full-detail reconstruction");
181
+ print({ valid: true, ...inspect(m) });
182
+ } else {
183
+ const data = asSource(json(await read(input)));
184
+ print({ valid: true, features: data.features.length });
185
+ }
186
+ return;
187
+ }
188
+ if (cmd === "query") {
189
+ const format = o.format ?? "geojson";
190
+ if (!["geojson", "topojson"].includes(format))
191
+ throw new UsageError("Invalid format");
192
+ const bounds = o.bounds === undefined ? undefined : bbox(o.bounds);
193
+ const { m, session } = await load(input, read);
194
+ const level = int(
195
+ o.level ?? String(m.maxLevel - 1),
196
+ 0,
197
+ m.maxLevel - 1,
198
+ "level",
199
+ );
200
+ const result = session.query({ level, bounds });
201
+ if (!result.complete) throw new Error("Incomplete query result");
202
+ const data =
203
+ format === "topojson"
204
+ ? exportTopoJSON(result.geojson)
205
+ : exportGeoJSON(result.geojson);
206
+ if (o.output !== undefined)
207
+ await writeFile(o.output, JSON.stringify(data) + "\n", { flag: "wx" });
208
+ else print(data);
209
+ return;
210
+ }
211
+ const iterations = int(o.iterations ?? "3", 1, 100, "iterations"),
212
+ level = maxLevel(),
213
+ data = asSource(json(await read(input))),
214
+ runs = [];
215
+ for (let i = 0; i < iterations; i++) {
216
+ const start = performance.now(),
217
+ dataset = buildQuadstream(data, { maxLevel: level }),
218
+ built = performance.now(),
219
+ bundle = exportPartitions(dataset, { fileDepth: Math.min(4, level) }),
220
+ packed = performance.now();
221
+ const coarse = dataset.query({ level: 0 }),
222
+ full = dataset.query({ level: level - 1 }),
223
+ done = performance.now();
224
+ runs.push({
225
+ buildMs: built - start,
226
+ partitionMs: packed - built,
227
+ queryMs: done - packed,
228
+ vertices: dataset.topology.vertices.length,
229
+ coarseVertices: coarse.selectedVertices,
230
+ fullVertices: full.selectedVertices,
231
+ coarseFallback: coarse.usedFallback,
232
+ partitionBytes: inspect(bundle.manifest).partitionBytes,
233
+ });
234
+ }
235
+ print({ iterations, maxLevel: level, runs });
236
+ }
237
+ main().catch((e) => {
238
+ process.stderr.write((e instanceof Error ? e.message : String(e)) + "\n");
239
+ process.exitCode = e instanceof UsageError ? 2 : 1;
240
+ });
@@ -0,0 +1,26 @@
1
+ import type { Feature, FeatureCollection, Geometry, Position } from "./types.js";
2
+ /** Strict planar GeoJSON subset. No CRS transformation, longitude wrapping or snapping. */
3
+ export declare function importGeoJSON(input: unknown): FeatureCollection;
4
+ /** Output accepts an empty query result, unlike the build input. */
5
+ export declare function exportGeoJSON(input: FeatureCollection): FeatureCollection;
6
+ type TopoGeometry = {
7
+ type: Geometry["type"];
8
+ arcs: unknown;
9
+ id?: string | number;
10
+ properties?: Feature["properties"];
11
+ };
12
+ export interface TopoJSONTopology {
13
+ type: "Topology";
14
+ objects: Record<string, {
15
+ type: "GeometryCollection";
16
+ geometries: TopoGeometry[];
17
+ }>;
18
+ arcs: Position[][];
19
+ }
20
+ /** Decode signed zero-based TopoJSON arcs; transformed arcs are delta-encoded per arc. */
21
+ export declare function importTopoJSON(input: unknown): FeatureCollection;
22
+ /** Internal decoder: caller must apply the appropriate coordinate validation. */
23
+ export declare function decodeTopoJSON(input: unknown, objectName?: string, normalize?: (p: Position) => Position): FeatureCollection;
24
+ /** Export unquantized absolute-coordinate TopoJSON, with shared arcs stored once. */
25
+ export declare function exportTopoJSON(input: FeatureCollection): TopoJSONTopology;
26
+ export {};
@@ -0,0 +1,229 @@
1
+ import { buildTopology } from "./topology.js";
2
+ function obj(v, label) {
3
+ if (!v || typeof v !== "object" || Array.isArray(v))
4
+ throw new Error("Invalid " + label);
5
+ return v;
6
+ }
7
+ function arr(v, label) {
8
+ if (!Array.isArray(v))
9
+ throw new Error("Invalid " + label);
10
+ return v;
11
+ }
12
+ function pos(v) {
13
+ const a = arr(v, "position");
14
+ if (a.length !== 2 ||
15
+ a.some((n) => typeof n !== "number" || !Number.isFinite(n)))
16
+ throw new Error("Expected finite planar 2D position");
17
+ return [a[0], a[1]];
18
+ }
19
+ function same(a, b) {
20
+ return a[0] === b[0] && a[1] === b[1];
21
+ }
22
+ function path(v, closed) {
23
+ const p = arr(v, "coordinate path").map(pos);
24
+ if (p.length < (closed ? 4 : 2) || (closed && !same(p[0], p.at(-1))))
25
+ throw new Error("Invalid or unclosed coordinate path");
26
+ return p;
27
+ }
28
+ function nonempty(a) {
29
+ if (!a.length)
30
+ throw new Error("Empty geometry");
31
+ return a;
32
+ }
33
+ function geom(v) {
34
+ const g = obj(v, "geometry"), c = g.coordinates;
35
+ switch (g.type) {
36
+ case "LineString":
37
+ return { type: g.type, coordinates: path(c, false) };
38
+ case "MultiLineString":
39
+ return {
40
+ type: g.type,
41
+ coordinates: nonempty(arr(c, "lines").map((x) => path(x, false))),
42
+ };
43
+ case "Polygon":
44
+ return {
45
+ type: g.type,
46
+ coordinates: nonempty(arr(c, "rings").map((x) => path(x, true))),
47
+ };
48
+ case "MultiPolygon":
49
+ return {
50
+ type: g.type,
51
+ coordinates: nonempty(arr(c, "polygons").map((x) => nonempty(arr(x, "rings").map((y) => path(y, true))))),
52
+ };
53
+ default:
54
+ throw new Error("Unsupported geometry: " + String(g.type));
55
+ }
56
+ }
57
+ function feature(g, metadata) {
58
+ const id = metadata.id;
59
+ if (id !== undefined &&
60
+ typeof id !== "string" &&
61
+ !(typeof id === "number" && Number.isFinite(id)))
62
+ throw new Error("Invalid feature id");
63
+ const properties = metadata.properties == null
64
+ ? null
65
+ : { ...obj(metadata.properties, "properties") };
66
+ return {
67
+ type: "Feature",
68
+ ...(id === undefined ? {} : { id: id }),
69
+ properties,
70
+ geometry: g,
71
+ };
72
+ }
73
+ function collection(features, allowEmpty = false) {
74
+ const fc = { type: "FeatureCollection", features };
75
+ if (features.length || !allowEmpty)
76
+ buildTopology(fc);
77
+ return fc;
78
+ }
79
+ /** Strict planar GeoJSON subset. No CRS transformation, longitude wrapping or snapping. */
80
+ export function importGeoJSON(input) {
81
+ const root = obj(input, "GeoJSON");
82
+ if ("crs" in root)
83
+ throw new Error("Explicit CRS is unsupported; reproject before import");
84
+ const values = root.type === "FeatureCollection" ? arr(root.features, "features") : [root];
85
+ return collection(values.map((value) => {
86
+ const f = obj(value, "feature");
87
+ if (f.type !== "Feature" || "crs" in f)
88
+ throw new Error("Expected GeoJSON Feature without CRS");
89
+ return feature(geom(f.geometry), f);
90
+ }));
91
+ }
92
+ /** Output accepts an empty query result, unlike the build input. */
93
+ export function exportGeoJSON(input) {
94
+ if (input.type !== "FeatureCollection" || !Array.isArray(input.features))
95
+ throw new Error("Expected FeatureCollection");
96
+ if (!input.features.length)
97
+ return { type: "FeatureCollection", features: [] };
98
+ return importGeoJSON(input);
99
+ }
100
+ /** Decode signed zero-based TopoJSON arcs; transformed arcs are delta-encoded per arc. */
101
+ export function importTopoJSON(input) {
102
+ const decoded = decodeTopoJSON(input);
103
+ return collection(decoded.features);
104
+ }
105
+ /** Internal decoder: caller must apply the appropriate coordinate validation. */
106
+ export function decodeTopoJSON(input, objectName, normalize) {
107
+ const root = obj(input, "TopoJSON");
108
+ if (root.type !== "Topology" || "crs" in root)
109
+ throw new Error("Expected Topology without explicit CRS");
110
+ let scale, translate;
111
+ if (root.transform !== undefined) {
112
+ const t = obj(root.transform, "transform");
113
+ scale = pos(t.scale);
114
+ translate = pos(t.translate);
115
+ if (scale.some((n) => n === 0))
116
+ throw new Error("Invalid transform scale");
117
+ }
118
+ const arcs = arr(root.arcs, "arcs").map((raw) => {
119
+ let x = 0, y = 0;
120
+ const points = arr(raw, "arc").map((v) => {
121
+ const p = pos(v);
122
+ if (!scale || !translate)
123
+ return normalize ? normalize(p) : p;
124
+ if (!p.every(Number.isSafeInteger))
125
+ throw new Error("Expected integer transformed delta");
126
+ x += p[0];
127
+ y += p[1];
128
+ if (!Number.isSafeInteger(x) || !Number.isSafeInteger(y))
129
+ throw new Error("Unsafe accumulated delta");
130
+ const decoded = pos([
131
+ x * scale[0] + translate[0],
132
+ y * scale[1] + translate[1],
133
+ ]);
134
+ return normalize ? normalize(decoded) : decoded;
135
+ });
136
+ if (points.length < 2)
137
+ throw new Error("Arc requires at least two positions");
138
+ return points;
139
+ });
140
+ function stitch(v, closed) {
141
+ const out = [];
142
+ for (const ref of nonempty(arr(v, "arc references"))) {
143
+ if (typeof ref !== "number" || !Number.isSafeInteger(ref))
144
+ throw new Error("Invalid arc reference");
145
+ const index = ref < 0 ? -ref - 1 : ref, a = arcs[index];
146
+ if (!a)
147
+ throw new Error("Arc reference out of range");
148
+ const oriented = ref < 0 ? [...a].reverse() : a;
149
+ if (out.length && !same(out.at(-1), oriented[0]))
150
+ throw new Error("Disconnected arcs");
151
+ for (let i = out.length ? 1 : 0; i < oriented.length; i++)
152
+ out.push(oriented[i]);
153
+ }
154
+ return path(out, closed);
155
+ }
156
+ function decode(value) {
157
+ const g = obj(value, "TopoJSON geometry"), a = g.arcs;
158
+ switch (g.type) {
159
+ case "LineString":
160
+ return feature({ type: g.type, coordinates: stitch(a, false) }, g);
161
+ case "MultiLineString":
162
+ return feature({
163
+ type: g.type,
164
+ coordinates: nonempty(arr(a, "lines").map((v) => stitch(v, false))),
165
+ }, g);
166
+ case "Polygon":
167
+ return feature({
168
+ type: g.type,
169
+ coordinates: nonempty(arr(a, "rings").map((v) => stitch(v, true))),
170
+ }, g);
171
+ case "MultiPolygon":
172
+ return feature({
173
+ type: g.type,
174
+ coordinates: nonempty(arr(a, "polygons").map((v) => nonempty(arr(v, "rings").map((w) => stitch(w, true))))),
175
+ }, g);
176
+ default:
177
+ throw new Error("Unsupported TopoJSON geometry: " + String(g.type));
178
+ }
179
+ }
180
+ const features = [];
181
+ const objects = obj(root.objects, "objects");
182
+ if (objectName !== undefined &&
183
+ !Object.prototype.hasOwnProperty.call(objects, objectName))
184
+ throw new Error("Unknown TopoJSON object: " + objectName);
185
+ for (const value of objectName === undefined
186
+ ? Object.values(objects)
187
+ : [objects[objectName]]) {
188
+ const g = obj(value, "named object");
189
+ if (g.type === "GeometryCollection")
190
+ for (const child of arr(g.geometries, "geometries"))
191
+ features.push(decode(child));
192
+ else
193
+ features.push(decode(g));
194
+ }
195
+ return { type: "FeatureCollection", features };
196
+ }
197
+ /** Export unquantized absolute-coordinate TopoJSON, with shared arcs stored once. */
198
+ export function exportTopoJSON(input) {
199
+ const fc = exportGeoJSON(input);
200
+ if (!fc.features.length)
201
+ return {
202
+ type: "Topology",
203
+ objects: { data: { type: "GeometryCollection", geometries: [] } },
204
+ arcs: [],
205
+ };
206
+ const t = buildTopology(fc);
207
+ const geometries = t.features.map((f, i) => {
208
+ const groups = f.groups.map((group) => group.map((p) => f.paths[p].arcs.map((ref) => (ref > 0 ? ref - 1 : ref))));
209
+ const arcs = f.geometryType === "LineString"
210
+ ? groups[0][0]
211
+ : f.geometryType === "MultiLineString"
212
+ ? groups.map((g) => g[0])
213
+ : f.geometryType === "Polygon"
214
+ ? groups[0]
215
+ : groups;
216
+ const original = fc.features[i];
217
+ return {
218
+ type: f.geometryType,
219
+ arcs,
220
+ ...(original.id === undefined ? {} : { id: original.id }),
221
+ properties: original.properties,
222
+ };
223
+ });
224
+ return {
225
+ type: "Topology",
226
+ objects: { data: { type: "GeometryCollection", geometries } },
227
+ arcs: t.arcs.map((a) => a.vertexIds.map((id) => [t.vertices[id].x, t.vertices[id].y])),
228
+ };
229
+ }
package/dist/blg.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /** Ordered min-Cartesian tree over vertex priorities; inorder restores exact input order. */
2
+ export interface BlgNode {
3
+ position: number;
4
+ level: number;
5
+ random: number;
6
+ left: BlgNode | null;
7
+ right: BlgNode | null;
8
+ }
9
+ export interface BlgTree {
10
+ root: BlgNode | null;
11
+ count: number;
12
+ }
13
+ export declare function stableBlgRandom(key: number): number;
14
+ export declare function buildBlgTree(levels: readonly number[], randomValues?: readonly number[]): BlgTree;
15
+ /** Iterative inorder traversal: no recursion depth limitation. */
16
+ export declare function selectBlgPositions(tree: BlgTree, maxLevel: number): number[];
17
+ export declare function assertBlgInvariants(tree: BlgTree): void;
package/dist/blg.js ADDED
@@ -0,0 +1,83 @@
1
+ export function stableBlgRandom(key) {
2
+ let hash = Math.imul(key + 1, 0x9e3779b1);
3
+ hash ^= hash >>> 16;
4
+ hash = Math.imul(hash, 0x85ebca6b);
5
+ hash ^= hash >>> 13;
6
+ return (hash >>> 0) / 0x100000000;
7
+ }
8
+ export function buildBlgTree(levels, randomValues) {
9
+ if (randomValues && randomValues.length !== levels.length)
10
+ throw new Error("BLG random values must match priorities");
11
+ const stack = [];
12
+ for (let position = 0; position < levels.length; position++) {
13
+ const level = levels[position];
14
+ if (!Number.isFinite(level) || level < 0)
15
+ throw new Error("BLG priorities must be nonnegative and finite");
16
+ const node = {
17
+ position,
18
+ level,
19
+ random: randomValues?.[position] ?? stableBlgRandom(position),
20
+ left: null,
21
+ right: null,
22
+ };
23
+ let last = null;
24
+ while (stack.length && stack[stack.length - 1].level > level)
25
+ last = stack.pop();
26
+ node.left = last;
27
+ if (stack.length)
28
+ stack[stack.length - 1].right = node;
29
+ stack.push(node);
30
+ }
31
+ return { root: stack[0] ?? null, count: levels.length };
32
+ }
33
+ /** Iterative inorder traversal: no recursion depth limitation. */
34
+ export function selectBlgPositions(tree, maxLevel) {
35
+ if (!Number.isFinite(maxLevel) && maxLevel !== Infinity)
36
+ throw new Error("Invalid selection level");
37
+ if (maxLevel < 0)
38
+ throw new Error("Invalid selection level");
39
+ if (maxLevel === Infinity)
40
+ maxLevel = Number.MAX_SAFE_INTEGER;
41
+ const wholeLevel = Math.floor(maxLevel), fraction = maxLevel - wholeLevel, partialLevel = wholeLevel + 1, traversalLevel = fraction === 0 ? wholeLevel : partialLevel;
42
+ const selected = [], stack = [];
43
+ let current = tree.root;
44
+ while (current || stack.length) {
45
+ while (current && current.level <= traversalLevel) {
46
+ stack.push(current);
47
+ current = current.left;
48
+ }
49
+ if (!stack.length)
50
+ break;
51
+ const node = stack.pop();
52
+ if (node.level <= wholeLevel ||
53
+ (fraction > 0 &&
54
+ node.level === partialLevel &&
55
+ (node.level === 0 || node.random >= 1 - fraction)))
56
+ selected.push(node.position);
57
+ current = node.right;
58
+ }
59
+ return selected;
60
+ }
61
+ export function assertBlgInvariants(tree) {
62
+ const stack = [];
63
+ if (tree.root)
64
+ stack.push({ node: tree.root, parentLevel: -Infinity });
65
+ const seen = new Set();
66
+ while (stack.length) {
67
+ const { node, parentLevel } = stack.pop();
68
+ if (node.level < parentLevel)
69
+ throw new Error("BLG heap invariant violated");
70
+ if (seen.has(node.position))
71
+ throw new Error("BLG duplicate position");
72
+ seen.add(node.position);
73
+ if (node.left)
74
+ stack.push({ node: node.left, parentLevel: node.level });
75
+ if (node.right)
76
+ stack.push({ node: node.right, parentLevel: node.level });
77
+ }
78
+ if (seen.size !== tree.count)
79
+ throw new Error("BLG vertex accounting mismatch");
80
+ const all = selectBlgPositions(tree, Infinity);
81
+ if (all.some((position, i) => position !== i))
82
+ throw new Error("BLG inorder invariant violated");
83
+ }
@@ -0,0 +1,16 @@
1
+ import type { FeatureCollection, QueryOptions, QueryResult, SparseQuadtree, Topology } from "./types.js";
2
+ import type { BlgTree } from "./blg.js";
3
+ export declare class QuadstreamDataset {
4
+ readonly topology: Topology;
5
+ readonly quadtree: SparseQuadtree;
6
+ readonly arcTrees: readonly BlgTree[];
7
+ private readonly featureIndex;
8
+ private readonly validityCache;
9
+ constructor(input: FeatureCollection, { maxLevel }?: {
10
+ maxLevel?: number;
11
+ });
12
+ query(options?: QueryOptions): QueryResult;
13
+ }
14
+ export declare function buildQuadstream(input: FeatureCollection, options?: {
15
+ maxLevel?: number;
16
+ }): QuadstreamDataset;
@@ -0,0 +1,61 @@
1
+ import { assertBounds } from "./geometry.js";
2
+ import { buildTopology } from "./topology.js";
3
+ import { buildSparseQuadtree } from "./quadtree.js";
4
+ import { createSpatialIndex } from "./spatial-index.js";
5
+ import { buildArcTrees, reconstructFeature } from "./reconstruct.js";
6
+ export class QuadstreamDataset {
7
+ topology;
8
+ quadtree;
9
+ arcTrees;
10
+ featureIndex;
11
+ 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));
16
+ this.featureIndex = createSpatialIndex(this.topology.features.map((f, i) => ({ bounds: f.bounds, value: i })));
17
+ }
18
+ query(options = {}) {
19
+ const level = options.level ?? this.quadtree.maxLevel - 1;
20
+ if (!Number.isFinite(level) || level < 0 || level >= this.quadtree.maxLevel)
21
+ throw new Error("Invalid query level");
22
+ if (options.bounds)
23
+ assertBounds(options.bounds);
24
+ const selected = options.bounds
25
+ ? this.featureIndex.query(options.bounds)
26
+ : this.topology.features.map((_, i) => i);
27
+ const coords = (id) => {
28
+ const v = this.topology.vertices[id];
29
+ return v ? [v.x, v.y] : undefined;
30
+ };
31
+ let globallyInvalid = false;
32
+ if (options.validate !== false) {
33
+ const cached = this.validityCache.get(level);
34
+ if (cached !== undefined)
35
+ globallyInvalid = !cached;
36
+ else {
37
+ // Viewport-independent decision: shared boundaries must render consistently
38
+ // 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);
40
+ this.validityCache.set(level, !globallyInvalid);
41
+ }
42
+ }
43
+ 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);
46
+ total += r.selectedVertices;
47
+ return r.feature;
48
+ });
49
+ return {
50
+ geojson: { type: "FeatureCollection", features: results },
51
+ level,
52
+ valid: !globallyInvalid,
53
+ usedFallback: globallyInvalid,
54
+ selectedFeatures: results.length,
55
+ selectedVertices: total,
56
+ };
57
+ }
58
+ }
59
+ export function buildQuadstream(input, options) {
60
+ return new QuadstreamDataset(input, options);
61
+ }
@@ -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;