@maplat/tin 0.13.1 → 0.14.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.
@@ -1,283 +1,557 @@
1
- import { lineString, lineIntersect } from "@turf/turf";
2
- import type { Position } from "geojson";
3
- import type { VertexPosition } from "./types/tin.d.ts";
4
-
5
- interface ConvexEntry {
6
- forw: Position;
7
- bakw: Position;
8
- }
9
-
10
- interface BoundaryVerticesParams {
11
- convexBuf: Record<string, ConvexEntry>;
12
- centroid: { forw: Position; bakw: Position };
13
- bbox: Position[];
14
- minx: number;
15
- maxx: number;
16
- miny: number;
17
- maxy: number;
18
- }
19
-
20
- type EdgeRayBuckets = Array<Array<ConvexEntry>>;
21
- type SamplePair = {
22
- forw: [number, number];
23
- bakw: [number, number];
24
- };
25
-
26
- function buildEdgeBuckets(
27
- convexBuf: Record<string, ConvexEntry>,
28
- centroid: { forw: Position; bakw: Position },
29
- minx: number,
30
- maxx: number,
31
- miny: number,
32
- maxy: number,
33
- ): EdgeRayBuckets {
34
- return Object.keys(convexBuf).reduce((prev, key) => {
35
- const item = convexBuf[key];
36
- const forw = item.forw;
37
- const bakw = item.bakw;
38
-
39
- const vec = {
40
- forw: [forw[0] - centroid.forw[0], forw[1] - centroid.forw[1]],
41
- bakw: [bakw[0] - centroid.bakw[0], bakw[1] - centroid.bakw[1]],
42
- };
43
-
44
- const xRate = vec.forw[0] === 0
45
- ? Infinity
46
- : ((vec.forw[0] < 0 ? minx : maxx) - centroid.forw[0]) / vec.forw[0];
47
- const yRate = vec.forw[1] === 0
48
- ? Infinity
49
- : ((vec.forw[1] < 0 ? miny : maxy) - centroid.forw[1]) / vec.forw[1];
50
-
51
- if (Math.abs(xRate) / Math.abs(yRate) < 1.1) {
52
- const node = {
53
- forw: [
54
- vec.forw[0] * xRate + centroid.forw[0],
55
- vec.forw[1] * xRate + centroid.forw[1],
56
- ] as Position,
57
- bakw: [
58
- vec.bakw[0] * xRate + centroid.bakw[0],
59
- vec.bakw[1] * xRate + centroid.bakw[1],
60
- ] as Position,
61
- };
62
- if (vec.forw[0] < 0) {
63
- prev[3].push(node);
64
- } else {
65
- prev[1].push(node);
66
- }
67
- }
68
-
69
- if (Math.abs(yRate) / Math.abs(xRate) < 1.1) {
70
- const node = {
71
- forw: [
72
- vec.forw[0] * yRate + centroid.forw[0],
73
- vec.forw[1] * yRate + centroid.forw[1],
74
- ] as Position,
75
- bakw: [
76
- vec.bakw[0] * yRate + centroid.bakw[0],
77
- vec.bakw[1] * yRate + centroid.bakw[1],
78
- ] as Position,
79
- };
80
- if (vec.forw[1] < 0) {
81
- prev[0].push(node);
82
- } else {
83
- prev[2].push(node);
84
- }
85
- }
86
-
87
- return prev;
88
- }, [[], [], [], []] as EdgeRayBuckets);
89
- }
90
-
91
- function collectSamples(
92
- convexBuf: Record<string, ConvexEntry>,
93
- centroid: { forw: Position; bakw: Position },
94
- ): { perQuad: SamplePair[][]; aggregate: SamplePair[] } {
95
- const perQuad: SamplePair[][] = [[], [], [], []];
96
- const aggregate: SamplePair[] = [];
97
-
98
- Object.keys(convexBuf).forEach((key) => {
99
- const item = convexBuf[key];
100
- const forw = item.forw;
101
- const bakw = item.bakw;
102
-
103
- const forwDelta: [number, number] = [
104
- forw[0] - centroid.forw[0],
105
- forw[1] - centroid.forw[1],
106
- ];
107
- const bakwDelta: [number, number] = [
108
- bakw[0] - centroid.bakw[0],
109
- centroid.bakw[1] - bakw[1],
110
- ];
111
-
112
- const sample: SamplePair = { forw: forwDelta, bakw: bakwDelta };
113
- aggregate.push(sample);
114
-
115
- if (forwDelta[0] === 0 || forwDelta[1] === 0) {
116
- return;
117
- }
118
-
119
- let quad = 0;
120
- if (forwDelta[0] > 0) quad += 1;
121
- if (forwDelta[1] > 0) quad += 2;
122
- perQuad[quad].push(sample);
123
- });
124
-
125
- return { perQuad, aggregate };
126
- }
127
-
128
- function reduceSamples(samples: SamplePair[]): [number, number] {
129
- let minRatio = Infinity;
130
- let sumCos = 0;
131
- let sumSin = 0;
132
-
133
- samples.forEach((sample) => {
134
- const { forw, bakw } = sample;
135
- const forwNorm = Math.hypot(forw[0], forw[1]);
136
- const bakwNorm = Math.hypot(bakw[0], bakw[1]);
137
- if (bakwNorm === 0) return;
138
-
139
- const ratio = forwNorm / bakwNorm;
140
- const theta = Math.atan2(forw[0], forw[1]) - Math.atan2(bakw[0], bakw[1]);
141
-
142
- minRatio = Math.min(minRatio, ratio);
143
- sumCos += Math.cos(theta);
144
- sumSin += Math.sin(theta);
145
- });
146
-
147
- if (!isFinite(minRatio)) {
148
- return [1, 0];
149
- }
150
-
151
- return [minRatio, Math.atan2(sumSin, sumCos)];
152
- }
153
-
154
- function buildVertexRatio(
155
- convexBuf: Record<string, ConvexEntry>,
156
- centroid: { forw: Position; bakw: Position },
157
- mode: "plain" | "birdeye",
158
- ): Array<[number, number]> {
159
- const { perQuad, aggregate } = collectSamples(convexBuf, centroid);
160
- const hasAllQuadrants = perQuad.every((samples) => samples.length > 0);
161
-
162
- const groups: SamplePair[][] = mode === "birdeye"
163
- ? (hasAllQuadrants ? perQuad : [aggregate])
164
- : [aggregate];
165
-
166
- const vertexRatio = groups.map((samples) => reduceSamples(samples));
167
-
168
- if (vertexRatio.length === 1) {
169
- return [vertexRatio[0], vertexRatio[0], vertexRatio[0], vertexRatio[0]];
170
- }
171
-
172
- return vertexRatio;
173
- }
174
-
175
- function checkAndAdjustVertices(
176
- vertices: VertexPosition[],
177
- edgeNodes: EdgeRayBuckets,
178
- centroid: { forw: Position; bakw: Position },
179
- ): void {
180
- const expandRatio = [1, 1, 1, 1];
181
-
182
- for (let i = 0; i < 4; i++) {
183
- const j = (i + 1) % 4;
184
- const side = lineString([vertices[i].bakw, vertices[j].bakw]);
185
-
186
- edgeNodes[i].map((node) => {
187
- const line = lineString([centroid.bakw, node.bakw]);
188
- const intersect = lineIntersect(side, line);
189
-
190
- if (intersect.features.length > 0 && intersect.features[0].geometry) {
191
- const intersectPt = intersect.features[0];
192
- const distance = Math.sqrt(
193
- Math.pow(node.bakw[0] - centroid.bakw[0], 2) +
194
- Math.pow(node.bakw[1] - centroid.bakw[1], 2),
195
- );
196
- const intDistance = Math.sqrt(
197
- Math.pow(
198
- intersectPt.geometry.coordinates[0] - centroid.bakw[0],
199
- 2,
200
- ) +
201
- Math.pow(
202
- intersectPt.geometry.coordinates[1] - centroid.bakw[1],
203
- 2,
204
- ),
205
- );
206
- const ratio = distance / intDistance;
207
-
208
- if (ratio > expandRatio[i]) expandRatio[i] = ratio;
209
- if (ratio > expandRatio[j]) expandRatio[j] = ratio;
210
- }
211
- });
212
- }
213
-
214
- vertices.forEach((vertex, i) => {
215
- const ratio = expandRatio[i];
216
- const bakw: Position = [
217
- (vertex.bakw[0] - centroid.bakw[0]) * ratio + centroid.bakw[0],
218
- (vertex.bakw[1] - centroid.bakw[1]) * ratio + centroid.bakw[1],
219
- ];
220
- vertex.bakw = bakw;
221
- });
222
- }
223
-
224
- function finalizeVertices(
225
- vertexRatio: Array<[number, number]>,
226
- bbox: Position[],
227
- centroid: { forw: Position; bakw: Position },
228
- edgeNodes: EdgeRayBuckets,
229
- ): VertexPosition[] {
230
- const vertices = vertexRatio.map((ratio, index) => {
231
- const forVertex = bbox[index];
232
- const forDelta = [
233
- forVertex[0] - centroid.forw[0],
234
- forVertex[1] - centroid.forw[1],
235
- ];
236
- const forDistance = Math.sqrt(
237
- Math.pow(forDelta[0], 2) + Math.pow(forDelta[1], 2),
238
- );
239
- const bakDistance = forDistance / ratio[0];
240
- const bakTheta = Math.atan2(forDelta[0], forDelta[1]) - ratio[1];
241
- const bakw: Position = [
242
- centroid.bakw[0] + bakDistance * Math.sin(bakTheta),
243
- centroid.bakw[1] - bakDistance * Math.cos(bakTheta),
244
- ];
245
-
246
- return { forw: forVertex, bakw };
247
- });
248
-
249
- const swap = vertices[2];
250
- vertices[2] = vertices[3];
251
- vertices[3] = swap;
252
-
253
- checkAndAdjustVertices(vertices, edgeNodes, centroid);
254
-
255
- return vertices;
256
- }
257
-
258
- /**
259
- * Calculate the standard four boundary vertices around the centroid.
260
- */
261
- export function calculatePlainVertices(
262
- params: BoundaryVerticesParams,
263
- ): VertexPosition[] {
264
- const { convexBuf, centroid, bbox, minx, maxx, miny, maxy } = params;
265
-
266
- const edgeNodes = buildEdgeBuckets(convexBuf, centroid, minx, maxx, miny, maxy);
267
- const vertexRatio = buildVertexRatio(convexBuf, centroid, "plain");
268
-
269
- return finalizeVertices(vertexRatio, bbox, centroid, edgeNodes);
270
- }
271
-
272
- /**
273
- * Calculate boundary vertices for bird's-eye mode using quadrant-aware ratios.
274
- */
275
- export function calculateBirdeyeVertices(
276
- params: BoundaryVerticesParams,
277
- ): VertexPosition[] {
278
- const { convexBuf, centroid, bbox, minx, maxx, miny, maxy } = params;
279
- const edgeNodes = buildEdgeBuckets(convexBuf, centroid, minx, maxx, miny, maxy);
280
- const vertexRatio = buildVertexRatio(convexBuf, centroid, "birdeye");
281
-
282
- return finalizeVertices(vertexRatio, bbox, centroid, edgeNodes);
283
- }
1
+ import { lineString, lineIntersect } from "@turf/turf";
2
+ import type { Position } from "geojson";
3
+ import type { VertexPosition } from "./types/tin.d.ts";
4
+
5
+ interface ConvexEntry {
6
+ forw: Position;
7
+ bakw: Position;
8
+ }
9
+
10
+ /**
11
+ * Unified parameters for all boundary vertex computations (V2 and V3).
12
+ *
13
+ * `allGcps` must include **all** interior points: GCPs from `this.points` **and**
14
+ * edge intermediate nodes from `this.edgeNodes`. This is necessary so that
15
+ * `checkAndAdjustVerticesN` can guarantee that every constrained-edge vertex in
16
+ * bakw space lies inside the boundary polygon.
17
+ */
18
+ export interface BoundaryVerticesParams {
19
+ convexBuf: Record<string, ConvexEntry>;
20
+ centroid: { forw: Position; bakw: Position };
21
+ /** GCPs + edge intermediate nodes */
22
+ allGcps: Array<{ forw: Position; bakw: Position }>;
23
+ minx: number;
24
+ maxx: number;
25
+ miny: number;
26
+ maxy: number;
27
+ }
28
+
29
+ // ─── Internal types ──────────────────────────────────────────────────────────
30
+
31
+ type SamplePair = {
32
+ forw: [number, number];
33
+ bakw: [number, number];
34
+ };
35
+
36
+ // ─── Ratio helpers ───────────────────────────────────────────────────────────
37
+
38
+ function collectSamples(
39
+ convexBuf: Record<string, ConvexEntry>,
40
+ centroid: { forw: Position; bakw: Position },
41
+ ): { perQuad: SamplePair[][]; aggregate: SamplePair[] } {
42
+ const perQuad: SamplePair[][] = [[], [], [], []];
43
+ const aggregate: SamplePair[] = [];
44
+
45
+ Object.keys(convexBuf).forEach((key) => {
46
+ const item = convexBuf[key];
47
+ const forw = item.forw;
48
+ const bakw = item.bakw;
49
+
50
+ const forwDelta: [number, number] = [
51
+ forw[0] - centroid.forw[0],
52
+ forw[1] - centroid.forw[1],
53
+ ];
54
+ const bakwDelta: [number, number] = [
55
+ bakw[0] - centroid.bakw[0],
56
+ centroid.bakw[1] - bakw[1],
57
+ ];
58
+
59
+ const sample: SamplePair = { forw: forwDelta, bakw: bakwDelta };
60
+ aggregate.push(sample);
61
+
62
+ if (forwDelta[0] === 0 || forwDelta[1] === 0) {
63
+ return;
64
+ }
65
+
66
+ let quad = 0;
67
+ if (forwDelta[0] > 0) quad += 1;
68
+ if (forwDelta[1] > 0) quad += 2;
69
+ perQuad[quad].push(sample);
70
+ });
71
+
72
+ return { perQuad, aggregate };
73
+ }
74
+
75
+ function reduceSamples(samples: SamplePair[]): [number, number] {
76
+ let minRatio = Infinity;
77
+ let sumCos = 0;
78
+ let sumSin = 0;
79
+
80
+ samples.forEach((sample) => {
81
+ const { forw, bakw } = sample;
82
+ const forwNorm = Math.hypot(forw[0], forw[1]);
83
+ const bakwNorm = Math.hypot(bakw[0], bakw[1]);
84
+ if (bakwNorm === 0) return;
85
+
86
+ const ratio = forwNorm / bakwNorm;
87
+ const theta = Math.atan2(forw[0], forw[1]) - Math.atan2(bakw[0], bakw[1]);
88
+
89
+ minRatio = Math.min(minRatio, ratio);
90
+ sumCos += Math.cos(theta);
91
+ sumSin += Math.sin(theta);
92
+ });
93
+
94
+ if (!isFinite(minRatio)) {
95
+ return [1, 0];
96
+ }
97
+
98
+ return [minRatio, Math.atan2(sumSin, sumCos)];
99
+ }
100
+
101
+ function buildVertexRatio(
102
+ convexBuf: Record<string, ConvexEntry>,
103
+ centroid: { forw: Position; bakw: Position },
104
+ mode: "plain" | "birdeye",
105
+ ): Array<[number, number]> {
106
+ const { perQuad, aggregate } = collectSamples(convexBuf, centroid);
107
+ const hasAllQuadrants = perQuad.every((samples) => samples.length > 0);
108
+
109
+ const groups: SamplePair[][] = mode === "birdeye"
110
+ ? (hasAllQuadrants ? perQuad : [aggregate])
111
+ : [aggregate];
112
+
113
+ const vertexRatio = groups.map((samples) => reduceSamples(samples));
114
+
115
+ if (vertexRatio.length === 1) {
116
+ return [vertexRatio[0], vertexRatio[0], vertexRatio[0], vertexRatio[0]];
117
+ }
118
+
119
+ return vertexRatio;
120
+ }
121
+
122
+ // ─── Geometry helpers ────────────────────────────────────────────────────────
123
+
124
+ /**
125
+ * Return quadrant index (0–3) of `forw` relative to `centroidForw`.
126
+ *
127
+ * Quadrant encoding:
128
+ * q0: Δx≤0, Δy≤0 q1: Δx>0, Δy≤0
129
+ * q2: Δx≤0, Δy>0 q3: Δx>0, Δy>0
130
+ */
131
+ function forwQuadrant(forw: Position, centroidForw: Position): number {
132
+ let q = 0;
133
+ if (forw[0] > centroidForw[0]) q += 1;
134
+ if (forw[1] > centroidForw[1]) q += 2;
135
+ return q;
136
+ }
137
+
138
+ /**
139
+ * Compute the bakw position for a given forw position using the centroid and
140
+ * an aggregate [scale, rotation] ratio.
141
+ */
142
+ function computeVertexBakwFromRatio(
143
+ forwPos: Position,
144
+ centroid: { forw: Position; bakw: Position },
145
+ ratio: [number, number],
146
+ ): Position {
147
+ const forDelta = [
148
+ forwPos[0] - centroid.forw[0],
149
+ forwPos[1] - centroid.forw[1],
150
+ ];
151
+ const forDistance = Math.sqrt(forDelta[0] ** 2 + forDelta[1] ** 2);
152
+ const bakDistance = forDistance / ratio[0];
153
+ const bakTheta = Math.atan2(forDelta[0], forDelta[1]) - ratio[1];
154
+ return [
155
+ centroid.bakw[0] + bakDistance * Math.sin(bakTheta),
156
+ centroid.bakw[1] - bakDistance * Math.cos(bakTheta),
157
+ ];
158
+ }
159
+
160
+ /**
161
+ * Find the intersection of the ray from `centroid` through `rayDir` with the
162
+ * segment [segStart, segEnd]. Returns {t, point} where t > 0 is the parameter
163
+ * along the ray, or null if no valid intersection.
164
+ */
165
+ function findRaySegmentIntersection(
166
+ centroid: Position,
167
+ rayDir: Position,
168
+ segStart: Position,
169
+ segEnd: Position,
170
+ ): { t: number; point: Position } | null {
171
+ const dx = rayDir[0] - centroid[0];
172
+ const dy = rayDir[1] - centroid[1];
173
+ if (Math.abs(dx) < 1e-12 && Math.abs(dy) < 1e-12) return null;
174
+
175
+ const ex = segEnd[0] - segStart[0];
176
+ const ey = segEnd[1] - segStart[1];
177
+ const fx = segStart[0] - centroid[0];
178
+ const fy = segStart[1] - centroid[1];
179
+
180
+ const denom = dx * ey - dy * ex;
181
+ if (Math.abs(denom) < 1e-12) return null;
182
+
183
+ const t = (fx * ey - fy * ex) / denom;
184
+ const s = (fx * dy - fy * dx) / denom;
185
+
186
+ if (t <= 1e-10) return null;
187
+ if (s < -1e-10 || s > 1 + 1e-10) return null;
188
+
189
+ return { t, point: [centroid[0] + t * dx, centroid[1] + t * dy] };
190
+ }
191
+
192
+ /**
193
+ * Find the exit intersection of the ray from `centroid` through `rayDir` with
194
+ * the convex polygon formed by `corners` (angularly-sorted VertexPosition[]).
195
+ */
196
+ function findRayQuadIntersection(
197
+ centroid: Position,
198
+ rayDir: Position,
199
+ corners: VertexPosition[],
200
+ ): Position | null {
201
+ const N = corners.length;
202
+ let bestT = -Infinity;
203
+ let bestPoint: Position | null = null;
204
+
205
+ for (let i = 0; i < N; i++) {
206
+ const j = (i + 1) % N;
207
+ const result = findRaySegmentIntersection(
208
+ centroid, rayDir, corners[i].bakw, corners[j].bakw,
209
+ );
210
+ if (result && result.t > bestT) {
211
+ bestT = result.t;
212
+ bestPoint = result.point;
213
+ }
214
+ }
215
+ return bestPoint;
216
+ }
217
+
218
+ /** Convert a forw position to [0, 360) degrees using the atan2(Δx, Δy) convention. */
219
+ function toAngleDeg360(pos: Position, centroid: Position): number {
220
+ const rawRad = Math.atan2(pos[0] - centroid[0], pos[1] - centroid[1]);
221
+ const deg = rawRad * (180 / Math.PI);
222
+ return deg < 0 ? deg + 360 : deg;
223
+ }
224
+
225
+ /**
226
+ * Find the first intersection of the ray from `centroid` THROUGH `vertex` with
227
+ * the axis-aligned bbox [minx,maxx] × [miny,maxy].
228
+ */
229
+ function findRayBboxIntersection(
230
+ centroid: Position,
231
+ vertex: Position,
232
+ minx: number,
233
+ maxx: number,
234
+ miny: number,
235
+ maxy: number,
236
+ ): Position | null {
237
+ const dx = vertex[0] - centroid[0];
238
+ const dy = vertex[1] - centroid[1];
239
+ if (dx === 0 && dy === 0) return null;
240
+
241
+ const candidates: { t: number; x: number; y: number }[] = [];
242
+
243
+ if (dx !== 0) {
244
+ for (const bx of [minx, maxx]) {
245
+ const t = (bx - centroid[0]) / dx;
246
+ if (t > 0) {
247
+ const y = centroid[1] + t * dy;
248
+ if (y >= miny && y <= maxy) candidates.push({ t, x: bx, y });
249
+ }
250
+ }
251
+ }
252
+ if (dy !== 0) {
253
+ for (const by of [miny, maxy]) {
254
+ const t = (by - centroid[1]) / dy;
255
+ if (t > 0) {
256
+ const x = centroid[0] + t * dx;
257
+ if (x >= minx && x <= maxx) candidates.push({ t, x, y: by });
258
+ }
259
+ }
260
+ }
261
+
262
+ if (candidates.length === 0) return null;
263
+ candidates.sort((a, b) => a.t - b.t);
264
+ const best = candidates[0];
265
+ return [best.x, best.y];
266
+ }
267
+
268
+ /**
269
+ * Expand N boundary vertices radially from `centroid.bakw` so that every point
270
+ * in `allPoints` has its bakw position enclosed inside the polygon formed by
271
+ * `vertices`.
272
+ *
273
+ * For each point, tests all N bakw polygon sides to find where the ray
274
+ * [centroid.bakw → point.bakw] exits. If the point is outside that side, both
275
+ * endpoints of the side are scaled outward until the point is enclosed.
276
+ */
277
+ function checkAndAdjustVerticesN(
278
+ vertices: VertexPosition[],
279
+ allPoints: Array<{ forw: Position; bakw: Position }>,
280
+ centroid: { forw: Position; bakw: Position },
281
+ ): void {
282
+ const N = vertices.length;
283
+ const expandRatio = new Array<number>(N).fill(1);
284
+
285
+ for (const node of allPoints) {
286
+ for (let i = 0; i < N; i++) {
287
+ const j = (i + 1) % N;
288
+ const side = lineString([vertices[i].bakw, vertices[j].bakw]);
289
+ const line = lineString([centroid.bakw, node.bakw]);
290
+ const intersect = lineIntersect(side, line);
291
+
292
+ if (intersect.features.length > 0 && intersect.features[0].geometry) {
293
+ const intersectPt = intersect.features[0];
294
+ const distance = Math.sqrt(
295
+ Math.pow(node.bakw[0] - centroid.bakw[0], 2) +
296
+ Math.pow(node.bakw[1] - centroid.bakw[1], 2),
297
+ );
298
+ const intDistance = Math.sqrt(
299
+ Math.pow(intersectPt.geometry.coordinates[0] - centroid.bakw[0], 2) +
300
+ Math.pow(intersectPt.geometry.coordinates[1] - centroid.bakw[1], 2),
301
+ );
302
+ const ratio = distance / intDistance;
303
+ if (ratio > expandRatio[i]) expandRatio[i] = ratio;
304
+ if (ratio > expandRatio[j]) expandRatio[j] = ratio;
305
+ }
306
+ }
307
+ }
308
+
309
+ vertices.forEach((vertex, i) => {
310
+ const ratio = expandRatio[i];
311
+ vertex.bakw = [
312
+ (vertex.bakw[0] - centroid.bakw[0]) * ratio + centroid.bakw[0],
313
+ (vertex.bakw[1] - centroid.bakw[1]) * ratio + centroid.bakw[1],
314
+ ];
315
+ });
316
+ }
317
+
318
+ // ─── Unified core ────────────────────────────────────────────────────────────
319
+
320
+ /**
321
+ * Unified boundary vertex computation shared by V2 (4 corners) and V3 (4 corners
322
+ * + up to 32 edge vertices).
323
+ *
324
+ * ## Algorithm
325
+ *
326
+ * ### Phase 1 – Ratios
327
+ * Compute per-quadrant (birdeye) or aggregate (plain) [minScale, avgRotation]
328
+ * ratios from the convex hull of all GCPs.
329
+ *
330
+ * ### Phase 2 – 4 bbox corners
331
+ * Each bbox corner's bakw position is extrapolated using the ratio for its
332
+ * quadrant. `checkAndAdjustVerticesN` then expands corners radially so that
333
+ * **every point in `allGcps`** (GCPs + edge intermediate nodes) is enclosed.
334
+ *
335
+ * If `withEdgeVertices` is false the function returns here (V2 path).
336
+ *
337
+ * ### Phase 3 – 36 × 10° bins (V3 only)
338
+ * For each non-corner 10° bin the most-extreme interior point (GCP or edge
339
+ * node) in that angular range is used as a guide:
340
+ *
341
+ * - **bakw direction**: linearly interpolated rotation between the two
342
+ * bracketing corner bakw rotations → smooth, no discontinuity.
343
+ * - **bakw distance**: the guide point's actual bakw distance from centroid,
344
+ * scaled up by `forwEdge_dist / forwGuide_dist` (extrapolation to the bbox
345
+ * boundary). This gives non-collinear positions independent of the
346
+ * corner-quad sides and avoids degenerate (zero-area) triangles.
347
+ *
348
+ * Bins with no interior points fall back to the interpolated corner scale.
349
+ *
350
+ * ### Phase 4 – Sort + final adjust
351
+ * All vertices are sorted by forw angle. `checkAndAdjustVerticesN` is called
352
+ * again on the full set so that the final polygon correctly encloses every
353
+ * interior point.
354
+ */
355
+ function calculateVerticesCore(
356
+ params: BoundaryVerticesParams,
357
+ mode: "plain" | "birdeye",
358
+ withEdgeVertices: boolean,
359
+ ): VertexPosition[] {
360
+ const { convexBuf, centroid, allGcps, minx, maxx, miny, maxy } = params;
361
+
362
+ // ── Phase 1 ───────────────────────────────────────────────────────────────
363
+ const cornerRatios = buildVertexRatio(convexBuf, centroid, mode);
364
+
365
+ // ── Phase 2: 4 bbox corner vertices ───────────────────────────────────────
366
+ const bboxCornerForws: Position[] = [
367
+ [minx, miny],
368
+ [maxx, miny],
369
+ [maxx, maxy],
370
+ [minx, maxy],
371
+ ];
372
+ const cornerVertices: VertexPosition[] = bboxCornerForws.map((forw) => ({
373
+ forw,
374
+ bakw: computeVertexBakwFromRatio(
375
+ forw,
376
+ centroid,
377
+ cornerRatios[forwQuadrant(forw, centroid.forw)],
378
+ ),
379
+ }));
380
+
381
+ // Sort corners CCW by forw angle (atan2(Δx, Δy) convention)
382
+ cornerVertices.sort((a, b) =>
383
+ Math.atan2(a.forw[0] - centroid.forw[0], a.forw[1] - centroid.forw[1]) -
384
+ Math.atan2(b.forw[0] - centroid.forw[0], b.forw[1] - centroid.forw[1])
385
+ );
386
+
387
+ // Expand corners to enclose all GCPs + edge nodes in bakw space
388
+ checkAndAdjustVerticesN(cornerVertices, allGcps, centroid);
389
+
390
+ if (!withEdgeVertices) return cornerVertices;
391
+
392
+ // ── Phase 3 prep: interpolation data from adjusted corners ────────────────
393
+ //
394
+ // For each edge vertex we interpolate the forw→bakw rotation from the two
395
+ // bracketing corner bakw rotations. At a corner's exact forw direction the
396
+ // interpolated rotation equals that corner's actual bakw rotation, so the
397
+ // boundary is continuous everywhere.
398
+ //
399
+ // The bakw distance is determined by projecting the interpolated direction
400
+ // onto the **corner polygon** sides. This places every Phase 3 edge vertex
401
+ // exactly on the adjusted corner-polygon boundary, so the 36-vertex bakw
402
+ // polygon is a refinement of (not larger than) the 4-corner polygon.
403
+ const N = 4; // always 4 corners
404
+ const cornerForwAngles = cornerVertices.map((cv) =>
405
+ Math.atan2(cv.forw[0] - centroid.forw[0], cv.forw[1] - centroid.forw[1])
406
+ );
407
+ const cornerBakwThetas = cornerVertices.map((cv) =>
408
+ Math.atan2(
409
+ cv.bakw[0] - centroid.bakw[0],
410
+ -(cv.bakw[1] - centroid.bakw[1]),
411
+ )
412
+ );
413
+ /** Find the angular sector [corners[i], corners[j]) containing theta. */
414
+ function findSector(theta: number): { i: number; j: number; frac: number } {
415
+ for (let i = 0; i < N; i++) {
416
+ const j = (i + 1) % N;
417
+ const ai = cornerForwAngles[i];
418
+ const aj = i < N - 1 ? cornerForwAngles[j] : cornerForwAngles[j] + 2 * Math.PI;
419
+ let t = theta;
420
+ while (t < ai) t += 2 * Math.PI;
421
+ while (t >= ai + 2 * Math.PI) t -= 2 * Math.PI;
422
+ if (t >= ai && t < aj) {
423
+ return { i, j, frac: (t - ai) / (aj - ai) };
424
+ }
425
+ }
426
+ return { i: 0, j: 1, frac: 0 };
427
+ }
428
+
429
+ /**
430
+ * Interpolate the bakw angle directly between adjacent corner bakw angles.
431
+ * This avoids the large rotation-delta problem that occurs when the forw→bakw
432
+ * rotation difference between adjacent corners exceeds 180°.
433
+ */
434
+ function interpolateBakwAngle(theta: number): number {
435
+ const { i, j, frac } = findSector(theta);
436
+ const bi = cornerBakwThetas[i];
437
+ const bj = cornerBakwThetas[j];
438
+ let delta = bj - bi;
439
+ while (delta > Math.PI) delta -= 2 * Math.PI;
440
+ while (delta < -Math.PI) delta += 2 * Math.PI;
441
+ return bi + frac * delta;
442
+ }
443
+
444
+ // ── Phase 3: 36-bin edge vertices ─────────────────────────────────────────
445
+ const cornerBins = new Set<number>(
446
+ cornerVertices.map(
447
+ (cv) => Math.floor(toAngleDeg360(cv.forw, centroid.forw) / 10) % 36,
448
+ ),
449
+ );
450
+
451
+ type GcpInfo = {
452
+ forw: Position;
453
+ bakw: Position;
454
+ angleDeg: number;
455
+ forwDist: number;
456
+ };
457
+ const gcpInfos: GcpInfo[] = allGcps.map((gcp) => ({
458
+ forw: gcp.forw,
459
+ bakw: gcp.bakw,
460
+ angleDeg: toAngleDeg360(gcp.forw, centroid.forw),
461
+ forwDist: Math.hypot(gcp.forw[0] - centroid.forw[0], gcp.forw[1] - centroid.forw[1]),
462
+ }));
463
+
464
+ const edgeVertices: VertexPosition[] = [];
465
+
466
+ for (let bin = 0; bin < 36; bin++) {
467
+ if (cornerBins.has(bin)) continue;
468
+
469
+ const binStart = bin * 10;
470
+ const inBin = gcpInfos.filter(
471
+ (g) => g.angleDeg >= binStart && g.angleDeg < binStart + 10,
472
+ );
473
+
474
+ let forwEdge: Position | null = null;
475
+
476
+ if (inBin.length > 0) {
477
+ // Most extreme interior point in this angular bin
478
+ const sel = inBin.reduce((best, g) => g.forwDist > best.forwDist ? g : best);
479
+ forwEdge = findRayBboxIntersection(centroid.forw, sel.forw, minx, maxx, miny, maxy);
480
+ }
481
+
482
+ if (!forwEdge) {
483
+ const binCenterRad = ((binStart + 5) % 360) * (Math.PI / 180);
484
+ const fallbackDir: Position = [
485
+ centroid.forw[0] + Math.sin(binCenterRad),
486
+ centroid.forw[1] + Math.cos(binCenterRad),
487
+ ];
488
+ forwEdge = findRayBboxIntersection(centroid.forw, fallbackDir, minx, maxx, miny, maxy);
489
+ }
490
+
491
+ if (!forwEdge) continue;
492
+
493
+ const forDelta = [forwEdge[0] - centroid.forw[0], forwEdge[1] - centroid.forw[1]];
494
+ const forwAngle = Math.atan2(forDelta[0], forDelta[1]);
495
+ const bakwTheta = interpolateBakwAngle(forwAngle);
496
+ const bakwDirPt: Position = [
497
+ centroid.bakw[0] + Math.sin(bakwTheta),
498
+ centroid.bakw[1] - Math.cos(bakwTheta),
499
+ ];
500
+ const bakwEdge = findRayQuadIntersection(centroid.bakw, bakwDirPt, cornerVertices);
501
+
502
+ if (bakwEdge) {
503
+ edgeVertices.push({ forw: forwEdge, bakw: bakwEdge });
504
+ }
505
+ }
506
+
507
+ // ── Phase 4: Combine, sort, final adjust ──────────────────────────────────
508
+ const allVertices: VertexPosition[] = [...cornerVertices, ...edgeVertices];
509
+ allVertices.sort((a, b) =>
510
+ Math.atan2(a.forw[0] - centroid.forw[0], a.forw[1] - centroid.forw[1]) -
511
+ Math.atan2(b.forw[0] - centroid.forw[0], b.forw[1] - centroid.forw[1])
512
+ );
513
+
514
+ // Final expansion: ensure the full polygon encloses all GCPs + edge nodes
515
+ // (some edge vertices may have been placed conservatively via extrapolation;
516
+ // this step corrects any remaining gaps).
517
+ checkAndAdjustVerticesN(allVertices, allGcps, centroid);
518
+
519
+ return allVertices;
520
+ }
521
+
522
+ // ─── Public API ──────────────────────────────────────────────────────────────
523
+
524
+ /**
525
+ * Calculate boundary vertices in plain mode.
526
+ *
527
+ * @param params - Input parameters including GCPs, centroid, and bounding box.
528
+ * @param v3 - When true (V3 format), runs the full 36-bin edge vertex pass
529
+ * (Phase 3) in addition to the 4 bbox corners, producing up to 36 vertices.
530
+ * When false (V2 format), returns only the 4 bbox corners.
531
+ *
532
+ * Plain mode uses a single aggregate [scale, rotation] ratio from all GCPs.
533
+ */
534
+ export function calculatePlainVertices(
535
+ params: BoundaryVerticesParams,
536
+ v3 = false,
537
+ ): VertexPosition[] {
538
+ return calculateVerticesCore(params, "plain", v3);
539
+ }
540
+
541
+ /**
542
+ * Calculate boundary vertices in bird's-eye mode.
543
+ *
544
+ * @param params - Input parameters including GCPs, centroid, and bounding box.
545
+ * @param v3 - When true (V3 format), runs the full 36-bin edge vertex pass
546
+ * (Phase 3) in addition to the 4 bbox corners, producing up to 36 vertices.
547
+ * When false (V2 format), returns only the 4 bbox corners.
548
+ *
549
+ * Birdeye mode uses per-quadrant [scale, rotation] ratios to capture
550
+ * perspective distortion in the 4 corner positions.
551
+ */
552
+ export function calculateBirdeyeVertices(
553
+ params: BoundaryVerticesParams,
554
+ v3 = false,
555
+ ): VertexPosition[] {
556
+ return calculateVerticesCore(params, "birdeye", v3);
557
+ }