@maplat/transform 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,569 @@
1
+ import booleanPointInPolygon from "@turf/boolean-point-in-polygon";
2
+ import { featureCollection, point } from "@turf/helpers";
3
+ import { getCoords } from "@turf/invariant";
4
+ import { indexesToTri, normalizeNodeKey } from "./triangulation";
5
+ import { Feature, Polygon, Position, Point, FeatureCollection } from "geojson";
6
+ import { normalizeEdges } from "./edgeutils";
7
+ import type {
8
+ WeightBuffer, Tins, VerticesParams, PropertyTriKey,
9
+ IndexedTins, Tri
10
+ } from "./geometry";
11
+ import { unitCalc, transformArr } from "./geometry";
12
+ import type { EdgeSet, EdgeSetLegacy } from "./edgeutils";
13
+
14
+ /**
15
+ * 座標ペアの型定義。[ソース座標, ターゲット座標] の形式
16
+ */
17
+ export type PointSet = [Position, Position];
18
+
19
+ /**
20
+ * 変換の方向を示す型定義
21
+ * - forw: 順方向(ソース → ターゲット)
22
+ * - bakw: 逆方向(ターゲット → ソース)
23
+ */
24
+ export type BiDirectionKey = "forw" | "bakw";
25
+
26
+ /**
27
+ * 両方向の重み付けバッファの型定義
28
+ */
29
+ export type WeightBufferBD = { [key in BiDirectionKey]?: WeightBuffer };
30
+
31
+ /**
32
+ * 頂点モードの型定義
33
+ * - plain: 通常モード
34
+ * - birdeye: 鳥瞰図モード
35
+ */
36
+ export type VertexMode = "plain" | "birdeye";
37
+
38
+ /**
39
+ * 厳密性モードの型定義
40
+ * - strict: 厳密モード(交差なしを保証)
41
+ * - auto: 自動モード(可能な限り厳密に)
42
+ * - loose: 緩和モード(交差を許容)
43
+ */
44
+ export type StrictMode = "strict" | "auto" | "loose";
45
+
46
+ /**
47
+ * 厳密性モードの生成結果
48
+ * - strict: 厳密モード生成成功
49
+ * - auto: 厳密モードでエラー
50
+ * - loose: 緩和モード
51
+ */
52
+ export type StrictStatus = "strict" | "strict_error" | "loose";
53
+
54
+ /**
55
+ * Y軸の向きの型定義
56
+ * - follow: Y軸の向きを維持
57
+ * - invert: Y軸の向きを反転
58
+ */
59
+ export type YaxisMode = "follow" | "invert";
60
+ export type Centroid = Feature<Point>;
61
+ export type CentroidBD = { [key in BiDirectionKey]?: Centroid };
62
+ export type TinsBD = { [key in BiDirectionKey]?: Tins };
63
+ export type Kinks = FeatureCollection<Point>;
64
+ export type KinksBD = { [key in BiDirectionKey]?: Kinks };
65
+ export type VerticesParamsBD = { [key in BiDirectionKey]?: VerticesParams };
66
+ export type IndexedTinsBD = { [key in BiDirectionKey]?: IndexedTins };
67
+
68
+ export const format_version = 2.00703; //(Version 2 format for library version 0.7.3)
69
+
70
+ /**
71
+ * コンパイルされた設定の型定義
72
+ * 変換に必要な全ての情報を含む
73
+ */
74
+ export interface Compiled {
75
+ version?: number;
76
+ points: PointSet[];
77
+ tins_points: (number | string)[][][];
78
+ weight_buffer: WeightBufferBD;
79
+ strict_status?: StrictStatus;
80
+ centroid_point: Position[];
81
+ edgeNodes?: PointSet[];
82
+ kinks_points?: Position[];
83
+ yaxisMode?: YaxisMode;
84
+ vertexMode?: VertexMode;
85
+ strictMode?: StrictMode;
86
+ vertices_params: number[][];
87
+ vertices_points: PointSet[];
88
+ edges: EdgeSet[];
89
+ bounds?: number[][];
90
+ boundsPolygon?: Feature<Polygon>;
91
+ wh?: number[];
92
+ xy?: number[];
93
+ }
94
+
95
+ // For old Interface
96
+ export interface CompiledLegacy extends Compiled {
97
+ tins?: TinsBD;
98
+ centroid?: CentroidBD;
99
+ kinks?: KinksBD;
100
+ vertices_params: number[][] & VerticesParamsBD;
101
+ edges: EdgeSet[] & EdgeSetLegacy[];
102
+ }
103
+
104
+ /**
105
+ * 座標変換の基本機能を提供するクラス
106
+ *
107
+ * 2つの座標系間の変換を、TINネットワークを使用して実現します。
108
+ * このクラスは基本的な変換機能のみを提供し、
109
+ * 設定ファイルの生成などの追加機能はTinクラスで提供されます。
110
+ */
111
+ export class Transform {
112
+ /**
113
+ * 各種モードの定数定義
114
+ * すべてreadonlyで、型安全性を確保
115
+ */
116
+ static VERTEX_PLAIN = "plain" as const;
117
+ static VERTEX_BIRDEYE = "birdeye" as const;
118
+ static MODE_STRICT = "strict" as const;
119
+ static MODE_AUTO = "auto" as const;
120
+ static MODE_LOOSE = "loose" as const;
121
+ static STATUS_STRICT = "strict" as const;
122
+ static STATUS_ERROR = "strict_error" as const;
123
+ static STATUS_LOOSE = "loose" as const;
124
+ static YAXIS_FOLLOW = "follow" as const;
125
+ static YAXIS_INVERT = "invert" as const;
126
+
127
+ points: PointSet[] = [];
128
+ pointsWeightBuffer?: WeightBufferBD;
129
+ strict_status?: StrictStatus;
130
+ vertices_params?: VerticesParamsBD;
131
+ centroid?: CentroidBD;
132
+ edgeNodes?: PointSet[];
133
+ edges?: EdgeSet[];
134
+ tins?: TinsBD;
135
+ kinks?: KinksBD;
136
+ yaxisMode: YaxisMode = Transform.YAXIS_INVERT;
137
+ strictMode: StrictMode = Transform.MODE_AUTO;
138
+ vertexMode?: VertexMode = Transform.VERTEX_PLAIN;
139
+ bounds?: number[][];
140
+ boundsPolygon?: Feature<Polygon>;
141
+ wh?: number[];
142
+ xy?: number[];
143
+ indexedTins?: IndexedTinsBD;
144
+ stateFull = false;
145
+ stateTriangle?: Tri;
146
+ stateBackward?: boolean;
147
+
148
+ constructor() {}
149
+
150
+ /**
151
+ * コンパイルされた設定を適用します
152
+ *
153
+ * @param compiled - コンパイルされた設定オブジェクト
154
+ * @returns 変換に必要な主要なオブジェクトのセット
155
+ *
156
+ * 以下の処理を行います:
157
+ * 1. バージョンに応じた設定の解釈
158
+ * 2. 各種パラメータの復元
159
+ * 3. TINネットワークの再構築
160
+ * 4. インデックスの作成
161
+ */
162
+ setCompiled(compiled: Compiled | CompiledLegacy) {
163
+ if (
164
+ compiled.version ||
165
+ (!(compiled as any).tins && compiled.points && compiled.tins_points)
166
+ ) {
167
+ // 新コンパイルロジック
168
+ // pointsはそのままpoints
169
+ this.points = compiled.points;
170
+ // After 0.7.3 Normalizing old formats for weightBuffer
171
+ this.pointsWeightBuffer =
172
+ !compiled.version || compiled.version < 2.00703
173
+ ? (["forw", "bakw"] as BiDirectionKey[]).reduce((bd, forb) => {
174
+ const base = compiled.weight_buffer[forb];
175
+ if (base) {
176
+ bd[forb] = Object.keys(base!).reduce((buffer, key) => {
177
+ const normKey = normalizeNodeKey(key);
178
+ buffer[normKey] = base![key];
179
+ return buffer;
180
+ }, {} as WeightBuffer);
181
+ }
182
+ return bd;
183
+ }, {} as WeightBufferBD)
184
+ : compiled.weight_buffer;
185
+ // kinksやtinsの存在状況でstrict_statusを判定
186
+ if (compiled.strict_status) {
187
+ this.strict_status = compiled.strict_status;
188
+ } else if (compiled.kinks_points) {
189
+ this.strict_status = Transform.STATUS_ERROR;
190
+ } else if (compiled.tins_points.length == 2) {
191
+ this.strict_status = Transform.STATUS_LOOSE;
192
+ } else {
193
+ this.strict_status = Transform.STATUS_STRICT;
194
+ }
195
+ // vertices_paramsを復元
196
+ this.vertices_params = {
197
+ forw: [(compiled.vertices_params as number[][])[0]],
198
+ bakw: [(compiled.vertices_params as number[][])[1]]
199
+ };
200
+ this.vertices_params.forw![1] = [0, 1, 2, 3].map(idx => {
201
+ const idxNxt = (idx + 1) % 4;
202
+ const tri = indexesToTri(
203
+ ["c", `b${idx}`, `b${idxNxt}`],
204
+ compiled.points,
205
+ compiled.edgeNodes || [],
206
+ compiled.centroid_point,
207
+ compiled.vertices_points,
208
+ false,
209
+ format_version
210
+ );
211
+ return featureCollection([tri]);
212
+ });
213
+ this.vertices_params.bakw![1] = [0, 1, 2, 3].map(idx => {
214
+ const idxNxt = (idx + 1) % 4;
215
+ const tri = indexesToTri(
216
+ ["c", `b${idx}`, `b${idxNxt}`],
217
+ compiled.points,
218
+ compiled.edgeNodes || [],
219
+ compiled.centroid_point,
220
+ compiled.vertices_points,
221
+ true,
222
+ format_version
223
+ );
224
+ return featureCollection([tri]);
225
+ });
226
+ // centroidを復元
227
+ this.centroid = {
228
+ forw: point(compiled.centroid_point[0], {
229
+ target: {
230
+ geom: compiled.centroid_point[1],
231
+ index: "c"
232
+ }
233
+ }),
234
+ bakw: point(compiled.centroid_point[1], {
235
+ target: {
236
+ geom: compiled.centroid_point[0],
237
+ index: "c"
238
+ }
239
+ })
240
+ };
241
+ // edgesを復元
242
+ this.edges = normalizeEdges(compiled.edges || []);
243
+ this.edgeNodes = compiled.edgeNodes || [];
244
+ // tinsを復元
245
+ const bakwI = compiled.tins_points.length == 1 ? 0 : 1;
246
+ this.tins = {
247
+ forw: featureCollection(
248
+ compiled.tins_points[0].map((idxes: any) =>
249
+ indexesToTri(
250
+ idxes,
251
+ compiled.points,
252
+ compiled.edgeNodes || [],
253
+ compiled.centroid_point,
254
+ compiled.vertices_points,
255
+ false,
256
+ compiled.version
257
+ )
258
+ )
259
+ ),
260
+ bakw: featureCollection(
261
+ compiled.tins_points[bakwI].map((idxes: any) =>
262
+ indexesToTri(
263
+ idxes,
264
+ compiled.points,
265
+ compiled.edgeNodes || [],
266
+ compiled.centroid_point,
267
+ compiled.vertices_points,
268
+ true,
269
+ compiled.version
270
+ )
271
+ )
272
+ )
273
+ };
274
+ this.addIndexedTin();
275
+ // kinksを復元
276
+ if (compiled.kinks_points) {
277
+ this.kinks = {
278
+ bakw: featureCollection(
279
+ compiled.kinks_points.map((coord: Position) => point(coord))
280
+ )
281
+ };
282
+ }
283
+ // yaxisModeを復元
284
+ if (compiled.yaxisMode) {
285
+ this.yaxisMode = compiled.yaxisMode;
286
+ } else {
287
+ this.yaxisMode = Transform.YAXIS_INVERT;
288
+ }
289
+ // After 0.7.3: Restore strict_mode & vertex_mode
290
+ if (compiled.vertexMode) {
291
+ this.vertexMode = compiled.vertexMode;
292
+ }
293
+ if (compiled.strictMode) {
294
+ this.strictMode = compiled.strictMode;
295
+ }
296
+ // boundsを復元
297
+ if (compiled.bounds) {
298
+ this.bounds = compiled.bounds;
299
+ this.boundsPolygon = compiled.boundsPolygon;
300
+ this.xy = compiled.xy;
301
+ this.wh = compiled.wh;
302
+ } else {
303
+ this.xy = [0, 0];
304
+ if (compiled.wh) this.wh = compiled.wh;
305
+ this.bounds = undefined;
306
+ this.boundsPolygon = undefined;
307
+ }
308
+ } else {
309
+ // 旧コンパイルロジック
310
+ compiled = JSON.parse(
311
+ JSON.stringify(compiled)
312
+ .replace('"cent"', '"c"')
313
+ .replace(/"bbox(\d+)"/g, '"b$1"')
314
+ );
315
+ this.tins = (compiled as CompiledLegacy).tins;
316
+ this.addIndexedTin();
317
+ this.strict_status = compiled.strict_status;
318
+ this.pointsWeightBuffer = compiled.weight_buffer;
319
+ this.vertices_params = compiled.vertices_params as VerticesParamsBD;
320
+ this.centroid = (compiled as CompiledLegacy).centroid;
321
+ this.kinks = (compiled as CompiledLegacy).kinks;
322
+ const points: any = [];
323
+ for (let i = 0; i < this.tins!.forw!.features.length; i++) {
324
+ const tri = this.tins!.forw!.features[i];
325
+ (["a", "b", "c"] as PropertyTriKey[]).map((key, idx) => {
326
+ const forw = tri.geometry!.coordinates[0][idx];
327
+ const bakw = tri.properties![key].geom;
328
+ const pIdx = tri.properties![key].index;
329
+ points[pIdx] = [forw, bakw];
330
+ });
331
+ }
332
+ this.points = points;
333
+ }
334
+ // 翻訳したオブジェクトを返す
335
+ return {
336
+ tins: this.tins,
337
+ strict_status: this.strict_status,
338
+ weight_buffer: this.pointsWeightBuffer,
339
+ vertices_params: this.vertices_params,
340
+ centroid: this.centroid,
341
+ kinks: this.kinks
342
+ };
343
+ }
344
+
345
+ /**
346
+ * TINネットワークのインデックスを作成します
347
+ *
348
+ * インデックスは変換処理を高速化するために使用されます。
349
+ * グリッド形式のインデックスを作成し、各グリッドに
350
+ * 含まれる三角形を記録します。
351
+ */
352
+ addIndexedTin() {
353
+ const tins = this.tins!;
354
+ const forw = tins.forw;
355
+ const bakw = tins.bakw;
356
+ const gridNum = Math.ceil(Math.sqrt(forw!.features.length));
357
+ if (gridNum < 3) {
358
+ this.indexedTins = undefined;
359
+ return;
360
+ }
361
+ let forwBound: Position[] = [];
362
+ let bakwBound: Position[] = [];
363
+ const forwEachBound = forw!.features.map((tri: Tri) => {
364
+ let eachBound: Position[] = [];
365
+ getCoords(tri)[0].map((point: Position) => {
366
+ if (forwBound.length === 0)
367
+ forwBound = [Array.from(point), Array.from(point)];
368
+ else {
369
+ if (point[0] < forwBound[0][0]) forwBound[0][0] = point[0];
370
+ if (point[0] > forwBound[1][0]) forwBound[1][0] = point[0];
371
+ if (point[1] < forwBound[0][1]) forwBound[0][1] = point[1];
372
+ if (point[1] > forwBound[1][1]) forwBound[1][1] = point[1];
373
+ }
374
+ if (eachBound.length === 0)
375
+ eachBound = [Array.from(point), Array.from(point)];
376
+ else {
377
+ if (point[0] < eachBound[0][0]) eachBound[0][0] = point[0];
378
+ if (point[0] > eachBound[1][0]) eachBound[1][0] = point[0];
379
+ if (point[1] < eachBound[0][1]) eachBound[0][1] = point[1];
380
+ if (point[1] > eachBound[1][1]) eachBound[1][1] = point[1];
381
+ }
382
+ });
383
+ return eachBound;
384
+ });
385
+ const forwXUnit = (forwBound[1][0] - forwBound[0][0]) / gridNum;
386
+ const forwYUnit = (forwBound[1][1] - forwBound[0][1]) / gridNum;
387
+ const forwGridCache = forwEachBound.reduce(
388
+ (prev: number[][][], bound: Position[], index: number) => {
389
+ const normXMin = unitCalc(
390
+ bound[0][0],
391
+ forwBound[0][0],
392
+ forwXUnit,
393
+ gridNum
394
+ );
395
+ const normXMax = unitCalc(
396
+ bound[1][0],
397
+ forwBound[0][0],
398
+ forwXUnit,
399
+ gridNum
400
+ );
401
+ const normYMin = unitCalc(
402
+ bound[0][1],
403
+ forwBound[0][1],
404
+ forwYUnit,
405
+ gridNum
406
+ );
407
+ const normYMax = unitCalc(
408
+ bound[1][1],
409
+ forwBound[0][1],
410
+ forwYUnit,
411
+ gridNum
412
+ );
413
+ for (let cx = normXMin; cx <= normXMax; cx++) {
414
+ if (!prev[cx]) prev[cx] = [];
415
+ for (let cy = normYMin; cy <= normYMax; cy++) {
416
+ if (!prev[cx][cy]) prev[cx][cy] = [];
417
+ prev[cx][cy].push(index);
418
+ }
419
+ }
420
+ return prev;
421
+ },
422
+ []
423
+ );
424
+ const bakwEachBound = bakw!.features.map((tri: Tri) => {
425
+ let eachBound: Position[] = [];
426
+ getCoords(tri)[0].map((point: Position) => {
427
+ if (bakwBound.length === 0)
428
+ bakwBound = [Array.from(point), Array.from(point)];
429
+ else {
430
+ if (point[0] < bakwBound[0][0]) bakwBound[0][0] = point[0];
431
+ if (point[0] > bakwBound[1][0]) bakwBound[1][0] = point[0];
432
+ if (point[1] < bakwBound[0][1]) bakwBound[0][1] = point[1];
433
+ if (point[1] > bakwBound[1][1]) bakwBound[1][1] = point[1];
434
+ }
435
+ if (eachBound.length === 0)
436
+ eachBound = [Array.from(point), Array.from(point)];
437
+ else {
438
+ if (point[0] < eachBound[0][0]) eachBound[0][0] = point[0];
439
+ if (point[0] > eachBound[1][0]) eachBound[1][0] = point[0];
440
+ if (point[1] < eachBound[0][1]) eachBound[0][1] = point[1];
441
+ if (point[1] > eachBound[1][1]) eachBound[1][1] = point[1];
442
+ }
443
+ });
444
+ return eachBound;
445
+ });
446
+ const bakwXUnit = (bakwBound[1][0] - bakwBound[0][0]) / gridNum;
447
+ const bakwYUnit = (bakwBound[1][1] - bakwBound[0][1]) / gridNum;
448
+ const bakwGridCache = bakwEachBound.reduce(
449
+ (prev: any, bound: any, index: number) => {
450
+ const normXMin = unitCalc(
451
+ bound[0][0],
452
+ bakwBound[0][0],
453
+ bakwXUnit,
454
+ gridNum
455
+ );
456
+ const normXMax = unitCalc(
457
+ bound[1][0],
458
+ bakwBound[0][0],
459
+ bakwXUnit,
460
+ gridNum
461
+ );
462
+ const normYMin = unitCalc(
463
+ bound[0][1],
464
+ bakwBound[0][1],
465
+ bakwYUnit,
466
+ gridNum
467
+ );
468
+ const normYMax = unitCalc(
469
+ bound[1][1],
470
+ bakwBound[0][1],
471
+ bakwYUnit,
472
+ gridNum
473
+ );
474
+ for (let cx = normXMin; cx <= normXMax; cx++) {
475
+ if (!prev[cx]) prev[cx] = [];
476
+ for (let cy = normYMin; cy <= normYMax; cy++) {
477
+ if (!prev[cx][cy]) prev[cx][cy] = [];
478
+ prev[cx][cy].push(index);
479
+ }
480
+ }
481
+ return prev;
482
+ },
483
+ []
484
+ );
485
+ this.indexedTins = {
486
+ forw: {
487
+ gridNum,
488
+ xOrigin: forwBound[0][0],
489
+ yOrigin: forwBound[0][1],
490
+ xUnit: forwXUnit,
491
+ yUnit: forwYUnit,
492
+ gridCache: forwGridCache
493
+ },
494
+ bakw: {
495
+ gridNum,
496
+ xOrigin: bakwBound[0][0],
497
+ yOrigin: bakwBound[0][1],
498
+ xUnit: bakwXUnit,
499
+ yUnit: bakwYUnit,
500
+ gridCache: bakwGridCache
501
+ }
502
+ };
503
+ }
504
+
505
+ /**
506
+ * 座標変換を実行します
507
+ *
508
+ * @param apoint - 変換する座標
509
+ * @param backward - 逆方向の変換かどうか
510
+ * @param ignoreBounds - 境界チェックを無視するかどうか
511
+ * @returns 変換後の座標、または境界外の場合はfalse
512
+ *
513
+ * @throws {Error} 逆方向変換が許可されていない状態での逆変換時
514
+ */
515
+ transform(apoint: number[], backward?: boolean, ignoreBounds?: boolean) {
516
+ if (backward && this.strict_status == Transform.STATUS_ERROR)
517
+ throw 'Backward transform is not allowed if strict_status == "strict_error"';
518
+ // if (!this.tins) this.updateTin();
519
+ if (this.yaxisMode == Transform.YAXIS_FOLLOW && backward) {
520
+ apoint = [apoint[0], -1 * apoint[1]];
521
+ }
522
+ const tpoint = point(apoint);
523
+ if (this.bounds && !backward && !ignoreBounds) {
524
+ if (!booleanPointInPolygon(tpoint, this.boundsPolygon!)) return false;
525
+ }
526
+ const tins = backward ? this.tins!.bakw : this.tins!.forw;
527
+ const indexedTins = backward
528
+ ? this.indexedTins!.bakw
529
+ : this.indexedTins!.forw;
530
+ const verticesParams = backward
531
+ ? this.vertices_params!.bakw
532
+ : this.vertices_params!.forw;
533
+ const centroid = backward ? this.centroid!.bakw : this.centroid!.forw;
534
+ const weightBuffer = backward
535
+ ? this.pointsWeightBuffer!.bakw
536
+ : this.pointsWeightBuffer!.forw;
537
+ let stateTriangle = undefined,
538
+ stateSetFunc = undefined;
539
+ if (this.stateFull) {
540
+ if (this.stateBackward == backward) {
541
+ stateTriangle = this.stateTriangle;
542
+ } else {
543
+ this.stateBackward = backward;
544
+ this.stateTriangle = undefined;
545
+ }
546
+ stateSetFunc = (tri?: Tri) => {
547
+ this.stateTriangle = tri;
548
+ };
549
+ }
550
+ let ret = transformArr(
551
+ tpoint,
552
+ tins!,
553
+ indexedTins,
554
+ verticesParams,
555
+ centroid,
556
+ weightBuffer,
557
+ stateTriangle,
558
+ stateSetFunc
559
+ );
560
+ if (this.bounds && backward && !ignoreBounds) {
561
+ const rpoint = point(ret);
562
+ if (!booleanPointInPolygon(rpoint, this.boundsPolygon!)) return false;
563
+ } else if (this.yaxisMode == Transform.YAXIS_FOLLOW && !backward) {
564
+ ret = [ret[0], -1 * ret[1]];
565
+ }
566
+ return ret;
567
+ }
568
+
569
+ }