@maplat/tin 0.11.4 → 0.12.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.
@@ -0,0 +1,498 @@
1
+ /**
2
+ * Edge constraint engine used for enforcing required edges on a Delaunator mesh.
3
+ * Based on @kninnug/constrainautor (ISC license, see this directory for details).
4
+ */
5
+ import { orient2d, incircle } from "robust-predicates";
6
+ import { BitSet8 } from "./bitset.ts";
7
+ import {
8
+ nextEdge,
9
+ prevEdge,
10
+ Base,
11
+ type DelaunatorLike,
12
+ intersectSegments as baseIntersectSegments,
13
+ } from "./base.ts";
14
+ import type { BitSet } from "./bitset.ts";
15
+
16
+ export class Constrain extends Base {
17
+ vertMap: Uint32Array;
18
+ flips: BitSet;
19
+ consd: BitSet;
20
+
21
+ /**
22
+ * Create a Constrain instance.
23
+ *
24
+ * @param del The triangulation output from Delaunator.
25
+ * @param edges If provided, constrain these edges via constrainAll.
26
+ */
27
+ constructor(del: DelaunatorLike, edges?: readonly [number, number][]) {
28
+ if (
29
+ !del ||
30
+ typeof del !== "object" ||
31
+ !del.triangles ||
32
+ !del.halfedges ||
33
+ !del.coords
34
+ ) {
35
+ throw new Error("Expected an object with Delaunator output");
36
+ }
37
+ if (
38
+ del.triangles.length % 3 ||
39
+ del.halfedges.length !== del.triangles.length ||
40
+ del.coords.length % 2
41
+ ) {
42
+ throw new Error("Delaunator output appears inconsistent");
43
+ }
44
+ if (del.triangles.length < 3) {
45
+ throw new Error("No edges in triangulation");
46
+ }
47
+
48
+ super(del);
49
+
50
+ const U32NIL = 2 ** 32 - 1;
51
+ const numPoints = del.coords.length >> 1;
52
+ const numEdges = del.triangles.length;
53
+
54
+ // Map every vertex id to the right-most edge that points to that vertex.
55
+ this.vertMap = new Uint32Array(numPoints).fill(U32NIL);
56
+ // Keep track of edges flipped while constraining.
57
+ this.flips = new BitSet8(numEdges);
58
+ // Keep track of constrained edges.
59
+ this.consd = new BitSet8(numEdges);
60
+
61
+ for (let e = 0; e < numEdges; e++) {
62
+ const v = del.triangles[e];
63
+ if (this.vertMap[v] === U32NIL) {
64
+ this.updateVert(e);
65
+ }
66
+ }
67
+
68
+ if (edges) {
69
+ this.constrainAll(edges);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Constrain the triangulation such that there is an edge between p1 and p2.
75
+ */
76
+ constrainOne(segP1: number, segP2: number): number {
77
+ const { triangles, halfedges } = this.del;
78
+ const start = this.vertMap[segP1];
79
+
80
+ // Loop over the edges touching segP1.
81
+ let edg = start;
82
+ do {
83
+ const p4 = triangles[edg];
84
+ const nxt = nextEdge(edg);
85
+
86
+ // already constrained, but in reverse order
87
+ if (p4 === segP2) {
88
+ return this.protect(edg);
89
+ }
90
+ // The edge opposite segP1
91
+ const opp = prevEdge(edg);
92
+ const p3 = triangles[opp];
93
+
94
+ // already constrained
95
+ if (p3 === segP2) {
96
+ this.protect(nxt);
97
+ return nxt;
98
+ }
99
+
100
+ // edge opposite segP1 intersects constraint
101
+ if (this.intersectSegments(segP1, segP2, p3, p4)) {
102
+ edg = opp;
103
+ break;
104
+ }
105
+
106
+ const adj = halfedges[nxt];
107
+ // The next edge pointing to segP1
108
+ edg = adj;
109
+ } while (edg !== -1 && edg !== start);
110
+
111
+ let conEdge = edg;
112
+ // Walk through the triangulation looking for further intersecting
113
+ // edges and flip them. If an intersecting edge cannot be flipped,
114
+ // assign its id to `rescan` and restart from there, until there are
115
+ // no more intersects.
116
+ let rescan = -1;
117
+ while (edg !== -1) {
118
+ const adj = halfedges[edg];
119
+ const bot = prevEdge(edg);
120
+ const top = prevEdge(adj);
121
+ const rgt = nextEdge(adj);
122
+
123
+ if (adj === -1) {
124
+ throw new Error("Constraining edge exited the hull");
125
+ }
126
+
127
+ if (this.consd.has(edg)) {
128
+ throw new Error("Edge intersects already constrained edge");
129
+ }
130
+
131
+ if (
132
+ this.isCollinear(segP1, segP2, triangles[edg]) ||
133
+ this.isCollinear(segP1, segP2, triangles[adj])
134
+ ) {
135
+ throw new Error("Constraining edge intersects point");
136
+ }
137
+
138
+ const convex = this.intersectSegments(
139
+ triangles[edg],
140
+ triangles[adj],
141
+ triangles[bot],
142
+ triangles[top],
143
+ );
144
+
145
+ if (!convex) {
146
+ if (rescan === -1) {
147
+ rescan = edg;
148
+ }
149
+
150
+ if (triangles[top] === segP2) {
151
+ if (edg === rescan) {
152
+ throw new Error("Infinite loop: non-convex quadrilateral");
153
+ }
154
+ edg = rescan;
155
+ rescan = -1;
156
+ continue;
157
+ }
158
+
159
+ if (
160
+ this.intersectSegments(
161
+ segP1,
162
+ segP2,
163
+ triangles[top],
164
+ triangles[adj],
165
+ )
166
+ ) {
167
+ edg = top;
168
+ } else if (
169
+ this.intersectSegments(
170
+ segP1,
171
+ segP2,
172
+ triangles[rgt],
173
+ triangles[top],
174
+ )
175
+ ) {
176
+ edg = rgt;
177
+ } else if (rescan === edg) {
178
+ throw new Error("Infinite loop: no further intersect after non-convex");
179
+ }
180
+
181
+ continue;
182
+ }
183
+
184
+ this.flipDiagonal(edg);
185
+
186
+ if (
187
+ this.intersectSegments(
188
+ segP1,
189
+ segP2,
190
+ triangles[bot],
191
+ triangles[top],
192
+ )
193
+ ) {
194
+ if (rescan === -1) {
195
+ rescan = bot;
196
+ }
197
+ if (rescan === bot) {
198
+ throw new Error("Infinite loop: flipped diagonal still intersects");
199
+ }
200
+ }
201
+
202
+ if (triangles[top] === segP2) {
203
+ conEdge = top;
204
+ edg = rescan;
205
+ rescan = -1;
206
+ } else if (
207
+ this.intersectSegments(
208
+ segP1,
209
+ segP2,
210
+ triangles[rgt],
211
+ triangles[top],
212
+ )
213
+ ) {
214
+ edg = rgt;
215
+ }
216
+ }
217
+
218
+ this.protect(conEdge);
219
+ this.delaunify(true);
220
+ return this.findEdge(segP1, segP2);
221
+ }
222
+
223
+ /**
224
+ * Fix the Delaunay condition.
225
+ */
226
+ delaunify(deep = false): this {
227
+ const { halfedges } = this.del;
228
+ const flips = this.flips;
229
+ const consd = this.consd;
230
+ const len = halfedges.length;
231
+
232
+ let flipped: number;
233
+ do {
234
+ flipped = 0;
235
+ for (let edg = 0; edg < len; edg++) {
236
+ if (consd.has(edg)) {
237
+ continue;
238
+ }
239
+ flips.delete(edg);
240
+
241
+ const adj = halfedges[edg];
242
+ if (adj === -1) {
243
+ continue;
244
+ }
245
+
246
+ flips.delete(adj);
247
+ if (!this.isDelaunay(edg)) {
248
+ this.flipDiagonal(edg);
249
+ flipped++;
250
+ }
251
+ }
252
+ } while (deep && flipped > 0);
253
+
254
+ return this;
255
+ }
256
+
257
+ /**
258
+ * Call constrainOne on each edge.
259
+ */
260
+ constrainAll(edges: readonly [number, number][]): this {
261
+ const len = edges.length;
262
+ for (let i = 0; i < len; i++) {
263
+ const e = edges[i];
264
+ this.constrainOne(e[0], e[1]);
265
+ }
266
+
267
+ return this;
268
+ }
269
+
270
+ /**
271
+ * Whether an edge is constrained.
272
+ */
273
+ isConstrained(edg: number): boolean {
274
+ return this.consd.has(edg);
275
+ }
276
+
277
+ /**
278
+ * Find the edge that points from p1 -> p2. If there is only an edge from
279
+ * p2 -> p1 (i.e. it is on the hull), returns the negative id of it.
280
+ */
281
+ findEdge(p1: number, p2: number): number {
282
+ const start1 = this.vertMap[p2];
283
+ const { triangles, halfedges } = this.del;
284
+ let edg = start1;
285
+ let prv = -1;
286
+ // Walk around p2, iterating over the edges pointing to it.
287
+ do {
288
+ if (triangles[edg] === p1) {
289
+ return edg;
290
+ }
291
+ prv = nextEdge(edg);
292
+ edg = halfedges[prv];
293
+ } while (edg !== -1 && edg !== start1);
294
+
295
+ // Did not find p1 -> p2, the only option is that it is on the hull on
296
+ // the 'left-hand' side, pointing p2 -> p1 (or there is no edge)
297
+ if (triangles[nextEdge(prv)] === p1) {
298
+ return -prv;
299
+ }
300
+
301
+ return Infinity;
302
+ }
303
+
304
+ /**
305
+ * Mark an edge as constrained, i.e. should not be touched by `delaunify`.
306
+ */
307
+ private protect(edg: number): number {
308
+ const adj = this.del.halfedges[edg];
309
+ const flips = this.flips;
310
+ const consd = this.consd;
311
+ flips.delete(edg);
312
+ consd.add(edg);
313
+
314
+ if (adj !== -1) {
315
+ flips.delete(adj);
316
+ consd.add(adj);
317
+ return adj;
318
+ }
319
+
320
+ return -edg;
321
+ }
322
+
323
+ /**
324
+ * Mark an edge as flipped unless constrained.
325
+ */
326
+ private markFlip(edg: number): boolean {
327
+ const halfedges = this.del.halfedges;
328
+ const flips = this.flips;
329
+ const consd = this.consd;
330
+ if (consd.has(edg)) {
331
+ return false;
332
+ }
333
+ const adj = halfedges[edg];
334
+ if (adj !== -1) {
335
+ flips.add(edg);
336
+ flips.add(adj);
337
+ }
338
+ return true;
339
+ }
340
+
341
+ /**
342
+ * Flip the edge shared by two triangles.
343
+ */
344
+ private flipDiagonal(edg: number): number {
345
+ const { triangles, halfedges } = this.del;
346
+ const flips = this.flips;
347
+ const consd = this.consd;
348
+ const adj = halfedges[edg];
349
+ const bot = prevEdge(edg);
350
+ const lft = nextEdge(edg);
351
+ const top = prevEdge(adj);
352
+ const rgt = nextEdge(adj);
353
+ const adjBot = halfedges[bot];
354
+ const adjTop = halfedges[top];
355
+
356
+ if (consd.has(edg)) {
357
+ throw new Error("Trying to flip a constrained edge");
358
+ }
359
+
360
+ triangles[edg] = triangles[top];
361
+ halfedges[edg] = adjTop;
362
+ if (!flips.set(edg, flips.has(top))) {
363
+ consd.set(edg, consd.has(top));
364
+ }
365
+ if (adjTop !== -1) {
366
+ halfedges[adjTop] = edg;
367
+ }
368
+ halfedges[bot] = top;
369
+
370
+ triangles[adj] = triangles[bot];
371
+ halfedges[adj] = adjBot;
372
+ if (!flips.set(adj, flips.has(bot))) {
373
+ consd.set(adj, consd.has(bot));
374
+ }
375
+ if (adjBot !== -1) {
376
+ halfedges[adjBot] = adj;
377
+ }
378
+ halfedges[top] = bot;
379
+
380
+ this.markFlip(edg);
381
+ this.markFlip(lft);
382
+ this.markFlip(adj);
383
+ this.markFlip(rgt);
384
+
385
+ flips.add(bot);
386
+ consd.delete(bot);
387
+ flips.add(top);
388
+ consd.delete(top);
389
+
390
+ this.updateVert(edg);
391
+ this.updateVert(lft);
392
+ this.updateVert(adj);
393
+ this.updateVert(rgt);
394
+
395
+ return bot;
396
+ }
397
+
398
+ /**
399
+ * Whether point p1, p2, and p are collinear.
400
+ */
401
+ private isCollinear(p1: number, p2: number, p: number): boolean {
402
+ const pts = this.del.coords;
403
+ return (
404
+ orient2d(
405
+ pts[p1 * 2],
406
+ pts[p1 * 2 + 1],
407
+ pts[p2 * 2],
408
+ pts[p2 * 2 + 1],
409
+ pts[p * 2],
410
+ pts[p * 2 + 1],
411
+ ) === 0.0
412
+ );
413
+ }
414
+
415
+ /**
416
+ * Whether the triangle formed by p1, p2, p3 keeps px outside the circumcircle.
417
+ */
418
+ private inCircle(p1: number, p2: number, p3: number, px: number): boolean {
419
+ const pts = this.del.coords;
420
+ return (
421
+ incircle(
422
+ pts[p1 * 2],
423
+ pts[p1 * 2 + 1],
424
+ pts[p2 * 2],
425
+ pts[p2 * 2 + 1],
426
+ pts[p3 * 2],
427
+ pts[p3 * 2 + 1],
428
+ pts[px * 2],
429
+ pts[px * 2 + 1],
430
+ ) < 0.0
431
+ );
432
+ }
433
+
434
+ /**
435
+ * Whether the triangles sharing edg conform to the Delaunay condition.
436
+ */
437
+ private isDelaunay(edg: number): boolean {
438
+ const { triangles, halfedges } = this.del;
439
+ const adj = halfedges[edg];
440
+ if (adj === -1) {
441
+ return true;
442
+ }
443
+
444
+ const p1 = triangles[prevEdge(edg)];
445
+ const p2 = triangles[edg];
446
+ const p3 = triangles[nextEdge(edg)];
447
+ const px = triangles[prevEdge(adj)];
448
+
449
+ return !this.inCircle(p1, p2, p3, px);
450
+ }
451
+
452
+ /**
453
+ * Update the vertex -> incoming edge map.
454
+ */
455
+ private updateVert(start: number): number {
456
+ const { triangles, halfedges } = this.del;
457
+ const vm = this.vertMap;
458
+ const v = triangles[start];
459
+
460
+ let inc = prevEdge(start);
461
+ let adj = halfedges[inc];
462
+
463
+ while (adj !== -1 && adj !== start) {
464
+ inc = prevEdge(adj);
465
+ adj = halfedges[inc];
466
+ }
467
+
468
+ vm[v] = inc;
469
+ return inc;
470
+ }
471
+
472
+ /**
473
+ * Whether the segments between vertices intersect.
474
+ */
475
+ protected intersectSegments(
476
+ p1: number,
477
+ p2: number,
478
+ p3: number,
479
+ p4: number,
480
+ ): boolean {
481
+ const pts = this.del.coords;
482
+ if (p1 === p3 || p1 === p4 || p2 === p3 || p2 === p4) {
483
+ return false;
484
+ }
485
+ return baseIntersectSegments(
486
+ pts[p1 * 2],
487
+ pts[p1 * 2 + 1],
488
+ pts[p2 * 2],
489
+ pts[p2 * 2 + 1],
490
+ pts[p3 * 2],
491
+ pts[p3 * 2 + 1],
492
+ pts[p4 * 2],
493
+ pts[p4 * 2 + 1],
494
+ );
495
+ }
496
+
497
+ static intersectSegments = baseIntersectSegments;
498
+ }
@@ -0,0 +1,10 @@
1
+ export { Constrain } from "./constrain.ts";
2
+ export {
3
+ nextEdge,
4
+ prevEdge,
5
+ intersectSegments,
6
+ type DelaunatorLike,
7
+ Base,
8
+ } from "./base.ts";
9
+ export { BitSet8, BitSet16, BitSet32 } from "./bitset.ts";
10
+ export type { BitSet } from "./bitset.ts";
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  // Main class exports
9
9
  export { Tin } from "./tin.ts";
10
10
  export type { Options } from "./tin.ts";
11
+ export { Tin as default } from "./tin.ts";
11
12
 
12
13
  // Utility function exports
13
14
  export { default as constrainedTin } from "./constrained-tin.ts";
package/src/kinks.ts CHANGED
@@ -8,24 +8,21 @@ import type { IntersectionPoint } from "./types/kinks.d.ts";
8
8
  * @param coords - 線分群の座標配列。各線分は始点と終点の座標で表現
9
9
  * @returns 検出された交差点のFeature配列
10
10
  */
11
- export default function findIntersections(coords: Position[][]) {
11
+ export default function findIntersections(
12
+ coords: Position[][],
13
+ ): Feature<Point>[] {
12
14
  const arcs = new ArcCollection(coords);
13
15
  const xy = arcs.findSegmentIntersections();
14
- return dedupIntersections(xy).reduce(
15
- (
16
- prev: Record<string, IntersectionPoint> | Feature<Point>[],
17
- apoint: IntersectionPoint,
18
- index: number,
19
- array: IntersectionPoint[],
20
- ) => {
21
- if (Array.isArray(prev)) return prev;
22
- if (!prev) prev = {};
23
- prev[`${apoint.x}:${apoint.y}`] = apoint;
24
- if (index != array.length - 1) return prev;
25
- return Object.keys(prev).map((key) => point([prev[key].x, prev[key].y]));
26
- },
27
- {} as Record<string, IntersectionPoint>,
28
- ) as Feature<Point>[];
16
+ const deduped: IntersectionPoint[] = dedupIntersections(xy);
17
+ const unique = new Map<string, IntersectionPoint>();
18
+
19
+ deduped.forEach((apoint: IntersectionPoint) => {
20
+ unique.set(`${apoint.x}:${apoint.y}`, apoint);
21
+ });
22
+
23
+ return Array.from(unique.values()).map((apoint) =>
24
+ point([apoint.x, apoint.y])
25
+ );
29
26
  }
30
27
 
31
28
  /**
@@ -3,7 +3,7 @@ import type { PropertyTriKey } from "@maplat/transform";
3
3
 
4
4
  type BiDirectionKey = "forw" | "bakw";
5
5
  type TinsBD = { [key in BiDirectionKey]?: Tins };
6
- type SearchTris = { [key in BiDirectionKey]: Tri };
6
+ export type SearchTris = { [key in BiDirectionKey]: Tri };
7
7
  export type SearchIndex = { [key: string]: SearchTris[] };
8
8
 
9
9
  /**
@@ -65,4 +65,38 @@ function insertSearchIndex(
65
65
  }
66
66
  }
67
67
 
68
- export { insertSearchIndex };
68
+ function removeSearchIndex(
69
+ searchIndex: SearchIndex,
70
+ tris: SearchTris,
71
+ tins?: TinsBD,
72
+ ) {
73
+ const keys = calcSearchKeys(tris.forw);
74
+ const bakKeys = calcSearchKeys(tris.bakw);
75
+ if (JSON.stringify(keys) != JSON.stringify(bakKeys)) {
76
+ throw `${JSON.stringify(tris, null, 2)}\n${JSON.stringify(keys)}\n${
77
+ JSON.stringify(bakKeys)
78
+ }`;
79
+ }
80
+
81
+ keys.forEach((key) => {
82
+ const current = searchIndex[key];
83
+ if (!current) return;
84
+ const filtered = current.filter((item) => item !== tris);
85
+ if (filtered.length === 0) {
86
+ delete searchIndex[key];
87
+ } else {
88
+ searchIndex[key] = filtered;
89
+ }
90
+ });
91
+
92
+ if (tins) {
93
+ const removeFeature = (collection?: Tins, target?: Tri) => {
94
+ if (!collection || !target) return;
95
+ collection.features = collection.features.filter((tri) => tri !== target);
96
+ };
97
+ removeFeature(tins.forw, tris.forw);
98
+ removeFeature(tins.bakw, tris.bakw);
99
+ }
100
+ }
101
+
102
+ export { calcSearchKeys, insertSearchIndex, removeSearchIndex };