@vizhub/quadstream 0.2.0 → 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.
package/dist/geometry.js CHANGED
@@ -60,6 +60,12 @@ function within(a, b, p) {
60
60
  }
61
61
  /** Includes touching endpoints; callers skip adjacent polygon edges. */
62
62
  export function segmentsIntersect(a, b, c, d) {
63
+ // Inclusive AABB rejection: disjoint boxes cannot touch or cross.
64
+ if (Math.max(a[0], b[0]) < Math.min(c[0], d[0]) ||
65
+ Math.max(c[0], d[0]) < Math.min(a[0], b[0]) ||
66
+ Math.max(a[1], b[1]) < Math.min(c[1], d[1]) ||
67
+ Math.max(c[1], d[1]) < Math.min(a[1], b[1]))
68
+ return false;
63
69
  const abC = orientation(a, b, c), abD = orientation(a, b, d), cdA = orientation(c, d, a), cdB = orientation(c, d, b);
64
70
  if (((abC > 0 && abD < 0) || (abC < 0 && abD > 0)) &&
65
71
  ((cdA > 0 && cdB < 0) || (cdA < 0 && cdB > 0)))
@@ -72,8 +78,8 @@ export function segmentsIntersect(a, b, c, d) {
72
78
  function same(a, b) {
73
79
  return a[0] === b[0] && a[1] === b[1];
74
80
  }
75
- /** O(n^2) reference predicate; safe but not intended as the final large-data validator. */
76
- export function simpleClosedRing(ring) {
81
+ /** O(n^2) reference predicate; retained as the oracle for the indexed validator. */
82
+ export function simpleClosedRingReference(ring) {
77
83
  const n = ring.length - 1;
78
84
  if (n < 3 || !same(ring[0], ring[n]) || signedArea(ring) === 0)
79
85
  return false;
@@ -89,6 +95,95 @@ export function simpleClosedRing(ring) {
89
95
  }
90
96
  return true;
91
97
  }
98
+ /** Rings below this many segments use the quadratic loops directly. */
99
+ const INDEX_MIN_SEGMENTS = 24;
100
+ function segmentBoxes(ring) {
101
+ const count = ring.length - 1, minX = new Float64Array(count), maxX = new Float64Array(count), minY = new Float64Array(count), maxY = new Float64Array(count);
102
+ for (let i = 0; i < count; i++) {
103
+ const a = ring[i], b = ring[i + 1];
104
+ if (!Number.isFinite(a[0] + a[1] + b[0] + b[1]) ||
105
+ a.length !== 2 ||
106
+ b.length !== 2)
107
+ return null;
108
+ minX[i] = Math.min(a[0], b[0]);
109
+ maxX[i] = Math.max(a[0], b[0]);
110
+ minY[i] = Math.min(a[1], b[1]);
111
+ maxY[i] = Math.max(a[1], b[1]);
112
+ }
113
+ const order = new Uint32Array(count);
114
+ for (let i = 0; i < count; i++)
115
+ order[i] = i;
116
+ order.sort((p, q) => minX[p] - minX[q] || p - q);
117
+ return { count, minX, maxX, minY, maxY, order };
118
+ }
119
+ /** Each unordered segment pair with overlapping boxes is visited once; true stops. */
120
+ function sweepSelf(s, visit) {
121
+ const { count, minX, maxX, minY, maxY, order } = s;
122
+ for (let a = 0; a < count; a++) {
123
+ const i = order[a], reach = maxX[i];
124
+ for (let b = a + 1; b < count; b++) {
125
+ const j = order[b];
126
+ if (minX[j] > reach)
127
+ break;
128
+ if (minY[j] > maxY[i] || maxY[j] < minY[i])
129
+ continue;
130
+ if (visit(i, j))
131
+ return true;
132
+ }
133
+ }
134
+ return false;
135
+ }
136
+ function sweepBetween(A, B, visit) {
137
+ let ia = 0, ib = 0;
138
+ while (ia < A.count && ib < B.count) {
139
+ const i = A.order[ia], j = B.order[ib];
140
+ if (A.minX[i] <= B.minX[j]) {
141
+ for (let k = ib; k < B.count; k++) {
142
+ const m = B.order[k];
143
+ if (B.minX[m] > A.maxX[i])
144
+ break;
145
+ if (B.minY[m] > A.maxY[i] || B.maxY[m] < A.minY[i])
146
+ continue;
147
+ if (visit(i, m))
148
+ return true;
149
+ }
150
+ ia++;
151
+ }
152
+ else {
153
+ for (let k = ia; k < A.count; k++) {
154
+ const m = A.order[k];
155
+ if (A.minX[m] > B.maxX[j])
156
+ break;
157
+ if (A.minY[m] > B.maxY[j] || A.maxY[m] < B.minY[j])
158
+ continue;
159
+ if (visit(m, j))
160
+ return true;
161
+ }
162
+ ib++;
163
+ }
164
+ }
165
+ return false;
166
+ }
167
+ /** Sweep-and-prune over segment boxes; exact predicates only on overlapping candidates. */
168
+ export function simpleClosedRing(ring) {
169
+ const n = ring.length - 1;
170
+ if (n < INDEX_MIN_SEGMENTS)
171
+ return simpleClosedRingReference(ring);
172
+ if (!same(ring[0], ring[n]) || signedArea(ring) === 0)
173
+ return false;
174
+ for (let i = 0; i < n; i++)
175
+ if (same(ring[i], ring[i + 1]))
176
+ return false;
177
+ const boxes = segmentBoxes(ring);
178
+ if (!boxes)
179
+ return simpleClosedRingReference(ring);
180
+ return !sweepSelf(boxes, (p, q) => {
181
+ const i = Math.min(p, q), j = Math.max(p, q);
182
+ if (j === i + 1 || (i === 0 && j === n - 1))
183
+ return false;
184
+ return segmentsIntersect(ring[i], ring[i + 1], ring[j], ring[j + 1]);
185
+ });
186
+ }
92
187
  export function pointInRing(p, ring) {
93
188
  let inside = false;
94
189
  for (let i = 0, j = ring.length - 2; i < ring.length - 1; j = i++) {
@@ -101,22 +196,37 @@ export function pointInRing(p, ring) {
101
196
  }
102
197
  return inside;
103
198
  }
104
- function ringsIntersect(a, b) {
199
+ function ringsIntersectReference(a, b) {
105
200
  for (let i = 0; i < a.length - 1; i++)
106
201
  for (let j = 0; j < b.length - 1; j++)
107
202
  if (segmentsIntersect(a[i], a[i + 1], b[j], b[j + 1]))
108
203
  return true;
109
204
  return false;
110
205
  }
206
+ /** Touching counts as intersecting. Boxes are cached per validPolygon call. */
207
+ function ringsIntersect(a, b, cache) {
208
+ if (a.length - 1 < INDEX_MIN_SEGMENTS && b.length - 1 < INDEX_MIN_SEGMENTS)
209
+ return ringsIntersectReference(a, b);
210
+ const boxesOf = (r) => {
211
+ if (!cache.has(r))
212
+ cache.set(r, segmentBoxes(r));
213
+ return cache.get(r);
214
+ };
215
+ const A = boxesOf(a), B = boxesOf(b);
216
+ if (!A || !B)
217
+ return ringsIntersectReference(a, b);
218
+ return sweepBetween(A, B, (i, j) => segmentsIntersect(a[i], a[i + 1], b[j], b[j + 1]));
219
+ }
111
220
  export function validPolygon(rings) {
112
221
  if (!rings.length || rings.some((r) => !simpleClosedRing(r)))
113
222
  return false;
223
+ const cache = new Map();
114
224
  for (let i = 1; i < rings.length; i++) {
115
225
  if (!pointInRing(rings[i][0], rings[0]) ||
116
- ringsIntersect(rings[0], rings[i]))
226
+ ringsIntersect(rings[0], rings[i], cache))
117
227
  return false;
118
228
  for (let j = 1; j < i; j++) {
119
- if (ringsIntersect(rings[j], rings[i]) ||
229
+ if (ringsIntersect(rings[j], rings[i], cache) ||
120
230
  pointInRing(rings[i][0], rings[j]) ||
121
231
  pointInRing(rings[j][0], rings[i]))
122
232
  return false;
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export { exportPartitions, encodePartition, decodePartition, checksum, requiredP
7
7
  export { QuadstreamSession } from "./session.js";
8
8
  export { QuadstreamLoader, fetchFromBundle } from "./loader.js";
9
9
  export type { PartitionFetcher, LoaderOptions } from "./loader.js";
10
- export { validPolygon, simpleClosedRing, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
10
+ export { validPolygon, simpleClosedRing, simpleClosedRingReference, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
11
11
  export type * from "./types.js";
12
12
  export { importGeoJSON, exportGeoJSON, importTopoJSON, exportTopoJSON, } from "./adapters.js";
13
13
  export type { TopoJSONTopology } from "./adapters.js";
@@ -20,3 +20,17 @@ export { canonicalLonLat, lonLatVector, angularDistance, validGreatCirclePath, s
20
20
  export type { UnitVector, CubeFace, SphericalCell, SphericalPriorities, SphericalChart, SphericalPolygonSignature, } from "./spherical-geometry.js";
21
21
  export { SphericalQuadstreamDataset, buildSphericalQuadstream, importSphericalTopoJSON, } from "./spherical-dataset.js";
22
22
  export type { SphericalQueryOptions } from "./spherical-dataset.js";
23
+ export { computeFeatureCap, computeFeatureCaps, isCapVisible, filterSphericalFeatures, } from "./spherical-cull.js";
24
+ export type { SphericalCap, SphericalViewCone } from "./spherical-cull.js";
25
+ export { clipWindow, clipToWindow } from "./spherical-clip.js";
26
+ export type { SphericalClipWindow, SphericalClipStats, SphericalClipResult, } from "./spherical-clip.js";
27
+ export { repairRing, repairGeometry } from "./spherical-repair.js";
28
+ export type { SphericalRepairOptions } from "./spherical-repair.js";
29
+ export { createLatestGeometry, improvesLod } from "./lod-scheduler.js";
30
+ export type { LatestGeometryOptions } from "./lod-scheduler.js";
31
+ export { sphericalConnectedComponents, buildRobustSphericalGroups, } from "./spherical-robust-dataset.js";
32
+ export type { SphericalBuildGroup, RobustSphericalOptions, } from "./spherical-robust-dataset.js";
33
+ export { packGeometry, unpackGeometry } from "./geometry-wire.js";
34
+ export type { PackedGeometry } from "./geometry-wire.js";
35
+ export { createSphericalViewClipper } from "./spherical-view-clipper.js";
36
+ export type { SphericalViewClipperOptions, CachedSphericalClipResult, } from "./spherical-view-clipper.js";
package/dist/index.js CHANGED
@@ -6,10 +6,17 @@ export { createSpatialIndex } from "./spatial-index.js";
6
6
  export { exportPartitions, encodePartition, decodePartition, checksum, requiredPartitionKeys, partitionsWithVerticesInBounds, } from "./partition.js";
7
7
  export { QuadstreamSession } from "./session.js";
8
8
  export { QuadstreamLoader, fetchFromBundle } from "./loader.js";
9
- export { validPolygon, simpleClosedRing, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
9
+ export { validPolygon, simpleClosedRing, simpleClosedRingReference, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
10
10
  export { importGeoJSON, exportGeoJSON, importTopoJSON, exportTopoJSON, } from "./adapters.js";
11
11
  export { validateManifest, MANIFEST_VERSION } from "./manifest-schema.js";
12
12
  export { ProgressiveMap } from "./progressive-map.js";
13
13
  export { attachMapLibre, mapLibreBounds } from "./maplibre-adapter.js";
14
14
  export { canonicalLonLat, lonLatVector, angularDistance, validGreatCirclePath, sphericalCellAddress, buildSphericalPriorities, sphericalChart, projectSpherical, sphericalPolygonSignature, validSphericalPolygon, } from "./spherical-geometry.js";
15
15
  export { SphericalQuadstreamDataset, buildSphericalQuadstream, importSphericalTopoJSON, } from "./spherical-dataset.js";
16
+ export { computeFeatureCap, computeFeatureCaps, isCapVisible, filterSphericalFeatures, } from "./spherical-cull.js";
17
+ export { clipWindow, clipToWindow } from "./spherical-clip.js";
18
+ export { repairRing, repairGeometry } from "./spherical-repair.js";
19
+ export { createLatestGeometry, improvesLod } from "./lod-scheduler.js";
20
+ export { sphericalConnectedComponents, buildRobustSphericalGroups, } from "./spherical-robust-dataset.js";
21
+ export { packGeometry, unpackGeometry } from "./geometry-wire.js";
22
+ export { createSphericalViewClipper } from "./spherical-view-clipper.js";
@@ -0,0 +1,15 @@
1
+ export interface LatestGeometryOptions<T> {
2
+ request: (level: number) => Promise<T>;
3
+ onFrame: (frame: T) => void;
4
+ onError?: (error: unknown) => void;
5
+ cacheCapacity?: number;
6
+ }
7
+ export declare function improvesLod(level: number, rendered: number | null, target: number | null): boolean;
8
+ export declare function createLatestGeometry<T extends {
9
+ seq?: number;
10
+ }>({ request, onFrame, onError, cacheCapacity, }: LatestGeometryOptions<T>): {
11
+ select(level: number): Promise<void>;
12
+ invalidate: () => void;
13
+ dispose(): void;
14
+ readonly target: number | null;
15
+ };
@@ -0,0 +1,85 @@
1
+ // Compare against the current target, not the target at dispatch time.
2
+ // A first frame is useful; subsequent frames must strictly reduce LOD error.
3
+ export function improvesLod(level, rendered, target) {
4
+ return (target != null &&
5
+ (rendered == null || Math.abs(level - target) < Math.abs(rendered - target)));
6
+ }
7
+ // Completion-driven throttle: one active query, one replaceable desired level.
8
+ // Completed obsolete frames remain cached but cannot regress visible detail.
9
+ export function createLatestGeometry({ request, onFrame, onError = () => { }, cacheCapacity = 4, }) {
10
+ if (!Number.isInteger(cacheCapacity) || cacheCapacity < 0)
11
+ throw new Error("Invalid cache capacity");
12
+ let generation = 0, lastSeq = 0, desired = null, rendered = null, running = false, disposed = false;
13
+ const cache = new Map();
14
+ async function drain() {
15
+ if (running || disposed)
16
+ return;
17
+ running = true;
18
+ try {
19
+ while (!disposed && desired !== null && desired !== rendered) {
20
+ const level = desired, id = generation;
21
+ try {
22
+ let frame = cache.get(level);
23
+ if (!frame) {
24
+ frame = await request(level);
25
+ if (disposed || id !== generation)
26
+ continue;
27
+ const seq = frame?.seq;
28
+ if (seq != null) {
29
+ if (seq < lastSeq)
30
+ throw new Error("Out-of-order geometry frame");
31
+ lastSeq = seq;
32
+ }
33
+ cache.set(level, frame);
34
+ if (cache.size > cacheCapacity)
35
+ cache.delete(cache.keys().next().value);
36
+ }
37
+ if (improvesLod(level, rendered, desired)) {
38
+ rendered = level;
39
+ onFrame(frame);
40
+ }
41
+ }
42
+ catch (e) {
43
+ if (disposed || id !== generation)
44
+ continue;
45
+ // An obsolete failure must not block the newest target. A failure
46
+ // of the current target may be retried by a subsequent selection.
47
+ if (desired === level) {
48
+ desired = null;
49
+ onError(e);
50
+ }
51
+ }
52
+ }
53
+ }
54
+ finally {
55
+ running = false;
56
+ }
57
+ }
58
+ function invalidate() {
59
+ generation++;
60
+ lastSeq = 0;
61
+ desired = null;
62
+ rendered = null;
63
+ cache.clear();
64
+ }
65
+ return {
66
+ async select(level) {
67
+ if (!Number.isFinite(level))
68
+ throw new Error("Invalid LOD");
69
+ if (disposed)
70
+ return;
71
+ desired = level;
72
+ // While busy this records intent only; the existing drain owns the
73
+ // query and will consume the latest target when that query completes.
74
+ await drain();
75
+ },
76
+ invalidate,
77
+ dispose() {
78
+ disposed = true;
79
+ invalidate();
80
+ },
81
+ get target() {
82
+ return desired;
83
+ },
84
+ };
85
+ }
@@ -8,6 +8,20 @@ export interface ReconstructionResult {
8
8
  missing: boolean;
9
9
  valid: boolean;
10
10
  selectedVertices: number;
11
+ /** Closed rings omitted from the output (hidden or collapsed). */
12
+ hiddenRings: number;
13
+ }
14
+ export type CollapsedRingPolicy = "restore" | "drop";
15
+ export interface ReconstructOptions {
16
+ /**
17
+ * A closed ring with fewer than 3 distinct selected vertices is either
18
+ * restored to its original vertices (default) or dropped: a hidden exterior
19
+ * drops its whole polygon, a hidden hole is filled. Topology anchors keep
20
+ * rings from collapsing in practice; `hiddenPaths` is what hides islands.
21
+ */
22
+ collapsed?: CollapsedRingPolicy;
23
+ /** Path indices that are omitted without being reconstructed. */
24
+ hiddenPaths?: ReadonlySet<number>;
11
25
  }
12
26
  export declare function buildArcTrees(arcs: readonly Arc[], levels: readonly number[], critical?: readonly boolean[]): BlgTree[];
13
- export declare function reconstructFeature(f: TopologyFeature, arcs: readonly Arc[], trees: readonly BlgTree[], level: number | ((arcId: number) => number), lookup: CoordinateLookup, includeMissing?: boolean, planarValidity?: boolean): ReconstructionResult;
27
+ export declare function reconstructFeature(f: TopologyFeature, arcs: readonly Arc[], trees: readonly BlgTree[], level: number | ((arcId: number) => number), lookup: CoordinateLookup, _includeMissing?: boolean, planarValidity?: boolean, options?: ReconstructOptions): ReconstructionResult;
@@ -1,31 +1,60 @@
1
- import { validPolygon, simpleClosedRing } from "./geometry.js";
1
+ import { validPolygon } from "./geometry.js";
2
2
  import { buildBlgTree, selectBlgPositions, stableBlgRandom, } from "./blg.js";
3
3
  export function buildArcTrees(arcs, levels, critical = []) {
4
4
  return arcs.map((arc) => buildBlgTree(arc.vertexIds.map((id, i) => i === 0 || i === arc.vertexIds.length - 1 ? 0 : levels[id]), arc.vertexIds.map((id) => (critical[id] ? 1 : stableBlgRandom(id)))));
5
5
  }
6
- export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing = false, planarValidity = true) {
6
+ /** True when fewer than 3 distinct positions precede the closing vertex. */
7
+ function distinctBelow3(coords) {
8
+ const n = coords.length - 1;
9
+ let first, second;
10
+ for (let i = 0; i < n; i++) {
11
+ const p = coords[i];
12
+ if (!first)
13
+ first = p;
14
+ else if (p[0] !== first[0] || p[1] !== first[1]) {
15
+ if (!second)
16
+ second = p;
17
+ else if ((p[0] !== second[0] || p[1] !== second[1]) &&
18
+ (first[0] !== second[0] || first[1] !== second[1]))
19
+ return false;
20
+ }
21
+ }
22
+ return true;
23
+ }
24
+ export function reconstructFeature(f, arcs, trees, level, lookup,
25
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
26
+ _includeMissing = false, planarValidity = true, options = {}) {
7
27
  let missing = false, selectedVertices = 0;
28
+ const dropCollapsed = options.collapsed === "drop";
29
+ const hidden = new Set(options.hiddenPaths);
30
+ // Holes of a hidden exterior go with it, so they are never reconstructed.
31
+ const shellOf = [];
32
+ if (f.geometryType === "Polygon" || f.geometryType === "MultiPolygon")
33
+ for (const group of f.groups)
34
+ for (const p of group) {
35
+ shellOf[p] = group[0];
36
+ if (hidden.has(group[0]))
37
+ hidden.add(p);
38
+ }
8
39
  const paths = [];
9
- for (const path of f.paths) {
10
- const coords = [], allIds = [];
40
+ for (let pathIndex = 0; pathIndex < f.paths.length; pathIndex++) {
41
+ const path = f.paths[pathIndex];
42
+ if (hidden.has(pathIndex) || hidden.has(shellOf[pathIndex] ?? -1)) {
43
+ hidden.add(pathIndex);
44
+ paths.push([]);
45
+ continue;
46
+ }
47
+ const coords = [];
11
48
  let pathSelectedVertices = 0;
12
49
  for (const ref of path.arcs) {
13
50
  const arcId = Math.abs(ref) - 1, arc = arcs[arcId], tree = trees[arcId];
14
51
  const positions = selectBlgPositions(tree, typeof level === "number" ? level : level(arcId));
15
- if (ref < 0)
16
- positions.reverse();
17
- const orderedIds = ref < 0 ? [...arc.vertexIds].reverse() : arc.vertexIds;
18
- for (const id of orderedIds)
19
- if (!allIds.length || allIds.at(-1) !== id)
20
- allIds.push(id);
52
+ const last = positions.length - 1;
21
53
  for (let i = 0; i < positions.length; i++) {
22
- const id = arc.vertexIds[positions[i]], xy = lookup(id);
54
+ const id = arc.vertexIds[positions[ref < 0 ? last - i : i]], xy = lookup(id);
23
55
  if (!xy) {
24
56
  missing = true;
25
- if (includeMissing)
26
- continue;
27
- else
28
- continue;
57
+ continue;
29
58
  }
30
59
  if (coords.length &&
31
60
  i === 0 &&
@@ -36,12 +65,24 @@ export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing
36
65
  pathSelectedVertices++;
37
66
  }
38
67
  }
39
- if (path.closed) {
40
- const distinct = new Set(coords.slice(0, -1).map((p) => p.join(",")));
41
- if (distinct.size < 3) {
42
- coords.length = 0;
43
- pathSelectedVertices = 0;
44
- for (const id of allIds) {
68
+ if (path.closed && dropCollapsed && distinctBelow3(coords)) {
69
+ hidden.add(pathIndex);
70
+ paths.push([]);
71
+ continue;
72
+ }
73
+ if (path.closed && distinctBelow3(coords)) {
74
+ // Collapsed ring: restore every original vertex. Only this rare path
75
+ // pays for walking all arc positions.
76
+ coords.length = 0;
77
+ pathSelectedVertices = 0;
78
+ let lastId = -1;
79
+ for (const ref of path.arcs) {
80
+ const ids = arcs[Math.abs(ref) - 1].vertexIds;
81
+ for (let k = 0; k < ids.length; k++) {
82
+ const id = ids[ref < 0 ? ids.length - 1 - k : k];
83
+ if (id === lastId)
84
+ continue;
85
+ lastId = id;
45
86
  const xy = lookup(id);
46
87
  if (xy &&
47
88
  (!coords.length ||
@@ -62,14 +103,16 @@ export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing
62
103
  selectedVertices += pathSelectedVertices;
63
104
  paths.push(coords);
64
105
  }
65
- const groups = f.groups.map((group) => group.map((i) => paths[i]));
106
+ const groups = f.groups
107
+ .filter((group) => !hidden.has(group[0]))
108
+ .map((group) => group.filter((i) => !hidden.has(i)).map((i) => paths[i]));
66
109
  let geometry;
67
110
  let valid = true;
68
111
  const checkPolygon = planarValidity ? validPolygon : () => true;
69
112
  switch (f.geometryType) {
70
113
  case "Polygon":
71
- geometry = { type: "Polygon", coordinates: groups[0] };
72
- valid = checkPolygon(groups[0]);
114
+ geometry = { type: "Polygon", coordinates: groups[0] ?? [] };
115
+ valid = !groups[0] || checkPolygon(groups[0]);
73
116
  break;
74
117
  case "MultiPolygon":
75
118
  geometry = { type: "MultiPolygon", coordinates: groups };
@@ -87,11 +130,6 @@ export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing
87
130
  valid = groups.every((g) => g[0].length >= 2);
88
131
  break;
89
132
  }
90
- // A closed ring whose last segment collapses must not be accepted by accident.
91
- if (planarValidity &&
92
- f.geometryType === "Polygon" &&
93
- !groups[0].every(simpleClosedRing))
94
- valid = false;
95
133
  return {
96
134
  feature: {
97
135
  type: "Feature",
@@ -102,5 +140,6 @@ export function reconstructFeature(f, arcs, trees, level, lookup, includeMissing
102
140
  missing,
103
141
  valid,
104
142
  selectedVertices,
143
+ hiddenRings: hidden.size,
105
144
  };
106
145
  }
@@ -0,0 +1,95 @@
1
+ import type { SphericalCap, SphericalViewCone } from "./spherical-cull.js";
2
+ import type { Feature, FeatureCollection, Position } from "./types.js";
3
+ export interface SphericalClipWindow extends SphericalViewCone {
4
+ cx: number;
5
+ cy: number;
6
+ cz: number;
7
+ radius: number;
8
+ cosR: number;
9
+ sinR: number;
10
+ ux: number;
11
+ uy: number;
12
+ uz: number;
13
+ bx: number;
14
+ by: number;
15
+ bz: number;
16
+ }
17
+ interface RingInfo {
18
+ ring: Position[];
19
+ n: number;
20
+ xyz: Float64Array;
21
+ cap: SphericalCap;
22
+ }
23
+ interface Piece {
24
+ pts: Position[];
25
+ from: number;
26
+ to: number;
27
+ }
28
+ type RingResult = {
29
+ status: "away" | "wraps";
30
+ } | {
31
+ status: "inside";
32
+ ring: Position[];
33
+ } | {
34
+ status: "clipped";
35
+ rings: Position[][];
36
+ };
37
+ interface ClipWork {
38
+ classified: number;
39
+ inside: number;
40
+ outside: number;
41
+ }
42
+ interface FeatureInfo {
43
+ cap: SphericalCap;
44
+ ring: (pi: number, ri: number) => RingInfo;
45
+ }
46
+ export interface SphericalClipStats {
47
+ features: number;
48
+ rings: {
49
+ kept: number;
50
+ clipped: number;
51
+ wrapped: number;
52
+ dropped: number;
53
+ };
54
+ vertices: number;
55
+ stream: ClipWork;
56
+ }
57
+ export interface SphericalClipResult {
58
+ geojson: FeatureCollection;
59
+ stats: SphericalClipStats;
60
+ }
61
+ export declare function clipWindow(cx: number, cy: number, cz: number, radius: number): SphericalClipWindow;
62
+ export declare function circleRing(w: SphericalClipWindow, side?: number): Position[];
63
+ export declare function ringInfo(ring: Position[]): RingInfo;
64
+ /** Reference O(c^2) pairing: the first entry met walking from each exit. */
65
+ export declare function pairPiecesReference(pieces: Pick<Piece, "from" | "to">[], side?: number): number[];
66
+ /**
67
+ * Sorted-event pairing: entries are ordered by azimuth, each exit binary
68
+ * searches its neighbourhood and the exact reference delta rule decides among
69
+ * the few candidates, so ties, wraparound and epsilon behave identically.
70
+ */
71
+ export declare function pairPieces(pieces: Pick<Piece, "from" | "to">[], side?: number): number[];
72
+ /**
73
+ * Clip one ring to the window. Status:
74
+ * - inside: every vertex inside, `ring` is the original array
75
+ * - clipped: `rings` are new closed rings (a ring that dips in and out of
76
+ * the window can split into several)
77
+ * - wraps: no crossing and the ring's material side (exterior) or enclosed
78
+ * region (hole) covers the whole window
79
+ * - away: no crossing and the window is on the other side
80
+ */
81
+ export declare function clipRingReference(w: SphericalClipWindow, info: RingInfo, side?: number): RingResult;
82
+ /**
83
+ * Stream the ring in the reference's cyclic order, starting at the first
84
+ * exterior vertex. Classify each position exactly once; the initial inside
85
+ * prefix is known when the traversal wraps. No per-ring visibility bitmap.
86
+ * Keep outside endpoints only long enough to test their actual joining edge.
87
+ */
88
+ export declare function clipRing(w: SphericalClipWindow, info: RingInfo, side?: number, work?: ClipWork): RingResult;
89
+ export declare function buildFeatureInfo(feature: Feature, cap?: SphericalCap): FeatureInfo;
90
+ /** Uncached clip of a collection to an explicit window. */
91
+ export declare function clipToWindow(geojson: FeatureCollection, w: SphericalClipWindow): SphericalClipResult;
92
+ export declare function countVertices(geojson: FeatureCollection | null | undefined): number;
93
+ /** Clip every feature to the window; unchanged features keep their identity. */
94
+ export declare function clipFeatureCollection(geojson: FeatureCollection, w: SphericalClipWindow, getInfo: (i: number, feature: Feature) => FeatureInfo): SphericalClipResult;
95
+ export {};