1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
/*!
A module containing the [`LineSegment`] struct, one of the available variants
for the [`Segment`](crate::segment::Segment) enum.
The [`LineSegment`] is one of the "primitive" geometric types defined in this
crate (implementing the [`Primitive`] type). Wrapped in the
[`Segment`](crate::segment::Segment) enum, it serves as a fundamental building
block of composite geometric types such as the
[`Polysegment`](crate::polysegment::Polysegment).
See the module documentation of [segment](crate::segment) for more.
Most users should interact with this module through the [`LineSegment`] type
itself; see its documentation for details on construction, invariants, and
usage.
*/
use std::f64::INFINITY;
use crate::{
primitive::{Primitive, PrimitiveIntersections},
{CentroidData, Rotation2, Transformation},
};
use approx::ulps_eq;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use bounding_box::{BoundingBox, ToBoundingBox};
/**
A straight, directed connection between a start and an end / stop point.
*/
#[doc = ""]
#[cfg_attr(
feature = "doc-images",
doc = "![Line segment example][example_line_segment]"
)]
#[cfg_attr(
feature = "doc-images",
embed_doc_image::embed_doc_image("example_line_segment", "docs/img/example_line_segment.svg")
)]
#[cfg_attr(
not(feature = "doc-images"),
doc = "**Doc images not enabled**. Compile docs with
`cargo doc --features 'doc-images'` and Rust version >= 1.54."
)]
/**
By definition, start and end point must not be identical, because otherwise the
line segment would degenerate to a point. The finite length defined by those two
points is the main difference between this type and the
[`Line`](crate::line::Line) struct. It is trivial to convert a [`LineSegment`]
to a [`Line`](crate::line::Line) via the corresponding [`From`]
/ [`Into`] implementations, however a direct conversion in the other direction
is not possible because the start and end point information is lost.
# Serialization and deserialization
When the `serde` feature is enabled, line segments can be serialized and
deserialized using the [`serde`] crate.
*/
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct LineSegment {
start: [f64; 2],
stop: [f64; 2],
}
impl LineSegment {
/**
Creates a new [`LineSegment`] instance if the `start` and `stop` are not
equal (within the tolerances defined by `epsilon` and `max_ulps`).
# Examples
```
use planar_geo::segment::LineSegment;
// Successfull construction
assert!(LineSegment::new([0.0, 0.0], [1.0, 0.0], 0.0, 0).is_ok());
// Points are identical
assert!(LineSegment::new([0.0, 0.0], [0.0, 0.0], 0.0, 0).is_err());
// Points are identical within the defined tolerance
assert!(LineSegment::new([0.0, 0.0], [1.0, 0.0], 1.0, 0).is_err());
```
*/
pub fn new(
start: [f64; 2],
stop: [f64; 2],
epsilon: f64,
max_ulps: u32,
) -> crate::error::Result<Self> {
if ulps_eq!(start, stop, epsilon = epsilon, max_ulps = max_ulps) {
return Err(crate::error::ErrorType::PointsIdentical { start, stop }.into());
} else {
return Ok(LineSegment { start, stop });
}
}
/**
Creates a [`LineSegment`] from a `start` point, an `angle` and its `length`.
If the `length` is zero, the points are identical and the construction
fails.
# Examples
```
use planar_geo::segment::LineSegment;
// Successfull construction
assert!(LineSegment::from_start_angle_length([0.0, 0.0], 0.0, 1.0, 0.0, 0).is_ok());
assert!(LineSegment::from_start_angle_length([0.0, 0.0], 0.0, -1.0, 0.0, 0).is_ok());
// Points are identical
assert!(LineSegment::from_start_angle_length([0.0, 0.0], 0.0, 0.0, 0.0, 0).is_err());
// Points are identical within the defined tolerance
assert!(LineSegment::from_start_angle_length([0.0, 0.0], 0.0, 1.0, 1.0, 0).is_err());
```
*/
pub fn from_start_angle_length(
start: [f64; 2],
angle: f64,
length: f64,
epsilon: f64,
max_ulps: u32,
) -> crate::error::Result<Self> {
let mut stop = start.clone();
stop.translate([length * angle.cos(), length * angle.sin()]);
return Self::new(start, stop, epsilon, max_ulps);
}
/**
Returns the smallest x-value of `self`.
# Examples
```
use planar_geo::segment::LineSegment;
// Successfull construction
let ls = LineSegment::new([0.0, 0.0], [1.0, -1.0], 0.0, 0).expect("points not identical");
assert_eq!(ls.xmin(), 0.0);
```
*/
pub fn xmin(&self) -> f64 {
if self.start[0] < self.stop[0] {
return self.start[0];
} else {
return self.stop[0];
}
}
/**
Returns the largest x-value of `self`.
# Examples
```
use planar_geo::segment::LineSegment;
// Successfull construction
let ls = LineSegment::new([0.0, 0.0], [1.0, -1.0], 0.0, 0).expect("points not identical");
assert_eq!(ls.xmax(), 1.0);
```
*/
pub fn xmax(&self) -> f64 {
if self.start[0] > self.stop[0] {
return self.start[0];
} else {
return self.stop[0];
}
}
/**
Returns the smallest y-value of `self`.
# Examples
```
use planar_geo::segment::LineSegment;
// Successfull construction
let ls = LineSegment::new([0.0, 0.0], [1.0, -1.0], 0.0, 0).expect("points not identical");
assert_eq!(ls.ymin(), -1.0);
```
*/
pub fn ymin(&self) -> f64 {
if self.start[1] < self.stop[1] {
return self.start[1];
} else {
return self.stop[1];
}
}
/**
Returns the largest y-value of `self`.
# Examples
```
use planar_geo::segment::LineSegment;
// Successfull construction
let ls = LineSegment::new([0.0, 0.0], [1.0, -1.0], 0.0, 0).expect("points not identical");
assert_eq!(ls.ymax(), 0.0);
```
*/
pub fn ymax(&self) -> f64 {
if self.start[1] > self.stop[1] {
return self.start[1];
} else {
return self.stop[1];
}
}
/**
Returns the slope of `self`.
# Examples
```
use planar_geo::segment::LineSegment;
// 45° slope
let line = LineSegment::new([0.0, 0.0], [1.0, -1.0], 0.0, 0).unwrap();
assert_eq!(line.slope(), -1.0);
// Infinite slope (vertical line)
let line = LineSegment::new([0.0, 0.0], [0.0, -1.0], 0.0, 0).unwrap();
assert!(line.slope().is_infinite());
```
*/
pub fn slope(&self) -> f64 {
if self.stop[0] == self.start[0] {
return INFINITY * (self.stop[1] - self.start[1]).signum();
} else {
return (self.stop[1] - self.start[1]) / (self.stop[0] - self.start[0]);
}
}
/**
Returns the angle of `self` from [`LineSegment::start`] to
[`LineSegment::stop`].
```
use planar_geo::prelude::*;
use std::f64::consts::PI;
// 45°
let line = LineSegment::new([0.0, 0.0], [1.0, 1.0], DEFAULT_EPSILON,
DEFAULT_MAX_ULPS).unwrap();
approx::assert_abs_diff_eq!(line.angle(), 0.25 * PI);
// 180°
let line = LineSegment::new([1.0, 1.0], [-1.0, 1.0], DEFAULT_EPSILON,
DEFAULT_MAX_ULPS).unwrap();
approx::assert_abs_diff_eq!(line.angle(), PI);
// 225°
let line = LineSegment::new([-2.0, -8.0], [-4.0, -10.0], DEFAULT_EPSILON,
DEFAULT_MAX_ULPS).unwrap();
approx::assert_abs_diff_eq!(line.angle(), -0.75 * PI);
// 315°
let line = LineSegment::new([5.0, 0.0], [6.0, -1.0], DEFAULT_EPSILON,
DEFAULT_MAX_ULPS).unwrap();
approx::assert_abs_diff_eq!(line.angle(), -0.25 * PI);
```
*/
pub fn angle(&self) -> f64 {
return (self.stop[1] - self.start[1]).atan2(self.stop[0] - self.start[0]);
}
/**
Returns the euclidian distance of the `point` to `self`. The euclidian
distance is the length of the shortest line which can be drawn between the
`point` and any point on `self`.
# Examples
```
use planar_geo::prelude::*;
let line = LineSegment::new([0.0, 0.0], [1.0, -1.0], DEFAULT_EPSILON, DEFAULT_MAX_ULPS).unwrap();
assert_eq!(line.euclidian_distance_to_point([-1.0, 0.0]), 1.0);
approx::assert_abs_diff_eq!(line.euclidian_distance_to_point([2.0, 0.0]), 2.0f64.sqrt());
// Point is on the line
assert_eq!(line.euclidian_distance_to_point([0.5, -0.5]), 0.0);
```
*/
pub fn euclidian_distance_to_point(&self, point: [f64; 2]) -> f64 {
let start = self.start;
let stop = self.stop;
let dx = stop[0] - start[0];
let dy = stop[1] - start[1];
// r is the ratio of the projection of point onto self. If it is between 0.0 and
// 1.0, the shortest distance from self to point is not from the end
// point
let r =
((point[0] - start[0]) * dx + (point[1] - start[1]) * dy) / (dx.powi(2) + dy.powi(2));
if r <= 0.0 {
return (start[0] - point[0]).hypot(start[1] - point[1]);
}
if r >= 1.0 {
return (stop[0] - point[0]).hypot(stop[1] - point[1]);
}
let s = ((start[1] - point[1]) * dx - (start[0] - point[0]) * dy) / (dx * dx + dy * dy);
s.abs() * dx.hypot(dy)
}
/**
Returns the length of `self` calculated with the Pythagorean theorem.
# Examples
```
use planar_geo::segment::LineSegment;
let ls = LineSegment::new([0.0, 0.0], [-2.0, 0.0], 0.0, 0).unwrap();
assert_eq!(ls.length(), 2.0);
```
*/
pub fn length(&self) -> f64 {
return self.length_sq().sqrt();
}
/**
Returns the squared length of `self` calculated with the Pythagorean theorem.
This function is more efficient / faster than [`LineSegment::length`], since
it does not require the expensive square root function. For example, if the
longer between two [`LineSegment`]s should be found, using this function
is the preferred way to do it:
```
use planar_geo::segment::LineSegment;
let ls1 = LineSegment::new([0.0, 0.0], [1.0, 0.0], 0.0, 0).unwrap();
let ls2 = LineSegment::new([0.0, 0.0], [2.0, 0.0], 0.0, 0).unwrap();
assert_eq!(ls1.length_sq() > ls2.length_sq(), ls1.length() > ls2.length());
```
*/
pub fn length_sq(&self) -> f64 {
return (self.stop[0] - self.start[0]).powi(2) + (self.stop[1] - self.start[1]).powi(2);
}
/**
Returns the start point of `self`.
*/
pub fn start(&self) -> [f64; 2] {
return self.start;
}
/**
Returns the stop point of `self`.
*/
pub fn stop(&self) -> [f64; 2] {
return self.stop;
}
/**
Returns the number of points in the segment. For a [`LineSegment`], this is
always 2.
*/
pub fn number_points(&self) -> usize {
return 2;
}
/**
Reverses the direction of `self` - i.e., exchange its start and stop point.
```
use planar_geo::segment::LineSegment;
let mut ls = LineSegment::new([0.0, 0.0], [1.0, 0.0], 0.0, 0).unwrap();
assert_eq!(ls.start(), [0.0, 0.0]);
assert_eq!(ls.stop(), [1.0, 0.0]);
ls.reverse();
assert_eq!(ls.start(), [1.0, 0.0]);
assert_eq!(ls.stop(), [0.0, 0.0]);
```
*/
pub fn reverse(&mut self) {
let tmp = self.start;
self.start = self.stop;
self.stop = tmp;
}
/**
Returns a point on the segment defined by its normalized position on it.
For example, `normalized = 0` returns the start point, `normalized = 1`
returns the end point and `normalized = 0.5` returns the middle point of the
segment. The input `normalized` is clamped to [0, 1].
# Examples
```
use planar_geo::segment::LineSegment;
let line = LineSegment::new([0.0, 0.0], [2.0, 0.0], 0.0, 0).unwrap();
// Middle point of the segment
assert_eq!(line.segment_point(0.5), [1.0, 0.0]);
assert_eq!(line.segment_point(-1.0), [0.0, 0.0]); // Start point
assert_eq!(line.segment_point(1.5), [2.0, 0.0]); // Stop point
```
*/
pub fn segment_point(&self, normalized: f64) -> [f64; 2] {
let normalized = normalized.clamp(0.0, 1.0);
return [
self.start[0] + normalized * (self.stop[0] - self.start[0]),
self.start[1] + normalized * (self.stop[1] - self.start[1]),
]
.into();
}
/**
Returns the centroid / center of mass of `self`. In case of the
[`LineSegment`], this is equal to the middle of the segment.
# Examples
```
use planar_geo::segment::LineSegment;
let line = LineSegment::new([0.0, 0.0], [2.0, 0.0], 0.0, 0).unwrap();
assert_eq!(line.centroid(), [1.0, 0.0]);
assert_eq!(line.centroid(), line.segment_point(0.5)); // Middle of the segment
```
*/
pub fn centroid(&self) -> [f64; 2] {
let x = 0.5 * (self.start()[0] + self.stop()[0]);
let y = 0.5 * (self.start()[1] + self.stop()[1]);
return [x, y];
}
/**
Returns the points of a polygon polysegment which approximates `self`. The number
of points is defined by the
[`SegmentPolygonizer`](crate::segment::SegmentPolygonizer) (see its
docstring). The points are regularily distributed over the segment, which
means that two subsequent points always have the same euclidian distance
from each other.
# Examples
```
use planar_geo::prelude::*;
let line = LineSegment::new([0.0, 0.0], [2.0, 0.0], 0.0, 0).unwrap();
let mut iter = line.polygonize(SegmentPolygonizer::InnerSegments(4));
assert_eq!(iter.next(), Some(line.segment_point(0.0)));
assert_eq!(iter.next(), Some(line.segment_point(0.25)));
assert_eq!(iter.next(), Some(line.segment_point(0.5)));
assert_eq!(iter.next(), Some(line.segment_point(0.75)));
assert_eq!(iter.next(), Some(line.segment_point(1.0)));
assert!(iter.next().is_none());
```
*/
pub fn polygonize<'a>(
&'a self,
polygonizer: super::SegmentPolygonizer,
) -> super::PolygonPointsIterator<'a> {
let num_segs = match polygonizer {
super::SegmentPolygonizer::InnerSegments(segs) => segs,
super::SegmentPolygonizer::MaximumSegmentLength(max_len) => {
if max_len <= 0.0 {
0
} else {
(self.length() / max_len).ceil() as usize
}
}
super::SegmentPolygonizer::MaximumAngle(_) => 0,
};
return super::PolygonPointsIterator {
index: 0,
num_segs,
segment: super::SegmentRef::LineSegment(self),
};
}
/**
Switches start and end / stop points of `self`.
# Examples
```
use planar_geo::prelude::*;
let mut ls = LineSegment::new([0.0, 0.0], [2.0, 0.0], 0.0, 0).unwrap();
assert_eq!(ls.start(), [0.0, 0.0]);
assert_eq!(ls.stop(), [2.0, 0.0]);
ls.invert();
assert_eq!(ls.start(), [2.0, 0.0]);
assert_eq!(ls.stop(), [0.0, 0.0]);
ls.invert();
assert_eq!(ls.start(), [0.0, 0.0]);
assert_eq!(ls.stop(), [2.0, 0.0]);
```
*/
pub fn invert(&mut self) {
let tmp = self.start;
self.start = self.stop;
self.stop = tmp;
}
/**
Returns an iterator over the start and stop point of `self`
This is a shorthand for `self.polygonize( Polygonizer::InnerSegments(1))`.
# Examples
```
use planar_geo::segment::LineSegment;
let line = LineSegment::new([0.0, 0.0], [2.0, 0.0], 0.0, 0).unwrap();
let mut iter = line.points();
assert_eq!(iter.next(), Some(line.segment_point(0.0)));
assert_eq!(iter.next(), Some(line.segment_point(1.0)));
assert!(iter.next().is_none());
```
*/
pub fn points<'a>(&'a self) -> super::PolygonPointsIterator<'a> {
return self.polygonize(super::SegmentPolygonizer::InnerSegments(1));
}
/// Returns whether `self` and `other` are touching.
///
/// Two segments are touching if they are intersecting but not dividing each
/// other. If `other` is a [`LineSegment`], one or both of the end points of
/// one line segment must be covered by the second one
/// (see [`Primitive::covers_point`]). If `other` is an
/// [`ArcSegment`](super::ArcSegment), `self` must be a tangent of `other`.
#[doc = ""]
#[cfg_attr(feature = "doc-images", doc = "![Touching and dividing][touching]")]
#[cfg_attr(
feature = "doc-images",
embed_doc_image::embed_doc_image("touching", "docs/img/touching.svg")
)]
#[cfg_attr(
not(feature = "doc-images"),
doc = "**Doc images not enabled**. Compile docs with `cargo doc --features 'doc-images'` and Rust version >= 1.54."
)]
///
/// # Examples
///
/// ```
/// use planar_geo::prelude::*;
///
/// let l1 = LineSegment::new([0.0, 0.0], [1.0, 0.0], 0.0, 0).unwrap();
/// let l2 = LineSegment::new([0.5, 0.0], [1.5, 0.0], 0.0, 0).unwrap();
/// let l3 = LineSegment::new([1.0, 0.0], [2.0, 0.0], 0.0, 0).unwrap();
/// let l4 = LineSegment::new([0.5, 0.0], [0.5, 1.0], 0.0, 0).unwrap();
/// let l5 = LineSegment::new([0.5, -1.0], [0.5, 1.0], 0.0, 0).unwrap();
///
/// // l1 and l2 overlap
/// assert!(l1.touches_segment(&l2, DEFAULT_EPSILON, DEFAULT_MAX_ULPS));
///
/// // l1 and l3 share the same end point
/// assert!(l1.touches_segment(&l3, DEFAULT_EPSILON, DEFAULT_MAX_ULPS));
///
/// // Start point of l4 is somewhere on l1
/// assert!(l1.touches_segment(&l4, DEFAULT_EPSILON, DEFAULT_MAX_ULPS));
///
/// // l5 divides l1
/// assert!(!l1.touches_segment(&l5, DEFAULT_EPSILON, DEFAULT_MAX_ULPS));
/// ```
pub fn touches_segment<'a, T: Into<super::SegmentRef<'a>>>(
&self,
other: T,
epsilon: f64,
max_ulps: u32,
) -> bool {
return self
.touches_and_intersections(other.into(), epsilon, max_ulps)
.0;
}
pub(crate) fn touches_and_intersections(
&self,
other: super::SegmentRef<'_>,
epsilon: f64,
max_ulps: u32,
) -> (bool, PrimitiveIntersections) {
fn ep_ls(s: &LineSegment, pt: [f64; 2], epsilon: f64, max_ulps: u32) -> bool {
return ulps_eq!(pt, s.start(), epsilon = epsilon, max_ulps = max_ulps)
|| ulps_eq!(pt, s.stop(), epsilon = epsilon, max_ulps = max_ulps);
}
fn ep_as(s: &super::ArcSegment, pt: [f64; 2], epsilon: f64, max_ulps: u32) -> bool {
return ulps_eq!(pt, s.start(), epsilon = epsilon, max_ulps = max_ulps)
|| ulps_eq!(pt, s.stop(), epsilon = epsilon, max_ulps = max_ulps);
}
let intersections = self.intersections_primitive(&other, epsilon, max_ulps);
let touches = match other {
super::SegmentRef::LineSegment(line_segment) => match intersections {
PrimitiveIntersections::Zero => false,
PrimitiveIntersections::One(i) => {
ep_ls(self, i, epsilon, max_ulps) || ep_ls(line_segment, i, epsilon, max_ulps)
}
PrimitiveIntersections::Two(_) => true,
},
super::SegmentRef::ArcSegment(arc_segment) => match intersections {
PrimitiveIntersections::Zero => false,
PrimitiveIntersections::One(i) => {
ep_ls(self, i, epsilon, max_ulps)
|| ep_as(arc_segment, i, epsilon, max_ulps)
|| self.is_tangent(arc_segment, epsilon, max_ulps)
}
PrimitiveIntersections::Two([i1, i2]) => {
// Are the intersections end points?
(ep_ls(self, i1, epsilon, max_ulps)
|| ep_as(arc_segment, i1, epsilon, max_ulps))
&& (ep_ls(self, i2, epsilon, max_ulps)
|| ep_as(arc_segment, i2, epsilon, max_ulps))
}
},
};
return (touches, intersections);
}
/**
Returns whether `self` is a tangent of `arc_segment`.
A [`LineSegment`] is a tangent of an [`ArcSegment`](super::ArcSegment) if
they touch in a single point and the line segment is perpendicular to the
straight line connecting this point and the center of the arc.
# Examples
```
use std::f64::consts::PI;
use planar_geo::prelude::*;
let ls = LineSegment::new([-2.0, 0.0], [2.0, 0.0], DEFAULT_EPSILON, DEFAULT_MAX_ULPS).unwrap();
// Arc touches ls at its end points, but ls is not a tangent
let arc = ArcSegment::from_center_radius_start_offset_angle([0.0, 0.0], 2.0, 0.0, PI, 0.0, 0).unwrap();
assert!(!ls.is_tangent(&arc, DEFAULT_EPSILON, DEFAULT_MAX_ULPS));
// Arc which touches ls at [0.0, 0.0]
let arc = ArcSegment::from_center_radius_start_offset_angle([0.0, 2.0], 2.0, PI, PI, 0.0, 0).unwrap();
assert!(ls.is_tangent(&arc, DEFAULT_EPSILON, DEFAULT_MAX_ULPS));
// Underlying circle touches ls in [0.0, 0.0], but that intersection point is not part of arc
let arc = ArcSegment::from_center_radius_start_offset_angle([0.0, 2.0], 2.0, 0.0, PI, 0.0, 0).unwrap();
assert!(!ls.is_tangent(&arc, DEFAULT_EPSILON, DEFAULT_MAX_ULPS));
```
*/
pub fn is_tangent(&self, arc_segment: &super::ArcSegment, epsilon: f64, max_ulps: u32) -> bool {
let [x1, y1] = self.start();
let [x2, y2] = self.stop();
let [cx, cy] = arc_segment.center();
let r = arc_segment.radius();
// Direction vector of the segment
let dx = x2 - x1;
let dy = y2 - y1;
let len_sq = dx * dx + dy * dy;
// Project center onto the line (parameter t)
let t = ((cx - x1) * dx + (cy - y1) * dy) / len_sq;
// Closest point on the infinite line
let px = x1 + t * dx;
let py = y1 + t * dy;
if !arc_segment.covers_point([px, py], epsilon, max_ulps) {
return false;
}
// Distance from center to projection
let dist = ((px - cx).powi(2) + (py - cy).powi(2)).sqrt();
// Check tangency
if approx::ulps_ne!(dist, r, epsilon = epsilon, max_ulps = max_ulps) {
return false;
}
// Check if projection lies within the segment
// (t must be between 0 and 1)
t >= -epsilon && t <= 1.0 + epsilon
}
/**
Finds the endpoint of the segments P and Q which is closest to the other segment. This is
a reasonable surrogate for the true intersection points in ill-conditioned cases (e.g.
where two segments are nearly coincident, or where the endpoint of one segment lies almost
on the other segment).
This replaces the older CentralEndpoint heuristic, which chose the wrong endpoint in some
cases where the segments had very distinct slopes and one endpoint lay almost on the other
segment.
*/
fn nearest_endpoint(&self, line_segment: &LineSegment) -> [f64; 2] {
let mut nearest_pt = self.start;
let mut min_dist = line_segment.euclidian_distance_to_point(self.start);
let dist = line_segment.euclidian_distance_to_point(self.stop);
if dist < min_dist {
min_dist = dist;
nearest_pt = self.stop;
}
let dist = self.euclidian_distance_to_point(line_segment.start);
if dist < min_dist {
min_dist = dist;
nearest_pt = line_segment.start;
}
let dist = self.euclidian_distance_to_point(line_segment.stop);
if dist < min_dist {
nearest_pt = line_segment.stop;
}
nearest_pt
}
fn raw_line_intersection(&self, line_segment: &LineSegment) -> Option<[f64; 2]> {
let p_min_x = self.start[0].min(self.stop[0]);
let p_min_y = self.start[1].min(self.stop[1]);
let p_max_x = self.start[0].max(self.stop[0]);
let p_max_y = self.start[1].max(self.stop[1]);
let q_min_x = line_segment.start[0].min(line_segment.stop[0]);
let q_min_y = line_segment.start[1].min(line_segment.stop[1]);
let q_max_x = line_segment.start[0].max(line_segment.stop[0]);
let q_max_y = line_segment.start[1].max(line_segment.stop[1]);
let int_min_x = p_min_x.max(q_min_x);
let int_max_x = p_max_x.min(q_max_x);
let int_min_y = p_min_y.max(q_min_y);
let int_max_y = p_max_y.min(q_max_y);
let mid_x = 0.5 * (int_min_x + int_max_x);
let mid_y = 0.5 * (int_min_y + int_max_y);
// condition ordinate values by subtracting midpoint
let p1x = self.start[0] - mid_x;
let p1y = self.start[1] - mid_y;
let p2x = self.stop[0] - mid_x;
let p2y = self.stop[1] - mid_y;
let q1x = line_segment.start[0] - mid_x;
let q1y = line_segment.start[1] - mid_y;
let q2x = line_segment.stop[0] - mid_x;
let q2y = line_segment.stop[1] - mid_y;
// unrolled computation using homogeneous coordinates eqn
let px = p1y - p2y;
let py = p2x - p1x;
let pw = p1x * p2y - p2x * p1y;
let qx = q1y - q2y;
let qy = q2x - q1x;
let qw = q1x * q2y - q2x * q1y;
let xw = py * qw - qy * pw;
let yw = qx * pw - px * qw;
let w = px * qy - qx * py;
let x_int = xw / w;
let y_int = yw / w;
// check for parallel lines
if (x_int.is_nan() || x_int.is_infinite()) || (y_int.is_nan() || y_int.is_infinite()) {
None
} else {
// de-condition intersection point
Some([x_int + mid_x, y_int + mid_y])
}
}
/**
This method computes the actual value of the intersection point.
To obtain the maximum precision from the intersection calculation,
the coordinates are normalized by subtracting the minimum
ordinate values (in absolute value). This has the effect of
removing common significant digits from the calculation to
maintain more bits of precision.
*/
fn proper_intersection(
&self,
line_segment: &LineSegment,
epsilon: f64,
max_ulps: u32,
) -> [f64; 2] {
// Computes a segment intersection using homogeneous coordinates.
// Round-off error can cause the raw computation to fail,
// (usually due to the segments being approximately parallel).
// If this happens, a reasonable approximation is computed instead.
let mut int_pt = self
.raw_line_intersection(line_segment)
.unwrap_or_else(|| self.nearest_endpoint(line_segment));
// NOTE: At this point, JTS does a `Envelope::contains(coord)` check, but
// confusingly, Envelope::contains(coord) in JTS is actually an
// *intersection* check, not a true SFS `contains`, because it includes
// the boundary of the rect.
if !(BoundingBox::from(self).approx_covers_point(int_pt, epsilon, max_ulps)
&& BoundingBox::from(line_segment).approx_covers_point(int_pt, epsilon, max_ulps))
{
// compute a safer result
// copy the coordinate, since it may be rounded later
int_pt = self.nearest_endpoint(line_segment);
}
int_pt
}
}
impl Transformation for LineSegment {
fn translate(&mut self, shift: [f64; 2]) {
self.start.translate(shift);
self.stop.translate(shift);
}
fn rotate(&mut self, center: [f64; 2], angle: f64) {
let t = Rotation2::new(angle);
let pt = [self.start[0] - center[0], self.start[1] - center[1]];
self.start = t * pt;
self.start.translate([center[0], center[1]]);
let pt = [self.stop[0] - center[0], self.stop[1] - center[1]];
self.stop = t * pt;
self.stop.translate([center[0], center[1]]);
}
fn scale(&mut self, factor: f64) {
self.start.scale(factor);
self.stop.scale(factor);
}
fn line_reflection(&mut self, start: [f64; 2], stop: [f64; 2]) -> () {
// Treatment of special case: vertical line
if start[0] == stop[0] {
self.start = [-self.start[0] + 2.0 * start[0], self.start[1]];
self.stop = [-self.stop[0] + 2.0 * stop[0], self.stop[1]];
// Treatment of special case: Horizontal line
} else if start[1] == stop[1] {
self.start = [self.start[0], -self.start[1] + 2.0 * start[1]];
self.stop = [self.stop[0], -self.stop[1] + 2.0 * start[1]];
// All other cases
} else {
// Solve the line equation
let m = (stop[1] - start[1]) / (stop[0] - start[0]);
let c = (stop[0] * start[1] - start[0] * stop[1]) / (stop[0] - start[0]);
let d = (self.start[0] + (self.start[1] - c) * m) / (1.0 + m.powi(2));
self.start = [
2.0 * d - self.start[0],
2.0 * d * m - self.start[1] + 2.0 * c,
];
let d = (self.stop[0] + (self.stop[1] - c) * m) / (1.0 + m.powi(2));
self.stop = [2.0 * d - self.stop[0], 2.0 * d * m - self.stop[1] + 2.0 * c];
}
}
}
impl ToBoundingBox for LineSegment {
fn bounding_box(&self) -> BoundingBox {
let [xmin, xmax] = if self.start()[0] > self.stop()[0] {
[self.stop()[0], self.start()[0]]
} else {
[self.start()[0], self.stop()[0]]
};
let [ymin, ymax] = if self.start()[1] > self.stop()[1] {
[self.stop()[1], self.start()[1]]
} else {
[self.start()[1], self.stop()[1]]
};
return BoundingBox::new(xmin, xmax, ymin, ymax);
}
}
impl From<&LineSegment> for CentroidData {
fn from(value: &LineSegment) -> Self {
// Apply the formula for a triangle with one vertex being (0,0)
let x = (value.start()[0] + value.stop()[0]) / 3.0;
let y = (value.start()[1] + value.stop()[1]) / 3.0;
let area = 0.5 * (value.start()[0] * value.stop()[1] - value.stop()[0] * value.start()[1]);
return Self { area, x, y };
}
}
impl std::fmt::Display for LineSegment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
return write!(f, "{:?} -> {:?}", self.start, self.stop);
}
}
impl crate::primitive::private::Sealed for LineSegment {}
impl Primitive for LineSegment {
fn covers_point(&self, p: [f64; 2], epsilon: f64, max_ulps: u32) -> bool {
// Quick first check: If point p is outside the segment bounding box, it can't
// be contained.
if !BoundingBox::from(self).approx_covers_point(p, epsilon, max_ulps) {
return false;
}
// Check if the points of the segment and p are collinear. If they aren't, p
// can't be contained. If they are, p is contained, since it is also
// inside the segment bounding box.
if epsilon == 0.0 && max_ulps == 0 {
return geometry_predicates::orient2d(self.start.into(), self.stop.into(), p.into())
== 0.0;
} else {
// This is the solution from https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment
let len_sq = self.length_sq();
let v = self.start();
let w = self.stop();
let t: f64 = ((p[0] - v[0]) * (w[0] - v[0]) + (p[1] - v[1]) * (w[1] - v[1])) / len_sq;
let t = t.clamp(0.0, 1.0); // This is equal to t = Math.max(0, Math.min(1, t)) in the link
// Calculate the (squared) distance between the segment and the given point
let pt = [v[0] + t * (w[0] - v[0]), v[1] + t * (w[1] - v[1])];
let dist = ((pt[0] - p[0]).powi(2) + (pt[1] - p[1]).powi(2)).sqrt();
return approx::ulps_eq!(dist, 0.0, epsilon = epsilon, max_ulps = max_ulps);
}
}
fn covers_arc_segment(
&self,
_arc_segment: &crate::segment::ArcSegment,
_epsilon: f64,
_max_ulps: u32,
) -> bool {
return false;
}
fn covers_line_segment(&self, line_segment: &LineSegment, epsilon: f64, max_ulps: u32) -> bool {
match self.intersections_primitive(line_segment, epsilon, max_ulps) {
// Deal with special case where self and line_segment are identical
PrimitiveIntersections::Zero => std::ptr::eq(self, line_segment),
PrimitiveIntersections::One(_) => false,
PrimitiveIntersections::Two([pt1, pt2]) => {
let start = line_segment.start();
let stop = line_segment.stop();
ulps_eq!(start, pt1, epsilon = epsilon, max_ulps = max_ulps)
&& ulps_eq!(stop, pt2, epsilon = epsilon, max_ulps = max_ulps)
|| ulps_eq!(start, pt2, epsilon = epsilon, max_ulps = max_ulps)
&& ulps_eq!(stop, pt1, epsilon = epsilon, max_ulps = max_ulps)
}
}
}
fn covers_line(&self, _line: &crate::line::Line, _epsilon: f64, _max_ulps: u32) -> bool {
return false;
}
fn intersections_line(
&self,
line: &crate::line::Line,
epsilon: f64,
max_ulps: u32,
) -> PrimitiveIntersections {
return line.intersections_line_segment(self, epsilon, max_ulps);
}
fn intersections_line_segment(
&self,
line_segment: &LineSegment,
epsilon: f64,
max_ulps: u32,
) -> PrimitiveIntersections {
// This is geo's line_intersection algorithm
// (https://github.com/georust/geo/blob/3b0d5738f54bd8964f7d1f573bd63dc114587dc4/geo/src/algorithm/line_intersection.rs)
// translated into the planar_geo crate.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
enum Orientation {
Clockwise,
CounterClockwise,
Collinear,
}
impl From<f64> for Orientation {
fn from(value: f64) -> Self {
if value < 0.0 {
return Orientation::Clockwise;
} else if value > 0.0 {
return Orientation::CounterClockwise;
} else {
return Orientation::Collinear;
}
}
}
// =====================================================================
// If the segments are identical, they do not intersect by definition
if std::ptr::eq(self, line_segment) {
return PrimitiveIntersections::Zero;
}
// If the bounding boxes of the line segments don't interact with each other,
// then the segments cannot intersect at all.
let bb1 = BoundingBox::from(self);
let bb2 = BoundingBox::from(line_segment);
if !bb1.intersects(&bb2) && !bb1.touches(&bb2) {
return PrimitiveIntersections::Zero;
}
let self_start: Orientation = geometry_predicates::orient2d(
self.start.into(),
self.stop.into(),
line_segment.start.into(),
)
.into();
let self_stop: Orientation = geometry_predicates::orient2d(
self.start.into(),
self.stop.into(),
line_segment.stop.into(),
)
.into();
if matches!(
(self_start, self_stop),
(Orientation::Clockwise, Orientation::Clockwise)
| (Orientation::CounterClockwise, Orientation::CounterClockwise)
) {
return PrimitiveIntersections::Zero;
}
let line_segment_start: Orientation = geometry_predicates::orient2d(
line_segment.start.into(),
line_segment.stop.into(),
self.start.into(),
)
.into();
let line_segment_stop: Orientation = geometry_predicates::orient2d(
line_segment.start.into(),
line_segment.stop.into(),
self.stop.into(),
)
.into();
if matches!(
(line_segment_start, line_segment_stop),
(Orientation::Clockwise, Orientation::Clockwise)
| (Orientation::CounterClockwise, Orientation::CounterClockwise)
) {
return PrimitiveIntersections::Zero;
}
if matches!(
(self_start, self_stop, line_segment_start, line_segment_stop),
(
Orientation::Collinear,
Orientation::Collinear,
Orientation::Collinear,
Orientation::Collinear
)
) {
let bb1 = BoundingBox::from(self);
let bb2 = BoundingBox::from(line_segment);
return match (
bb1.approx_covers_point(line_segment.start, epsilon, max_ulps),
bb1.approx_covers_point(line_segment.stop, epsilon, max_ulps),
bb2.approx_covers_point(self.start, epsilon, max_ulps),
bb2.approx_covers_point(self.stop, epsilon, max_ulps),
) {
(true, true, _, _) => {
PrimitiveIntersections::Two([line_segment.start, line_segment.stop])
}
(_, _, true, true) => PrimitiveIntersections::Two([self.start, self.stop]),
(true, false, true, false) if line_segment.start == self.start => {
PrimitiveIntersections::One(line_segment.start)
}
(true, _, true, _) => PrimitiveIntersections::Two([line_segment.start, self.start]),
(true, false, false, true) if line_segment.start == self.stop => {
PrimitiveIntersections::One(line_segment.start)
}
(true, _, _, true) => PrimitiveIntersections::Two([line_segment.start, self.stop]),
(false, true, true, false) if line_segment.stop == self.start => {
PrimitiveIntersections::One(line_segment.stop)
}
(_, true, true, _) => PrimitiveIntersections::Two([line_segment.stop, self.start]),
(false, true, false, true) if line_segment.stop == self.stop => {
PrimitiveIntersections::One(line_segment.stop)
}
(_, true, _, true) => PrimitiveIntersections::Two([line_segment.stop, self.stop]),
_ => PrimitiveIntersections::Zero,
};
}
// At this point we know that there is a single intersection point (since the
// lines are not collinear).
//
// Check if the intersection is an endpoint. If it is, copy the endpoint as the
// intersection point. Copying the point rather than computing it ensures the
// point has the exact value, which is important for robustness. It is
// sufficient to simply check for an endpoint which is on the other
// line, since at this point we know that the input lines
// must intersect.
if self_start == Orientation::Collinear
|| self_stop == Orientation::Collinear
|| line_segment_start == Orientation::Collinear
|| line_segment_stop == Orientation::Collinear
{
// Check for two equal endpoints.
// This is done explicitly rather than by the orientation tests below in order
// to improve robustness.
let intersection =
if self.start == line_segment.start || self.start == line_segment.stop {
self.start
} else if self.stop == line_segment.start || self.stop == line_segment.stop {
self.stop
// Now check to see if any endpoint lies on the interior of
// the other segment.
} else if self_start == Orientation::Collinear {
line_segment.start
} else if self_stop == Orientation::Collinear {
line_segment.stop
} else if line_segment_start == Orientation::Collinear {
self.start
} else {
assert_eq!(line_segment_stop, Orientation::Collinear);
self.stop
};
PrimitiveIntersections::One(intersection)
} else {
let intersection = self.proper_intersection(line_segment, epsilon, max_ulps);
return PrimitiveIntersections::One(intersection);
}
}
fn intersections_arc_segment(
&self,
arc_segment: &crate::segment::ArcSegment,
epsilon: f64,
max_ulps: u32,
) -> PrimitiveIntersections {
// Algorithm from https://cp-algorithms.com/geometry/circle-line-intersection.html
let center = arc_segment.center();
let x1 = self.start[0] - center[0];
let y1 = self.start[1] - center[1];
let x2 = self.stop[0] - center[0];
let y2 = self.stop[1] - center[1];
// Calculate values A, B and C as used in the circle-line-intersection algorithm
// "Koordinatenform", see https://de.wikipedia.org/wiki/Koordinatenform
let a = y1 - y2;
let b = x2 - x1;
// Multiply C by -1 to account for the different definitions of the Wikipedia
// and the cp-algorithms.com approach
let c = -(x2 * y1 - x1 * y2);
let mut intersections = PrimitiveIntersections::Zero;
for pt in arc_segment
.intersections_line_circle(a, b, c, epsilon, max_ulps)
.into_iter()
.map(From::from)
{
if self.covers_point(pt, epsilon, max_ulps) {
intersections.push(pt);
}
}
return intersections;
}
fn intersections_primitive<T: Primitive>(
&self,
other: &T,
epsilon: f64,
max_ulps: u32,
) -> PrimitiveIntersections {
other.intersections_line_segment(self, epsilon, max_ulps)
}
}