@maplat/tin 0.12.0 → 0.13.1

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/src/tin.ts CHANGED
@@ -1,695 +1,703 @@
1
- /**
2
- * Tin (Triangulated Irregular Network) クラス
3
- * 2つの平面座標系間の同相変換を実現します。
4
- */
5
-
6
- import booleanPointInPolygon from "@turf/boolean-point-in-polygon";
7
- import turfCentroid from "@turf/centroid";
8
- import convex from "@turf/convex";
9
- import { featureCollection, point, polygon } from "@turf/helpers";
10
- import type { Feature, Point, Position } from "geojson";
11
- import {
12
- counterTri,
13
- format_version,
14
- normalizeEdges,
15
- rotateVerticesTriangle,
16
- Transform,
17
- transformArr,
18
- } from "@maplat/transform";
19
-
20
- // Ensure format_version is available
21
- const FALLBACK_FORMAT_VERSION = 2.00703;
22
- const safeFormatVersion = typeof format_version !== "undefined"
23
- ? format_version
24
- : FALLBACK_FORMAT_VERSION;
25
- import type {
26
- Compiled,
27
- Edge,
28
- EdgeSet,
29
- EdgeSetLegacy,
30
- PointSet,
31
- PropertyTriKey,
32
- StrictMode,
33
- Tins,
34
- TinsBD,
35
- Tri,
36
- VertexMode,
37
- YaxisMode,
38
- } from "@maplat/transform";
39
- import constrainedTin from "./constrained-tin.ts";
40
- import {
41
- calculateBirdeyeVertices,
42
- calculatePlainVertices,
43
- } from "./boundary-vertices.ts";
44
- import findIntersections from "./kinks.ts";
45
- import { insertSearchIndex } from "./searchutils.ts";
46
- import { counterPoint, createPoint, vertexCalc } from "./vertexutils.ts";
47
- import { buildPointsWeightBuffer } from "./weight-buffer.ts";
48
- import { resolveOverlaps } from "./strict-overlap.ts";
49
- import type { SearchIndex } from "./searchutils.ts";
50
- import type { PointsSetBD } from "./types/tin.d.ts";
51
-
52
- /**
53
- * Tinクラスの初期化オプション
54
- */
55
- export interface Options {
56
- bounds?: Position[];
57
- wh?: number[];
58
- vertexMode?: VertexMode;
59
- strictMode?: StrictMode;
60
- yaxisMode?: YaxisMode;
61
- importance?: number;
62
- priority?: number;
63
- stateFull?: boolean;
64
- points?: PointSet[];
65
- edges?: EdgeSet[];
66
- }
67
-
68
- /**
69
- * Tin (Triangulated Irregular Network) クラス
70
- * Transformクラスを拡張し、TINネットワークの生成機能を追加
71
- */
72
- export class Tin extends Transform {
73
- importance: number;
74
- priority: number;
75
- pointsSet: PointsSetBD | undefined;
76
-
77
- /**
78
- * Tinクラスのインスタンスを生成します
79
- * @param options - 初期化オプション
80
- */
81
- constructor(options: Options = {}) {
82
- super();
83
-
84
- if (options.bounds) {
85
- this.setBounds(options.bounds);
86
- } else {
87
- this.setWh(options.wh);
88
- this.vertexMode = options.vertexMode || Tin.VERTEX_PLAIN;
89
- }
90
-
91
- this.strictMode = options.strictMode || Tin.MODE_AUTO;
92
- this.yaxisMode = options.yaxisMode || Tin.YAXIS_INVERT;
93
- this.importance = options.importance || 0;
94
- this.priority = options.priority || 0;
95
- this.stateFull = options.stateFull || false;
96
-
97
- if (options.points) {
98
- this.setPoints(options.points);
99
- }
100
- if (options.edges) {
101
- this.setEdges(options.edges);
102
- }
103
- }
104
-
105
- /**
106
- * フォーマットバージョンを取得します
107
- */
108
- getFormatVersion(): number {
109
- return safeFormatVersion;
110
- }
111
-
112
- /**
113
- * 制御点(GCP: Ground Control Points)を設定します。
114
- * 指定した点群に合わせて内部のTINキャッシュをリセットします。
115
- */
116
- setPoints(points: PointSet[]): void {
117
- if (this.yaxisMode === Tin.YAXIS_FOLLOW) {
118
- points = points.map((point) => [
119
- point[0],
120
- [point[1][0], -1 * point[1][1]],
121
- ]);
122
- }
123
- this.points = points;
124
- this.tins = undefined;
125
- this.indexedTins = undefined;
126
- }
127
-
128
- /**
129
- * エッジ(制約線)を設定します。
130
- * 制約線を正規化した上で、依存するキャッシュをリセットします。
131
- */
132
- setEdges(edges: EdgeSet[] | EdgeSetLegacy[] = []): void {
133
- this.edges = normalizeEdges(edges);
134
- this.edgeNodes = undefined;
135
- this.tins = undefined;
136
- this.indexedTins = undefined;
137
- }
138
-
139
- /**
140
- * 境界ポリゴンを設定します
141
- */
142
- setBounds(bounds: Position[]): void {
143
- this.bounds = bounds;
144
-
145
- let minx = bounds[0][0];
146
- let maxx = minx;
147
- let miny = bounds[0][1];
148
- let maxy = miny;
149
- const coords = [bounds[0]];
150
-
151
- for (let i = 1; i < bounds.length; i++) {
152
- const bound = bounds[i];
153
- if (bound[0] < minx) minx = bound[0];
154
- if (bound[0] > maxx) maxx = bound[0];
155
- if (bound[1] < miny) miny = bound[1];
156
- if (bound[1] > maxy) maxy = bound[1];
157
- coords.push(bound);
158
- }
159
- coords.push(bounds[0]);
160
-
161
- this.boundsPolygon = polygon([coords]);
162
- this.xy = [minx, miny];
163
- this.wh = [maxx - minx, maxy - miny];
164
- this.vertexMode = Tin.VERTEX_PLAIN;
165
- this.tins = undefined;
166
- this.indexedTins = undefined;
167
- }
168
-
169
- /**
170
- * 現在の設定を永続化可能な形式にコンパイルします
171
- */
172
- getCompiled(): Compiled {
173
- const compiled: any = {};
174
- compiled.version = safeFormatVersion;
175
- compiled.points = this.points;
176
- compiled.weight_buffer = this.pointsWeightBuffer;
177
- compiled.centroid_point = [
178
- this.centroid!.forw!.geometry!.coordinates,
179
- this.centroid!.forw!.properties!.target.geom,
180
- ];
181
- compiled.vertices_params = [
182
- this.vertices_params!.forw![0],
183
- this.vertices_params!.bakw![0],
184
- ];
185
- compiled.vertices_points = [];
186
-
187
- const vertices = this.vertices_params!.forw![1];
188
- if (vertices) {
189
- [0, 1, 2, 3].map((i) => {
190
- const vertex = vertices[i].features[0];
191
- const forw = vertex.geometry!.coordinates[0][1];
192
- const bakw = vertex.properties!.b.geom;
193
- compiled.vertices_points[i] = [forw, bakw];
194
- });
195
- }
196
-
197
- compiled.strict_status = this.strict_status;
198
- compiled.tins_points = [[]];
199
-
200
- this.tins!.forw!.features.map((tin: Tri) => {
201
- compiled.tins_points[0].push(
202
- (["a", "b", "c"] as PropertyTriKey[]).map((key) =>
203
- tin.properties![key].index
204
- ),
205
- );
206
- });
207
-
208
- if (this.strict_status === Tin.STATUS_LOOSE) {
209
- compiled.tins_points[1] = [];
210
- this.tins!.bakw!.features.map((tin: Tri) => {
211
- compiled.tins_points[1].push(
212
- (["a", "b", "c"] as PropertyTriKey[]).map((key) =>
213
- tin.properties![key].index
214
- ),
215
- );
216
- });
217
- } else if (this.strict_status === Tin.STATUS_ERROR && this.kinks?.bakw) {
218
- compiled.kinks_points = this.kinks.bakw.features.map(
219
- (kink) => kink.geometry!.coordinates,
220
- );
221
- }
222
-
223
- compiled.yaxisMode = this.yaxisMode;
224
- compiled.vertexMode = this.vertexMode;
225
- compiled.strictMode = this.strictMode;
226
-
227
- if (this.bounds) {
228
- compiled.bounds = this.bounds;
229
- compiled.boundsPolygon = this.boundsPolygon;
230
- compiled.xy = this.xy;
231
- compiled.wh = this.wh;
232
- } else {
233
- compiled.wh = this.wh;
234
- }
235
-
236
- compiled.edges = this.edges;
237
- compiled.edgeNodes = this.edgeNodes;
238
-
239
- return compiled;
240
- }
241
-
242
- /**
243
- * 幅と高さを設定します
244
- */
245
- setWh(wh?: number[]): void {
246
- this.wh = wh || [100, 100]; // デフォルト値を設定
247
- this.xy = [0, 0];
248
- this.bounds = undefined;
249
- this.boundsPolygon = undefined;
250
- this.tins = undefined;
251
- this.indexedTins = undefined;
252
- }
253
-
254
- /**
255
- * 頂点モードを設定します
256
- */
257
- setVertexMode(mode: VertexMode): void {
258
- this.vertexMode = mode;
259
- this.tins = undefined;
260
- this.indexedTins = undefined;
261
- }
262
-
263
- /**
264
- * 厳密性モードを設定します
265
- */
266
- setStrictMode(mode: StrictMode): void {
267
- this.strictMode = mode;
268
- this.tins = undefined;
269
- this.indexedTins = undefined;
270
- }
271
-
272
- /**
273
- * 厳密なTINを計算します
274
- */
275
- calcurateStrictTin(): void {
276
- const bakTins = this.tins!.forw!.features.map((tri: Tri) =>
277
- counterTri(tri)
278
- );
279
- this.tins!.bakw = featureCollection(bakTins);
280
-
281
- const searchIndex: SearchIndex = {};
282
- this.tins!.forw!.features.forEach((forTri: Tri, index: number) => {
283
- const bakTri = this.tins!.bakw!.features[index];
284
- insertSearchIndex(searchIndex, { forw: forTri, bakw: bakTri });
285
- });
286
-
287
- resolveOverlaps(
288
- this.tins!,
289
- searchIndex,
290
- this.pointsSet?.edges || [],
291
- );
292
-
293
- const kinks = ["forw", "bakw"].map((direction) => {
294
- const tins = this.tins![direction as keyof TinsBD]!.features.map(
295
- (tin: Tri) => tin.geometry!.coordinates[0],
296
- );
297
- return findIntersections(tins);
298
- });
299
-
300
- if (kinks[0].length === 0 && kinks[1].length === 0) {
301
- this.strict_status = Tin.STATUS_STRICT;
302
- delete this.kinks;
303
- } else {
304
- this.strict_status = Tin.STATUS_ERROR;
305
- this.kinks = {
306
- forw: featureCollection(kinks[0]),
307
- bakw: featureCollection(kinks[1]),
308
- };
309
- }
310
- }
311
-
312
- /**
313
- * 点群セットを生成します。
314
- * GCP と中間エッジノードを GeoJSON Point に変換し、後続の三角分割に備えます。
315
- */
316
- generatePointsSet(): {
317
- forw: Feature<Point>[];
318
- bakw: Feature<Point>[];
319
- edges: Edge[];
320
- } {
321
- const pointsSet: { forw: Feature<Point>[]; bakw: Feature<Point>[] } = {
322
- forw: [],
323
- bakw: [],
324
- };
325
-
326
- // Generate points
327
- for (let i = 0; i < this.points.length; i++) {
328
- const forw = this.points[i][0];
329
- const bakw = this.points[i][1];
330
- const forPoint = createPoint(forw, bakw, i);
331
- pointsSet.forw.push(forPoint);
332
- pointsSet.bakw.push(counterPoint(forPoint));
333
- }
334
-
335
- // Generate edge nodes
336
- const edges: Edge[] = [];
337
- let edgeNodeIndex = 0;
338
- this.edgeNodes = [];
339
-
340
- if (!this.edges) this.edges = [];
341
-
342
- for (let i = 0; i < this.edges.length; i++) {
343
- const edge = this.edges[i][2];
344
- const illstNodes = Object.assign([], this.edges[i][0]);
345
- const mercNodes = Object.assign([], this.edges[i][1]);
346
-
347
- if (illstNodes.length === 0 && mercNodes.length === 0) {
348
- edges.push(edge);
349
- continue;
350
- }
351
-
352
- // Add start and end points
353
- illstNodes.unshift(this.points[edge[0]][0]);
354
- illstNodes.push(this.points[edge[1]][0]);
355
- mercNodes.unshift(this.points[edge[0]][1]);
356
- mercNodes.push(this.points[edge[1]][1]);
357
-
358
- // Calculate edge segments
359
- const segments = [illstNodes, mercNodes].map((nodes) => {
360
- const lengths = nodes.map((node, index, arr) => {
361
- if (index === 0) return 0;
362
- const prev = arr[index - 1];
363
- return Math.sqrt(
364
- Math.pow(node[0] - prev[0], 2) + Math.pow(node[1] - prev[1], 2),
365
- );
366
- });
367
-
368
- const accumLengths = lengths.reduce((acc, len, idx) => {
369
- if (idx === 0) return [0];
370
- acc.push(acc[idx - 1] + len);
371
- return acc;
372
- }, [] as number[]);
373
-
374
- return accumLengths.map((accum, idx, arr) => {
375
- const ratio = accum / arr[arr.length - 1];
376
- return [nodes[idx], lengths[idx], accumLengths[idx], ratio];
377
- });
378
- });
379
-
380
- // Generate edge nodes
381
- segments
382
- .map((segment, idx) => {
383
- const otherSegment = segments[idx ? 0 : 1];
384
- return segment
385
- .filter((item, index) => {
386
- return !(
387
- index === 0 ||
388
- index === segment.length - 1 ||
389
- (item as any)[4] === "handled"
390
- );
391
- })
392
- .map((item) => {
393
- const node = item[0] as unknown as Position;
394
- const ratio = item[3] as number;
395
-
396
- const counterpart = otherSegment.reduce(
397
- (prev, curr, currIdx, arr) => {
398
- if (prev) return prev;
399
- const nextItem = arr[currIdx + 1];
400
- if ((curr[3] as number) === ratio) {
401
- (curr as any)[4] = "handled";
402
- return [curr];
403
- }
404
- if (
405
- (curr[3] as number) < ratio && nextItem &&
406
- (nextItem[3] as number) > ratio
407
- ) {
408
- return [curr, nextItem];
409
- }
410
- return undefined;
411
- },
412
- undefined as any,
413
- );
414
-
415
- if (counterpart && counterpart.length === 1) {
416
- return idx === 0
417
- ? [node, counterpart[0][0], ratio]
418
- : [counterpart[0][0], node, ratio];
419
- }
420
-
421
- if (counterpart && counterpart.length === 2) {
422
- const curr = counterpart[0];
423
- const next = counterpart[1];
424
- const ratioInSegment = (ratio - (curr[3] as number)) /
425
- ((next[3] as number) - (curr[3] as number));
426
- const interpNode: Position = [
427
- ((next[0] as Position)[0] - (curr[0] as Position)[0]) *
428
- ratioInSegment + (curr[0] as Position)[0],
429
- ((next[0] as Position)[1] - (curr[0] as Position)[1]) *
430
- ratioInSegment + (curr[0] as Position)[1],
431
- ];
432
- return idx === 0
433
- ? [node, interpNode, ratio]
434
- : [interpNode, node, ratio];
435
- }
436
-
437
- return [];
438
- });
439
- })
440
- .reduce((prev, curr) => prev.concat(curr), [])
441
- .sort((a, b) => (a[2] as number) < (b[2] as number) ? -1 : 1)
442
- .map((item, index, arr) => {
443
- this.edgeNodes![edgeNodeIndex] = [
444
- item[0] as Position,
445
- item[1] as Position,
446
- ];
447
- const forPoint = createPoint(
448
- item[0] as Position,
449
- item[1] as Position,
450
- `e${edgeNodeIndex}`,
451
- );
452
- edgeNodeIndex++;
453
- pointsSet.forw!.push(forPoint);
454
- pointsSet.bakw!.push(counterPoint(forPoint));
455
-
456
- if (index === 0) {
457
- edges.push([edge[0], pointsSet.forw!.length - 1]);
458
- } else {
459
- edges.push([
460
- pointsSet.forw!.length - 2,
461
- pointsSet.forw!.length - 1,
462
- ]);
463
- }
464
-
465
- if (index === arr.length - 1) {
466
- edges.push([pointsSet.forw!.length - 1, edge[1]]);
467
- }
468
- });
469
- }
470
-
471
- return {
472
- forw: pointsSet.forw,
473
- bakw: pointsSet.bakw,
474
- edges,
475
- };
476
- }
477
-
478
- /**
479
- * 入力データの検証と初期データの準備
480
- */
481
- private validateAndPrepareInputs() {
482
- const minx = this.xy![0] - 0.05 * this.wh![0];
483
- const maxx = this.xy![0] + 1.05 * this.wh![0];
484
- const miny = this.xy![1] - 0.05 * this.wh![1];
485
- const maxy = this.xy![1] + 1.05 * this.wh![1];
486
-
487
- const allPointsInside = this.points.reduce((prev, point) => {
488
- return prev &&
489
- (this.bounds
490
- ? booleanPointInPolygon(point[0] as any, this.boundsPolygon!)
491
- : point[0][0] >= minx && point[0][0] <= maxx &&
492
- point[0][1] >= miny && point[0][1] <= maxy);
493
- }, true);
494
-
495
- if (!allPointsInside) {
496
- throw "SOME POINTS OUTSIDE";
497
- }
498
-
499
- let bbox: Position[] = [];
500
- if (this.wh) {
501
- bbox = [[minx, miny], [maxx, miny], [minx, maxy], [maxx, maxy]];
502
- }
503
-
504
- return {
505
- pointsSet: this.generatePointsSet(),
506
- bbox,
507
- minx,
508
- maxx,
509
- miny,
510
- maxy,
511
- };
512
- }
513
-
514
- /**
515
- * TINネットワークを同期的に更新し、座標変換の準備を行います。
516
- * 重めの計算を伴うため、呼び出し側が非同期制御を行いたい場合は
517
- * {@link updateTinAsync} を利用してください。
518
- */
519
- updateTin(): void {
520
- let strict = this.strictMode;
521
- if (strict !== Tin.MODE_STRICT && strict !== Tin.MODE_LOOSE) {
522
- strict = Tin.MODE_AUTO;
523
- }
524
-
525
- const { pointsSet: rawPointsSet, bbox, minx, maxx, miny, maxy } = this
526
- .validateAndPrepareInputs();
527
-
528
- // Create FeatureCollections for use in calculations
529
- const pointsSetFC = {
530
- forw: featureCollection(rawPointsSet.forw),
531
- bakw: featureCollection(rawPointsSet.bakw),
532
- };
533
-
534
- const tinForw = constrainedTin(
535
- pointsSetFC.forw,
536
- rawPointsSet.edges,
537
- "target",
538
- );
539
- const tinBakw = constrainedTin(
540
- pointsSetFC.bakw,
541
- rawPointsSet.edges,
542
- "target",
543
- );
544
-
545
- if (tinForw.features.length === 0 || tinBakw.features.length === 0) {
546
- throw "TOO LINEAR1";
547
- }
548
-
549
- const forCentroid = turfCentroid(pointsSetFC.forw);
550
- const forwConvex = convex(pointsSetFC.forw);
551
- if (!forwConvex) throw "TOO LINEAR2";
552
-
553
- const convexBuf: Record<string, { forw: Position; bakw: Position }> = {};
554
- const forwCoords = forwConvex.geometry!.coordinates[0];
555
-
556
- // Calculate forward convex hull transformation
557
- let convexCalc;
558
- try {
559
- convexCalc = forwCoords.map((coord: Position) => ({
560
- forw: coord,
561
- bakw: transformArr(point(coord), tinForw as any) as Position,
562
- }));
563
- convexCalc.forEach((item: any) => {
564
- convexBuf[`${item.forw[0]}:${item.forw[1]}`] = item;
565
- });
566
- } catch {
567
- throw "TOO LINEAR2";
568
- }
569
-
570
- // Calculate backward convex hull transformation
571
- const bakwConvex = convex(pointsSetFC.bakw);
572
- if (!bakwConvex) throw "TOO LINEAR2";
573
-
574
- const bakwCoords = bakwConvex.geometry!.coordinates[0];
575
- try {
576
- convexCalc = bakwCoords.map((coord: Position) => ({
577
- bakw: coord,
578
- forw: transformArr(point(coord), tinBakw as any) as Position,
579
- }));
580
- convexCalc.forEach((item: any) => {
581
- convexBuf[`${item.forw[0]}:${item.forw[1]}`] = item;
582
- });
583
- } catch {
584
- throw "TOO LINEAR2";
585
- }
586
-
587
- // Set centroids
588
- const centCalc = {
589
- forw: forCentroid.geometry!.coordinates,
590
- bakw: transformArr(forCentroid, tinForw as any) as Position,
591
- };
592
-
593
- const centroidPoint = createPoint(centCalc.forw, centCalc.bakw, "c");
594
- this.centroid = {
595
- forw: centroidPoint,
596
- bakw: counterPoint(centroidPoint),
597
- };
598
-
599
- // Calculate vertices
600
- const boundaryParams = {
601
- convexBuf,
602
- centroid: centCalc,
603
- bbox,
604
- minx,
605
- maxx,
606
- miny,
607
- maxy,
608
- };
609
- const verticesSet = this.vertexMode === Tin.VERTEX_BIRDEYE
610
- ? calculateBirdeyeVertices(boundaryParams)
611
- : calculatePlainVertices(boundaryParams);
612
-
613
- // Add vertices to points set
614
- const verticesList = {
615
- forw: [] as Feature<Point>[],
616
- bakw: [] as Feature<Point>[],
617
- };
618
- for (let i = 0; i < verticesSet.length; i++) {
619
- const forw = verticesSet[i].forw;
620
- const bakw = verticesSet[i].bakw;
621
- const forPoint = createPoint(forw, bakw, `b${i}`);
622
- const bakPoint = counterPoint(forPoint);
623
- rawPointsSet.forw.push(forPoint);
624
- rawPointsSet.bakw.push(bakPoint);
625
- verticesList.forw.push(forPoint);
626
- verticesList.bakw.push(bakPoint);
627
- }
628
-
629
- this.pointsSet = {
630
- forw: featureCollection(rawPointsSet.forw),
631
- bakw: featureCollection(rawPointsSet.bakw),
632
- edges: rawPointsSet.edges,
633
- };
634
-
635
- // Generate forward TIN
636
- this.tins = {
637
- forw: rotateVerticesTriangle(
638
- constrainedTin(
639
- this.pointsSet!.forw,
640
- rawPointsSet.edges,
641
- "target",
642
- ) as Tins,
643
- ),
644
- };
645
-
646
- // Calculate strict TIN if needed
647
- if (strict === Tin.MODE_STRICT || strict === Tin.MODE_AUTO) {
648
- this.calcurateStrictTin();
649
- }
650
-
651
- // Generate backward TIN if needed
652
- if (
653
- strict === Tin.MODE_LOOSE ||
654
- (strict === Tin.MODE_AUTO && this.strict_status === Tin.STATUS_ERROR)
655
- ) {
656
- this.tins!.bakw = rotateVerticesTriangle(
657
- constrainedTin(
658
- this.pointsSet!.bakw,
659
- rawPointsSet.edges,
660
- "target",
661
- ) as Tins,
662
- );
663
- delete this.kinks;
664
- this.strict_status = Tin.STATUS_LOOSE;
665
- }
666
-
667
- // Calculate vertices parameters
668
- this.vertices_params = {
669
- forw: vertexCalc(verticesList.forw, this.centroid.forw!),
670
- bakw: vertexCalc(verticesList.bakw, this.centroid.bakw!),
671
- };
672
-
673
- this.addIndexedTin();
674
-
675
- const targets: Array<keyof TinsBD> = ["forw"];
676
- if (this.strict_status === Tin.STATUS_LOOSE) {
677
- targets.push("bakw");
678
- }
679
-
680
- const includeReciprocals = this.strict_status === Tin.STATUS_STRICT;
681
- this.pointsWeightBuffer = buildPointsWeightBuffer({
682
- tins: this.tins!,
683
- targets,
684
- includeReciprocals,
685
- });
686
- }
687
-
688
- /**
689
- * 非同期ラッパーを提供します。
690
- * 互換性のために Promise ベースの API を維持しますが、内部処理は同期的です。
691
- */
692
- async updateTinAsync(): Promise<void> {
693
- this.updateTin();
694
- }
695
- }
1
+ /**
2
+ * Tin (Triangulated Irregular Network) クラス
3
+ * 2つの平面座標系間の同相変換を実現します。
4
+ */
5
+
6
+ import {
7
+ booleanPointInPolygon,
8
+ centroid as turfCentroid,
9
+ convex,
10
+ featureCollection,
11
+ point,
12
+ polygon,
13
+ } from "@turf/turf";
14
+ import type { Feature, Point, Position } from "geojson";
15
+ import {
16
+ counterTri,
17
+ format_version,
18
+ normalizeEdges,
19
+ rotateVerticesTriangle,
20
+ Transform,
21
+ transformArr,
22
+ } from "@maplat/transform";
23
+
24
+ // Ensure format_version is available
25
+ const FALLBACK_FORMAT_VERSION = 2.00703;
26
+ const safeFormatVersion = typeof format_version !== "undefined"
27
+ ? format_version
28
+ : FALLBACK_FORMAT_VERSION;
29
+ import type {
30
+ Compiled,
31
+ Edge,
32
+ EdgeSet,
33
+ EdgeSetLegacy,
34
+ PointSet,
35
+ PropertyTriKey,
36
+ StrictMode,
37
+ Tins,
38
+ TinsBD,
39
+ Tri,
40
+ VertexMode,
41
+ YaxisMode,
42
+ } from "@maplat/transform";
43
+ import constrainedTin from "./constrained-tin.ts";
44
+ import {
45
+ calculateBirdeyeVertices,
46
+ calculatePlainVertices,
47
+ } from "./boundary-vertices.ts";
48
+ import findIntersections from "./kinks.ts";
49
+ import { insertSearchIndex } from "./searchutils.ts";
50
+ import { counterPoint, createPoint, vertexCalc } from "./vertexutils.ts";
51
+ import { buildPointsWeightBuffer } from "./weight-buffer.ts";
52
+ import { resolveOverlaps } from "./strict-overlap.ts";
53
+ import type { SearchIndex } from "./searchutils.ts";
54
+ import type { PointsSetBD } from "./types/tin.d.ts";
55
+
56
+ type EdgeSegmentItem = [Position, number, number, number, string?];
57
+ type EdgeNodeItem = [Position, Position, number];
58
+
59
+ /**
60
+ * Tinクラスの初期化オプション
61
+ */
62
+ export interface Options {
63
+ bounds?: Position[];
64
+ wh?: number[];
65
+ vertexMode?: VertexMode;
66
+ strictMode?: StrictMode;
67
+ yaxisMode?: YaxisMode;
68
+ importance?: number;
69
+ priority?: number;
70
+ stateFull?: boolean;
71
+ points?: PointSet[];
72
+ edges?: EdgeSet[];
73
+ }
74
+
75
+ /**
76
+ * Tin (Triangulated Irregular Network) クラス
77
+ * Transformクラスを拡張し、TINネットワークの生成機能を追加
78
+ */
79
+ export class Tin extends Transform {
80
+ importance: number;
81
+ priority: number;
82
+ pointsSet: PointsSetBD | undefined;
83
+
84
+ /**
85
+ * Tinクラスのインスタンスを生成します
86
+ * @param options - 初期化オプション
87
+ */
88
+ constructor(options: Options = {}) {
89
+ super();
90
+
91
+ if (options.bounds) {
92
+ this.setBounds(options.bounds);
93
+ } else {
94
+ this.setWh(options.wh);
95
+ this.vertexMode = options.vertexMode || Tin.VERTEX_PLAIN;
96
+ }
97
+
98
+ this.strictMode = options.strictMode || Tin.MODE_AUTO;
99
+ this.yaxisMode = options.yaxisMode || Tin.YAXIS_INVERT;
100
+ this.importance = options.importance || 0;
101
+ this.priority = options.priority || 0;
102
+ this.stateFull = options.stateFull || false;
103
+
104
+ if (options.points) {
105
+ this.setPoints(options.points);
106
+ }
107
+ if (options.edges) {
108
+ this.setEdges(options.edges);
109
+ }
110
+ }
111
+
112
+ /**
113
+ * フォーマットバージョンを取得します
114
+ */
115
+ getFormatVersion(): number {
116
+ return safeFormatVersion;
117
+ }
118
+
119
+ /**
120
+ * 制御点(GCP: Ground Control Points)を設定します。
121
+ * 指定した点群に合わせて内部のTINキャッシュをリセットします。
122
+ */
123
+ setPoints(points: PointSet[]): void {
124
+ if (this.yaxisMode === Tin.YAXIS_FOLLOW) {
125
+ points = points.map((point) => [
126
+ point[0],
127
+ [point[1][0], -1 * point[1][1]],
128
+ ]);
129
+ }
130
+ this.points = points;
131
+ this.tins = undefined;
132
+ this.indexedTins = undefined;
133
+ }
134
+
135
+ /**
136
+ * エッジ(制約線)を設定します。
137
+ * 制約線を正規化した上で、依存するキャッシュをリセットします。
138
+ */
139
+ setEdges(edges: EdgeSet[] | EdgeSetLegacy[] = []): void {
140
+ this.edges = normalizeEdges(edges);
141
+ this.edgeNodes = undefined;
142
+ this.tins = undefined;
143
+ this.indexedTins = undefined;
144
+ }
145
+
146
+ /**
147
+ * 境界ポリゴンを設定します
148
+ */
149
+ setBounds(bounds: Position[]): void {
150
+ this.bounds = bounds;
151
+
152
+ let minx = bounds[0][0];
153
+ let maxx = minx;
154
+ let miny = bounds[0][1];
155
+ let maxy = miny;
156
+ const coords = [bounds[0]];
157
+
158
+ for (let i = 1; i < bounds.length; i++) {
159
+ const bound = bounds[i];
160
+ if (bound[0] < minx) minx = bound[0];
161
+ if (bound[0] > maxx) maxx = bound[0];
162
+ if (bound[1] < miny) miny = bound[1];
163
+ if (bound[1] > maxy) maxy = bound[1];
164
+ coords.push(bound);
165
+ }
166
+ coords.push(bounds[0]);
167
+
168
+ this.boundsPolygon = polygon([coords]);
169
+ this.xy = [minx, miny];
170
+ this.wh = [maxx - minx, maxy - miny];
171
+ this.vertexMode = Tin.VERTEX_PLAIN;
172
+ this.tins = undefined;
173
+ this.indexedTins = undefined;
174
+ }
175
+
176
+ /**
177
+ * 現在の設定を永続化可能な形式にコンパイルします
178
+ */
179
+ getCompiled(): Compiled {
180
+ const compiled: Compiled = {} as Compiled;
181
+ compiled.version = safeFormatVersion;
182
+ compiled.points = this.points;
183
+ compiled.weight_buffer = this.pointsWeightBuffer ?? {};
184
+ compiled.centroid_point = [
185
+ this.centroid!.forw!.geometry!.coordinates,
186
+ this.centroid!.forw!.properties!.target.geom,
187
+ ];
188
+ compiled.vertices_params = [
189
+ this.vertices_params!.forw![0],
190
+ this.vertices_params!.bakw![0],
191
+ ];
192
+ compiled.vertices_points = [];
193
+
194
+ const vertices = this.vertices_params!.forw![1];
195
+ if (vertices) {
196
+ [0, 1, 2, 3].map((i) => {
197
+ const vertex = vertices[i].features[0];
198
+ const forw = vertex.geometry!.coordinates[0][1];
199
+ const bakw = vertex.properties!.b.geom;
200
+ compiled.vertices_points[i] = [forw, bakw];
201
+ });
202
+ }
203
+
204
+ compiled.strict_status = this.strict_status;
205
+ compiled.tins_points = [[]];
206
+
207
+ this.tins!.forw!.features.map((tin: Tri) => {
208
+ compiled.tins_points[0].push(
209
+ (["a", "b", "c"] as PropertyTriKey[]).map((key) =>
210
+ tin.properties![key].index
211
+ ),
212
+ );
213
+ });
214
+
215
+ if (this.strict_status === Tin.STATUS_LOOSE) {
216
+ compiled.tins_points[1] = [];
217
+ this.tins!.bakw!.features.map((tin: Tri) => {
218
+ compiled.tins_points[1].push(
219
+ (["a", "b", "c"] as PropertyTriKey[]).map((key) =>
220
+ tin.properties![key].index
221
+ ),
222
+ );
223
+ });
224
+ } else if (this.strict_status === Tin.STATUS_ERROR && this.kinks?.bakw) {
225
+ compiled.kinks_points = this.kinks.bakw.features.map(
226
+ (kink) => kink.geometry!.coordinates,
227
+ );
228
+ }
229
+
230
+ compiled.yaxisMode = this.yaxisMode;
231
+ compiled.vertexMode = this.vertexMode;
232
+ compiled.strictMode = this.strictMode;
233
+
234
+ if (this.bounds) {
235
+ compiled.bounds = this.bounds;
236
+ compiled.boundsPolygon = this.boundsPolygon;
237
+ compiled.xy = this.xy;
238
+ compiled.wh = this.wh;
239
+ } else {
240
+ compiled.wh = this.wh;
241
+ }
242
+
243
+ compiled.edges = this.edges ?? [];
244
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
245
+ compiled.edgeNodes = (this.edgeNodes ?? []) as any;
246
+
247
+ return compiled;
248
+ }
249
+
250
+ /**
251
+ * 幅と高さを設定します
252
+ */
253
+ setWh(wh?: number[]): void {
254
+ this.wh = wh || [100, 100]; // デフォルト値を設定
255
+ this.xy = [0, 0];
256
+ this.bounds = undefined;
257
+ this.boundsPolygon = undefined;
258
+ this.tins = undefined;
259
+ this.indexedTins = undefined;
260
+ }
261
+
262
+ /**
263
+ * 頂点モードを設定します
264
+ */
265
+ setVertexMode(mode: VertexMode): void {
266
+ this.vertexMode = mode;
267
+ this.tins = undefined;
268
+ this.indexedTins = undefined;
269
+ }
270
+
271
+ /**
272
+ * 厳密性モードを設定します
273
+ */
274
+ setStrictMode(mode: StrictMode): void {
275
+ this.strictMode = mode;
276
+ this.tins = undefined;
277
+ this.indexedTins = undefined;
278
+ }
279
+
280
+ /**
281
+ * 厳密なTINを計算します
282
+ */
283
+ calcurateStrictTin(): void {
284
+ const bakTins = this.tins!.forw!.features.map((tri: Tri) =>
285
+ counterTri(tri)
286
+ );
287
+ this.tins!.bakw = featureCollection(bakTins);
288
+
289
+ const searchIndex: SearchIndex = {};
290
+ this.tins!.forw!.features.forEach((forTri: Tri, index: number) => {
291
+ const bakTri = this.tins!.bakw!.features[index];
292
+ insertSearchIndex(searchIndex, { forw: forTri, bakw: bakTri });
293
+ });
294
+
295
+ resolveOverlaps(
296
+ this.tins!,
297
+ searchIndex,
298
+ this.pointsSet?.edges || [],
299
+ );
300
+
301
+ const kinks = ["forw", "bakw"].map((direction) => {
302
+ const tins = this.tins![direction as keyof TinsBD]!.features.map(
303
+ (tin: Tri) => tin.geometry!.coordinates[0],
304
+ );
305
+ return findIntersections(tins);
306
+ });
307
+
308
+ if (kinks[0].length === 0 && kinks[1].length === 0) {
309
+ this.strict_status = Tin.STATUS_STRICT;
310
+ delete this.kinks;
311
+ } else {
312
+ this.strict_status = Tin.STATUS_ERROR;
313
+ this.kinks = {
314
+ forw: featureCollection(kinks[0]),
315
+ bakw: featureCollection(kinks[1]),
316
+ };
317
+ }
318
+ }
319
+
320
+ /**
321
+ * 点群セットを生成します。
322
+ * GCP と中間エッジノードを GeoJSON Point に変換し、後続の三角分割に備えます。
323
+ */
324
+ generatePointsSet(): {
325
+ forw: Feature<Point>[];
326
+ bakw: Feature<Point>[];
327
+ edges: Edge[];
328
+ } {
329
+ const pointsSet: { forw: Feature<Point>[]; bakw: Feature<Point>[] } = {
330
+ forw: [],
331
+ bakw: [],
332
+ };
333
+
334
+ // Generate points
335
+ for (let i = 0; i < this.points.length; i++) {
336
+ const forw = this.points[i][0];
337
+ const bakw = this.points[i][1];
338
+ const forPoint = createPoint(forw, bakw, i);
339
+ pointsSet.forw.push(forPoint);
340
+ pointsSet.bakw.push(counterPoint(forPoint));
341
+ }
342
+
343
+ // Generate edge nodes
344
+ const edges: Edge[] = [];
345
+ let edgeNodeIndex = 0;
346
+ this.edgeNodes = [];
347
+
348
+ if (!this.edges) this.edges = [];
349
+
350
+ for (let i = 0; i < this.edges.length; i++) {
351
+ const edge = this.edges[i][2];
352
+ const illstNodes = Object.assign([], this.edges[i][0]);
353
+ const mercNodes = Object.assign([], this.edges[i][1]);
354
+
355
+ if (illstNodes.length === 0 && mercNodes.length === 0) {
356
+ edges.push(edge);
357
+ continue;
358
+ }
359
+
360
+ // Add start and end points
361
+ illstNodes.unshift(this.points[edge[0]][0]);
362
+ illstNodes.push(this.points[edge[1]][0]);
363
+ mercNodes.unshift(this.points[edge[0]][1]);
364
+ mercNodes.push(this.points[edge[1]][1]);
365
+
366
+ // Calculate edge segments
367
+ const segments = [illstNodes, mercNodes].map((nodes: Position[]): EdgeSegmentItem[] => {
368
+ const lengths = nodes.map((node: Position, index: number, arr: Position[]) => {
369
+ if (index === 0) return 0;
370
+ const prev = arr[index - 1];
371
+ return Math.sqrt(
372
+ Math.pow(node[0] - prev[0], 2) + Math.pow(node[1] - prev[1], 2),
373
+ );
374
+ });
375
+
376
+ const accumLengths = lengths.reduce((acc: number[], len: number, idx: number) => {
377
+ if (idx === 0) return [0];
378
+ acc.push(acc[idx - 1] + len);
379
+ return acc;
380
+ }, [] as number[]);
381
+
382
+ return accumLengths.map((accum: number, idx: number, arr: number[]): EdgeSegmentItem => {
383
+ const ratio = accum / arr[arr.length - 1];
384
+ return [nodes[idx], lengths[idx], accumLengths[idx], ratio];
385
+ });
386
+ });
387
+
388
+ // Generate edge nodes
389
+ segments
390
+ .map((segment: EdgeSegmentItem[], idx: number) => {
391
+ const otherSegment = segments[idx ? 0 : 1];
392
+ return segment
393
+ .filter((item: EdgeSegmentItem, index: number) => {
394
+ return !(
395
+ index === 0 ||
396
+ index === segment.length - 1 ||
397
+ item[4] === "handled"
398
+ );
399
+ })
400
+ .flatMap((item: EdgeSegmentItem): EdgeNodeItem[] => {
401
+ const node = item[0];
402
+ const ratio = item[3];
403
+
404
+ const counterpart = otherSegment.reduce(
405
+ (prev: EdgeSegmentItem[] | undefined, curr: EdgeSegmentItem, currIdx: number, arr: EdgeSegmentItem[]) => {
406
+ if (prev) return prev;
407
+ const nextItem = arr[currIdx + 1];
408
+ if (curr[3] === ratio) {
409
+ curr[4] = "handled";
410
+ return [curr];
411
+ }
412
+ if (
413
+ curr[3] < ratio && nextItem &&
414
+ nextItem[3] > ratio
415
+ ) {
416
+ return [curr, nextItem];
417
+ }
418
+ return undefined;
419
+ },
420
+ undefined as EdgeSegmentItem[] | undefined,
421
+ );
422
+
423
+ if (counterpart && counterpart.length === 1) {
424
+ return idx === 0
425
+ ? [[node, counterpart[0][0], ratio]]
426
+ : [[counterpart[0][0], node, ratio]];
427
+ }
428
+
429
+ if (counterpart && counterpart.length === 2) {
430
+ const curr = counterpart[0];
431
+ const next = counterpart[1];
432
+ const ratioInSegment = (ratio - (curr[3] as number)) /
433
+ ((next[3] as number) - (curr[3] as number));
434
+ const interpNode: Position = [
435
+ (next[0][0] - curr[0][0]) *
436
+ ratioInSegment + curr[0][0],
437
+ (next[0][1] - curr[0][1]) *
438
+ ratioInSegment + curr[0][1],
439
+ ];
440
+ return idx === 0
441
+ ? [[node, interpNode, ratio]]
442
+ : [[interpNode, node, ratio]];
443
+ }
444
+
445
+ return [];
446
+ });
447
+ })
448
+ .reduce((prev: EdgeNodeItem[], curr: EdgeNodeItem[]) => prev.concat(curr), [])
449
+ .sort((a: EdgeNodeItem, b: EdgeNodeItem) => a[2] < b[2] ? -1 : 1)
450
+ .map((item: EdgeNodeItem, index: number, arr: EdgeNodeItem[]) => {
451
+ this.edgeNodes![edgeNodeIndex] = [
452
+ item[0],
453
+ item[1],
454
+ ];
455
+ const forPoint = createPoint(
456
+ item[0],
457
+ item[1],
458
+ `e${edgeNodeIndex}`,
459
+ );
460
+ edgeNodeIndex++;
461
+ pointsSet.forw!.push(forPoint);
462
+ pointsSet.bakw!.push(counterPoint(forPoint));
463
+
464
+ if (index === 0) {
465
+ edges.push([edge[0], pointsSet.forw!.length - 1]);
466
+ } else {
467
+ edges.push([
468
+ pointsSet.forw!.length - 2,
469
+ pointsSet.forw!.length - 1,
470
+ ]);
471
+ }
472
+
473
+ if (index === arr.length - 1) {
474
+ edges.push([pointsSet.forw!.length - 1, edge[1]]);
475
+ }
476
+ });
477
+ }
478
+
479
+ return {
480
+ forw: pointsSet.forw,
481
+ bakw: pointsSet.bakw,
482
+ edges,
483
+ };
484
+ }
485
+
486
+ /**
487
+ * 入力データの検証と初期データの準備
488
+ */
489
+ private validateAndPrepareInputs() {
490
+ const minx = this.xy![0] - 0.05 * this.wh![0];
491
+ const maxx = this.xy![0] + 1.05 * this.wh![0];
492
+ const miny = this.xy![1] - 0.05 * this.wh![1];
493
+ const maxy = this.xy![1] + 1.05 * this.wh![1];
494
+
495
+ const allPointsInside = this.points.reduce((prev: boolean, point: PointSet) => {
496
+ return prev &&
497
+ (this.bounds
498
+ ? booleanPointInPolygon(point[0] as Position, this.boundsPolygon!)
499
+ : point[0][0] >= minx && point[0][0] <= maxx &&
500
+ point[0][1] >= miny && point[0][1] <= maxy);
501
+ }, true);
502
+
503
+ if (!allPointsInside) {
504
+ throw "SOME POINTS OUTSIDE";
505
+ }
506
+
507
+ let bbox: Position[] = [];
508
+ if (this.wh) {
509
+ bbox = [[minx, miny], [maxx, miny], [minx, maxy], [maxx, maxy]];
510
+ }
511
+
512
+ return {
513
+ pointsSet: this.generatePointsSet(),
514
+ bbox,
515
+ minx,
516
+ maxx,
517
+ miny,
518
+ maxy,
519
+ };
520
+ }
521
+
522
+ /**
523
+ * TINネットワークを同期的に更新し、座標変換の準備を行います。
524
+ * 重めの計算を伴うため、呼び出し側が非同期制御を行いたい場合は
525
+ * {@link updateTinAsync} を利用してください。
526
+ */
527
+ updateTin(): void {
528
+ let strict = this.strictMode;
529
+ if (strict !== Tin.MODE_STRICT && strict !== Tin.MODE_LOOSE) {
530
+ strict = Tin.MODE_AUTO;
531
+ }
532
+
533
+ const { pointsSet: rawPointsSet, bbox, minx, maxx, miny, maxy } = this
534
+ .validateAndPrepareInputs();
535
+
536
+ // Create FeatureCollections for use in calculations
537
+ const pointsSetFC = {
538
+ forw: featureCollection(rawPointsSet.forw),
539
+ bakw: featureCollection(rawPointsSet.bakw),
540
+ };
541
+
542
+ const tinForw = constrainedTin(
543
+ pointsSetFC.forw,
544
+ rawPointsSet.edges,
545
+ "target",
546
+ );
547
+ const tinBakw = constrainedTin(
548
+ pointsSetFC.bakw,
549
+ rawPointsSet.edges,
550
+ "target",
551
+ );
552
+
553
+ if (tinForw.features.length === 0 || tinBakw.features.length === 0) {
554
+ throw "TOO LINEAR1";
555
+ }
556
+
557
+ const forCentroid = turfCentroid(pointsSetFC.forw);
558
+ const forwConvex = convex(pointsSetFC.forw);
559
+ if (!forwConvex) throw "TOO LINEAR2";
560
+
561
+ const convexBuf: Record<string, { forw: Position; bakw: Position }> = {};
562
+ const forwCoords = forwConvex.geometry!.coordinates[0];
563
+
564
+ // Calculate forward convex hull transformation
565
+ let convexCalc;
566
+ try {
567
+ convexCalc = forwCoords.map((coord: Position) => ({
568
+ forw: coord,
569
+ bakw: transformArr(point(coord), tinForw as Tins) as Position,
570
+ }));
571
+ convexCalc.forEach((item: { forw: Position; bakw: Position }) => {
572
+ convexBuf[`${item.forw[0]}:${item.forw[1]}`] = item;
573
+ });
574
+ } catch {
575
+ throw "TOO LINEAR2";
576
+ }
577
+
578
+ // Calculate backward convex hull transformation
579
+ const bakwConvex = convex(pointsSetFC.bakw);
580
+ if (!bakwConvex) throw "TOO LINEAR2";
581
+
582
+ const bakwCoords = bakwConvex.geometry!.coordinates[0];
583
+ try {
584
+ convexCalc = bakwCoords.map((coord: Position) => ({
585
+ bakw: coord,
586
+ forw: transformArr(point(coord), tinBakw as Tins) as Position,
587
+ }));
588
+ convexCalc.forEach((item: { forw: Position; bakw: Position }) => {
589
+ convexBuf[`${item.forw[0]}:${item.forw[1]}`] = item;
590
+ });
591
+ } catch {
592
+ throw "TOO LINEAR2";
593
+ }
594
+
595
+ // Set centroids
596
+ const centCalc = {
597
+ forw: forCentroid.geometry!.coordinates,
598
+ bakw: transformArr(forCentroid, tinForw as Tins) as Position,
599
+ };
600
+
601
+ const centroidPoint = createPoint(centCalc.forw, centCalc.bakw, "c");
602
+ this.centroid = {
603
+ forw: centroidPoint,
604
+ bakw: counterPoint(centroidPoint),
605
+ };
606
+
607
+ // Calculate vertices
608
+ const boundaryParams = {
609
+ convexBuf,
610
+ centroid: centCalc,
611
+ bbox,
612
+ minx,
613
+ maxx,
614
+ miny,
615
+ maxy,
616
+ };
617
+ const verticesSet = this.vertexMode === Tin.VERTEX_BIRDEYE
618
+ ? calculateBirdeyeVertices(boundaryParams)
619
+ : calculatePlainVertices(boundaryParams);
620
+
621
+ // Add vertices to points set
622
+ const verticesList = {
623
+ forw: [] as Feature<Point>[],
624
+ bakw: [] as Feature<Point>[],
625
+ };
626
+ for (let i = 0; i < verticesSet.length; i++) {
627
+ const forw = verticesSet[i].forw;
628
+ const bakw = verticesSet[i].bakw;
629
+ const forPoint = createPoint(forw, bakw, `b${i}`);
630
+ const bakPoint = counterPoint(forPoint);
631
+ rawPointsSet.forw.push(forPoint);
632
+ rawPointsSet.bakw.push(bakPoint);
633
+ verticesList.forw.push(forPoint);
634
+ verticesList.bakw.push(bakPoint);
635
+ }
636
+
637
+ this.pointsSet = {
638
+ forw: featureCollection(rawPointsSet.forw),
639
+ bakw: featureCollection(rawPointsSet.bakw),
640
+ edges: rawPointsSet.edges,
641
+ };
642
+
643
+ // Generate forward TIN
644
+ this.tins = {
645
+ forw: rotateVerticesTriangle(
646
+ constrainedTin(
647
+ this.pointsSet!.forw,
648
+ rawPointsSet.edges,
649
+ "target",
650
+ ) as Tins,
651
+ ),
652
+ };
653
+
654
+ // Calculate strict TIN if needed
655
+ if (strict === Tin.MODE_STRICT || strict === Tin.MODE_AUTO) {
656
+ this.calcurateStrictTin();
657
+ }
658
+
659
+ // Generate backward TIN if needed
660
+ if (
661
+ strict === Tin.MODE_LOOSE ||
662
+ (strict === Tin.MODE_AUTO && this.strict_status === Tin.STATUS_ERROR)
663
+ ) {
664
+ this.tins!.bakw = rotateVerticesTriangle(
665
+ constrainedTin(
666
+ this.pointsSet!.bakw,
667
+ rawPointsSet.edges,
668
+ "target",
669
+ ) as Tins,
670
+ );
671
+ delete this.kinks;
672
+ this.strict_status = Tin.STATUS_LOOSE;
673
+ }
674
+
675
+ // Calculate vertices parameters
676
+ this.vertices_params = {
677
+ forw: vertexCalc(verticesList.forw, this.centroid.forw!),
678
+ bakw: vertexCalc(verticesList.bakw, this.centroid.bakw!),
679
+ };
680
+
681
+ this.addIndexedTin();
682
+
683
+ const targets: Array<keyof TinsBD> = ["forw"];
684
+ if (this.strict_status === Tin.STATUS_LOOSE) {
685
+ targets.push("bakw");
686
+ }
687
+
688
+ const includeReciprocals = this.strict_status === Tin.STATUS_STRICT;
689
+ this.pointsWeightBuffer = buildPointsWeightBuffer({
690
+ tins: this.tins!,
691
+ targets,
692
+ includeReciprocals,
693
+ });
694
+ }
695
+
696
+ /**
697
+ * 非同期ラッパーを提供します。
698
+ * 互換性のために Promise ベースの API を維持しますが、内部処理は同期的です。
699
+ */
700
+ async updateTinAsync(): Promise<void> {
701
+ this.updateTin();
702
+ }
703
+ }