@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,55 @@
1
+ import { type CollapsedRingPolicy } from "./reconstruct.js";
2
+ import type { SphericalPriorities } from "./spherical-geometry.js";
3
+ import type { FeatureCollection, QueryResult, Topology } from "./types.js";
4
+ import type { BlgTree } from "./blg.js";
5
+ /** Explicit geographic import: decode only the selected object and validate minor arcs. */
6
+ export declare function importSphericalTopoJSON(input: unknown, objectName: string): FeatureCollection;
7
+ export interface SphericalQueryOptions {
8
+ level?: number;
9
+ /**
10
+ * "restore" (default) keeps every polygon. "drop" hides each polygon (and
11
+ * hole) whose ring has fewer than 3 distinct quadtree-activated vertices at
12
+ * the query level, except for explicitly retained polygon exteriors.
13
+ */
14
+ collapsedRingPolicy?: CollapsedRingPolicy;
15
+ }
16
+ export interface SphericalInterruptOptions extends SphericalQueryOptions {
17
+ shouldAbort?: () => boolean;
18
+ yieldTurn?: () => Promise<void>;
19
+ sliceMs?: number;
20
+ }
21
+ /** Optional preprocessing policy for explicitly retained polygon exteriors. */
22
+ export interface SphericalBuildOptions {
23
+ maxLevel?: number;
24
+ /** Feature ID to source polygon index; only the selected exterior is visible at level zero. */
25
+ alwaysVisiblePolygons?: ReadonlyMap<string, number>;
26
+ }
27
+ /** Geographic in-memory dataset. No planar viewport index or v1 partition serialization. */
28
+ export declare class SphericalQuadstreamDataset {
29
+ readonly coordinateMode: "spherical-d3";
30
+ readonly topology: Topology;
31
+ readonly priorities: SphericalPriorities;
32
+ readonly arcTrees: readonly BlgTree[];
33
+ /** Corrected global vertex thresholds, independent of query order. */
34
+ readonly activationLevels: readonly number[];
35
+ /** Vertices retained at all levels because a removal failed validation. */
36
+ readonly retainedVertices: number;
37
+ /**
38
+ * Per feature and path: the lowest level at which the closed ring has 3
39
+ * distinct vertices activated by the sparse quadtree (the third-smallest
40
+ * vertex activation level), or Infinity when it never does. Open paths and
41
+ * explicitly retained exteriors are 0.
42
+ */
43
+ readonly ringActivation: readonly (readonly number[])[];
44
+ private readonly source;
45
+ private readonly signatures;
46
+ constructor(input: FeatureCollection, { maxLevel, alwaysVisiblePolygons }?: SphericalBuildOptions);
47
+ private pathActivation;
48
+ /** Nominal-level polygon eligibility, independent of corrected vertex thresholds. */
49
+ private visibility;
50
+ private session;
51
+ query(options?: SphericalQueryOptions): QueryResult;
52
+ private formatResult;
53
+ queryInterruptible(options?: SphericalInterruptOptions): Promise<QueryResult | null>;
54
+ }
55
+ export declare function buildSphericalQuadstream(input: FeatureCollection, options?: SphericalBuildOptions): SphericalQuadstreamDataset;
@@ -0,0 +1,305 @@
1
+ import { buildTopologyWithPolicy } from "./topology.js";
2
+ import { decodeTopoJSON } from "./adapters.js";
3
+ import { reconstructFeature } from "./reconstruct.js";
4
+ import { stableBlgRandom } from "./blg.js";
5
+ import { buildTopologySafeArcTrees } from "./spherical-preprocess.js";
6
+ import { signedArea } from "./geometry.js";
7
+ import { canonicalLonLat, buildSphericalPriorities, projectSpherical, validGreatCirclePath, sphericalPolygonSignature, validSphericalPolygon, } from "./spherical-geometry.js";
8
+ function polygons(g) {
9
+ return g.type === "Polygon"
10
+ ? [g.coordinates]
11
+ : g.type === "MultiPolygon"
12
+ ? g.coordinates
13
+ : [];
14
+ }
15
+ function lines(g) {
16
+ return g.type === "LineString"
17
+ ? [g.coordinates]
18
+ : g.type === "MultiLineString"
19
+ ? g.coordinates
20
+ : [];
21
+ }
22
+ function canonicalGeometry(g) {
23
+ switch (g.type) {
24
+ case "LineString":
25
+ return { type: g.type, coordinates: g.coordinates.map(canonicalLonLat) };
26
+ case "MultiLineString":
27
+ return {
28
+ type: g.type,
29
+ coordinates: g.coordinates.map((p) => p.map(canonicalLonLat)),
30
+ };
31
+ case "Polygon":
32
+ return {
33
+ type: g.type,
34
+ coordinates: g.coordinates.map((p) => p.map(canonicalLonLat)),
35
+ };
36
+ case "MultiPolygon":
37
+ return {
38
+ type: g.type,
39
+ coordinates: g.coordinates.map((p) => p.map((r) => r.map(canonicalLonLat))),
40
+ };
41
+ default:
42
+ throw new Error("Unsupported spherical geometry");
43
+ }
44
+ }
45
+ function sourceGeometry(input) {
46
+ if (input?.type !== "FeatureCollection" ||
47
+ !Array.isArray(input.features) ||
48
+ !input.features.length)
49
+ throw new Error("Expected nonempty geographic FeatureCollection");
50
+ return {
51
+ type: "FeatureCollection",
52
+ features: input.features.map((f) => {
53
+ if (f?.type !== "Feature" || !f.geometry)
54
+ throw new Error("Expected geographic feature");
55
+ return {
56
+ ...f,
57
+ properties: f.properties === null ? null : { ...f.properties },
58
+ geometry: canonicalGeometry(f.geometry),
59
+ };
60
+ }),
61
+ };
62
+ }
63
+ function topology(input) {
64
+ return buildTopologyWithPolicy(input, {
65
+ position: canonicalLonLat,
66
+ ring: (r) => validSphericalPolygon([[...r]]),
67
+ polygon: (r) => validSphericalPolygon(r),
68
+ line: validGreatCirclePath,
69
+ });
70
+ }
71
+ function preserveSphericalValidity(topology, source, signatures) {
72
+ const vertexByPosition = new Map(topology.vertices.map((v) => [
73
+ JSON.stringify(canonicalLonLat([v.x, v.y])),
74
+ v,
75
+ ]));
76
+ source.features.forEach((feature, featureIndex) => {
77
+ polygons(feature.geometry).forEach((rings, polygonIndex) => {
78
+ rings.forEach((ring, ringIndex) => {
79
+ const ids = ring
80
+ .slice(0, -1)
81
+ .map((p) => vertexByPosition.get(JSON.stringify(p))?.id);
82
+ const projected = ring.map((p) => projectSpherical(p, signatures[featureIndex][polygonIndex].chart)), area = signedArea(projected), sourceSign = signatures[featureIndex][polygonIndex].signs[ringIndex];
83
+ ids.forEach((id, i) => {
84
+ if (id === undefined)
85
+ return;
86
+ const previous = projected[(i + projected.length - 2) % (projected.length - 1)], current = projected[i], next = projected[(i + 1) % (projected.length - 1)], removed = current[0] * next[1] -
87
+ current[1] * next[0] -
88
+ (previous[0] * current[1] - previous[1] * current[0]) +
89
+ (previous[0] * next[1] - previous[1] * next[0]), candidateArea = area - removed / 2;
90
+ let invalidCandidate = false;
91
+ if (ring.length <= 32) {
92
+ const points = [...ring.slice(0, i), ...ring.slice(i + 1, -1)], candidate = [...points, points[0]], candidateRings = rings.map((r, j) => j === ringIndex ? candidate : r);
93
+ invalidCandidate = !validSphericalPolygon(candidateRings, signatures[featureIndex]?.[polygonIndex]);
94
+ }
95
+ if (ring.length <= 4 ||
96
+ Math.sign(candidateArea) !== sourceSign ||
97
+ candidateArea === 0 ||
98
+ invalidCandidate)
99
+ topology.vertices[id].critical = true;
100
+ });
101
+ });
102
+ });
103
+ });
104
+ }
105
+ /** Explicit geographic import: decode only the selected object and validate minor arcs. */
106
+ export function importSphericalTopoJSON(input, objectName) {
107
+ const decoded = sourceGeometry(decodeTopoJSON(input, objectName, canonicalLonLat));
108
+ for (const f of decoded.features)
109
+ for (const p of polygons(f.geometry))
110
+ sphericalPolygonSignature(p);
111
+ topology(decoded);
112
+ return decoded;
113
+ }
114
+ const ACTIVATION_EPSILON = 1e-9;
115
+ /**
116
+ * Level at which a vertex becomes selected in its arc's BLG tree. Selection at
117
+ * level L is `level <= floor(L)` or, for the next level, `random >= 1 - frac`,
118
+ * i.e. L >= level - random: a stable per-vertex threshold, so selections nest.
119
+ */
120
+ function activationLevel(level, random) {
121
+ return level === 0
122
+ ? 0
123
+ : level - random + (random === 1 ? ACTIVATION_EPSILON : 0);
124
+ }
125
+ /** Geographic in-memory dataset. No planar viewport index or v1 partition serialization. */
126
+ export class SphericalQuadstreamDataset {
127
+ coordinateMode = "spherical-d3";
128
+ topology;
129
+ priorities;
130
+ arcTrees;
131
+ /** Corrected global vertex thresholds, independent of query order. */
132
+ activationLevels;
133
+ /** Vertices retained at all levels because a removal failed validation. */
134
+ retainedVertices;
135
+ /**
136
+ * Per feature and path: the lowest level at which the closed ring has 3
137
+ * distinct vertices activated by the sparse quadtree (the third-smallest
138
+ * vertex activation level), or Infinity when it never does. Open paths and
139
+ * explicitly retained exteriors are 0.
140
+ */
141
+ ringActivation;
142
+ source;
143
+ signatures;
144
+ constructor(input, { maxLevel = 20, alwaysVisiblePolygons } = {}) {
145
+ this.source = sourceGeometry(input);
146
+ this.signatures = this.source.features.map((f) => polygons(f.geometry).map((p) => sphericalPolygonSignature(p)));
147
+ this.topology = topology(this.source);
148
+ preserveSphericalValidity(this.topology, this.source, this.signatures);
149
+ this.priorities = buildSphericalPriorities(this.topology.vertices, maxLevel);
150
+ const prepared = buildTopologySafeArcTrees(this.topology, this.topology.vertices.map((v) => activationLevel(this.priorities.levelByVertexId[v.id], v.critical ? 1 : stableBlgRandom(v.id))), this.signatures);
151
+ this.arcTrees = prepared.trees;
152
+ this.activationLevels = prepared.activationLevels;
153
+ this.retainedVertices = prepared.retainedVertices;
154
+ this.ringActivation = this.topology.features.map((f) => {
155
+ const polygon = alwaysVisiblePolygons?.get(f.id);
156
+ const exterior = polygon !== undefined &&
157
+ (f.geometryType === "Polygon" || f.geometryType === "MultiPolygon")
158
+ ? f.groups[polygon]?.[0]
159
+ : undefined;
160
+ return f.paths.map((path, i) => i === exterior ? 0 : this.pathActivation(path));
161
+ });
162
+ }
163
+ pathActivation(path) {
164
+ if (!path.closed)
165
+ return 0;
166
+ // Arc endpoints are always selected (topology anchors, three per closed
167
+ // ring), so they cannot define visibility: use each vertex's own priority.
168
+ const best = new Map();
169
+ for (const ref of path.arcs)
170
+ for (const id of this.topology.arcs[Math.abs(ref) - 1].vertexIds) {
171
+ const a = activationLevel(this.priorities.levelByVertexId[id], this.topology.vertices[id].critical ? 1 : stableBlgRandom(id));
172
+ if (a < (best.get(id) ?? Infinity))
173
+ best.set(id, a);
174
+ }
175
+ let m1 = Infinity, m2 = Infinity, m3 = Infinity;
176
+ for (const a of best.values()) {
177
+ if (a < m1)
178
+ [m1, m2, m3] = [a, m1, m2];
179
+ else if (a < m2)
180
+ [m2, m3] = [a, m2];
181
+ else if (a < m3)
182
+ m3 = a;
183
+ }
184
+ return m3;
185
+ }
186
+ /** Nominal-level polygon eligibility, independent of corrected vertex thresholds. */
187
+ visibility(level) {
188
+ let hiddenPolygons = 0;
189
+ const hidden = [], signatures = [];
190
+ this.topology.features.forEach((f, i) => {
191
+ const act = this.ringActivation[i], source = this.signatures[i];
192
+ let set;
193
+ const sigs = [];
194
+ if (f.geometryType === "Polygon" || f.geometryType === "MultiPolygon")
195
+ f.groups.forEach((group, j) => {
196
+ if (act[group[0]] > level) {
197
+ (set ??= new Set()).add(group[0]);
198
+ hiddenPolygons++;
199
+ return;
200
+ }
201
+ const shown = group.filter((p) => act[p] <= level);
202
+ for (const p of group)
203
+ if (!shown.includes(p))
204
+ (set ??= new Set()).add(p);
205
+ const sig = source[j];
206
+ sigs.push(shown.length === group.length
207
+ ? sig
208
+ : {
209
+ chart: sig.chart,
210
+ signs: sig.signs.filter((_, k) => act[group[k]] <= level),
211
+ });
212
+ });
213
+ hidden.push(set);
214
+ signatures.push(sigs);
215
+ });
216
+ return { hidden, signatures, hiddenPolygons };
217
+ }
218
+ session(options) {
219
+ if ("bounds" in options || "validate" in options)
220
+ throw new Error("Spherical queries require global validated retrieval");
221
+ const level = options.level ?? this.priorities.maxLevel - 1;
222
+ if (!Number.isFinite(level) ||
223
+ level < 0 ||
224
+ level >= this.priorities.maxLevel)
225
+ throw new Error("Invalid spherical query level");
226
+ const drop = options.collapsedRingPolicy === "drop", vis = drop ? this.visibility(level) : undefined, lookup = (id) => {
227
+ const v = this.topology.vertices[id];
228
+ return v ? [v.x, v.y] : undefined;
229
+ }, check = (i, r) => {
230
+ const p = polygons(r.feature.geometry).filter((g) => g.length), s = vis ? vis.signatures[i] : this.signatures[i];
231
+ return (!r.missing &&
232
+ p.length === s.length &&
233
+ p.every((g, j) => validSphericalPolygon(g, s[j])) &&
234
+ lines(r.feature.geometry).every(validGreatCirclePath));
235
+ }, run = (f, i) => reconstructFeature(f, this.topology.arcs, this.arcTrees, level, lookup, false, false, drop
236
+ ? { collapsed: "drop", hiddenPaths: vis.hidden[i] }
237
+ : { collapsed: "drop" });
238
+ return { level, check, run, vis };
239
+ }
240
+ query(options = {}) {
241
+ const s = this.session(options);
242
+ const results = this.topology.features.map(s.run);
243
+ const valid = results.every((r, i) => s.check(i, r));
244
+ return this.formatResult(s, results, valid);
245
+ }
246
+ formatResult(s, results, valid) {
247
+ return {
248
+ geojson: {
249
+ type: "FeatureCollection",
250
+ features: results.map((r, i) => {
251
+ const f = this.source.features[i];
252
+ return {
253
+ type: "Feature",
254
+ ...(f.id === undefined ? {} : { id: f.id }),
255
+ properties: f.properties === null ? null : { ...f.properties },
256
+ geometry: r.feature.geometry,
257
+ };
258
+ }),
259
+ },
260
+ level: s.level,
261
+ valid,
262
+ promotedArcs: 0,
263
+ ...(s.vis
264
+ ? {
265
+ hiddenPolygons: s.vis.hiddenPolygons,
266
+ hiddenRings: results.reduce((n, r) => n + r.hiddenRings, 0),
267
+ }
268
+ : {}),
269
+ usedFallback: false,
270
+ selectedFeatures: results.length,
271
+ selectedVertices: results.reduce((n, r) => n + r.selectedVertices, 0),
272
+ };
273
+ }
274
+ async queryInterruptible(options = {}) {
275
+ const { shouldAbort, yieldTurn, sliceMs = 8 } = options;
276
+ const s = this.session(options);
277
+ if (shouldAbort?.())
278
+ return null;
279
+ const results = [];
280
+ const ok = [];
281
+ let sliceStart = performance.now();
282
+ const tick = async () => {
283
+ if (yieldTurn && performance.now() - sliceStart >= sliceMs) {
284
+ await yieldTurn();
285
+ if (shouldAbort?.())
286
+ return false;
287
+ sliceStart = performance.now();
288
+ }
289
+ return true;
290
+ };
291
+ for (let i = 0; i < this.topology.features.length; i++) {
292
+ const r = s.run(this.topology.features[i], i);
293
+ results.push(r);
294
+ ok.push(s.check(i, r));
295
+ if (!(await tick()))
296
+ return null;
297
+ }
298
+ if (shouldAbort?.())
299
+ return null;
300
+ return this.formatResult(s, results, ok.every(Boolean));
301
+ }
302
+ }
303
+ export function buildSphericalQuadstream(input, options) {
304
+ return new SphericalQuadstreamDataset(input, options);
305
+ }
@@ -0,0 +1,39 @@
1
+ import type { Position, Vertex } from "./types.js";
2
+ export type UnitVector = readonly [number, number, number];
3
+ /** Exact seam aliases only; no near-coordinate snapping. */
4
+ export declare function canonicalLonLat(value: unknown): Position;
5
+ export declare function lonLatVector(p: Position): UnitVector;
6
+ export declare function angularDistance(a: Position, b: Position): number;
7
+ export declare function validGreatCirclePath(path: readonly Position[]): boolean;
8
+ export type CubeFace = "+X" | "-X" | "+Y" | "-Y" | "+Z" | "-Z";
9
+ export interface SphericalCell {
10
+ vertexId: number;
11
+ face: CubeFace;
12
+ level: number;
13
+ i: number;
14
+ j: number;
15
+ key: string;
16
+ }
17
+ export interface SphericalPriorities {
18
+ maxLevel: number;
19
+ cells: SphericalCell[];
20
+ levelByVertexId: number[];
21
+ }
22
+ export declare function sphericalCellAddress(p: Position, level: number): Omit<SphericalCell, "vertexId">;
23
+ export declare function buildSphericalPriorities(vertices: readonly Vertex[], maxLevel?: number): SphericalPriorities;
24
+ /** Conservative reference chart: minor geodesics become straight segments in an open hemisphere. */
25
+ export interface SphericalChart {
26
+ center: UnitVector;
27
+ east: UnitVector;
28
+ north: UnitVector;
29
+ }
30
+ export declare function sphericalChart(ring: readonly Position[]): SphericalChart;
31
+ export declare function projectSpherical(p: Position, chart: SphericalChart): Position;
32
+ export interface SphericalPolygonSignature {
33
+ chart: SphericalChart;
34
+ signs: number[];
35
+ }
36
+ /** D3 convention: clockwise shell denotes the small interior. Counterclockwise
37
+ * shells denote the complement; complement polygons with holes are not supported. */
38
+ export declare function sphericalPolygonSignature(rings: readonly Position[][], chart?: SphericalChart): SphericalPolygonSignature;
39
+ export declare function validSphericalPolygon(rings: readonly Position[][], source?: SphericalPolygonSignature): boolean;
@@ -0,0 +1,229 @@
1
+ import { simpleClosedRing, validPolygon, signedArea } from "./geometry.js";
2
+ const rad = Math.PI / 180;
3
+ const eps = 1e-10;
4
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
5
+ const cross = (a, b) => [
6
+ a[1] * b[2] - a[2] * b[1],
7
+ a[2] * b[0] - a[0] * b[2],
8
+ a[0] * b[1] - a[1] * b[0],
9
+ ];
10
+ const norm = (a) => Math.hypot(...a);
11
+ function unit(a) {
12
+ const n = norm(a);
13
+ if (n < eps)
14
+ throw new Error("Ambiguous spherical direction");
15
+ return [a[0] / n, a[1] / n, a[2] / n];
16
+ }
17
+ /** Exact seam aliases only; no near-coordinate snapping. */
18
+ export function canonicalLonLat(value) {
19
+ if (!Array.isArray(value) ||
20
+ value.length !== 2 ||
21
+ !value.every((x) => typeof x === "number" && Number.isFinite(x)))
22
+ throw new Error("Expected finite longitude/latitude pair");
23
+ const [lon, lat] = value;
24
+ if (lon < -180 || lon > 180 || lat < -90 || lat > 90)
25
+ throw new Error("Longitude/latitude outside geographic range");
26
+ return [
27
+ Math.abs(lat) === 90 ? 0 : lon === 180 ? -180 : lon === 0 ? 0 : lon,
28
+ lat === 0 ? 0 : lat,
29
+ ];
30
+ }
31
+ /** Vector of an already canonical (validated, seam-aliased) longitude/latitude. */
32
+ function canonicalVector(lon, lat) {
33
+ if (Math.abs(lat) === 90)
34
+ return [0, 0, Math.sign(lat)];
35
+ const c = Math.cos(lat * rad), z = Math.sin(lat * rad);
36
+ // Exact cardinal meridians lie on cube-cell boundaries. Avoid trig
37
+ // residuals such as sin(-pi), without snapping nearby longitudes.
38
+ switch (lon) {
39
+ case -180:
40
+ return [-c, 0, z];
41
+ case -90:
42
+ return [0, -c, z];
43
+ case 0:
44
+ return [c, 0, z];
45
+ case 90:
46
+ return [0, c, z];
47
+ default:
48
+ return [c * Math.cos(lon * rad), c * Math.sin(lon * rad), z];
49
+ }
50
+ }
51
+ export function lonLatVector(p) {
52
+ const [lon, lat] = canonicalLonLat(p);
53
+ return canonicalVector(lon, lat);
54
+ }
55
+ export function angularDistance(a, b) {
56
+ const u = lonLatVector(a), v = lonLatVector(b);
57
+ return Math.atan2(norm(cross(u, v)), dot(u, v));
58
+ }
59
+ function validVectorPath(vectors) {
60
+ if (vectors.length < 2)
61
+ return false;
62
+ for (let i = 1; i < vectors.length; i++) {
63
+ const u = vectors[i - 1], v = vectors[i], d = Math.atan2(norm(cross(u, v)), dot(u, v));
64
+ if (d <= eps || Math.PI - d <= eps)
65
+ return false;
66
+ }
67
+ return true;
68
+ }
69
+ export function validGreatCirclePath(path) {
70
+ if (path.length < 2)
71
+ return false;
72
+ return validVectorPath(path.map(lonLatVector));
73
+ }
74
+ const FACES = ["+X", "-X", "+Y", "-Y", "+Z", "-Z"];
75
+ function faceCoords([x, y, z]) {
76
+ // Fixed axis order breaks exact and roundoff-sized seam ties.
77
+ const m = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
78
+ if (m - Math.abs(x) <= 1e-15)
79
+ return { face: x >= 0 ? 0 : 1, u: y / Math.abs(x), v: z / Math.abs(x) };
80
+ if (m - Math.abs(y) <= 1e-15)
81
+ return { face: y >= 0 ? 2 : 3, u: x / Math.abs(y), v: z / Math.abs(y) };
82
+ return { face: z >= 0 ? 4 : 5, u: x / Math.abs(z), v: y / Math.abs(z) };
83
+ }
84
+ function cellIndex(t, side) {
85
+ return Math.max(0, Math.min(side - 1, Math.floor(((t + 1) * side) / 2)));
86
+ }
87
+ function assertLevel(level) {
88
+ if (!Number.isInteger(level) || level < 0 || level > 25)
89
+ throw new Error("Spherical level must be 0..25");
90
+ }
91
+ export function sphericalCellAddress(p, level) {
92
+ assertLevel(level);
93
+ const { face, u, v } = faceCoords(lonLatVector(p)), side = 2 ** level, i = cellIndex(u, side), j = cellIndex(v, side), name = FACES[face];
94
+ return {
95
+ face: name,
96
+ level,
97
+ i,
98
+ j,
99
+ key: name + ":" + level + ":" + i + ":" + j,
100
+ };
101
+ }
102
+ // Face and indices pack into one exact double: 6 * 2^50 < 2^53.
103
+ const SIDE_MAX = 2 ** 25;
104
+ const packCell = (face, i, j) => (face * SIDE_MAX + i) * SIDE_MAX + j;
105
+ export function buildSphericalPriorities(vertices, maxLevel = 20) {
106
+ if (!Number.isInteger(maxLevel) || maxLevel < 1 || maxLevel > 26)
107
+ throw new Error("maxLevel must be 1..26");
108
+ const seen = new Set(), ids = new Uint8Array(vertices.length);
109
+ const sorted = vertices
110
+ .map((v) => {
111
+ const [x, y] = canonicalLonLat([v.x, v.y]);
112
+ const k = x + "," + y;
113
+ if (seen.has(k) ||
114
+ !Number.isSafeInteger(v.id) ||
115
+ v.id < 0 ||
116
+ v.id >= vertices.length ||
117
+ ids[v.id])
118
+ throw new Error("Expected distinct canonical vertices and dense IDs");
119
+ seen.add(k);
120
+ ids[v.id] = 1;
121
+ return {
122
+ id: v.id,
123
+ critical: v.critical,
124
+ x,
125
+ y,
126
+ face: faceCoords(canonicalVector(x, y)),
127
+ };
128
+ })
129
+ .sort((a, b) => Number(b.critical) - Number(a.critical) ||
130
+ a.x - b.x ||
131
+ a.y - b.y ||
132
+ a.id - b.id);
133
+ const occupied = Array.from({ length: maxLevel }, () => new Set()), sides = Array.from({ length: maxLevel }, (_, level) => 2 ** level), cells = [], levelByVertexId = [];
134
+ for (const v of sorted) {
135
+ let found = false;
136
+ for (let level = 0; level < maxLevel; level++) {
137
+ const side = sides[level], i = cellIndex(v.face.u, side), j = cellIndex(v.face.v, side), packed = packCell(v.face.face, i, j);
138
+ if (occupied[level].has(packed))
139
+ continue;
140
+ occupied[level].add(packed);
141
+ const face = FACES[v.face.face];
142
+ cells.push({
143
+ vertexId: v.id,
144
+ face,
145
+ level,
146
+ i,
147
+ j,
148
+ key: face + ":" + level + ":" + i + ":" + j,
149
+ });
150
+ levelByVertexId[v.id] = level;
151
+ found = true;
152
+ break;
153
+ }
154
+ if (!found)
155
+ throw new Error("Spherical quadtree capacity exceeded at vertex " + v.id);
156
+ }
157
+ cells.sort((a, b) => a.level - b.level ||
158
+ (a.face < b.face ? -1 : a.face > b.face ? 1 : 0) ||
159
+ a.i - b.i ||
160
+ a.j - b.j ||
161
+ a.vertexId - b.vertexId);
162
+ return { maxLevel, cells, levelByVertexId };
163
+ }
164
+ export function sphericalChart(ring) {
165
+ const points = ring.slice(0, -1).map(lonLatVector);
166
+ let sum = [0, 0, 0];
167
+ for (const p of points)
168
+ sum = [sum[0] + p[0], sum[1] + p[1], sum[2] + p[2]];
169
+ const center = unit(sum);
170
+ if (points.some((p) => dot(p, center) <= eps))
171
+ throw new Error("Ring outside supported open-hemisphere chart");
172
+ const ref = Math.abs(center[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0];
173
+ const east = unit(cross(ref, center)), north = cross(center, east);
174
+ return { center, east, north };
175
+ }
176
+ export function projectSpherical(p, chart) {
177
+ return projectVector(lonLatVector(p), chart);
178
+ }
179
+ function projectVector(v, chart) {
180
+ const d = dot(v, chart.center);
181
+ if (d <= eps)
182
+ throw new Error("Position outside supported open-hemisphere chart");
183
+ return [dot(v, chart.east) / d, dot(v, chart.north) / d];
184
+ }
185
+ function ringOnChart(ring, chart) {
186
+ const p = ring.map(canonicalLonLat), vectors = p.map(([lon, lat]) => canonicalVector(lon, lat));
187
+ if (p.length < 4 ||
188
+ p[0][0] !== p[p.length - 1][0] ||
189
+ p[0][1] !== p[p.length - 1][1] ||
190
+ !validVectorPath(vectors))
191
+ throw new Error("Invalid spherical ring");
192
+ const xy = vectors.map((v) => projectVector(v, chart));
193
+ if (!simpleClosedRing(xy) || Math.abs(signedArea(xy)) <= eps * eps)
194
+ throw new Error("Degenerate or self-intersecting spherical ring");
195
+ // Reject overlapping adjacent great-circle edges (including numerical near-overlap).
196
+ for (let i = 0; i < xy.length - 1; i++) {
197
+ const a = xy[(i + xy.length - 2) % (xy.length - 1)], b = xy[i], c = xy[i + 1];
198
+ const ux = a[0] - b[0], uy = a[1] - b[1], vx = c[0] - b[0], vy = c[1] - b[1];
199
+ if (ux * vx + uy * vy > 0 &&
200
+ Math.abs(ux * vy - uy * vx) <=
201
+ eps * Math.hypot(ux, uy) * Math.hypot(vx, vy))
202
+ throw new Error("Overlapping adjacent spherical edges");
203
+ }
204
+ return xy;
205
+ }
206
+ /** D3 convention: clockwise shell denotes the small interior. Counterclockwise
207
+ * shells denote the complement; complement polygons with holes are not supported. */
208
+ export function sphericalPolygonSignature(rings, chart) {
209
+ if (!rings.length)
210
+ throw new Error("Empty spherical polygon");
211
+ const c = chart ?? sphericalChart(rings[0]);
212
+ const xy = rings.map((r) => ringOnChart(r, c)), signs = xy.map((r) => Math.sign(signedArea(r)));
213
+ if (signs[0] === 1 && rings.length > 1)
214
+ throw new Error("Complement polygons with holes are unsupported");
215
+ if (signs.slice(1).some((s) => s === signs[0]) || !validPolygon(xy))
216
+ throw new Error("Invalid spherical hole winding or containment");
217
+ return { chart: c, signs };
218
+ }
219
+ export function validSphericalPolygon(rings, source) {
220
+ try {
221
+ const result = sphericalPolygonSignature(rings, source?.chart);
222
+ return (!source ||
223
+ (result.signs.length === source.signs.length &&
224
+ result.signs.every((s, i) => s === source.signs[i])));
225
+ }
226
+ catch {
227
+ return false;
228
+ }
229
+ }
@@ -0,0 +1,19 @@
1
+ import { type BlgTree } from "./blg.js";
2
+ import { type SphericalPolygonSignature } from "./spherical-geometry.js";
3
+ import type { Topology } from "./types.js";
4
+ /**
5
+ * Build a nested hierarchy by removing vertices from valid full detail.
6
+ * Batch at conservative tenth-LOD boundaries; when a batch fails, bisect it
7
+ * until we identify individually unsafe removals. Rejected vertices remain
8
+ * at level zero. Every accepted transition is validated in its actual context.
9
+ *
10
+ * The source quadtree priorities and ring visibility thresholds are not
11
+ * changed. A shared vertex has one removal decision across all of its owners.
12
+ * This uses the existing per-polygon/line reference validator, not a global
13
+ * intersection arrangement for unrelated boundaries.
14
+ */
15
+ export declare function buildTopologySafeArcTrees(topology: Topology, nominalActivation: readonly number[], signatures: readonly SphericalPolygonSignature[][]): {
16
+ trees: BlgTree[];
17
+ activationLevels: number[];
18
+ retainedVertices: number;
19
+ };