@maplat/tin 0.9.4 → 0.11.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 ADDED
@@ -0,0 +1,894 @@
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 { point, featureCollection, polygon, lineString } from "@turf/helpers";
10
+ import lineIntersect from "@turf/line-intersect";
11
+ import type { Feature, Point, Position } from "geojson";
12
+ import {
13
+ Transform,
14
+ format_version,
15
+ normalizeEdges,
16
+ counterTri,
17
+ transformArr,
18
+ rotateVerticesTriangle
19
+ } from "@maplat/transform";
20
+ import type {
21
+ Compiled,
22
+ Edge,
23
+ EdgeSet,
24
+ EdgeSetLegacy,
25
+ PointSet,
26
+ StrictMode,
27
+ VertexMode,
28
+ YaxisMode,
29
+ Tri,
30
+ Tins,
31
+ WeightBufferBD,
32
+ TinsBD,
33
+ PropertyTriKey
34
+ } from "@maplat/transform";
35
+ import constrainedTin from "./constrained-tin.ts";
36
+ import findIntersections from "./kinks.ts";
37
+ import { insertSearchIndex } from "./searchutils.ts";
38
+ import { createPoint, counterPoint, vertexCalc } from "./vertexutils.ts";
39
+ import type { SearchIndex } from "./searchutils.ts";
40
+ import type { PointsSetBD } from "./types/tin.ts";
41
+
42
+ /**
43
+ * Tinクラスの初期化オプション
44
+ */
45
+ export interface Options {
46
+ bounds?: Position[];
47
+ wh?: number[];
48
+ vertexMode?: VertexMode;
49
+ strictMode?: StrictMode;
50
+ yaxisMode?: YaxisMode;
51
+ importance?: number;
52
+ priority?: number;
53
+ stateFull?: boolean;
54
+ points?: PointSet[];
55
+ edges?: EdgeSet[];
56
+ }
57
+
58
+ /**
59
+ * Tin (Triangulated Irregular Network) クラス
60
+ * Transformクラスを拡張し、TINネットワークの生成機能を追加
61
+ */
62
+ export class Tin extends Transform {
63
+ importance: number;
64
+ priority: number;
65
+ pointsSet: PointsSetBD | undefined;
66
+
67
+ /**
68
+ * Tinクラスのインスタンスを生成します
69
+ * @param options - 初期化オプション
70
+ */
71
+ constructor(options: Options = {}) {
72
+ super();
73
+
74
+ if (options.bounds) {
75
+ this.setBounds(options.bounds);
76
+ } else {
77
+ this.setWh(options.wh);
78
+ this.vertexMode = options.vertexMode || Tin.VERTEX_PLAIN;
79
+ }
80
+
81
+ this.strictMode = options.strictMode || Tin.MODE_AUTO;
82
+ this.yaxisMode = options.yaxisMode || Tin.YAXIS_INVERT;
83
+ this.importance = options.importance || 0;
84
+ this.priority = options.priority || 0;
85
+ this.stateFull = options.stateFull || false;
86
+
87
+ if (options.points) {
88
+ this.setPoints(options.points);
89
+ }
90
+ if (options.edges) {
91
+ this.setEdges(options.edges);
92
+ }
93
+ }
94
+
95
+ /**
96
+ * フォーマットバージョンを取得します
97
+ */
98
+ getFormatVersion(): number {
99
+ return format_version;
100
+ }
101
+
102
+ /**
103
+ * 制御点(GCP: Ground Control Points)を設定します
104
+ */
105
+ setPoints(points: PointSet[]): void {
106
+ if (this.yaxisMode === Tin.YAXIS_FOLLOW) {
107
+ points = points.map(point => [
108
+ point[0],
109
+ [point[1][0], -1 * point[1][1]]
110
+ ]);
111
+ }
112
+ this.points = points;
113
+ this.tins = undefined;
114
+ this.indexedTins = undefined;
115
+ }
116
+
117
+ /**
118
+ * エッジ(制約線)を設定します
119
+ */
120
+ setEdges(edges: EdgeSet[] | EdgeSetLegacy[] = []): void {
121
+ this.edges = normalizeEdges(edges);
122
+ this.edgeNodes = undefined;
123
+ this.tins = undefined;
124
+ this.indexedTins = undefined;
125
+ }
126
+
127
+ /**
128
+ * 境界ポリゴンを設定します
129
+ */
130
+ setBounds(bounds: Position[]): void {
131
+ this.bounds = bounds;
132
+
133
+ let minx = bounds[0][0];
134
+ let maxx = minx;
135
+ let miny = bounds[0][1];
136
+ let maxy = miny;
137
+ const coords = [bounds[0]];
138
+
139
+ for (let i = 1; i < bounds.length; i++) {
140
+ const bound = bounds[i];
141
+ if (bound[0] < minx) minx = bound[0];
142
+ if (bound[0] > maxx) maxx = bound[0];
143
+ if (bound[1] < miny) miny = bound[1];
144
+ if (bound[1] > maxy) maxy = bound[1];
145
+ coords.push(bound);
146
+ }
147
+ coords.push(bounds[0]);
148
+
149
+ this.boundsPolygon = polygon([coords]);
150
+ this.xy = [minx, miny];
151
+ this.wh = [maxx - minx, maxy - miny];
152
+ this.vertexMode = Tin.VERTEX_PLAIN;
153
+ this.tins = undefined;
154
+ this.indexedTins = undefined;
155
+ }
156
+
157
+ /**
158
+ * 現在の設定を永続化可能な形式にコンパイルします
159
+ */
160
+ getCompiled(): Compiled {
161
+ const compiled: any = {};
162
+ compiled.version = format_version;
163
+ compiled.points = this.points;
164
+ compiled.weight_buffer = this.pointsWeightBuffer;
165
+ compiled.centroid_point = [
166
+ this.centroid!.forw!.geometry!.coordinates,
167
+ this.centroid!.forw!.properties!.target.geom
168
+ ];
169
+ compiled.vertices_params = [
170
+ this.vertices_params!.forw![0],
171
+ this.vertices_params!.bakw![0]
172
+ ];
173
+ compiled.vertices_points = [];
174
+
175
+ const vertices = this.vertices_params!.forw![1];
176
+ if (vertices) {
177
+ [0, 1, 2, 3].map(i => {
178
+ const vertex = vertices[i].features[0];
179
+ const forw = vertex.geometry!.coordinates[0][1];
180
+ const bakw = vertex.properties!.b.geom;
181
+ compiled.vertices_points[i] = [forw, bakw];
182
+ });
183
+ }
184
+
185
+ compiled.strict_status = this.strict_status;
186
+ compiled.tins_points = [[]];
187
+
188
+ this.tins!.forw!.features.map((tin: Tri) => {
189
+ compiled.tins_points[0].push(
190
+ (["a", "b", "c"] as PropertyTriKey[]).map(key => tin.properties![key].index)
191
+ );
192
+ });
193
+
194
+ if (this.strict_status === Tin.STATUS_LOOSE) {
195
+ compiled.tins_points[1] = [];
196
+ this.tins!.bakw!.features.map((tin: Tri) => {
197
+ compiled.tins_points[1].push(
198
+ (["a", "b", "c"] as PropertyTriKey[]).map(key => tin.properties![key].index)
199
+ );
200
+ });
201
+ } else if (this.strict_status === Tin.STATUS_ERROR && this.kinks?.bakw) {
202
+ compiled.kinks_points = this.kinks.bakw.features.map(
203
+ kink => kink.geometry!.coordinates
204
+ );
205
+ }
206
+
207
+ compiled.yaxisMode = this.yaxisMode;
208
+ compiled.vertexMode = this.vertexMode;
209
+ compiled.strictMode = this.strictMode;
210
+
211
+ if (this.bounds) {
212
+ compiled.bounds = this.bounds;
213
+ compiled.boundsPolygon = this.boundsPolygon;
214
+ compiled.xy = this.xy;
215
+ compiled.wh = this.wh;
216
+ } else {
217
+ compiled.wh = this.wh;
218
+ }
219
+
220
+ compiled.edges = this.edges;
221
+ compiled.edgeNodes = this.edgeNodes;
222
+
223
+ return compiled;
224
+ }
225
+
226
+ /**
227
+ * 幅と高さを設定します
228
+ */
229
+ setWh(wh?: number[]): void {
230
+ this.wh = wh || [100, 100]; // デフォルト値を設定
231
+ this.xy = [0, 0];
232
+ this.bounds = undefined;
233
+ this.boundsPolygon = undefined;
234
+ this.tins = undefined;
235
+ this.indexedTins = undefined;
236
+ }
237
+
238
+ /**
239
+ * 頂点モードを設定します
240
+ */
241
+ setVertexMode(mode: VertexMode): void {
242
+ this.vertexMode = mode;
243
+ this.tins = undefined;
244
+ this.indexedTins = undefined;
245
+ }
246
+
247
+ /**
248
+ * 厳密性モードを設定します
249
+ */
250
+ setStrictMode(mode: StrictMode): void {
251
+ this.strictMode = mode;
252
+ this.tins = undefined;
253
+ this.indexedTins = undefined;
254
+ }
255
+
256
+ /**
257
+ * 厳密なTINを計算します
258
+ */
259
+ calcurateStrictTin(): void {
260
+ const bakTins = this.tins!.forw!.features.map((tri: Tri) => counterTri(tri));
261
+ this.tins!.bakw = featureCollection(bakTins);
262
+
263
+ const searchIndex: SearchIndex = {};
264
+ this.tins!.forw!.features.forEach((forTri: Tri, index: number) => {
265
+ const bakTri = this.tins!.bakw!.features[index];
266
+ insertSearchIndex(searchIndex, { forw: forTri, bakw: bakTri });
267
+ });
268
+
269
+ const kinks = ["forw", "bakw"].map(direction => {
270
+ const tins = this.tins![direction as keyof TinsBD]!.features.map(
271
+ (tin: Tri) => tin.geometry!.coordinates[0]
272
+ );
273
+ return findIntersections(tins);
274
+ });
275
+
276
+ if (kinks[0].length === 0 && kinks[1].length === 0) {
277
+ this.strict_status = Tin.STATUS_STRICT;
278
+ delete this.kinks;
279
+ } else {
280
+ this.strict_status = Tin.STATUS_ERROR;
281
+ this.kinks = {};
282
+ if (kinks[0].length > 0) {
283
+ this.kinks.forw = featureCollection(kinks[0]);
284
+ }
285
+ if (kinks[1].length > 0) {
286
+ this.kinks.bakw = featureCollection(kinks[1]);
287
+ }
288
+ }
289
+ }
290
+
291
+ /**
292
+ * 点群セットを生成します
293
+ */
294
+ generatePointsSet(): {
295
+ forw: Feature<Point>[];
296
+ bakw: Feature<Point>[];
297
+ edges: Edge[];
298
+ } {
299
+ const pointsSet: { forw: Feature<Point>[]; bakw: Feature<Point>[] } = { forw: [], bakw: [] };
300
+
301
+ // Generate points
302
+ for (let i = 0; i < this.points.length; i++) {
303
+ const forw = this.points[i][0];
304
+ const bakw = this.points[i][1];
305
+ const forPoint = createPoint(forw, bakw, i);
306
+ pointsSet.forw.push(forPoint);
307
+ pointsSet.bakw.push(counterPoint(forPoint));
308
+ }
309
+
310
+ // Generate edge nodes
311
+ const edges: Edge[] = [];
312
+ let edgeNodeIndex = 0;
313
+ this.edgeNodes = [];
314
+
315
+ if (!this.edges) this.edges = [];
316
+
317
+ for (let i = 0; i < this.edges.length; i++) {
318
+ const edge = this.edges[i][2];
319
+ const illstNodes = Object.assign([], this.edges[i][0]);
320
+ const mercNodes = Object.assign([], this.edges[i][1]);
321
+
322
+ if (illstNodes.length === 0 && mercNodes.length === 0) {
323
+ edges.push(edge);
324
+ continue;
325
+ }
326
+
327
+ // Add start and end points
328
+ illstNodes.unshift(this.points[edge[0]][0]);
329
+ illstNodes.push(this.points[edge[1]][0]);
330
+ mercNodes.unshift(this.points[edge[0]][1]);
331
+ mercNodes.push(this.points[edge[1]][1]);
332
+
333
+ // Calculate edge segments
334
+ const segments = [illstNodes, mercNodes].map(nodes => {
335
+ const lengths = nodes.map((node, index, arr) => {
336
+ if (index === 0) return 0;
337
+ const prev = arr[index - 1];
338
+ return Math.sqrt(
339
+ Math.pow(node[0] - prev[0], 2) + Math.pow(node[1] - prev[1], 2)
340
+ );
341
+ });
342
+
343
+ const accumLengths = lengths.reduce((acc, len, idx) => {
344
+ if (idx === 0) return [0];
345
+ acc.push(acc[idx - 1] + len);
346
+ return acc;
347
+ }, [] as number[]);
348
+
349
+ return accumLengths.map((accum, idx, arr) => {
350
+ const ratio = accum / arr[arr.length - 1];
351
+ return [nodes[idx], lengths[idx], accumLengths[idx], ratio];
352
+ });
353
+ });
354
+
355
+ // Generate edge nodes
356
+ segments
357
+ .map((segment, idx) => {
358
+ const otherSegment = segments[idx ? 0 : 1];
359
+ return segment
360
+ .filter((item, index) => {
361
+ return !(
362
+ index === 0 ||
363
+ index === segment.length - 1 ||
364
+ (item as any)[4] === "handled"
365
+ );
366
+ })
367
+ .map(item => {
368
+ const node = item[0] as unknown as Position;
369
+ const ratio = item[3] as number;
370
+
371
+ const counterpart = otherSegment.reduce((prev, curr, currIdx, arr) => {
372
+ if (prev) return prev;
373
+ const nextItem = arr[currIdx + 1];
374
+ if ((curr[3] as number) === ratio) {
375
+ (curr as any)[4] = "handled";
376
+ return [curr];
377
+ }
378
+ if ((curr[3] as number) < ratio && nextItem && (nextItem[3] as number) > ratio) {
379
+ return [curr, nextItem];
380
+ }
381
+ return undefined;
382
+ }, undefined as any);
383
+
384
+ if (counterpart && counterpart.length === 1) {
385
+ return idx === 0
386
+ ? [node, counterpart[0][0], ratio]
387
+ : [counterpart[0][0], node, ratio];
388
+ }
389
+
390
+ if (counterpart && counterpart.length === 2) {
391
+ const curr = counterpart[0];
392
+ const next = counterpart[1];
393
+ const ratioInSegment = (ratio - (curr[3] as number)) / ((next[3] as number) - (curr[3] as number));
394
+ const interpNode: Position = [
395
+ ((next[0] as Position)[0] - (curr[0] as Position)[0]) * ratioInSegment + (curr[0] as Position)[0],
396
+ ((next[0] as Position)[1] - (curr[0] as Position)[1]) * ratioInSegment + (curr[0] as Position)[1]
397
+ ];
398
+ return idx === 0 ? [node, interpNode, ratio] : [interpNode, node, ratio];
399
+ }
400
+
401
+ return [];
402
+ });
403
+ })
404
+ .reduce((prev, curr) => prev.concat(curr), [])
405
+ .sort((a, b) => (a[2] as number) < (b[2] as number) ? -1 : 1)
406
+ .map((item, index, arr) => {
407
+ this.edgeNodes![edgeNodeIndex] = [item[0] as Position, item[1] as Position];
408
+ const forPoint = createPoint(item[0] as Position, item[1] as Position, `e${edgeNodeIndex}`);
409
+ edgeNodeIndex++;
410
+ pointsSet.forw!.push(forPoint);
411
+ pointsSet.bakw!.push(counterPoint(forPoint));
412
+
413
+ if (index === 0) {
414
+ edges.push([edge[0], pointsSet.forw!.length - 1]);
415
+ } else {
416
+ edges.push([pointsSet.forw!.length - 2, pointsSet.forw!.length - 1]);
417
+ }
418
+
419
+ if (index === arr.length - 1) {
420
+ edges.push([pointsSet.forw!.length - 1, edge[1]]);
421
+ }
422
+ });
423
+ }
424
+
425
+ return {
426
+ forw: pointsSet.forw,
427
+ bakw: pointsSet.bakw,
428
+ edges
429
+ };
430
+ }
431
+
432
+ /**
433
+ * 入力データの検証と初期データの準備
434
+ */
435
+ private validateAndPrepareInputs() {
436
+ const minx = this.xy![0] - 0.05 * this.wh![0];
437
+ const maxx = this.xy![0] + 1.05 * this.wh![0];
438
+ const miny = this.xy![1] - 0.05 * this.wh![1];
439
+ const maxy = this.xy![1] + 1.05 * this.wh![1];
440
+
441
+ const allPointsInside = this.points.reduce((prev, point) => {
442
+ return prev && (this.bounds
443
+ ? booleanPointInPolygon(point[0] as any, this.boundsPolygon!)
444
+ : point[0][0] >= minx && point[0][0] <= maxx &&
445
+ point[0][1] >= miny && point[0][1] <= maxy);
446
+ }, true);
447
+
448
+ if (!allPointsInside) {
449
+ throw "SOME POINTS OUTSIDE";
450
+ }
451
+
452
+ let bbox: Position[] = [];
453
+ if (this.wh) {
454
+ bbox = [[minx, miny], [maxx, miny], [minx, maxy], [maxx, maxy]];
455
+ }
456
+
457
+ return {
458
+ pointsSet: this.generatePointsSet(),
459
+ bbox,
460
+ minx,
461
+ maxx,
462
+ miny,
463
+ maxy
464
+ };
465
+ }
466
+
467
+ /**
468
+ * TINネットワークを更新し、座標変換の準備を行います
469
+ */
470
+ updateTin(): void {
471
+ let strict = this.strictMode;
472
+ if (strict !== Tin.MODE_STRICT && strict !== Tin.MODE_LOOSE) {
473
+ strict = Tin.MODE_AUTO;
474
+ }
475
+
476
+ const { pointsSet: rawPointsSet, bbox, minx, maxx, miny, maxy } = this.validateAndPrepareInputs();
477
+
478
+ // Create FeatureCollections for use in calculations
479
+ const pointsSetFC = {
480
+ forw: featureCollection(rawPointsSet.forw),
481
+ bakw: featureCollection(rawPointsSet.bakw)
482
+ };
483
+
484
+
485
+ const tinForw = constrainedTin(pointsSetFC.forw, rawPointsSet.edges, "target");
486
+ const tinBakw = constrainedTin(pointsSetFC.bakw, rawPointsSet.edges, "target");
487
+
488
+ if (tinForw.features.length === 0 || tinBakw.features.length === 0) {
489
+ throw "TOO LINEAR1";
490
+ }
491
+
492
+ const forCentroid = turfCentroid(pointsSetFC.forw);
493
+ const forwConvex = convex(pointsSetFC.forw);
494
+ if (!forwConvex) throw "TOO LINEAR2";
495
+
496
+ const convexBuf: Record<string, { forw: Position; bakw: Position }> = {};
497
+ const forwCoords = forwConvex.geometry!.coordinates[0];
498
+
499
+ // Calculate forward convex hull transformation
500
+ let convexCalc;
501
+ try {
502
+ convexCalc = forwCoords.map((coord: Position) => ({
503
+ forw: coord,
504
+ bakw: transformArr(point(coord), tinForw as any) as Position
505
+ }));
506
+ convexCalc.forEach((item: any) => {
507
+ convexBuf[`${item.forw[0]}:${item.forw[1]}`] = item;
508
+ });
509
+ } catch {
510
+ throw "TOO LINEAR2";
511
+ }
512
+
513
+ // Calculate backward convex hull transformation
514
+ const bakwConvex = convex(pointsSetFC.bakw);
515
+ if (!bakwConvex) throw "TOO LINEAR2";
516
+
517
+ const bakwCoords = bakwConvex.geometry!.coordinates[0];
518
+ try {
519
+ convexCalc = bakwCoords.map((coord: Position) => ({
520
+ bakw: coord,
521
+ forw: transformArr(point(coord), tinBakw as any) as Position
522
+ }));
523
+ convexCalc.forEach((item: any) => {
524
+ convexBuf[`${item.forw[0]}:${item.forw[1]}`] = item;
525
+ });
526
+ } catch {
527
+ throw "TOO LINEAR2";
528
+ }
529
+
530
+ // Set centroids
531
+ const centCalc = {
532
+ forw: forCentroid.geometry!.coordinates,
533
+ bakw: transformArr(forCentroid, tinForw as any) as Position
534
+ };
535
+
536
+ const centroidPoint = createPoint(centCalc.forw, centCalc.bakw, "c");
537
+ this.centroid = {
538
+ forw: centroidPoint,
539
+ bakw: counterPoint(centroidPoint)
540
+ };
541
+
542
+ // Calculate vertices
543
+ const verticesSet = this.vertexMode === Tin.VERTEX_BIRDEYE
544
+ ? this.calculateBirdeyeVertices(convexBuf, centCalc, bbox, minx, maxx, miny, maxy)
545
+ : this.calculatePlainVertices(convexBuf, centCalc, bbox, minx, maxx, miny, maxy);
546
+
547
+ // Add vertices to points set
548
+ const verticesList = { forw: [] as Feature<Point>[], bakw: [] as Feature<Point>[] };
549
+ for (let i = 0; i < verticesSet.length; i++) {
550
+ const forw = verticesSet[i].forw;
551
+ const bakw = verticesSet[i].bakw;
552
+ const forPoint = createPoint(forw, bakw, `b${i}`);
553
+ const bakPoint = counterPoint(forPoint);
554
+ rawPointsSet.forw.push(forPoint);
555
+ rawPointsSet.bakw.push(bakPoint);
556
+ verticesList.forw.push(forPoint);
557
+ verticesList.bakw.push(bakPoint);
558
+ }
559
+
560
+ this.pointsSet = {
561
+ forw: featureCollection(rawPointsSet.forw),
562
+ bakw: featureCollection(rawPointsSet.bakw),
563
+ edges: []
564
+ };
565
+
566
+ // Generate forward TIN
567
+ this.tins = {
568
+ forw: rotateVerticesTriangle(constrainedTin(this.pointsSet!.forw, rawPointsSet.edges, "target") as Tins)
569
+ };
570
+
571
+ // Calculate strict TIN if needed
572
+ if (strict === Tin.MODE_STRICT || strict === Tin.MODE_AUTO) {
573
+ this.calcurateStrictTin();
574
+ }
575
+
576
+ // Generate backward TIN if needed
577
+ if (strict === Tin.MODE_LOOSE ||
578
+ (strict === Tin.MODE_AUTO && this.strict_status === Tin.STATUS_ERROR)) {
579
+ this.tins!.bakw = rotateVerticesTriangle(
580
+ constrainedTin(this.pointsSet!.bakw, rawPointsSet.edges, "target") as Tins
581
+ );
582
+ delete this.kinks;
583
+ this.strict_status = Tin.STATUS_LOOSE;
584
+ }
585
+
586
+ // Calculate vertices parameters
587
+ this.vertices_params = {
588
+ forw: vertexCalc(verticesList.forw, this.centroid.forw!),
589
+ bakw: vertexCalc(verticesList.bakw, this.centroid.bakw!)
590
+ };
591
+
592
+ this.addIndexedTin();
593
+ this.calculatePointsWeight();
594
+ }
595
+
596
+ /**
597
+ * 通常の頂点を計算
598
+ */
599
+ private calculatePlainVertices(
600
+ convexBuf: Record<string, { forw: Position; bakw: Position }>,
601
+ centCalc: { forw: Position; bakw: Position },
602
+ bbox: Position[],
603
+ minx: number,
604
+ maxx: number,
605
+ miny: number,
606
+ maxy: number
607
+ ): Array<{ forw: Position; bakw: Position }> {
608
+ // Calculate edge vertices
609
+ const edgeNodes = Object.keys(convexBuf).reduce((prev, key) => {
610
+ const item = convexBuf[key];
611
+ const forw = item.forw;
612
+ const bakw = item.bakw;
613
+
614
+ const vec = {
615
+ forw: [forw[0] - centCalc.forw[0], forw[1] - centCalc.forw[1]],
616
+ bakw: [bakw[0] - centCalc.bakw[0], bakw[1] - centCalc.bakw[1]]
617
+ };
618
+
619
+ const xRate = vec.forw[0] === 0 ? Infinity :
620
+ ((vec.forw[0] < 0 ? minx : maxx) - centCalc.forw[0]) / vec.forw[0];
621
+ const yRate = vec.forw[1] === 0 ? Infinity :
622
+ ((vec.forw[1] < 0 ? miny : maxy) - centCalc.forw[1]) / vec.forw[1];
623
+
624
+ if (Math.abs(xRate) / Math.abs(yRate) < 1.1) {
625
+ const node = {
626
+ forw: [vec.forw[0] * xRate + centCalc.forw[0], vec.forw[1] * xRate + centCalc.forw[1]] as Position,
627
+ bakw: [vec.bakw[0] * xRate + centCalc.bakw[0], vec.bakw[1] * xRate + centCalc.bakw[1]] as Position
628
+ };
629
+ if (vec.forw[0] < 0) {
630
+ prev[3].push(node);
631
+ } else {
632
+ prev[1].push(node);
633
+ }
634
+ }
635
+
636
+ if (Math.abs(yRate) / Math.abs(xRate) < 1.1) {
637
+ const node = {
638
+ forw: [vec.forw[0] * yRate + centCalc.forw[0], vec.forw[1] * yRate + centCalc.forw[1]] as Position,
639
+ bakw: [vec.bakw[0] * yRate + centCalc.bakw[0], vec.bakw[1] * yRate + centCalc.bakw[1]] as Position
640
+ };
641
+ if (vec.forw[1] < 0) {
642
+ prev[0].push(node);
643
+ } else {
644
+ prev[2].push(node);
645
+ }
646
+ }
647
+
648
+ return prev;
649
+ }, [[], [], [], []] as Array<Array<{ forw: Position; bakw: Position }>>);
650
+
651
+ // Calculate vertex angles
652
+ const vertexCalc = Object.keys(convexBuf).reduce((prev, key, index, arr) => {
653
+ const item = convexBuf[key];
654
+ const forw = item.forw;
655
+ const bakw = item.bakw;
656
+
657
+ const vec = {
658
+ forw: [forw[0] - centCalc.forw[0], forw[1] - centCalc.forw[1]],
659
+ bakw: [bakw[0] - centCalc.bakw[0], centCalc.bakw[1] - bakw[1]]
660
+ };
661
+
662
+ if (vec.forw[0] === 0 || vec.forw[1] === 0) return prev;
663
+
664
+ let quad = 0;
665
+ if (vec.forw[0] > 0) quad += 1;
666
+ if (vec.forw[1] > 0) quad += 2;
667
+
668
+ prev[quad].push([vec.forw, vec.bakw]);
669
+
670
+ if (index === arr.length - 1) {
671
+ return prev.map(quadArr => {
672
+ return quadArr.reduce((qprev: number[] | undefined, curr: number[][], qindex: number, qarr: number[][][]) => {
673
+ if (!qprev) qprev = [Infinity, 0, 0];
674
+
675
+ let ratio = Math.sqrt(Math.pow(curr[0][0], 2) + Math.pow(curr[0][1], 2)) /
676
+ Math.sqrt(Math.pow(curr[1][0], 2) + Math.pow(curr[1][1], 2));
677
+ ratio = ratio < qprev[0] ? ratio : qprev[0];
678
+
679
+ const theta = Math.atan2(curr[0][0], curr[0][1]) - Math.atan2(curr[1][0], curr[1][1]);
680
+ const sumcos = qprev[1] + Math.cos(theta);
681
+ const sumsin = qprev[2] + Math.sin(theta);
682
+
683
+ if (qindex === qarr.length - 1) {
684
+ return [ratio, Math.atan2(sumsin, sumcos)];
685
+ }
686
+ return [ratio, sumcos, sumsin];
687
+ }, null as any);
688
+ });
689
+ }
690
+
691
+ return prev;
692
+ }, [[], [], [], []] as any[]);
693
+
694
+ let vertexRatio: any[] = vertexCalc;
695
+ if (vertexRatio.length === 1) {
696
+ vertexRatio = [vertexRatio[0], vertexRatio[0], vertexRatio[0], vertexRatio[0]];
697
+ }
698
+
699
+ // Calculate vertices
700
+ const vertices = vertexRatio.map((ratio: any, index: number) => {
701
+ const forVertex = bbox[index];
702
+ const forDelta = [forVertex[0] - centCalc.forw[0], forVertex[1] - centCalc.forw[1]];
703
+ const forDistance = Math.sqrt(Math.pow(forDelta[0], 2) + Math.pow(forDelta[1], 2));
704
+ const bakDistance = forDistance / ratio[0];
705
+ const bakTheta = Math.atan2(forDelta[0], forDelta[1]) - ratio[1];
706
+ const bakw: Position = [
707
+ centCalc.bakw[0] + bakDistance * Math.sin(bakTheta),
708
+ centCalc.bakw[1] - bakDistance * Math.cos(bakTheta)
709
+ ];
710
+
711
+ return { forw: forVertex, bakw };
712
+ });
713
+
714
+ // Swap vertices 2 and 3 for correct ordering
715
+ const swap = vertices[2];
716
+ vertices[2] = vertices[3];
717
+ vertices[3] = swap;
718
+
719
+ // Check edge intersections
720
+ this.checkAndAdjustVertices(vertices, edgeNodes, centCalc);
721
+
722
+ return vertices;
723
+ }
724
+
725
+ /**
726
+ * 鳥瞰図モードの頂点を計算
727
+ */
728
+ private calculateBirdeyeVertices(
729
+ convexBuf: Record<string, { forw: Position; bakw: Position }>,
730
+ centCalc: { forw: Position; bakw: Position },
731
+ bbox: Position[],
732
+ minx: number,
733
+ maxx: number,
734
+ miny: number,
735
+ maxy: number
736
+ ): Array<{ forw: Position; bakw: Position }> {
737
+ // For birdeye mode, implement special vertex calculation
738
+ // This is a simplified version, actual implementation might be more complex
739
+ return this.calculatePlainVertices(convexBuf, centCalc, bbox, minx, maxx, miny, maxy);
740
+ }
741
+
742
+ /**
743
+ * 頂点の位置を調整
744
+ */
745
+ private checkAndAdjustVertices(
746
+ vertices: Array<{ forw: Position; bakw: Position }>,
747
+ edgeNodes: Array<Array<{ forw: Position; bakw: Position }>>,
748
+ centCalc: { forw: Position; bakw: Position }
749
+ ): void {
750
+ const expandRatio = [1, 1, 1, 1];
751
+
752
+ for (let i = 0; i < 4; i++) {
753
+ const j = (i + 1) % 4;
754
+ const side = lineString([vertices[i].bakw, vertices[j].bakw]);
755
+
756
+ edgeNodes[i].map(node => {
757
+ const line = lineString([centCalc.bakw, node.bakw]);
758
+ const intersect = lineIntersect(side, line);
759
+
760
+ if (intersect.features.length > 0 && intersect.features[0].geometry) {
761
+ const intersectPt = intersect.features[0];
762
+ const distance = Math.sqrt(
763
+ Math.pow(node.bakw[0] - centCalc.bakw[0], 2) +
764
+ Math.pow(node.bakw[1] - centCalc.bakw[1], 2)
765
+ );
766
+ const intDistance = Math.sqrt(
767
+ Math.pow(intersectPt.geometry.coordinates[0] - centCalc.bakw[0], 2) +
768
+ Math.pow(intersectPt.geometry.coordinates[1] - centCalc.bakw[1], 2)
769
+ );
770
+ const ratio = distance / intDistance;
771
+
772
+ if (ratio > expandRatio[i]) expandRatio[i] = ratio;
773
+ if (ratio > expandRatio[j]) expandRatio[j] = ratio;
774
+ }
775
+ });
776
+ }
777
+
778
+ vertices.forEach((vertex, i) => {
779
+ const ratio = expandRatio[i];
780
+ const bakw: Position = [
781
+ (vertex.bakw[0] - centCalc.bakw[0]) * ratio + centCalc.bakw[0],
782
+ (vertex.bakw[1] - centCalc.bakw[1]) * ratio + centCalc.bakw[1]
783
+ ];
784
+ vertex.bakw = bakw;
785
+ });
786
+ }
787
+
788
+ /**
789
+ * 点の重み付けを計算します
790
+ */
791
+ calculatePointsWeight(): void {
792
+ const calcTargets = ["forw"];
793
+ if (this.strict_status === Tin.STATUS_LOOSE) {
794
+ calcTargets.push("bakw");
795
+ }
796
+
797
+ const weightBuffer: WeightBufferBD = {};
798
+
799
+ calcTargets.forEach(target => {
800
+ weightBuffer[target as keyof WeightBufferBD] = {};
801
+ const tin_points: Record<string, number> = {};
802
+
803
+ this.tins![target as keyof TinsBD]!.features.map((tri: Tri) => {
804
+ const props = ["a", "b", "c"] as PropertyTriKey[];
805
+ for (let i = 0; i < 3; i++) {
806
+ const j = (i + 1) % 3;
807
+ const prop_i = props[i];
808
+ const prop_j = props[j];
809
+ const index_i = tri.properties![prop_i].index;
810
+ const index_j = tri.properties![prop_j].index;
811
+ const key = [index_i, index_j].sort().join("-");
812
+
813
+ if (!tin_points[key]) {
814
+ const i_xy = tri.geometry!.coordinates[0][i];
815
+ const j_xy = tri.geometry!.coordinates[0][j];
816
+ const i_merc = tri.properties![prop_i].geom;
817
+ const j_merc = tri.properties![prop_j].geom;
818
+
819
+ tin_points[key] = 1;
820
+ const ratio = Math.sqrt(
821
+ Math.pow(i_merc[0] - j_merc[0], 2) + Math.pow(i_merc[1] - j_merc[1], 2)
822
+ ) / Math.sqrt(
823
+ Math.pow(i_xy[0] - j_xy[0], 2) + Math.pow(i_xy[1] - j_xy[1], 2)
824
+ );
825
+
826
+ if (!weightBuffer[target as keyof WeightBufferBD]) {
827
+ weightBuffer[target as keyof WeightBufferBD] = {};
828
+ }
829
+
830
+ const targetBuffer = weightBuffer[target as keyof WeightBufferBD]!;
831
+ targetBuffer[`${index_i}:${key}`] = ratio;
832
+ targetBuffer[`${index_j}:${key}`] = ratio;
833
+ }
834
+ }
835
+ });
836
+ });
837
+
838
+ // Calculate average weights
839
+ const pointsWeightBuffer: WeightBufferBD = {};
840
+
841
+ calcTargets.map(target => {
842
+ pointsWeightBuffer[target as keyof WeightBufferBD] = {};
843
+
844
+ if (this.strict_status === Tin.STATUS_STRICT) {
845
+ pointsWeightBuffer.bakw = {};
846
+ }
847
+
848
+ const targetBuffer = weightBuffer[target as keyof WeightBufferBD]!;
849
+ const pointWeights: { [pointId: string]: number[] } = {};
850
+
851
+ // Group weights by point ID
852
+ Object.keys(targetBuffer).forEach(key => {
853
+ const [pointId] = key.split(':');
854
+ if (!pointWeights[pointId]) {
855
+ pointWeights[pointId] = [];
856
+ }
857
+ pointWeights[pointId].push(targetBuffer[key]);
858
+ });
859
+
860
+ // Calculate average weight for each point
861
+ Object.keys(pointWeights).forEach(pointId => {
862
+ const weights = pointWeights[pointId];
863
+ const avgWeight = weights.reduce((sum, w) => sum + w, 0) / weights.length;
864
+
865
+ if (!pointsWeightBuffer[target as keyof WeightBufferBD]) {
866
+ pointsWeightBuffer[target as keyof WeightBufferBD] = {};
867
+ }
868
+ pointsWeightBuffer[target as keyof WeightBufferBD]![pointId] = avgWeight;
869
+
870
+ if (this.strict_status === Tin.STATUS_STRICT) {
871
+ if (!pointsWeightBuffer.bakw) {
872
+ pointsWeightBuffer.bakw = {};
873
+ }
874
+ pointsWeightBuffer.bakw[pointId] = 1 / avgWeight;
875
+ }
876
+ });
877
+
878
+ // Calculate centroid weight
879
+ let centroidSum = 0;
880
+ for (let i = 0; i < 4; i++) {
881
+ const key = `b${i}`;
882
+ const weight = pointsWeightBuffer[target as keyof WeightBufferBD]![key] || 0;
883
+ centroidSum += weight;
884
+ }
885
+ pointsWeightBuffer[target as keyof WeightBufferBD]!["c"] = centroidSum / 4;
886
+
887
+ if (this.strict_status === Tin.STATUS_STRICT && pointsWeightBuffer.bakw) {
888
+ pointsWeightBuffer.bakw["c"] = 1 / pointsWeightBuffer[target as keyof WeightBufferBD]!["c"];
889
+ }
890
+ });
891
+
892
+ this.pointsWeightBuffer = pointsWeightBuffer;
893
+ }
894
+ }