@maplat/tin 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/kinks.ts CHANGED
@@ -1,1092 +1,1092 @@
1
- import type { Feature, Point, Position } from "geojson";
2
- import { point } from "@turf/turf";
3
- import type { IntersectionPoint } from "./types/kinks.d.ts";
4
-
5
- /**
6
- * 線分の交差点を検出するメインの関数
7
- *
8
- * @param coords - 線分群の座標配列。各線分は始点と終点の座標で表現
9
- * @returns 検出された交差点のFeature配列
10
- */
11
- export default function findIntersections(
12
- coords: Position[][],
13
- ): Feature<Point>[] {
14
- const arcs = new ArcCollection(coords);
15
- const xy = arcs.findSegmentIntersections();
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
- );
26
- }
27
-
28
- /**
29
- * 線分群を管理するクラス
30
- * 効率的な交差判定のためのデータ構造と機能を提供
31
- */
32
- class ArcCollection {
33
- /**
34
- * 座標データの配列
35
- * _xx, _yy: Float64Array形式で座標を保持
36
- * _ii: 各線分の開始インデックス
37
- * _nn: 各線分の頂点数
38
- */
39
- _xx?: Float64Array;
40
- _yy?: Float64Array; // coordinates data
41
- _ii?: Uint32Array;
42
- _nn?: Uint32Array; // indexes, sizes
43
- _zz: Float64Array | null = null;
44
- _zlimit = 0; // simplification
45
- _bb: Float64Array | null = null;
46
- _allBounds: Bounds | null = null; // bounding boxes
47
- _arcIter: ArcIter | null = null;
48
- _filteredArcIter: ArcIter | null = null; // path iterators
49
- buf?: ArrayBuffer;
50
-
51
- /**
52
- * 線分群からArcCollectionを初期化
53
- * @param coords - 線分群の座標配列
54
- */
55
- constructor(coords: Position[][]) {
56
- this.initArcs(coords);
57
- }
58
-
59
- initArcs(arcs: Position[][]) {
60
- const xx: number[] = [],
61
- yy: number[] = [];
62
- const nn = arcs.map((points) => {
63
- const n = points ? points.length : 0;
64
- for (let i = 0; i < n; i++) {
65
- xx.push(points[i][0]);
66
- yy.push(points[i][1]);
67
- }
68
- return n;
69
- });
70
- this.initXYData(nn, xx, yy);
71
- }
72
-
73
- initXYData(nn: number[], xx: number[], yy: number[]) {
74
- const size = nn.length;
75
- this._xx = new Float64Array(xx);
76
- this._yy = new Float64Array(yy);
77
- this._nn = new Uint32Array(nn);
78
- this._zz = null;
79
- this._zlimit = 0;
80
- this._filteredArcIter = null;
81
-
82
- // generate array of starting idxs of each arc
83
- this._ii = new Uint32Array(size);
84
- let idx = 0;
85
- for (let j = 0; j < size; j++) {
86
- this._ii[j] = idx;
87
- idx += nn[j];
88
- }
89
-
90
- if (idx != this._xx.length || this._xx.length != this._yy.length) {
91
- error("ArcCollection#initXYData() Counting error");
92
- }
93
-
94
- this.initBounds();
95
- // Pre-allocate some path iterators for repeated use.
96
- this._arcIter = new ArcIter(this._xx, this._yy);
97
- }
98
-
99
- initBounds() {
100
- const data = this.calcArcBounds_(this._xx!, this._yy!, this._nn!);
101
- this._bb = data.bb;
102
- this._allBounds = data.bounds;
103
- }
104
-
105
- /**
106
- * データの境界を計算
107
- * @returns バウンディングボックス情報
108
- */
109
- calcArcBounds_(xx: Float64Array, yy: Float64Array, nn: Uint32Array) {
110
- const numArcs = nn.length,
111
- bb = new Float64Array(numArcs * 4),
112
- bounds = new Bounds();
113
- let arcOffs = 0,
114
- arcLen: number,
115
- j: number,
116
- b: number[];
117
- for (let i = 0; i < numArcs; i++) {
118
- arcLen = nn[i];
119
- if (arcLen > 0) {
120
- j = i * 4;
121
- b = calcArcBounds(xx, yy, arcOffs, arcLen) as number[];
122
- bb[j++] = b[0];
123
- bb[j++] = b[1];
124
- bb[j++] = b[2];
125
- bb[j] = b[3];
126
- arcOffs += arcLen;
127
- bounds.mergeBounds(b);
128
- }
129
- }
130
- return {
131
- bb,
132
- bounds,
133
- };
134
- }
135
-
136
- getBounds() {
137
- return this._allBounds ? this._allBounds.clone() : new Bounds();
138
- }
139
-
140
- // @cb function(i, j, xx, yy)
141
- forEachSegment(
142
- cb: (i: number, j: number, xx: Float64Array, yy: Float64Array) => void,
143
- ) {
144
- let count = 0;
145
- for (let i = 0, n = this.size(); i < n; i++) {
146
- count += this.forEachArcSegment(i, cb);
147
- }
148
- return count;
149
- }
150
-
151
- size() {
152
- return (this._ii && this._ii.length) || 0;
153
- }
154
-
155
- // @cb function(i, j, xx, yy)
156
- forEachArcSegment(
157
- arcId: number,
158
- cb: (i: number, j: number, xx: Float64Array, yy: Float64Array) => void,
159
- ): number {
160
- const fw = arcId >= 0,
161
- absId = fw ? arcId : ~arcId,
162
- zlim = this.getRetainedInterval(),
163
- n = this._nn![absId],
164
- step = fw ? 1 : -1;
165
- let v1 = fw ? this._ii![absId] : this._ii![absId] + n - 1,
166
- v2 = v1,
167
- count = 0;
168
-
169
- for (let j = 1; j < n; j++) {
170
- v2 += step;
171
- if (zlim === 0 || this._zz![v2] >= zlim) {
172
- cb(v1, v2, this._xx!, this._yy!);
173
- v1 = v2;
174
- count++;
175
- }
176
- }
177
- return count;
178
- }
179
-
180
- getRetainedInterval() {
181
- return this._zlimit;
182
- }
183
-
184
- // Give access to raw data arrays...
185
- getVertexData() {
186
- return {
187
- xx: this._xx,
188
- yy: this._yy,
189
- zz: this._zz,
190
- bb: this._bb,
191
- nn: this._nn,
192
- ii: this._ii,
193
- };
194
- }
195
-
196
- getUint32Array(count: number) {
197
- const bytes = count * 4;
198
- if (!this.buf || this.buf.byteLength < bytes) {
199
- this.buf = new ArrayBuffer(bytes);
200
- }
201
- return new Uint32Array(this.buf, 0, count);
202
- }
203
-
204
- // Return average magnitudes of dx, dy (with simplification)
205
- getAvgSegment2() {
206
- let dx = 0,
207
- dy = 0;
208
- const count = this.forEachSegment(
209
- (i: number, j: number, xx: Float64Array, yy: Float64Array) => {
210
- dx += Math.abs(xx[i] - xx[j]);
211
- dy += Math.abs(yy[i] - yy[j]);
212
- },
213
- );
214
- return [dx / count || 0, dy / count || 0];
215
- }
216
-
217
- /**
218
- * 交差判定のためのストライプ数を計算
219
- * 線分の平均長さに基づいて最適な分割数を決定
220
- */
221
- calcSegmentIntersectionStripeCount() {
222
- const yrange = this.getBounds().height(),
223
- segLen = this.getAvgSegment2()[1];
224
- let count = 1;
225
- if (segLen > 0 && yrange > 0) {
226
- count = Math.ceil(yrange / segLen / 20);
227
- }
228
- return count || 1;
229
- }
230
-
231
- /**
232
- * 線分の交差を検出
233
- * ストライプ分割による効率的な判定を実装
234
- *
235
- * @returns 検出された交差点の配列
236
- */
237
- findSegmentIntersections() {
238
- const bounds = this.getBounds(),
239
- ymin = bounds.ymin || 0,
240
- yrange = (bounds.ymax || 0) - ymin,
241
- stripeCount = this.calcSegmentIntersectionStripeCount(),
242
- stripeSizes = new Uint32Array(stripeCount),
243
- stripeId = stripeCount > 1
244
- ? (y: number) => Math.floor(((stripeCount - 1) * (y - ymin)) / yrange)
245
- : () => 0;
246
- let i, j;
247
-
248
- // Count segments in each stripe
249
- this.forEachSegment(
250
- (id1: number, id2: number, _xx: Float64Array, yy: Float64Array) => {
251
- let s1 = stripeId(yy[id1]);
252
- const s2 = stripeId(yy[id2]);
253
- while (true) {
254
- stripeSizes[s1] = stripeSizes[s1] + 2;
255
- if (s1 == s2) break;
256
- s1 += s2 > s1 ? 1 : -1;
257
- }
258
- },
259
- );
260
-
261
- // Allocate arrays for segments in each stripe
262
- const stripeData = this.getUint32Array(utilsSum(stripeSizes));
263
- let offs = 0;
264
- const stripes: Uint32Array[] = [];
265
- utilsForEach(stripeSizes, (stripeSize: number) => {
266
- const start = offs;
267
- offs += stripeSize;
268
- stripes.push(stripeData.subarray(start, offs));
269
- });
270
- // Assign segment ids to each stripe
271
- initializeArray(stripeSizes, 0);
272
-
273
- this.forEachSegment(
274
- (id1: number, id2: number, _xx: Float64Array, yy: Float64Array) => {
275
- let s1 = stripeId(yy[id1]);
276
- const s2 = stripeId(yy[id2]);
277
- let count, stripe;
278
- while (true) {
279
- count = stripeSizes[s1];
280
- stripeSizes[s1] = count + 2;
281
- stripe = stripes[s1];
282
- stripe[count] = id1;
283
- stripe[count + 1] = id2;
284
- if (s1 == s2) break;
285
- s1 += s2 > s1 ? 1 : -1;
286
- }
287
- },
288
- );
289
-
290
- // Detect intersections among segments in each stripe.
291
- const raw = this.getVertexData(),
292
- intersections = [];
293
- let arr;
294
- for (i = 0; i < stripeCount; i++) {
295
- if (raw.xx && raw.yy) {
296
- arr = intersectSegments(stripes[i], raw.xx, raw.yy);
297
- for (j = 0; j < arr.length; j++) {
298
- intersections.push(arr[j]);
299
- }
300
- }
301
- }
302
- return dedupIntersections(intersections);
303
- }
304
- }
305
-
306
- function error(...args: unknown[]) {
307
- const msg = args.join(" ");
308
- throw new Error(msg);
309
- }
310
-
311
- function isArrayLike(obj: unknown): obj is ArrayLike<unknown> {
312
- if (!obj) return false;
313
- if (isArray(obj)) return true;
314
- if (isString(obj)) return false;
315
- if ((obj as { length: number }).length === 0) return true;
316
- return (obj as { length: number }).length > 0;
317
- }
318
-
319
- function isString(obj: unknown): obj is string {
320
- return obj != null && obj.toString === String.prototype.toString;
321
- }
322
-
323
- function isArray(obj: unknown): obj is unknown[] {
324
- return Array.isArray(obj);
325
- }
326
-
327
- // Calc sum, skip falsy and NaN values
328
- // Assumes: no other non-numeric objects in array
329
- //
330
- function utilsSum(arr: Uint32Array, info?: { nan: number }) {
331
- if (!isArrayLike(arr)) error("utils.sum() expects an array, received:", arr);
332
- let tot = 0,
333
- nan = 0,
334
- val;
335
- for (let i = 0, n = arr.length; i < n; i++) {
336
- val = arr[i];
337
- if (val) {
338
- tot += val;
339
- } else if (isNaN(val)) {
340
- nan++;
341
- }
342
- }
343
- if (info) {
344
- info.nan = nan;
345
- }
346
- return tot;
347
- }
348
-
349
- // Support for iterating over array-like objects, like typed arrays
350
- // Support for iterating over array-like objects, like typed arrays
351
- function utilsForEach<T>(
352
- arr: ArrayLike<T>,
353
- func: (val: T, i: number) => void,
354
- ctx?: unknown,
355
- ) {
356
- if (!isArrayLike(arr)) {
357
- throw new Error(`#forEach() takes an array-like argument. ${arr}`);
358
- }
359
- for (let i = 0, n = arr.length; i < n; i++) {
360
- func.call(ctx, arr[i], i);
361
- }
362
- }
363
-
364
- function initializeArray(
365
- arr: number[] | Uint32Array | Float64Array,
366
- init: number,
367
- ) {
368
- for (let i = 0, len = arr.length; i < len; i++) {
369
- arr[i] = init;
370
- }
371
- return arr;
372
- }
373
-
374
- // Find intersections among a group of line segments
375
- //
376
- // TODO: handle case where a segment starts and ends at the same point (i.e. duplicate coords);
377
- //
378
- // @ids: Array of indexes: [s0p0, s0p1, s1p0, s1p1, ...] where xx[sip0] <= xx[sip1]
379
- // @xx, @yy: Arrays of x- and y-coordinates
380
- //
381
- function intersectSegments(
382
- ids: Uint32Array,
383
- xx: Float64Array,
384
- yy: Float64Array,
385
- ) {
386
- const lim = ids.length - 2,
387
- intersections = [];
388
- let s1p1,
389
- s1p2,
390
- s2p1,
391
- s2p2,
392
- s1p1x,
393
- s1p2x,
394
- s2p1x,
395
- s2p2x,
396
- s1p1y,
397
- s1p2y,
398
- s2p1y,
399
- s2p2y,
400
- hit,
401
- seg1,
402
- seg2,
403
- i,
404
- j;
405
-
406
- // Sort segments by xmin, to allow efficient exclusion of segments with
407
- // non-overlapping x extents.
408
- sortSegmentIds(xx, ids); // sort by ascending xmin
409
-
410
- i = 0;
411
- while (i < lim) {
412
- s1p1 = ids[i];
413
- s1p2 = ids[i + 1];
414
- s1p1x = xx[s1p1];
415
- s1p2x = xx[s1p2];
416
- s1p1y = yy[s1p1];
417
- s1p2y = yy[s1p2];
418
- // count++;
419
-
420
- j = i;
421
- while (j < lim) {
422
- j += 2;
423
- s2p1 = ids[j];
424
- s2p1x = xx[s2p1];
425
-
426
- if (s1p2x < s2p1x) break; // x extent of seg 2 is greater than seg 1: done with seg 1
427
- //if (s1p2x <= s2p1x) break; // this misses point-segment intersections when s1 or s2 is vertical
428
-
429
- s2p1y = yy[s2p1];
430
- s2p2 = ids[j + 1];
431
- s2p2x = xx[s2p2];
432
- s2p2y = yy[s2p2];
433
-
434
- // skip segments with non-overlapping y ranges
435
- if (s1p1y >= s2p1y) {
436
- if (s1p1y > s2p2y && s1p2y > s2p1y && s1p2y > s2p2y) continue;
437
- } else {
438
- if (s1p1y < s2p2y && s1p2y < s2p1y && s1p2y < s2p2y) continue;
439
- }
440
-
441
- // skip segments that are adjacent in a path (optimization)
442
- // TODO: consider if this eliminates some cases that should
443
- // be detected, e.g. spikes formed by unequal segments
444
- if (s1p1 == s2p1 || s1p1 == s2p2 || s1p2 == s2p1 || s1p2 == s2p2) {
445
- continue;
446
- }
447
-
448
- // test two candidate segments for intersection
449
- hit = segmentIntersection(
450
- s1p1x,
451
- s1p1y,
452
- s1p2x,
453
- s1p2y,
454
- s2p1x,
455
- s2p1y,
456
- s2p2x,
457
- s2p2y,
458
- );
459
- if (hit) {
460
- seg1 = [s1p1, s1p2];
461
- seg2 = [s2p1, s2p2];
462
- intersections.push(formatIntersection(hit, seg1, seg2, xx, yy));
463
- if (hit.length == 4) {
464
- // two collinear segments may have two endpoint intersections
465
- intersections.push(
466
- formatIntersection(hit.slice(2), seg1, seg2, xx, yy),
467
- );
468
- }
469
- }
470
- }
471
- i += 2;
472
- }
473
- return intersections;
474
- }
475
-
476
- /**
477
- * 2つの2D線分間の交差を判定し、交差点を計算します
478
- *
479
- * @param ax, ay - 第1線分の始点座標
480
- * @param bx, by - 第1線分の終点座標
481
- * @param cx, cy - 第2線分の始点座標
482
- * @param dx, dy - 第2線分の終点座標
483
- *
484
- * @returns 以下のいずれか:
485
- * - null: 交差なし
486
- * - [x, y]: 1点での交差
487
- * - [x1, y1, x2, y2]: 線分が重なる場合の2点での交差
488
- *
489
- * 特殊ケースの扱い:
490
- * 1. 両線分の端点で接触する場合 → 交差としない
491
- * 2. T字型に接触する場合 → 交差として扱う
492
- * 3. 線分が同一直線上で部分的に重なる場合 → 重なる部分の端点を交差点として扱う(1または2点)
493
- * - 例: 線分ABとCDが重なる場合、重なり部分の両端点が交差点となる
494
- * - [x1, y1, x2, y2] の形式で返される
495
- */
496
- function segmentIntersection(
497
- ax: number,
498
- ay: number,
499
- bx: number,
500
- by: number,
501
- cx: number,
502
- cy: number,
503
- dx: number,
504
- dy: number,
505
- ) {
506
- const hit = segmentHit(ax, ay, bx, by, cx, cy, dx, dy);
507
- let p = null;
508
- if (hit) {
509
- p = crossIntersection(ax, ay, bx, by, cx, cy, dx, dy);
510
- if (!p) {
511
- // collinear if p is null
512
- p = collinearIntersection(ax, ay, bx, by, cx, cy, dx, dy);
513
- } else if (endpointHit(ax, ay, bx, by, cx, cy, dx, dy)) {
514
- p = null; // filter out segments that only intersect at an endpoint
515
- }
516
- }
517
- return p;
518
- }
519
-
520
- // Source: Sedgewick, _Algorithms in C_
521
- // (Tried various other functions that failed owing to floating point errors)
522
- function segmentHit(
523
- ax: number,
524
- ay: number,
525
- bx: number,
526
- by: number,
527
- cx: number,
528
- cy: number,
529
- dx: number,
530
- dy: number,
531
- ) {
532
- return (
533
- orient2D(ax, ay, bx, by, cx, cy) * orient2D(ax, ay, bx, by, dx, dy) <= 0 &&
534
- orient2D(cx, cy, dx, dy, ax, ay) * orient2D(cx, cy, dx, dy, bx, by) <= 0
535
- );
536
- }
537
-
538
- // returns a positive value if the points a, b, and c are arranged in
539
- // counterclockwise order, a negative value if the points are in clockwise
540
- // order, and zero if the points are collinear.
541
- // Source: Jonathan Shewchuk http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf
542
- function orient2D(
543
- ax: number,
544
- ay: number,
545
- bx: number,
546
- by: number,
547
- cx: number,
548
- cy: number,
549
- ) {
550
- return determinant2D(ax - cx, ay - cy, bx - cx, by - cy);
551
- }
552
-
553
- /**
554
- * 2次元の行列式を計算
555
- *
556
- * @param a, b - 行列の第1行
557
- * @param c, d - 行列の第2行
558
- * @returns 行列式の値
559
- */
560
- function determinant2D(a: number, b: number, c: number, d: number) {
561
- return a * d - b * c;
562
- }
563
-
564
- // Get intersection point if segments are non-collinear, else return null
565
- // Assumes that segments have been intersect
566
- function crossIntersection(
567
- ax: number,
568
- ay: number,
569
- bx: number,
570
- by: number,
571
- cx: number,
572
- cy: number,
573
- dx: number,
574
- dy: number,
575
- ) {
576
- let p = lineIntersection(ax, ay, bx, by, cx, cy, dx, dy);
577
- let nearest;
578
- if (p) {
579
- // Re-order operands so intersection point is closest to a (better precision)
580
- // Source: Jonathan Shewchuk http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf
581
- nearest = nearestPoint(p[0], p[1], ax, ay, bx, by, cx, cy, dx, dy);
582
- if (nearest == 1) {
583
- p = lineIntersection(bx, by, ax, ay, cx, cy, dx, dy);
584
- } else if (nearest == 2) {
585
- p = lineIntersection(cx, cy, dx, dy, ax, ay, bx, by);
586
- } else if (nearest == 3) {
587
- p = lineIntersection(dx, dy, cx, cy, ax, ay, bx, by);
588
- }
589
- }
590
- if (p) {
591
- clampIntersectionPoint(p, ax, ay, bx, by, cx, cy, dx, dy);
592
- }
593
- return p;
594
- }
595
-
596
- function lineIntersection(
597
- ax: number,
598
- ay: number,
599
- bx: number,
600
- by: number,
601
- cx: number,
602
- cy: number,
603
- dx: number,
604
- dy: number,
605
- ) {
606
- const den = determinant2D(bx - ax, by - ay, dx - cx, dy - cy);
607
- const eps = 1e-18;
608
- let p;
609
- if (den === 0) return null;
610
- const m = orient2D(cx, cy, dx, dy, ax, ay) / den;
611
- if (den <= eps && den >= -eps) {
612
- // tiny denominator = low precision; using one of the endpoints as intersection
613
- p = findEndpointInRange(ax, ay, bx, by, cx, cy, dx, dy);
614
- /*if (!p) {
615
- debug("[lineIntersection()]");
616
- debugSegmentIntersection([], ax, ay, bx, by, cx, cy, dx, dy);
617
- }*/
618
- } else {
619
- p = [ax + m * (bx - ax), ay + m * (by - ay)];
620
- }
621
- return p;
622
- }
623
-
624
- function findEndpointInRange(
625
- ax: number,
626
- ay: number,
627
- bx: number,
628
- by: number,
629
- cx: number,
630
- cy: number,
631
- dx: number,
632
- dy: number,
633
- ) {
634
- let p = null;
635
- if (!outsideRange(ax, cx, dx) && !outsideRange(ay, cy, dy)) {
636
- p = [ax, ay];
637
- } else if (!outsideRange(bx, cx, dx) && !outsideRange(by, cy, dy)) {
638
- p = [bx, by];
639
- } else if (!outsideRange(cx, ax, bx) && !outsideRange(cy, ay, by)) {
640
- p = [cx, cy];
641
- } else if (!outsideRange(dx, ax, bx) && !outsideRange(dy, ay, by)) {
642
- p = [dx, dy];
643
- }
644
- return p;
645
- }
646
-
647
- /**
648
- * 点が線分の範囲外にあるかを判定
649
- *
650
- * @param a - 判定する点の座標
651
- * @param b - 線分の一方の端点
652
- * @param c - 線分のもう一方の端点
653
- */
654
- function outsideRange(a: number, b: number, c: number) {
655
- let out;
656
- if (b < c) {
657
- out = a < b || a > c;
658
- } else if (b > c) {
659
- out = a > b || a < c;
660
- } else {
661
- out = a != b;
662
- }
663
- return out;
664
- }
665
-
666
- // Return id of nearest point to x, y, among x0, y0, x1, y1, ...
667
- function nearestPoint(x: number, y: number, ...args: number[]) {
668
- let minIdx = -1,
669
- minDist = Infinity,
670
- dist;
671
- for (let i = 0, j = 0, n = args.length; j < n; i++, j += 2) {
672
- dist = distanceSq(x, y, args[j], args[j + 1]);
673
- if (dist < minDist) {
674
- minDist = dist;
675
- minIdx = i;
676
- }
677
- }
678
- return minIdx;
679
- }
680
-
681
- function distanceSq(ax: number, ay: number, bx: number, by: number) {
682
- const dx = ax - bx,
683
- dy = ay - by;
684
- return dx * dx + dy * dy;
685
- }
686
-
687
- function clampIntersectionPoint(
688
- p: number[],
689
- ax: number,
690
- ay: number,
691
- bx: number,
692
- by: number,
693
- cx: number,
694
- cy: number,
695
- dx: number,
696
- dy: number,
697
- ) {
698
- // Handle intersection points that fall outside the x-y range of either
699
- // segment by snapping to nearest endpoint coordinate. Out-of-range
700
- // intersection points can be caused by floating point rounding errors
701
- // when a segment is vertical or horizontal. This has caused problems when
702
- // repeatedly applying bbox clipping along the same segment
703
- let x = p[0],
704
- y = p[1];
705
- // assumes that segment ranges intersect
706
- x = clampToCloseRange(x, ax, bx);
707
- x = clampToCloseRange(x, cx, dx);
708
- y = clampToCloseRange(y, ay, by);
709
- y = clampToCloseRange(y, cy, dy);
710
- p[0] = x;
711
- p[1] = y;
712
- }
713
-
714
- function clampToCloseRange(a: number, b: number, c: number) {
715
- let lim;
716
- if (outsideRange(a, b, c)) {
717
- lim = Math.abs(a - b) < Math.abs(a - c) ? b : c;
718
- if (Math.abs(a - lim) > 1e-15) {
719
- //debug("[clampToCloseRange()] large clamping interval", a, b, c);
720
- }
721
- a = lim;
722
- }
723
- return a;
724
- }
725
-
726
- // Assume segments s1 and s2 are collinear and overlap; find one or two internal endpoints
727
- function collinearIntersection(
728
- ax: number,
729
- ay: number,
730
- bx: number,
731
- by: number,
732
- cx: number,
733
- cy: number,
734
- dx: number,
735
- dy: number,
736
- ) {
737
- const minX = Math.min(ax, bx, cx, dx),
738
- maxX = Math.max(ax, bx, cx, dx),
739
- minY = Math.min(ay, by, cy, dy),
740
- maxY = Math.max(ay, by, cy, dy);
741
- const useY = maxY - minY > maxX - minX;
742
- let coords: number[] | null = [];
743
-
744
- if (useY ? inside(ay, minY, maxY) : inside(ax, minX, maxX)) {
745
- coords.push(ax, ay);
746
- }
747
- if (useY ? inside(by, minY, maxY) : inside(bx, minX, maxX)) {
748
- coords.push(bx, by);
749
- }
750
- if (useY ? inside(cy, minY, maxY) : inside(cx, minX, maxX)) {
751
- coords.push(cx, cy);
752
- }
753
- if (useY ? inside(dy, minY, maxY) : inside(dx, minX, maxX)) {
754
- coords.push(dx, dy);
755
- }
756
- if (coords.length != 2 && coords.length != 4) {
757
- coords = null;
758
- //debug("Invalid collinear segment intersection", coords);
759
- } else if (
760
- coords.length == 4 &&
761
- coords[0] == coords[2] &&
762
- coords[1] == coords[3]
763
- ) {
764
- // segs that meet in the middle don't count
765
- coords = null;
766
- }
767
- return coords;
768
- }
769
-
770
- function endpointHit(
771
- ax: number,
772
- ay: number,
773
- bx: number,
774
- by: number,
775
- cx: number,
776
- cy: number,
777
- dx: number,
778
- dy: number,
779
- ) {
780
- return (
781
- (ax == cx && ay == cy) ||
782
- (ax == dx && ay == dy) ||
783
- (bx == cx && by == cy) ||
784
- (bx == dx && by == dy)
785
- );
786
- }
787
-
788
- function inside(x: number, minX: number, maxX: number) {
789
- return x > minX && x < maxX;
790
- }
791
-
792
- // @xx array of x coords
793
- // @ids an array of segment endpoint ids [a0, b0, a1, b1, ...]
794
- // Sort @ids in place so that xx[a(n)] <= xx[b(n)] and xx[a(n)] <= xx[a(n+1)]
795
- function sortSegmentIds(xx: Float64Array, ids: Uint32Array) {
796
- orderSegmentIds(xx, ids);
797
- quicksortSegmentIds(xx, ids, 0, ids.length - 2);
798
- }
799
-
800
- function orderSegmentIds(xx: Float64Array, ids: Uint32Array) {
801
- for (let i = 0, n = ids.length; i < n; i += 2) {
802
- if (xx[ids[i]] > xx[ids[i + 1]]) {
803
- swap(ids, i, i + 1);
804
- }
805
- }
806
- }
807
-
808
- function swap(ids: Uint32Array, i: number, j: number) {
809
- const tmp = ids[i];
810
- ids[i] = ids[j];
811
- ids[j] = tmp;
812
- }
813
-
814
- function quicksortSegmentIds(
815
- a: Float64Array,
816
- ids: Uint32Array,
817
- lo: number,
818
- hi: number,
819
- ) {
820
- let i = lo,
821
- j = hi,
822
- pivot,
823
- tmp;
824
- while (i < hi) {
825
- pivot = a[ids[((lo + hi) >> 2) << 1]]; // avoid n^2 performance on sorted arrays
826
- while (i <= j) {
827
- while (a[ids[i]] < pivot) i += 2;
828
- while (a[ids[j]] > pivot) j -= 2;
829
- if (i <= j) {
830
- tmp = ids[i];
831
- ids[i] = ids[j];
832
- ids[j] = tmp;
833
- tmp = ids[i + 1];
834
- ids[i + 1] = ids[j + 1];
835
- ids[j + 1] = tmp;
836
- i += 2;
837
- j -= 2;
838
- }
839
- }
840
-
841
- if (j - lo < 40) insertionSortSegmentIds(a, ids, lo, j);
842
- else quicksortSegmentIds(a, ids, lo, j);
843
- if (hi - i < 40) {
844
- insertionSortSegmentIds(a, ids, i, hi);
845
- return;
846
- }
847
- lo = i;
848
- j = hi;
849
- }
850
- }
851
-
852
- function insertionSortSegmentIds(
853
- arr: Float64Array,
854
- ids: Uint32Array,
855
- start: number,
856
- end: number,
857
- ) {
858
- let id, id2;
859
- for (let j = start + 2; j <= end; j += 2) {
860
- id = ids[j];
861
- id2 = ids[j + 1];
862
- let i;
863
- for (i = j - 2; i >= start && arr[id] < arr[ids[i]]; i -= 2) {
864
- ids[i + 2] = ids[i];
865
- ids[i + 3] = ids[i + 1];
866
- }
867
- ids[i + 2] = id;
868
- ids[i + 3] = id2;
869
- }
870
- }
871
-
872
- function formatIntersection(
873
- xy: number[],
874
- s1: number[],
875
- s2: number[],
876
- xx: Float64Array,
877
- yy: Float64Array,
878
- ) {
879
- const x = xy[0],
880
- y = xy[1];
881
- s1 = formatIntersectingSegment(x, y, s1[0], s1[1], xx, yy);
882
- s2 = formatIntersectingSegment(x, y, s2[0], s2[1], xx, yy);
883
- const a = s1[0] < s2[0] ? s1 : s2;
884
- const b = a == s1 ? s2 : s1;
885
- return { x, y, a, b };
886
- }
887
-
888
- function formatIntersectingSegment(
889
- x: number,
890
- y: number,
891
- id1: number,
892
- id2: number,
893
- xx: Float64Array,
894
- yy: Float64Array,
895
- ) {
896
- let i = id1 < id2 ? id1 : id2,
897
- j = i === id1 ? id2 : id1;
898
- if (xx[i] == x && yy[i] == y) {
899
- j = i;
900
- } else if (xx[j] == x && yy[j] == y) {
901
- i = j;
902
- }
903
- return [i, j];
904
- }
905
-
906
- /**
907
- * 交差判定結果から重複を除去
908
- *
909
- * @param arr - 交差点情報の配列
910
- * @returns 重複を除去した交差点情報の配列
911
- */
912
- function dedupIntersections(arr: IntersectionPoint[]) {
913
- const index: Record<string, boolean> = {};
914
- return arr.filter((o: IntersectionPoint) => {
915
- const key = getIntersectionKey(o);
916
- if (key in index) {
917
- return false;
918
- }
919
- index[key] = true;
920
- return true;
921
- });
922
- }
923
-
924
- // Get an indexable key from an intersection object
925
- // Assumes that vertex ids of o.a and o.b are sorted
926
- function getIntersectionKey(o: IntersectionPoint) {
927
- return `${o.a.join(",")};${o.b.join(",")}`;
928
- }
929
-
930
- // Constructor takes arrays of coords: xx, yy, zz (optional)
931
- //
932
- class ArcIter {
933
- _i = 0;
934
- _n = 0;
935
- _inc = 1;
936
- _xx: Float64Array;
937
- _yy: Float64Array;
938
- i = 0;
939
- x = 0;
940
- y = 0;
941
-
942
- constructor(xx: Float64Array, yy: Float64Array) {
943
- this._xx = xx;
944
- this._yy = yy;
945
- }
946
- }
947
-
948
- function calcArcBounds(
949
- xx: Float64Array,
950
- yy: Float64Array,
951
- start: number,
952
- len: number,
953
- ) {
954
- let i = start | 0;
955
- const n = isNaN(len) ? xx.length - i : len + i;
956
- let x: number,
957
- y: number,
958
- xmin: number,
959
- ymin: number,
960
- xmax: number,
961
- ymax: number;
962
- if (n > 0) {
963
- xmin = xmax = xx[i];
964
- ymin = ymax = yy[i];
965
- } else return [undefined, undefined, undefined, undefined];
966
- for (i++; i < n; i++) {
967
- x = xx[i];
968
- y = yy[i];
969
- if (x < xmin) xmin = x;
970
- if (x > xmax) xmax = x;
971
- if (y < ymin) ymin = y;
972
- if (y > ymax) ymax = y;
973
- }
974
- return [xmin, ymin, xmax, ymax];
975
- }
976
-
977
- class Bounds {
978
- xmin?: number;
979
- ymin?: number;
980
- xmax?: number;
981
- ymax?: number;
982
-
983
- constructor(...args: number[] | [Bounds] | []) {
984
- if (args.length > 0) {
985
- this.setBounds(args as number[]);
986
- }
987
- }
988
-
989
- // Return a bounding box with the same extent as this one.
990
- cloneBounds() {
991
- return this.clone();
992
- }
993
-
994
- clone() {
995
- // alias so child classes can override clone()
996
- return new Bounds(
997
- this.xmin!,
998
- this.ymin!,
999
- this.xmax!,
1000
- this.ymax!,
1001
- );
1002
- }
1003
-
1004
- width() {
1005
- return this.xmax! - this.xmin! || 0;
1006
- }
1007
-
1008
- height() {
1009
- return this.ymax! - this.ymin! || 0;
1010
- }
1011
-
1012
- setBounds(a: number | number[] | Bounds, b?: number, c?: number, d?: number) {
1013
- let xmin: number, ymin: number, xmax: number, ymax: number;
1014
-
1015
- if (arguments.length == 1) {
1016
- // assume first arg is a Bounds or array
1017
- if (isArrayLike(a)) {
1018
- const arr = a as number[];
1019
- xmin = arr[0];
1020
- ymin = arr[1];
1021
- xmax = arr[2];
1022
- ymax = arr[3];
1023
- } else {
1024
- const bounds = a as Bounds;
1025
- xmin = bounds.xmin!;
1026
- ymin = bounds.ymin!;
1027
- xmax = bounds.xmax!;
1028
- ymax = bounds.ymax!;
1029
- }
1030
- } else {
1031
- xmin = a as number;
1032
- ymin = b!;
1033
- xmax = c!;
1034
- ymax = d!;
1035
- }
1036
-
1037
- this.xmin = xmin;
1038
- this.ymin = ymin;
1039
- this.xmax = xmax;
1040
- this.ymax = ymax;
1041
- if (xmin > xmax || ymin > ymax) this.update();
1042
- // error("Bounds#setBounds() min/max reversed:", a, b, c, d);
1043
- return this;
1044
- }
1045
-
1046
- update() {
1047
- let tmp: number;
1048
- if (this.xmin! > this.xmax!) {
1049
- tmp = this.xmin!;
1050
- this.xmin = this.xmax;
1051
- this.xmax = tmp;
1052
- }
1053
- if (this.ymin! > this.ymax!) {
1054
- tmp = this.ymin!;
1055
- this.ymin = this.ymax;
1056
- this.ymax = tmp;
1057
- }
1058
- }
1059
-
1060
- mergeBounds(bb: number | number[] | Bounds, ...args: number[]) {
1061
- let a: number, b: number, c: number, d: number;
1062
- if (bb instanceof Bounds) {
1063
- a = bb.xmin!;
1064
- b = bb.ymin!;
1065
- c = bb.xmax!;
1066
- d = bb.ymax!;
1067
- } else if (args.length == 3) {
1068
- a = bb as number;
1069
- b = args[0];
1070
- c = args[1];
1071
- d = args[2];
1072
- } else if ((bb as number[]).length == 4) {
1073
- // assume array: [xmin, ymin, xmax, ymax]
1074
- a = (bb as number[])[0];
1075
- b = (bb as number[])[1];
1076
- c = (bb as number[])[2];
1077
- d = (bb as number[])[3];
1078
- } else {
1079
- error("Bounds#mergeBounds() invalid argument:", bb);
1080
- }
1081
-
1082
- if (this.xmin === void 0) {
1083
- this.setBounds(a!, b!, c!, d!);
1084
- } else {
1085
- if (a! < this.xmin) this.xmin = a!;
1086
- if (b! < this.ymin!) this.ymin = b!;
1087
- if (c! > this.xmax!) this.xmax = c!;
1088
- if (d! > this.ymax!) this.ymax = d!;
1089
- }
1090
- return this;
1091
- }
1092
- }
1
+ import type { Feature, Point, Position } from "geojson";
2
+ import { point } from "@turf/turf";
3
+ import type { IntersectionPoint } from "./types/kinks.d.ts";
4
+
5
+ /**
6
+ * 線分の交差点を検出するメインの関数
7
+ *
8
+ * @param coords - 線分群の座標配列。各線分は始点と終点の座標で表現
9
+ * @returns 検出された交差点のFeature配列
10
+ */
11
+ export default function findIntersections(
12
+ coords: Position[][],
13
+ ): Feature<Point>[] {
14
+ const arcs = new ArcCollection(coords);
15
+ const xy = arcs.findSegmentIntersections();
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
+ );
26
+ }
27
+
28
+ /**
29
+ * 線分群を管理するクラス
30
+ * 効率的な交差判定のためのデータ構造と機能を提供
31
+ */
32
+ class ArcCollection {
33
+ /**
34
+ * 座標データの配列
35
+ * _xx, _yy: Float64Array形式で座標を保持
36
+ * _ii: 各線分の開始インデックス
37
+ * _nn: 各線分の頂点数
38
+ */
39
+ _xx?: Float64Array;
40
+ _yy?: Float64Array; // coordinates data
41
+ _ii?: Uint32Array;
42
+ _nn?: Uint32Array; // indexes, sizes
43
+ _zz: Float64Array | null = null;
44
+ _zlimit = 0; // simplification
45
+ _bb: Float64Array | null = null;
46
+ _allBounds: Bounds | null = null; // bounding boxes
47
+ _arcIter: ArcIter | null = null;
48
+ _filteredArcIter: ArcIter | null = null; // path iterators
49
+ buf?: ArrayBuffer;
50
+
51
+ /**
52
+ * 線分群からArcCollectionを初期化
53
+ * @param coords - 線分群の座標配列
54
+ */
55
+ constructor(coords: Position[][]) {
56
+ this.initArcs(coords);
57
+ }
58
+
59
+ initArcs(arcs: Position[][]) {
60
+ const xx: number[] = [],
61
+ yy: number[] = [];
62
+ const nn = arcs.map((points) => {
63
+ const n = points ? points.length : 0;
64
+ for (let i = 0; i < n; i++) {
65
+ xx.push(points[i][0]);
66
+ yy.push(points[i][1]);
67
+ }
68
+ return n;
69
+ });
70
+ this.initXYData(nn, xx, yy);
71
+ }
72
+
73
+ initXYData(nn: number[], xx: number[], yy: number[]) {
74
+ const size = nn.length;
75
+ this._xx = new Float64Array(xx);
76
+ this._yy = new Float64Array(yy);
77
+ this._nn = new Uint32Array(nn);
78
+ this._zz = null;
79
+ this._zlimit = 0;
80
+ this._filteredArcIter = null;
81
+
82
+ // generate array of starting idxs of each arc
83
+ this._ii = new Uint32Array(size);
84
+ let idx = 0;
85
+ for (let j = 0; j < size; j++) {
86
+ this._ii[j] = idx;
87
+ idx += nn[j];
88
+ }
89
+
90
+ if (idx != this._xx.length || this._xx.length != this._yy.length) {
91
+ error("ArcCollection#initXYData() Counting error");
92
+ }
93
+
94
+ this.initBounds();
95
+ // Pre-allocate some path iterators for repeated use.
96
+ this._arcIter = new ArcIter(this._xx, this._yy);
97
+ }
98
+
99
+ initBounds() {
100
+ const data = this.calcArcBounds_(this._xx!, this._yy!, this._nn!);
101
+ this._bb = data.bb;
102
+ this._allBounds = data.bounds;
103
+ }
104
+
105
+ /**
106
+ * データの境界を計算
107
+ * @returns バウンディングボックス情報
108
+ */
109
+ calcArcBounds_(xx: Float64Array, yy: Float64Array, nn: Uint32Array) {
110
+ const numArcs = nn.length,
111
+ bb = new Float64Array(numArcs * 4),
112
+ bounds = new Bounds();
113
+ let arcOffs = 0,
114
+ arcLen: number,
115
+ j: number,
116
+ b: number[];
117
+ for (let i = 0; i < numArcs; i++) {
118
+ arcLen = nn[i];
119
+ if (arcLen > 0) {
120
+ j = i * 4;
121
+ b = calcArcBounds(xx, yy, arcOffs, arcLen) as number[];
122
+ bb[j++] = b[0];
123
+ bb[j++] = b[1];
124
+ bb[j++] = b[2];
125
+ bb[j] = b[3];
126
+ arcOffs += arcLen;
127
+ bounds.mergeBounds(b);
128
+ }
129
+ }
130
+ return {
131
+ bb,
132
+ bounds,
133
+ };
134
+ }
135
+
136
+ getBounds() {
137
+ return this._allBounds ? this._allBounds.clone() : new Bounds();
138
+ }
139
+
140
+ // @cb function(i, j, xx, yy)
141
+ forEachSegment(
142
+ cb: (i: number, j: number, xx: Float64Array, yy: Float64Array) => void,
143
+ ) {
144
+ let count = 0;
145
+ for (let i = 0, n = this.size(); i < n; i++) {
146
+ count += this.forEachArcSegment(i, cb);
147
+ }
148
+ return count;
149
+ }
150
+
151
+ size() {
152
+ return (this._ii && this._ii.length) || 0;
153
+ }
154
+
155
+ // @cb function(i, j, xx, yy)
156
+ forEachArcSegment(
157
+ arcId: number,
158
+ cb: (i: number, j: number, xx: Float64Array, yy: Float64Array) => void,
159
+ ): number {
160
+ const fw = arcId >= 0,
161
+ absId = fw ? arcId : ~arcId,
162
+ zlim = this.getRetainedInterval(),
163
+ n = this._nn![absId],
164
+ step = fw ? 1 : -1;
165
+ let v1 = fw ? this._ii![absId] : this._ii![absId] + n - 1,
166
+ v2 = v1,
167
+ count = 0;
168
+
169
+ for (let j = 1; j < n; j++) {
170
+ v2 += step;
171
+ if (zlim === 0 || this._zz![v2] >= zlim) {
172
+ cb(v1, v2, this._xx!, this._yy!);
173
+ v1 = v2;
174
+ count++;
175
+ }
176
+ }
177
+ return count;
178
+ }
179
+
180
+ getRetainedInterval() {
181
+ return this._zlimit;
182
+ }
183
+
184
+ // Give access to raw data arrays...
185
+ getVertexData() {
186
+ return {
187
+ xx: this._xx,
188
+ yy: this._yy,
189
+ zz: this._zz,
190
+ bb: this._bb,
191
+ nn: this._nn,
192
+ ii: this._ii,
193
+ };
194
+ }
195
+
196
+ getUint32Array(count: number) {
197
+ const bytes = count * 4;
198
+ if (!this.buf || this.buf.byteLength < bytes) {
199
+ this.buf = new ArrayBuffer(bytes);
200
+ }
201
+ return new Uint32Array(this.buf, 0, count);
202
+ }
203
+
204
+ // Return average magnitudes of dx, dy (with simplification)
205
+ getAvgSegment2() {
206
+ let dx = 0,
207
+ dy = 0;
208
+ const count = this.forEachSegment(
209
+ (i: number, j: number, xx: Float64Array, yy: Float64Array) => {
210
+ dx += Math.abs(xx[i] - xx[j]);
211
+ dy += Math.abs(yy[i] - yy[j]);
212
+ },
213
+ );
214
+ return [dx / count || 0, dy / count || 0];
215
+ }
216
+
217
+ /**
218
+ * 交差判定のためのストライプ数を計算
219
+ * 線分の平均長さに基づいて最適な分割数を決定
220
+ */
221
+ calcSegmentIntersectionStripeCount() {
222
+ const yrange = this.getBounds().height(),
223
+ segLen = this.getAvgSegment2()[1];
224
+ let count = 1;
225
+ if (segLen > 0 && yrange > 0) {
226
+ count = Math.ceil(yrange / segLen / 20);
227
+ }
228
+ return count || 1;
229
+ }
230
+
231
+ /**
232
+ * 線分の交差を検出
233
+ * ストライプ分割による効率的な判定を実装
234
+ *
235
+ * @returns 検出された交差点の配列
236
+ */
237
+ findSegmentIntersections() {
238
+ const bounds = this.getBounds(),
239
+ ymin = bounds.ymin || 0,
240
+ yrange = (bounds.ymax || 0) - ymin,
241
+ stripeCount = this.calcSegmentIntersectionStripeCount(),
242
+ stripeSizes = new Uint32Array(stripeCount),
243
+ stripeId = stripeCount > 1
244
+ ? (y: number) => Math.floor(((stripeCount - 1) * (y - ymin)) / yrange)
245
+ : () => 0;
246
+ let i, j;
247
+
248
+ // Count segments in each stripe
249
+ this.forEachSegment(
250
+ (id1: number, id2: number, _xx: Float64Array, yy: Float64Array) => {
251
+ let s1 = stripeId(yy[id1]);
252
+ const s2 = stripeId(yy[id2]);
253
+ while (true) {
254
+ stripeSizes[s1] = stripeSizes[s1] + 2;
255
+ if (s1 == s2) break;
256
+ s1 += s2 > s1 ? 1 : -1;
257
+ }
258
+ },
259
+ );
260
+
261
+ // Allocate arrays for segments in each stripe
262
+ const stripeData = this.getUint32Array(utilsSum(stripeSizes));
263
+ let offs = 0;
264
+ const stripes: Uint32Array[] = [];
265
+ utilsForEach(stripeSizes, (stripeSize: number) => {
266
+ const start = offs;
267
+ offs += stripeSize;
268
+ stripes.push(stripeData.subarray(start, offs));
269
+ });
270
+ // Assign segment ids to each stripe
271
+ initializeArray(stripeSizes, 0);
272
+
273
+ this.forEachSegment(
274
+ (id1: number, id2: number, _xx: Float64Array, yy: Float64Array) => {
275
+ let s1 = stripeId(yy[id1]);
276
+ const s2 = stripeId(yy[id2]);
277
+ let count, stripe;
278
+ while (true) {
279
+ count = stripeSizes[s1];
280
+ stripeSizes[s1] = count + 2;
281
+ stripe = stripes[s1];
282
+ stripe[count] = id1;
283
+ stripe[count + 1] = id2;
284
+ if (s1 == s2) break;
285
+ s1 += s2 > s1 ? 1 : -1;
286
+ }
287
+ },
288
+ );
289
+
290
+ // Detect intersections among segments in each stripe.
291
+ const raw = this.getVertexData(),
292
+ intersections = [];
293
+ let arr;
294
+ for (i = 0; i < stripeCount; i++) {
295
+ if (raw.xx && raw.yy) {
296
+ arr = intersectSegments(stripes[i], raw.xx, raw.yy);
297
+ for (j = 0; j < arr.length; j++) {
298
+ intersections.push(arr[j]);
299
+ }
300
+ }
301
+ }
302
+ return dedupIntersections(intersections);
303
+ }
304
+ }
305
+
306
+ function error(...args: unknown[]) {
307
+ const msg = args.join(" ");
308
+ throw new Error(msg);
309
+ }
310
+
311
+ function isArrayLike(obj: unknown): obj is ArrayLike<unknown> {
312
+ if (!obj) return false;
313
+ if (isArray(obj)) return true;
314
+ if (isString(obj)) return false;
315
+ if ((obj as { length: number }).length === 0) return true;
316
+ return (obj as { length: number }).length > 0;
317
+ }
318
+
319
+ function isString(obj: unknown): obj is string {
320
+ return obj != null && obj.toString === String.prototype.toString;
321
+ }
322
+
323
+ function isArray(obj: unknown): obj is unknown[] {
324
+ return Array.isArray(obj);
325
+ }
326
+
327
+ // Calc sum, skip falsy and NaN values
328
+ // Assumes: no other non-numeric objects in array
329
+ //
330
+ function utilsSum(arr: Uint32Array, info?: { nan: number }) {
331
+ if (!isArrayLike(arr)) error("utils.sum() expects an array, received:", arr);
332
+ let tot = 0,
333
+ nan = 0,
334
+ val;
335
+ for (let i = 0, n = arr.length; i < n; i++) {
336
+ val = arr[i];
337
+ if (val) {
338
+ tot += val;
339
+ } else if (isNaN(val)) {
340
+ nan++;
341
+ }
342
+ }
343
+ if (info) {
344
+ info.nan = nan;
345
+ }
346
+ return tot;
347
+ }
348
+
349
+ // Support for iterating over array-like objects, like typed arrays
350
+ // Support for iterating over array-like objects, like typed arrays
351
+ function utilsForEach<T>(
352
+ arr: ArrayLike<T>,
353
+ func: (val: T, i: number) => void,
354
+ ctx?: unknown,
355
+ ) {
356
+ if (!isArrayLike(arr)) {
357
+ throw new Error(`#forEach() takes an array-like argument. ${arr}`);
358
+ }
359
+ for (let i = 0, n = arr.length; i < n; i++) {
360
+ func.call(ctx, arr[i], i);
361
+ }
362
+ }
363
+
364
+ function initializeArray(
365
+ arr: number[] | Uint32Array | Float64Array,
366
+ init: number,
367
+ ) {
368
+ for (let i = 0, len = arr.length; i < len; i++) {
369
+ arr[i] = init;
370
+ }
371
+ return arr;
372
+ }
373
+
374
+ // Find intersections among a group of line segments
375
+ //
376
+ // TODO: handle case where a segment starts and ends at the same point (i.e. duplicate coords);
377
+ //
378
+ // @ids: Array of indexes: [s0p0, s0p1, s1p0, s1p1, ...] where xx[sip0] <= xx[sip1]
379
+ // @xx, @yy: Arrays of x- and y-coordinates
380
+ //
381
+ function intersectSegments(
382
+ ids: Uint32Array,
383
+ xx: Float64Array,
384
+ yy: Float64Array,
385
+ ) {
386
+ const lim = ids.length - 2,
387
+ intersections = [];
388
+ let s1p1,
389
+ s1p2,
390
+ s2p1,
391
+ s2p2,
392
+ s1p1x,
393
+ s1p2x,
394
+ s2p1x,
395
+ s2p2x,
396
+ s1p1y,
397
+ s1p2y,
398
+ s2p1y,
399
+ s2p2y,
400
+ hit,
401
+ seg1,
402
+ seg2,
403
+ i,
404
+ j;
405
+
406
+ // Sort segments by xmin, to allow efficient exclusion of segments with
407
+ // non-overlapping x extents.
408
+ sortSegmentIds(xx, ids); // sort by ascending xmin
409
+
410
+ i = 0;
411
+ while (i < lim) {
412
+ s1p1 = ids[i];
413
+ s1p2 = ids[i + 1];
414
+ s1p1x = xx[s1p1];
415
+ s1p2x = xx[s1p2];
416
+ s1p1y = yy[s1p1];
417
+ s1p2y = yy[s1p2];
418
+ // count++;
419
+
420
+ j = i;
421
+ while (j < lim) {
422
+ j += 2;
423
+ s2p1 = ids[j];
424
+ s2p1x = xx[s2p1];
425
+
426
+ if (s1p2x < s2p1x) break; // x extent of seg 2 is greater than seg 1: done with seg 1
427
+ //if (s1p2x <= s2p1x) break; // this misses point-segment intersections when s1 or s2 is vertical
428
+
429
+ s2p1y = yy[s2p1];
430
+ s2p2 = ids[j + 1];
431
+ s2p2x = xx[s2p2];
432
+ s2p2y = yy[s2p2];
433
+
434
+ // skip segments with non-overlapping y ranges
435
+ if (s1p1y >= s2p1y) {
436
+ if (s1p1y > s2p2y && s1p2y > s2p1y && s1p2y > s2p2y) continue;
437
+ } else {
438
+ if (s1p1y < s2p2y && s1p2y < s2p1y && s1p2y < s2p2y) continue;
439
+ }
440
+
441
+ // skip segments that are adjacent in a path (optimization)
442
+ // TODO: consider if this eliminates some cases that should
443
+ // be detected, e.g. spikes formed by unequal segments
444
+ if (s1p1 == s2p1 || s1p1 == s2p2 || s1p2 == s2p1 || s1p2 == s2p2) {
445
+ continue;
446
+ }
447
+
448
+ // test two candidate segments for intersection
449
+ hit = segmentIntersection(
450
+ s1p1x,
451
+ s1p1y,
452
+ s1p2x,
453
+ s1p2y,
454
+ s2p1x,
455
+ s2p1y,
456
+ s2p2x,
457
+ s2p2y,
458
+ );
459
+ if (hit) {
460
+ seg1 = [s1p1, s1p2];
461
+ seg2 = [s2p1, s2p2];
462
+ intersections.push(formatIntersection(hit, seg1, seg2, xx, yy));
463
+ if (hit.length == 4) {
464
+ // two collinear segments may have two endpoint intersections
465
+ intersections.push(
466
+ formatIntersection(hit.slice(2), seg1, seg2, xx, yy),
467
+ );
468
+ }
469
+ }
470
+ }
471
+ i += 2;
472
+ }
473
+ return intersections;
474
+ }
475
+
476
+ /**
477
+ * 2つの2D線分間の交差を判定し、交差点を計算します
478
+ *
479
+ * @param ax, ay - 第1線分の始点座標
480
+ * @param bx, by - 第1線分の終点座標
481
+ * @param cx, cy - 第2線分の始点座標
482
+ * @param dx, dy - 第2線分の終点座標
483
+ *
484
+ * @returns 以下のいずれか:
485
+ * - null: 交差なし
486
+ * - [x, y]: 1点での交差
487
+ * - [x1, y1, x2, y2]: 線分が重なる場合の2点での交差
488
+ *
489
+ * 特殊ケースの扱い:
490
+ * 1. 両線分の端点で接触する場合 → 交差としない
491
+ * 2. T字型に接触する場合 → 交差として扱う
492
+ * 3. 線分が同一直線上で部分的に重なる場合 → 重なる部分の端点を交差点として扱う(1または2点)
493
+ * - 例: 線分ABとCDが重なる場合、重なり部分の両端点が交差点となる
494
+ * - [x1, y1, x2, y2] の形式で返される
495
+ */
496
+ function segmentIntersection(
497
+ ax: number,
498
+ ay: number,
499
+ bx: number,
500
+ by: number,
501
+ cx: number,
502
+ cy: number,
503
+ dx: number,
504
+ dy: number,
505
+ ) {
506
+ const hit = segmentHit(ax, ay, bx, by, cx, cy, dx, dy);
507
+ let p = null;
508
+ if (hit) {
509
+ p = crossIntersection(ax, ay, bx, by, cx, cy, dx, dy);
510
+ if (!p) {
511
+ // collinear if p is null
512
+ p = collinearIntersection(ax, ay, bx, by, cx, cy, dx, dy);
513
+ } else if (endpointHit(ax, ay, bx, by, cx, cy, dx, dy)) {
514
+ p = null; // filter out segments that only intersect at an endpoint
515
+ }
516
+ }
517
+ return p;
518
+ }
519
+
520
+ // Source: Sedgewick, _Algorithms in C_
521
+ // (Tried various other functions that failed owing to floating point errors)
522
+ function segmentHit(
523
+ ax: number,
524
+ ay: number,
525
+ bx: number,
526
+ by: number,
527
+ cx: number,
528
+ cy: number,
529
+ dx: number,
530
+ dy: number,
531
+ ) {
532
+ return (
533
+ orient2D(ax, ay, bx, by, cx, cy) * orient2D(ax, ay, bx, by, dx, dy) <= 0 &&
534
+ orient2D(cx, cy, dx, dy, ax, ay) * orient2D(cx, cy, dx, dy, bx, by) <= 0
535
+ );
536
+ }
537
+
538
+ // returns a positive value if the points a, b, and c are arranged in
539
+ // counterclockwise order, a negative value if the points are in clockwise
540
+ // order, and zero if the points are collinear.
541
+ // Source: Jonathan Shewchuk http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf
542
+ function orient2D(
543
+ ax: number,
544
+ ay: number,
545
+ bx: number,
546
+ by: number,
547
+ cx: number,
548
+ cy: number,
549
+ ) {
550
+ return determinant2D(ax - cx, ay - cy, bx - cx, by - cy);
551
+ }
552
+
553
+ /**
554
+ * 2次元の行列式を計算
555
+ *
556
+ * @param a, b - 行列の第1行
557
+ * @param c, d - 行列の第2行
558
+ * @returns 行列式の値
559
+ */
560
+ function determinant2D(a: number, b: number, c: number, d: number) {
561
+ return a * d - b * c;
562
+ }
563
+
564
+ // Get intersection point if segments are non-collinear, else return null
565
+ // Assumes that segments have been intersect
566
+ function crossIntersection(
567
+ ax: number,
568
+ ay: number,
569
+ bx: number,
570
+ by: number,
571
+ cx: number,
572
+ cy: number,
573
+ dx: number,
574
+ dy: number,
575
+ ) {
576
+ let p = lineIntersection(ax, ay, bx, by, cx, cy, dx, dy);
577
+ let nearest;
578
+ if (p) {
579
+ // Re-order operands so intersection point is closest to a (better precision)
580
+ // Source: Jonathan Shewchuk http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf
581
+ nearest = nearestPoint(p[0], p[1], ax, ay, bx, by, cx, cy, dx, dy);
582
+ if (nearest == 1) {
583
+ p = lineIntersection(bx, by, ax, ay, cx, cy, dx, dy);
584
+ } else if (nearest == 2) {
585
+ p = lineIntersection(cx, cy, dx, dy, ax, ay, bx, by);
586
+ } else if (nearest == 3) {
587
+ p = lineIntersection(dx, dy, cx, cy, ax, ay, bx, by);
588
+ }
589
+ }
590
+ if (p) {
591
+ clampIntersectionPoint(p, ax, ay, bx, by, cx, cy, dx, dy);
592
+ }
593
+ return p;
594
+ }
595
+
596
+ function lineIntersection(
597
+ ax: number,
598
+ ay: number,
599
+ bx: number,
600
+ by: number,
601
+ cx: number,
602
+ cy: number,
603
+ dx: number,
604
+ dy: number,
605
+ ) {
606
+ const den = determinant2D(bx - ax, by - ay, dx - cx, dy - cy);
607
+ const eps = 1e-18;
608
+ let p;
609
+ if (den === 0) return null;
610
+ const m = orient2D(cx, cy, dx, dy, ax, ay) / den;
611
+ if (den <= eps && den >= -eps) {
612
+ // tiny denominator = low precision; using one of the endpoints as intersection
613
+ p = findEndpointInRange(ax, ay, bx, by, cx, cy, dx, dy);
614
+ /*if (!p) {
615
+ debug("[lineIntersection()]");
616
+ debugSegmentIntersection([], ax, ay, bx, by, cx, cy, dx, dy);
617
+ }*/
618
+ } else {
619
+ p = [ax + m * (bx - ax), ay + m * (by - ay)];
620
+ }
621
+ return p;
622
+ }
623
+
624
+ function findEndpointInRange(
625
+ ax: number,
626
+ ay: number,
627
+ bx: number,
628
+ by: number,
629
+ cx: number,
630
+ cy: number,
631
+ dx: number,
632
+ dy: number,
633
+ ) {
634
+ let p = null;
635
+ if (!outsideRange(ax, cx, dx) && !outsideRange(ay, cy, dy)) {
636
+ p = [ax, ay];
637
+ } else if (!outsideRange(bx, cx, dx) && !outsideRange(by, cy, dy)) {
638
+ p = [bx, by];
639
+ } else if (!outsideRange(cx, ax, bx) && !outsideRange(cy, ay, by)) {
640
+ p = [cx, cy];
641
+ } else if (!outsideRange(dx, ax, bx) && !outsideRange(dy, ay, by)) {
642
+ p = [dx, dy];
643
+ }
644
+ return p;
645
+ }
646
+
647
+ /**
648
+ * 点が線分の範囲外にあるかを判定
649
+ *
650
+ * @param a - 判定する点の座標
651
+ * @param b - 線分の一方の端点
652
+ * @param c - 線分のもう一方の端点
653
+ */
654
+ function outsideRange(a: number, b: number, c: number) {
655
+ let out;
656
+ if (b < c) {
657
+ out = a < b || a > c;
658
+ } else if (b > c) {
659
+ out = a > b || a < c;
660
+ } else {
661
+ out = a != b;
662
+ }
663
+ return out;
664
+ }
665
+
666
+ // Return id of nearest point to x, y, among x0, y0, x1, y1, ...
667
+ function nearestPoint(x: number, y: number, ...args: number[]) {
668
+ let minIdx = -1,
669
+ minDist = Infinity,
670
+ dist;
671
+ for (let i = 0, j = 0, n = args.length; j < n; i++, j += 2) {
672
+ dist = distanceSq(x, y, args[j], args[j + 1]);
673
+ if (dist < minDist) {
674
+ minDist = dist;
675
+ minIdx = i;
676
+ }
677
+ }
678
+ return minIdx;
679
+ }
680
+
681
+ function distanceSq(ax: number, ay: number, bx: number, by: number) {
682
+ const dx = ax - bx,
683
+ dy = ay - by;
684
+ return dx * dx + dy * dy;
685
+ }
686
+
687
+ function clampIntersectionPoint(
688
+ p: number[],
689
+ ax: number,
690
+ ay: number,
691
+ bx: number,
692
+ by: number,
693
+ cx: number,
694
+ cy: number,
695
+ dx: number,
696
+ dy: number,
697
+ ) {
698
+ // Handle intersection points that fall outside the x-y range of either
699
+ // segment by snapping to nearest endpoint coordinate. Out-of-range
700
+ // intersection points can be caused by floating point rounding errors
701
+ // when a segment is vertical or horizontal. This has caused problems when
702
+ // repeatedly applying bbox clipping along the same segment
703
+ let x = p[0],
704
+ y = p[1];
705
+ // assumes that segment ranges intersect
706
+ x = clampToCloseRange(x, ax, bx);
707
+ x = clampToCloseRange(x, cx, dx);
708
+ y = clampToCloseRange(y, ay, by);
709
+ y = clampToCloseRange(y, cy, dy);
710
+ p[0] = x;
711
+ p[1] = y;
712
+ }
713
+
714
+ function clampToCloseRange(a: number, b: number, c: number) {
715
+ let lim;
716
+ if (outsideRange(a, b, c)) {
717
+ lim = Math.abs(a - b) < Math.abs(a - c) ? b : c;
718
+ if (Math.abs(a - lim) > 1e-15) {
719
+ //debug("[clampToCloseRange()] large clamping interval", a, b, c);
720
+ }
721
+ a = lim;
722
+ }
723
+ return a;
724
+ }
725
+
726
+ // Assume segments s1 and s2 are collinear and overlap; find one or two internal endpoints
727
+ function collinearIntersection(
728
+ ax: number,
729
+ ay: number,
730
+ bx: number,
731
+ by: number,
732
+ cx: number,
733
+ cy: number,
734
+ dx: number,
735
+ dy: number,
736
+ ) {
737
+ const minX = Math.min(ax, bx, cx, dx),
738
+ maxX = Math.max(ax, bx, cx, dx),
739
+ minY = Math.min(ay, by, cy, dy),
740
+ maxY = Math.max(ay, by, cy, dy);
741
+ const useY = maxY - minY > maxX - minX;
742
+ let coords: number[] | null = [];
743
+
744
+ if (useY ? inside(ay, minY, maxY) : inside(ax, minX, maxX)) {
745
+ coords.push(ax, ay);
746
+ }
747
+ if (useY ? inside(by, minY, maxY) : inside(bx, minX, maxX)) {
748
+ coords.push(bx, by);
749
+ }
750
+ if (useY ? inside(cy, minY, maxY) : inside(cx, minX, maxX)) {
751
+ coords.push(cx, cy);
752
+ }
753
+ if (useY ? inside(dy, minY, maxY) : inside(dx, minX, maxX)) {
754
+ coords.push(dx, dy);
755
+ }
756
+ if (coords.length != 2 && coords.length != 4) {
757
+ coords = null;
758
+ //debug("Invalid collinear segment intersection", coords);
759
+ } else if (
760
+ coords.length == 4 &&
761
+ coords[0] == coords[2] &&
762
+ coords[1] == coords[3]
763
+ ) {
764
+ // segs that meet in the middle don't count
765
+ coords = null;
766
+ }
767
+ return coords;
768
+ }
769
+
770
+ function endpointHit(
771
+ ax: number,
772
+ ay: number,
773
+ bx: number,
774
+ by: number,
775
+ cx: number,
776
+ cy: number,
777
+ dx: number,
778
+ dy: number,
779
+ ) {
780
+ return (
781
+ (ax == cx && ay == cy) ||
782
+ (ax == dx && ay == dy) ||
783
+ (bx == cx && by == cy) ||
784
+ (bx == dx && by == dy)
785
+ );
786
+ }
787
+
788
+ function inside(x: number, minX: number, maxX: number) {
789
+ return x > minX && x < maxX;
790
+ }
791
+
792
+ // @xx array of x coords
793
+ // @ids an array of segment endpoint ids [a0, b0, a1, b1, ...]
794
+ // Sort @ids in place so that xx[a(n)] <= xx[b(n)] and xx[a(n)] <= xx[a(n+1)]
795
+ function sortSegmentIds(xx: Float64Array, ids: Uint32Array) {
796
+ orderSegmentIds(xx, ids);
797
+ quicksortSegmentIds(xx, ids, 0, ids.length - 2);
798
+ }
799
+
800
+ function orderSegmentIds(xx: Float64Array, ids: Uint32Array) {
801
+ for (let i = 0, n = ids.length; i < n; i += 2) {
802
+ if (xx[ids[i]] > xx[ids[i + 1]]) {
803
+ swap(ids, i, i + 1);
804
+ }
805
+ }
806
+ }
807
+
808
+ function swap(ids: Uint32Array, i: number, j: number) {
809
+ const tmp = ids[i];
810
+ ids[i] = ids[j];
811
+ ids[j] = tmp;
812
+ }
813
+
814
+ function quicksortSegmentIds(
815
+ a: Float64Array,
816
+ ids: Uint32Array,
817
+ lo: number,
818
+ hi: number,
819
+ ) {
820
+ let i = lo,
821
+ j = hi,
822
+ pivot,
823
+ tmp;
824
+ while (i < hi) {
825
+ pivot = a[ids[((lo + hi) >> 2) << 1]]; // avoid n^2 performance on sorted arrays
826
+ while (i <= j) {
827
+ while (a[ids[i]] < pivot) i += 2;
828
+ while (a[ids[j]] > pivot) j -= 2;
829
+ if (i <= j) {
830
+ tmp = ids[i];
831
+ ids[i] = ids[j];
832
+ ids[j] = tmp;
833
+ tmp = ids[i + 1];
834
+ ids[i + 1] = ids[j + 1];
835
+ ids[j + 1] = tmp;
836
+ i += 2;
837
+ j -= 2;
838
+ }
839
+ }
840
+
841
+ if (j - lo < 40) insertionSortSegmentIds(a, ids, lo, j);
842
+ else quicksortSegmentIds(a, ids, lo, j);
843
+ if (hi - i < 40) {
844
+ insertionSortSegmentIds(a, ids, i, hi);
845
+ return;
846
+ }
847
+ lo = i;
848
+ j = hi;
849
+ }
850
+ }
851
+
852
+ function insertionSortSegmentIds(
853
+ arr: Float64Array,
854
+ ids: Uint32Array,
855
+ start: number,
856
+ end: number,
857
+ ) {
858
+ let id, id2;
859
+ for (let j = start + 2; j <= end; j += 2) {
860
+ id = ids[j];
861
+ id2 = ids[j + 1];
862
+ let i;
863
+ for (i = j - 2; i >= start && arr[id] < arr[ids[i]]; i -= 2) {
864
+ ids[i + 2] = ids[i];
865
+ ids[i + 3] = ids[i + 1];
866
+ }
867
+ ids[i + 2] = id;
868
+ ids[i + 3] = id2;
869
+ }
870
+ }
871
+
872
+ function formatIntersection(
873
+ xy: number[],
874
+ s1: number[],
875
+ s2: number[],
876
+ xx: Float64Array,
877
+ yy: Float64Array,
878
+ ) {
879
+ const x = xy[0],
880
+ y = xy[1];
881
+ s1 = formatIntersectingSegment(x, y, s1[0], s1[1], xx, yy);
882
+ s2 = formatIntersectingSegment(x, y, s2[0], s2[1], xx, yy);
883
+ const a = s1[0] < s2[0] ? s1 : s2;
884
+ const b = a == s1 ? s2 : s1;
885
+ return { x, y, a, b };
886
+ }
887
+
888
+ function formatIntersectingSegment(
889
+ x: number,
890
+ y: number,
891
+ id1: number,
892
+ id2: number,
893
+ xx: Float64Array,
894
+ yy: Float64Array,
895
+ ) {
896
+ let i = id1 < id2 ? id1 : id2,
897
+ j = i === id1 ? id2 : id1;
898
+ if (xx[i] == x && yy[i] == y) {
899
+ j = i;
900
+ } else if (xx[j] == x && yy[j] == y) {
901
+ i = j;
902
+ }
903
+ return [i, j];
904
+ }
905
+
906
+ /**
907
+ * 交差判定結果から重複を除去
908
+ *
909
+ * @param arr - 交差点情報の配列
910
+ * @returns 重複を除去した交差点情報の配列
911
+ */
912
+ function dedupIntersections(arr: IntersectionPoint[]) {
913
+ const index: Record<string, boolean> = {};
914
+ return arr.filter((o: IntersectionPoint) => {
915
+ const key = getIntersectionKey(o);
916
+ if (key in index) {
917
+ return false;
918
+ }
919
+ index[key] = true;
920
+ return true;
921
+ });
922
+ }
923
+
924
+ // Get an indexable key from an intersection object
925
+ // Assumes that vertex ids of o.a and o.b are sorted
926
+ function getIntersectionKey(o: IntersectionPoint) {
927
+ return `${o.a.join(",")};${o.b.join(",")}`;
928
+ }
929
+
930
+ // Constructor takes arrays of coords: xx, yy, zz (optional)
931
+ //
932
+ class ArcIter {
933
+ _i = 0;
934
+ _n = 0;
935
+ _inc = 1;
936
+ _xx: Float64Array;
937
+ _yy: Float64Array;
938
+ i = 0;
939
+ x = 0;
940
+ y = 0;
941
+
942
+ constructor(xx: Float64Array, yy: Float64Array) {
943
+ this._xx = xx;
944
+ this._yy = yy;
945
+ }
946
+ }
947
+
948
+ function calcArcBounds(
949
+ xx: Float64Array,
950
+ yy: Float64Array,
951
+ start: number,
952
+ len: number,
953
+ ) {
954
+ let i = start | 0;
955
+ const n = isNaN(len) ? xx.length - i : len + i;
956
+ let x: number,
957
+ y: number,
958
+ xmin: number,
959
+ ymin: number,
960
+ xmax: number,
961
+ ymax: number;
962
+ if (n > 0) {
963
+ xmin = xmax = xx[i];
964
+ ymin = ymax = yy[i];
965
+ } else return [undefined, undefined, undefined, undefined];
966
+ for (i++; i < n; i++) {
967
+ x = xx[i];
968
+ y = yy[i];
969
+ if (x < xmin) xmin = x;
970
+ if (x > xmax) xmax = x;
971
+ if (y < ymin) ymin = y;
972
+ if (y > ymax) ymax = y;
973
+ }
974
+ return [xmin, ymin, xmax, ymax];
975
+ }
976
+
977
+ class Bounds {
978
+ xmin?: number;
979
+ ymin?: number;
980
+ xmax?: number;
981
+ ymax?: number;
982
+
983
+ constructor(...args: number[] | [Bounds] | []) {
984
+ if (args.length > 0) {
985
+ this.setBounds(args as number[]);
986
+ }
987
+ }
988
+
989
+ // Return a bounding box with the same extent as this one.
990
+ cloneBounds() {
991
+ return this.clone();
992
+ }
993
+
994
+ clone() {
995
+ // alias so child classes can override clone()
996
+ return new Bounds(
997
+ this.xmin!,
998
+ this.ymin!,
999
+ this.xmax!,
1000
+ this.ymax!,
1001
+ );
1002
+ }
1003
+
1004
+ width() {
1005
+ return this.xmax! - this.xmin! || 0;
1006
+ }
1007
+
1008
+ height() {
1009
+ return this.ymax! - this.ymin! || 0;
1010
+ }
1011
+
1012
+ setBounds(a: number | number[] | Bounds, b?: number, c?: number, d?: number) {
1013
+ let xmin: number, ymin: number, xmax: number, ymax: number;
1014
+
1015
+ if (arguments.length == 1) {
1016
+ // assume first arg is a Bounds or array
1017
+ if (isArrayLike(a)) {
1018
+ const arr = a as number[];
1019
+ xmin = arr[0];
1020
+ ymin = arr[1];
1021
+ xmax = arr[2];
1022
+ ymax = arr[3];
1023
+ } else {
1024
+ const bounds = a as Bounds;
1025
+ xmin = bounds.xmin!;
1026
+ ymin = bounds.ymin!;
1027
+ xmax = bounds.xmax!;
1028
+ ymax = bounds.ymax!;
1029
+ }
1030
+ } else {
1031
+ xmin = a as number;
1032
+ ymin = b!;
1033
+ xmax = c!;
1034
+ ymax = d!;
1035
+ }
1036
+
1037
+ this.xmin = xmin;
1038
+ this.ymin = ymin;
1039
+ this.xmax = xmax;
1040
+ this.ymax = ymax;
1041
+ if (xmin > xmax || ymin > ymax) this.update();
1042
+ // error("Bounds#setBounds() min/max reversed:", a, b, c, d);
1043
+ return this;
1044
+ }
1045
+
1046
+ update() {
1047
+ let tmp: number;
1048
+ if (this.xmin! > this.xmax!) {
1049
+ tmp = this.xmin!;
1050
+ this.xmin = this.xmax;
1051
+ this.xmax = tmp;
1052
+ }
1053
+ if (this.ymin! > this.ymax!) {
1054
+ tmp = this.ymin!;
1055
+ this.ymin = this.ymax;
1056
+ this.ymax = tmp;
1057
+ }
1058
+ }
1059
+
1060
+ mergeBounds(bb: number | number[] | Bounds, ...args: number[]) {
1061
+ let a: number, b: number, c: number, d: number;
1062
+ if (bb instanceof Bounds) {
1063
+ a = bb.xmin!;
1064
+ b = bb.ymin!;
1065
+ c = bb.xmax!;
1066
+ d = bb.ymax!;
1067
+ } else if (args.length == 3) {
1068
+ a = bb as number;
1069
+ b = args[0];
1070
+ c = args[1];
1071
+ d = args[2];
1072
+ } else if ((bb as number[]).length == 4) {
1073
+ // assume array: [xmin, ymin, xmax, ymax]
1074
+ a = (bb as number[])[0];
1075
+ b = (bb as number[])[1];
1076
+ c = (bb as number[])[2];
1077
+ d = (bb as number[])[3];
1078
+ } else {
1079
+ error("Bounds#mergeBounds() invalid argument:", bb);
1080
+ }
1081
+
1082
+ if (this.xmin === void 0) {
1083
+ this.setBounds(a!, b!, c!, d!);
1084
+ } else {
1085
+ if (a! < this.xmin) this.xmin = a!;
1086
+ if (b! < this.ymin!) this.ymin = b!;
1087
+ if (c! > this.xmax!) this.xmax = c!;
1088
+ if (d! > this.ymax!) this.ymax = d!;
1089
+ }
1090
+ return this;
1091
+ }
1092
+ }