@immugio/three-math-extensions 0.0.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/Line2D.ts ADDED
@@ -0,0 +1,615 @@
1
+ import { Point2 } from "./Point2";
2
+ import { Vector2 } from "three";
3
+ import { Vec2 } from "./Vec2";
4
+
5
+ export class Line2D {
6
+
7
+ constructor(public start: Vec2, public end: Vec2, public index: number = 0) {
8
+ }
9
+
10
+ public static fromCoordinates(x1: number, y1: number, x2: number, y2: number, index: number = 0): Line2D {
11
+ return new Line2D(new Vec2(x1, y1), new Vec2(x2, y2), index);
12
+ }
13
+
14
+ public static fromPoints(p1: Point2, p2: Point2, index: number = 0): Line2D {
15
+ return new Line2D(new Vec2(p1.x, p1.y), new Vec2(p2.x, p2.y), index);
16
+ }
17
+
18
+ public static fromPolygon(polygon: Point2[]): Line2D[] {
19
+ if (polygon[0].x === polygon[polygon.length - 1].x && polygon[0].y === polygon[polygon.length - 1].y) {
20
+ polygon = polygon.slice(0, polygon.length - 1);
21
+ }
22
+
23
+ return polygon.map((p, i) => {
24
+ const next = polygon[(i + 1) % polygon.length];
25
+ return Line2D.fromPoints(p, next, i);
26
+ });
27
+ }
28
+
29
+ public static fromLength(length: number): Line2D {
30
+ return Line2D.fromCoordinates(-length / 2, 0, length / 2, 0);
31
+ }
32
+
33
+ public get center(): Vec2 {
34
+ return new Vec2((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2);
35
+ }
36
+
37
+ /**
38
+ * Set the center of the line to the provided point. Length and direction remain unchanged.
39
+ * Modifies this line.
40
+ * @param value
41
+ */
42
+ public set center(value: Point2) {
43
+ const current = this.center;
44
+ const diffX = current.x - value.x;
45
+ const diffY = current.y - value.y;
46
+ this.start.x -= diffX;
47
+ this.start.y -= diffY;
48
+ this.end.x -= diffX;
49
+ this.end.y -= diffY;
50
+ }
51
+
52
+ /**
53
+ * Set the center of the line to the provided point. Length and direction remain unchanged.
54
+ * Modifies this line.
55
+ * @param value
56
+ */
57
+ public setCenter(value: Point2): Line2D {
58
+ this.center = value;
59
+ return this;
60
+ }
61
+
62
+ /*
63
+ * Extends or reduces the line by the given length while keeping the center of the line constant.
64
+ * Modifies this line.
65
+ */
66
+ public resize(amount: number): Line2D {
67
+ this.moveStartPoint(amount / 2);
68
+ this.moveEndPoint(amount / 2);
69
+ return this;
70
+ }
71
+
72
+ /*
73
+ * Moves start point on the line by the given amount. Plus values move the point further away from the center.
74
+ * Modifies this line.
75
+ */
76
+ public moveStartPoint(amount: number): Line2D {
77
+ const p1 = this.movePointOnThisLine(this.start, amount);
78
+ this.start.copy(p1);
79
+
80
+ return this;
81
+ }
82
+
83
+ /**
84
+ * Moves end point on the line by the given amount. Plus values move the point further away from the center.
85
+ * Modifies this line.
86
+ */
87
+ public moveEndPoint(amount: number): Line2D {
88
+ const p2 = this.movePointOnThisLine(this.end, amount);
89
+ this.end.copy(p2);
90
+
91
+ return this;
92
+ }
93
+
94
+ private movePointOnThisLine(point: Point2, amount: number): Vec2 {
95
+ const vec = new Vector2(this.center.x - point.x, this.center.y - point.y);
96
+ const length = vec.length();
97
+ vec.normalize().multiplyScalar(length + amount);
98
+
99
+ return new Vec2(this.center.x - vec.x,this.center.y - vec.y);
100
+ }
101
+
102
+ /**
103
+ * Set the length of this line. Center and direction remain unchanged.
104
+ * Modifies this line.
105
+ * @param l
106
+ */
107
+ public set length(l: number) {
108
+ const length = this.length;
109
+ this.resize(l - length);
110
+ }
111
+
112
+ public get length(): number {
113
+ return this.start.distanceTo(this.end);
114
+ }
115
+
116
+ /**
117
+ * Returns the start and end points of the line as an array.
118
+ * Endpoints are not cloned.
119
+ */
120
+ public get endpoints(): Vec2[] {
121
+ return [this.start, this.end];
122
+ }
123
+
124
+ /**
125
+ * Returns the direction of this line.
126
+ */
127
+ public get direction(): Vec2 {
128
+ return this.end.clone().sub(this.start).normalize();
129
+ }
130
+
131
+ /**
132
+ * Inverts the direction of the line.
133
+ * Modifies this line.
134
+ */
135
+ public flip(): Line2D {
136
+ const temp = this.start.clone();
137
+ this.start.copy(this.end);
138
+ this.end.copy(temp);
139
+
140
+ return this;
141
+ }
142
+
143
+ /**
144
+ * Rotates the line around the center by the given angle in radians.
145
+ * Modifies this line.
146
+ * @param radians Positive values rotate counter-clockwise.
147
+ * @param center
148
+ */
149
+ public rotate(radians: number, center: Vec2 = this.center): Line2D {
150
+ this.start.rotateAround(center, radians);
151
+ this.end.rotateAround(center, radians);
152
+
153
+ return this;
154
+ }
155
+
156
+ /**
157
+ * Move the line by the given vector.
158
+ * Modifies this line.
159
+ */
160
+ public translate(value: Point2): Line2D {
161
+ this.start.x += value.x;
162
+ this.start.y += value.y;
163
+ this.end.x += value.x;
164
+ this.end.y += value.y;
165
+
166
+ return this;
167
+ }
168
+
169
+ /**
170
+ * Move the line to its left by the given amount.
171
+ * Modifies this line.
172
+ */
173
+ public translateLeft(amount: number): Line2D {
174
+ const translation = this.direction.rotateAround(new Vec2(), -Math.PI / 2).multiplyScalar(amount);
175
+ return this.translate(translation);
176
+ }
177
+
178
+ /**
179
+ * Move the line to its right by the given amount.
180
+ * Modifies this line.
181
+ */
182
+ public translateRight(amount: number): Line2D {
183
+ const translation = this.direction.rotateAround(new Vec2(), Math.PI / 2).multiplyScalar(amount);
184
+ return this.translate(translation);
185
+ }
186
+
187
+ /**
188
+ * Returns true when the point is actually inside the (finite) line segment.
189
+ * https://jsfiddle.net/c06zdxtL/2/
190
+ * https://stackoverflow.com/questions/6865832/detecting-if-a-point-is-of-a-line-segment/6877674
191
+ * @param point: Point2
192
+ */
193
+ public isPointOnLineSection(point: Point2): boolean {
194
+ if (!this.isPointOnInfiniteLine(point)) {
195
+ return false;
196
+ }
197
+
198
+ return this.isPointBesideLineSection(point);
199
+ }
200
+
201
+ /**
202
+ * Returns true when the point is beside the line **segment** and within the maxDistance.
203
+ * @param point
204
+ * @param maxDistance
205
+ */
206
+ public isPointCloseToAndBesideLineSection(point: Point2, maxDistance: number): boolean {
207
+ const distance = this.distanceToPointOnInfiniteLine(point);
208
+ return distance <= maxDistance && this.isPointBesideLineSection(point);
209
+ }
210
+
211
+ /**
212
+ * Returns true when the point is beside the line **segment**
213
+ * @param point
214
+ */
215
+ public isPointBesideLineSection(point: Point2): boolean {
216
+ const l2 = (((this.end.x - this.start.x) * (this.end.x - this.start.x)) + ((this.end.y - this.start.y) * (this.end.y - this.start.y)));
217
+ if (l2 == 0) return false;
218
+ const r = (((point.x - this.start.x) * (this.end.x - this.start.x)) + ((point.y - this.start.y) * (this.end.y - this.start.y))) / l2;
219
+
220
+ return (0 <= r) && (r <= 1);
221
+ }
222
+
223
+ /**
224
+ * Returns true when the point is on the **infinite** line.
225
+ * @param point
226
+ */
227
+ public isPointOnInfiniteLine(point: Point2): boolean {
228
+ return (point.y - this.start.y) * (this.end.x - this.start.x) === (this.end.y - this.start.y) * (point.x - this.start.x);
229
+ }
230
+
231
+ /**
232
+ * Returns true if other line is collinear and overlaps or at least touching this line.
233
+ * @param other
234
+ */
235
+ public isCollinearWithTouchOrOverlap(other: Line2D): boolean {
236
+ if (!this.isPointOnInfiniteLine(other.start) || !this.isPointOnInfiniteLine(other.end)) {
237
+ return false;
238
+ }
239
+
240
+ return this.isPointOnLineSection(other.start) || this.isPointOnLineSection(other.end) ||
241
+ other.isPointOnLineSection(this.start) || other.isPointOnLineSection(this.end);
242
+ }
243
+
244
+ /**
245
+ * Returns true if there is any overlap between this line and the @other line section.
246
+ */
247
+ public overlaps(other: Line2D): boolean {
248
+ if (!this.isCollinearWithTouchOrOverlap(other)) {
249
+ return false;
250
+ }
251
+
252
+ if (this.start.equals(other.start) && this.end.equals(other.end)) {
253
+ return true;
254
+ }
255
+
256
+ return !this.start.equals(other.end) && !this.end.equals(other.start);
257
+ }
258
+
259
+ /**
260
+ * Logical AND of this and the other line section.
261
+ * @param other
262
+ */
263
+ public getOverlap(other: Line2D): Line2D {
264
+ if (!this.overlaps(other)) {
265
+ return null;
266
+ }
267
+
268
+ if (this.equals(other)) {
269
+ return this.clone();
270
+ }
271
+
272
+ const points = [
273
+ [this.start, this.end].filter(thisPoint => other.isPointOnLineSection(thisPoint)),
274
+ [other.start, other.end].filter(otherPoint => this.isPointOnLineSection(otherPoint))
275
+ ].flat();
276
+
277
+ if (points.length !== 2) {
278
+ return null;
279
+ }
280
+
281
+ const overlap = Line2D.fromPoints(points[0], points[1]);
282
+ if (overlap.direction.manhattanDistanceTo(this.direction) > Number.EPSILON) {
283
+ overlap.flip();
284
+ }
285
+
286
+ return overlap;
287
+ }
288
+
289
+ /**
290
+ * Joins a copy of @line with the @other line.
291
+ * Other must be parallel to this line.
292
+ * Returns null if there is no overlap
293
+ * Clones the line, does not modify.
294
+ * @param line
295
+ * @param other
296
+ */
297
+ public static joinLine(line: Line2D, other: Line2D): Line2D {
298
+ if (!line.isCollinearWithTouchOrOverlap(other)) {
299
+ return null;
300
+ }
301
+
302
+ const p1 = !line.isPointOnLineSection(other.start) ? other.start : line.start;
303
+ const p2 = !line.isPointOnLineSection(other.end) ? other.end : line.end;
304
+
305
+ return new Line2D(p1.clone(), p2.clone(), line.index);
306
+ }
307
+
308
+ /**
309
+ * Joins provided lines into several joined lines.
310
+ * Lines must be parallel for joining.
311
+ * Clone the lines, does not modify.
312
+ * @param lines
313
+ */
314
+ public static joinLines(lines: Line2D[]): Line2D[] {
315
+ if (lines.length < 2) {
316
+ return lines.map(x => x.clone());
317
+ }
318
+
319
+ const toProcess = lines.slice();
320
+ const result: Line2D[] = [];
321
+
322
+ while (toProcess.length > 0) {
323
+
324
+ const current = toProcess.pop();
325
+ let joined = false;
326
+
327
+ for (let i = 0; i < result.length; i++) {
328
+ const other = result[i];
329
+ const joinedLine = Line2D.joinLine(current, other);
330
+ if (joinedLine) {
331
+ result[i] = joinedLine;
332
+ joined = true;
333
+ break;
334
+ }
335
+ }
336
+
337
+ if (!joined) {
338
+ result.push(current.clone());
339
+ }
340
+ }
341
+
342
+ return result;
343
+ }
344
+
345
+ /**
346
+ * Divides the Line3D into a number of segments of the given length.
347
+ * Clone the line, does not modify.
348
+ * @param maxSegmentLength number
349
+ */
350
+ public chunk(maxSegmentLength: number): Line2D[] {
351
+ const source = this.clone();
352
+ const result: Line2D[] = [];
353
+ while (source.length > maxSegmentLength) {
354
+ const chunk = source.clone();
355
+ chunk.moveEndPoint(-(chunk.length - maxSegmentLength));
356
+ result.push(chunk);
357
+ source.start = chunk.end.clone();
358
+ }
359
+ result.push(source);
360
+ return result;
361
+ }
362
+
363
+ /**
364
+ * Returns the closest point parameter on the **infinite** line to the given point.
365
+ * @param point
366
+ */
367
+ public closestPointToPointParameterOnInfiniteLine(point: Vector2): number {
368
+ const startP = new Vec2().subVectors(point, this.start);
369
+ const startEnd = new Vec2().subVectors(this.end, this.start);
370
+
371
+ const startEnd2 = startEnd.dot(startEnd);
372
+ const startEnd_startP = startEnd.dot(startP);
373
+
374
+ return startEnd_startP / startEnd2;
375
+ }
376
+
377
+ /**
378
+ * Returns the closest point on the **infinite** line to the given point.
379
+ * @param point
380
+ */
381
+ public closestPointOnInfiniteLine(point: Vector2): Vec2 {
382
+ const t = this.closestPointToPointParameterOnInfiniteLine(point);
383
+ return new Vec2().subVectors(this.end, this.start).multiplyScalar(t).add(this.start);
384
+ }
385
+
386
+ /**
387
+ * Returns the closest point on the line **section** to the given point.
388
+ * @param point
389
+ */
390
+ public closestPointOnLine(point: Vector2): Vec2 {
391
+ const closestPoint = this.closestPointOnInfiniteLine(point);
392
+ if (this.isPointOnLineSection(closestPoint)) {
393
+ return closestPoint;
394
+ }
395
+
396
+ return closestPoint.distanceTo(this.start) < closestPoint.distanceTo(this.end) ? this.start : this.end;
397
+ }
398
+
399
+ /**
400
+ * Returns the distance between the **infinite** line and the point.
401
+ * @param point
402
+ */
403
+ public distanceToPointOnInfiniteLine(point: Point2): number {
404
+ const l2 = (((this.end.x - this.start.x) * (this.end.x - this.start.x)) + ((this.end.y - this.start.y) * (this.end.y - this.start.y)));
405
+ if (l2 == 0) return Infinity;
406
+ const s = (((this.start.y - point.y) * (this.end.x - this.start.x)) - ((this.start.x - point.x) * (this.end.y - this.start.y))) / l2;
407
+ return Math.abs(s) * Math.sqrt(l2);
408
+ }
409
+
410
+ /**
411
+ * Returns lines that are the result of clipping @source line by the @clips.
412
+ * Clips must be parallel to this line.
413
+ * Clones the line, does not modify this.
414
+ * @param source
415
+ * @param clips
416
+ */
417
+ public static clipLines(source: Line2D, clips: Line2D[]): Line2D[] {
418
+ if (!clips || clips.length === 0) return [source];
419
+
420
+ clips = clips.map(c => {
421
+ const copy = c.clone();
422
+ if (copy.direction.manhattanDistanceTo(source.direction) > Number.EPSILON) {
423
+ copy.flip();
424
+ }
425
+ return copy;
426
+ });
427
+
428
+ const free: Line2D[] = [];
429
+ const sources = [source];
430
+
431
+ while (sources.length > 0) {
432
+
433
+ let isFree = true;
434
+
435
+ const tested = sources.pop();
436
+
437
+ for (const cover of clips) {
438
+
439
+ if (tested.overlaps(cover)) {
440
+ isFree = false;
441
+ const subtracted = this.subtractSingle(tested, cover);
442
+ sources.push(...subtracted);
443
+ break;
444
+ }
445
+ }
446
+
447
+ if (isFree) free.push(tested);
448
+ }
449
+
450
+ return this.order(source, free);
451
+ }
452
+
453
+ /**
454
+ * Returns the original line section split into two parts, if the line **sections** overlap, otherwise null
455
+ */
456
+ public splitAtIntersection(other: Line2D, tolerance: number = 0): Line2D[] {
457
+ const intersection = this.intersect(other);
458
+ if (intersection) {
459
+ if (this.isPointCloseToAndBesideLineSection(intersection, tolerance) && other.isPointCloseToAndBesideLineSection(intersection, tolerance)) {
460
+ return [
461
+ Line2D.fromPoints(this.start, intersection),
462
+ Line2D.fromPoints(intersection, this.end)
463
+ ];
464
+ }
465
+ }
466
+
467
+ return null;
468
+ }
469
+
470
+ /**
471
+ * If lines **sections** overlap, returns the original line section split into two parts, sorted by length
472
+ * Else, if the **infinite** lines intersect, returns a new line extended to the intersection point
473
+ * Otherwise, null if the lines are parallel and do not intersect
474
+ */
475
+ public splitAtOrExtendToIntersection(other: Line2D): Line2D[] {
476
+ const intersection = this.intersect(other);
477
+ if (intersection) {
478
+ return [
479
+ Line2D.fromPoints(this.start, intersection),
480
+ Line2D.fromPoints(intersection, this.end)
481
+ ].filter(x => x.length > Number.EPSILON).sort((a, b) => a.length - b.length);
482
+ }
483
+
484
+ return null;
485
+ }
486
+
487
+ private static order(source: Line2D, lines: Line2D[]): Line2D[] {
488
+ if (source.start.x < source.end.x) {
489
+ lines.sort((a, b) => a.start.x - b.start.x);
490
+ } else if (source.start.x > source.end.x) {
491
+ lines.sort((a, b) => b.start.x - a.start.x);
492
+ }
493
+
494
+ if (source.start.y < source.end.y) {
495
+ lines.sort((a, b) => a.start.y - b.start.y);
496
+ } else if (source.start.y > source.end.y) {
497
+ lines.sort((a, b) => b.start.y - a.start.y);
498
+ }
499
+
500
+ return lines;
501
+ }
502
+
503
+ private static subtractSingle(source: Line2D, cover: Line2D): Line2D[] {
504
+ const left = source.clone();
505
+ left.end.copy(cover.start);
506
+
507
+ const right = source.clone();
508
+ right.start.copy(cover.end);
509
+
510
+ return [left, right].filter(x => x.length > 1 && x.direction.manhattanDistanceTo(source.direction) < Number.EPSILON);
511
+ }
512
+
513
+ /**
514
+ * If other line is not contained within this line, the excess is trimmed.
515
+ * Does not create a copy. Provided line is modified.
516
+ * @param lineToTrim
517
+ */
518
+ public trimExcess(lineToTrim: Line2D): void {
519
+ if (!this.isCollinearWithTouchOrOverlap(lineToTrim)) {
520
+ return;
521
+ }
522
+
523
+ if (!this.isPointOnLineSection(lineToTrim.start)) {
524
+ const closest = this.closestPointOnLine(lineToTrim.start);
525
+ lineToTrim.start.copy(closest);
526
+ }
527
+
528
+ if (!this.isPointOnLineSection(lineToTrim.end)) {
529
+ const closest = this.closestPointOnLine(lineToTrim.end);
530
+ lineToTrim.end.copy(closest);
531
+ }
532
+ }
533
+
534
+ /**
535
+ * If other line is shorter than this, endpoints are moved to extend other
536
+ * Does not create a copy. Provided line is modified.
537
+ * @param lineToExtend
538
+ * @param tolerance
539
+ */
540
+ public extendToEnds(lineToExtend: Line2D, tolerance: number): void {
541
+ if (!this.isCollinearWithTouchOrOverlap(lineToExtend)) {
542
+ console.log("Can't clip, lines that are not collinear with touch or overlap");
543
+ return;
544
+ }
545
+
546
+ if (this.start.distanceTo(lineToExtend.start) <= tolerance) {
547
+ lineToExtend.start.copy(this.start);
548
+ }
549
+
550
+ if (this.end.distanceTo(lineToExtend.end) <= tolerance) {
551
+ lineToExtend.end.copy(this.end);
552
+ }
553
+ }
554
+
555
+ /**
556
+ * Returns the intersection point of two lines. The lines are assumed to be infinite.
557
+ */
558
+ public intersect(other: Line2D): Vec2 {
559
+ // Check if none of the lines are of length 0
560
+ if ((this.start.x === this.end.x && this.start.y === this.end.y) || (other.start.x === other.end.x && other.start.y === other.end.y)) {
561
+ return null;
562
+ }
563
+
564
+ const denominator = ((other.end.y - other.start.y) * (this.end.x - this.start.x) - (other.end.x - other.start.x) * (this.end.y - this.start.y));
565
+
566
+ // Lines are parallel
567
+ if (denominator === 0) {
568
+ return null;
569
+ }
570
+
571
+ const ua = ((other.end.x - other.start.x) * (this.start.y - other.start.y) - (other.end.y - other.start.y) * (this.start.x - other.start.x)) / denominator;
572
+
573
+ // Return an object with the x and y coordinates of the intersection
574
+ const x = this.start.x + ua * (this.end.x - this.start.x);
575
+ const y = this.start.y + ua * (this.end.y - this.start.y);
576
+
577
+ return new Vec2(x, y);
578
+ }
579
+
580
+ /**
581
+ * Check that the infinite lines intersect and that they are in the specified angle to each other
582
+ * @param other Line
583
+ * @param expectedAngleInRads number
584
+ */
585
+ public hasIntersectionWithAngle(other: Line2D, expectedAngleInRads: number): Vec2 {
586
+ const angle = this.direction.angle();
587
+ const otherAngle = other.direction.angle();
588
+ const actualAngle = Math.abs(angle - otherAngle);
589
+
590
+ if (Math.abs(actualAngle - expectedAngleInRads) < Number.EPSILON) {
591
+ const intersection = this.intersect(other);
592
+ if (intersection && this.isPointOnLineSection(intersection) && other.isPointOnLineSection(intersection)) {
593
+
594
+ return intersection;
595
+ }
596
+ }
597
+
598
+ return null;
599
+ }
600
+
601
+ /**
602
+ * Deep clone of this line
603
+ */
604
+ public clone(): Line2D {
605
+ return new Line2D(this.start.clone(), this.end.clone(), this.index);
606
+ }
607
+
608
+ public toString(): string {
609
+ return `Line(${this.start.x}, ${this.start.y}, ${this.end.x}, ${this.end.y})`;
610
+ }
611
+
612
+ public equals(other: Line2D): boolean {
613
+ return !!other && this.start.equals(other.start) && this.end.equals(other.end);
614
+ }
615
+ }