reda_geometry/shape/
edge.rs

1use num_traits::NumCast;
2
3use crate::shape::Point;
4use crate::base::Vec2;
5use crate::traits::{BoundingBox, Cast, DType, MapPoint, TryBoundingBox};
6pub use crate::base::Angle;
7pub use crate::base::{Contains, Side};
8
9use super::Rect;
10
11/// An edge (line segment) is represented by its starting point and end point.
12#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
13#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
14pub struct Edge<T> {
15    pub start: Point<T>,
16    pub end: Point<T>,
17}
18
19impl<T: Copy> Edge<T> {
20    pub fn new(start: impl Into<Point<T>>, end: impl Into<Point<T>>) -> Self {
21        Self {
22            start: start.into(),
23            end: end.into(),
24        }
25    }
26
27    /// Return the same edge but with the two points swapped.
28    pub fn reversed(&self) -> Self {
29        Self {
30            start: self.end,
31            end: self.start,
32        }
33    }
34}
35
36impl<T: PartialEq> Edge<T> {
37    /// Check if edge is degenerate.
38    /// An edge is degenerate if start point == end point.
39    pub fn is_degenerate(&self) -> bool {
40        self.start == self.end
41    }
42
43    pub fn is_rectilinear(&self) -> bool {
44        !self.is_degenerate() && (self.start.x == self.end.x || self.start.y == self.end.y)
45    }
46
47    pub fn is_horizontal(&self) -> bool {
48        !self.is_degenerate() && self.start.y == self.end.y
49    }
50
51    pub fn is_vertical(&self) -> bool {
52        !self.is_degenerate() && self.start.x == self.end.x
53    }
54}
55
56impl<T: DType> Edge<T> {
57    /// Returns the vec2 from `self.start` to `self.end`.
58    pub fn vec2(&self) -> Vec2<T> {
59        self.end - self.start
60    }
61
62    /// Tells on which side of the edge a point is.
63    ///
64    /// # Panics
65    /// Panics if the edge is degenerate.
66    ///
67    /// Returns `Side::Left` if the point is on the left side,
68    /// `Side::Right` if the point is on the right side
69    /// or `Side::Center` if the point lies exactly on the line.
70    pub fn side_of(&self, point: Point<T>) -> Side {
71        assert!(!self.is_degenerate());
72
73        let a = self.vec2();
74        let b = point - self.start;
75
76        // Handle rectilinear cases.
77        if a.x.is_zero() {
78            let side = if point.x < self.start.x {
79                Side::Left
80            } else if point.x > self.start.x {
81                Side::Right
82            } else {
83                Side::Center
84            };
85
86            // Maybe flip the side depending on the orientation of the edge.
87            let side = if self.start.y < self.end.y {
88                side
89            } else {
90                side.other()
91            };
92
93            return side;
94        } else if a.y.is_zero() {
95            let side = if point.y < self.start.y {
96                Side::Right
97            } else if point.y > self.start.y {
98                Side::Left
99            } else {
100                Side::Center
101            };
102
103            // Maybe flip the side depending on the orientation of the edge.
104            let side = if self.start.x < self.end.x {
105                side
106            } else {
107                side.other()
108            };
109
110            return side;
111        }
112
113        let area = b.cross_prod(a);
114
115        if area.is_zero() {
116            Side::Center
117        } else if area < T::zero() {
118            Side::Left
119        } else {
120            Side::Right
121        }
122    }
123
124    /// Test if point lies on the edge.
125    /// Includes start and end points of edge.
126    pub fn contains_point(&self, point: Point<T>) -> Contains {
127        if self.start == point || self.end == point {
128            Contains::OnBounds
129        } else if self.is_degenerate() {
130            Contains::No
131        } else {
132            let a = self.start - point;
133            let b = self.end - point;
134            // Check if the triangle point-start-end has zero area and that a and b have opposite directions.
135            // If a and b have opposite directions then point is between start and end.
136            if a.cross_prod(b).is_zero() && a.dot(b) <= T::zero() {
137                Contains::WithinBounds
138            } else {
139                Contains::No
140            }
141        }
142    }
143
144    /// Test if point lies on the line defined by the edge.
145    pub fn line_contains_point(&self, point: Point<T>) -> bool {
146        if self.is_degenerate() {
147            self.start == point
148        } else {
149            let l = self.vec2();
150            let b = point - self.start;
151
152            l.cross_prod(b).is_zero()
153        }
154    }
155
156    /// if two edges are parallel.
157    pub fn is_parallel(&self, other: &Self) -> bool {
158        if self.is_degenerate() || other.is_degenerate() {
159            false
160        } else {
161            let a = self.vec2();
162            let b = other.vec2();
163
164            if a.x.is_zero() {
165                // Both vertical?
166                b.x.is_zero()
167            } else if a.y.is_zero() {
168                // Both horizontal?
169                b.y.is_zero()
170            } else if b.x.is_zero() || b.y.is_zero() {
171                false
172            } else {
173                a.cross_prod(b).is_zero()
174            }
175        }
176    }
177
178    /// if two edges are collinear, i.e. are on the same line.
179    pub fn is_collinear(&self, other: &Self) -> bool {
180        if self.is_degenerate() || other.is_degenerate() {
181            false
182        } else {
183            let v = self.vec2();
184            let a = other.start - self.start;
185            let b = other.end - self.start;
186
187            if self.start.x == self.end.x {
188                // Self is vertical.
189                // The edges are collinear iff `other` has the same x coordinates as `self`.
190                other.start.x == self.start.x && other.end.x == self.start.x
191            } else if self.start.y == self.end.y {
192                // `self` is horizontal
193                other.start.y == self.start.y && other.end.y == self.start.y
194            } else if other.start.x == other.end.x {
195                self.start.x == other.start.x && self.end.x == other.start.x
196            } else if other.start.y == other.end.y {
197                // `other` is horizontal
198                self.start.y == other.start.y && self.end.y == other.start.y
199            } else {
200                v.cross_prod(a).is_zero() && v.cross_prod(b).is_zero()
201            }
202        }
203    }
204
205    /// Test edges for coincidence.
206    /// Two edges are coincident if they are oriented the same way
207    /// and share more than one point (implies that they must be parallel).
208    pub fn is_coincident(&self, other: &Self) -> bool {
209        // TODO: use is_collinear
210        // TODO: approximate version for floating point types
211
212        let self_start_in_other = other.contains_point(self.start).inclusive_bounds();
213        let self_end_in_other = other.contains_point(self.end).inclusive_bounds();
214        let other_start_in_self = self.contains_point(other.start).inclusive_bounds();
215        let other_end_in_self = self.contains_point(other.end).inclusive_bounds();
216
217        let share_more_than_one_point = self.end != other.start
218            && self.start != other.end
219            && (self_start_in_other || other_start_in_self)
220            && (other_end_in_self || self_end_in_other);
221
222        // Sharing more than one point should imply that the edges are parallel.
223        debug_assert!(if share_more_than_one_point {
224            self.is_parallel(other)
225        } else {
226            true
227        });
228
229        let oriented_the_same_way = self.vec2().dot(other.vec2()) > T::zero();
230
231        share_more_than_one_point && oriented_the_same_way
232    }
233
234    /// Test if two edges are approximately parallel.
235    /// To be used for float coordinates.
236    /// Inspired by algorithm on page 241 of "Geometric Tools for Computer Graphics".
237    pub fn is_parallel_approx(&self, other: &Self, epsilon_squared: T) -> bool {
238        if self.is_degenerate() || other.is_degenerate() {
239            false
240        } else {
241            let d1 = self.vec2();
242            let d2 = other.vec2();
243
244            let len1_sqr = d1.norm2_squared();
245            let len2_sqr = d2.norm2_squared();
246
247            let cross = d1.cross_prod(d2);
248            let cross_sqr = cross * cross;
249
250            // TODO: require square tolerance form caller?
251            cross_sqr <= len1_sqr * len2_sqr * epsilon_squared
252        }
253    }
254
255    /// Test if two edges are approximately collinear, i.e. are on the same line.
256    /// Inspired by algorithm on page 241 of "Geometric Tools for Computer Graphics".
257    pub fn is_collinear_approx(&self, other: &Self, epsilon_squared: T) -> bool {
258        if self.is_degenerate() || other.is_degenerate() {
259            false
260        } else {
261            let d1 = self.vec2();
262            let d2 = other.vec2();
263
264            let len1_sqr = d1.norm2_squared();
265            let len2_sqr = d2.norm2_squared();
266
267            let cross = d1.cross_prod(d2);
268            let cross_sqr = cross * cross;
269
270            let approx_parallel = cross_sqr <= len1_sqr * len2_sqr * epsilon_squared;
271
272            if approx_parallel {
273                let e = other.start - self.start;
274                let len_e_sqrt = e.norm2_squared();
275                let cross = e.cross_prod(d1);
276                let cross_sqr = cross * cross;
277                cross_sqr <= len1_sqr * len_e_sqrt * epsilon_squared
278            } else {
279                false
280            }
281        }
282    }
283
284    /// Test if lines defined by the edges intersect.
285    /// If the lines are collinear they are also considered intersecting.
286    pub fn lines_intersect_approx(&self, other: &Self, epsilon_squared: T) -> bool {
287        !self.is_parallel_approx(other, epsilon_squared)
288            || self.is_collinear_approx(other, epsilon_squared)
289    }
290
291    /// Test if this edge is crossed by the line defined by the other edge.
292    ///
293    /// Returns `WithinBounds` if start and end point of this edge lie on different sides
294    /// of the line defined by the `other` edge or `OnBounds` if at least one of the points
295    /// lies on the line.
296    pub fn crossed_by_line(&self, other: &Self) -> Contains {
297        // TODO: Handle degenerate cases.
298        let side1 = other.side_of(self.start);
299
300        if side1 == Side::Center {
301            Contains::OnBounds
302        } else {
303            let side2 = other.side_of(self.end);
304
305            if side2 == Side::Center {
306                Contains::OnBounds
307            } else if side1 == side2 {
308                Contains::No
309            } else {
310                Contains::WithinBounds
311            }
312        }
313    }
314
315    /// Test if lines defined by the edges intersect.
316    /// If the lines are collinear they are also considered intersecting.
317    pub fn lines_intersect(&self, other: &Self) -> bool {
318        !self.is_parallel(other) || self.is_collinear(other)
319    }
320}
321
322impl<T: Copy> From<Edge<T>> for (Point<T>, Point<T>) {
323    fn from(e: Edge<T>) -> Self {
324        (e.start, e.end)
325    }
326}
327
328impl<T: Copy> From<&Edge<T>> for (Point<T>, Point<T>) {
329    fn from(e: &Edge<T>) -> Self {
330        (e.start, e.end)
331    }
332}
333
334impl<T: DType> From<(Point<T>, Point<T>)> for Edge<T> {
335    fn from(points: (Point<T>, Point<T>)) -> Self {
336        Edge::new(points.0, points.1)
337    }
338}
339
340impl<T: DType> From<[Point<T>; 2]> for Edge<T> {
341    fn from(points: [Point<T>; 2]) -> Self {
342        Edge::new(points[0], points[1])
343    }
344}
345
346impl<T: Copy> MapPoint<T> for Edge<T> {
347    fn transform<F>(&self, transformate: F) -> Self
348        where 
349            F: Fn(Point<T>) -> Point<T> 
350    {
351        Self {
352            start: transformate(self.start),
353            end: transformate(self.end)
354        }    
355    }
356}
357
358impl<T: Copy + PartialOrd> BoundingBox<T> for Edge<T> {
359    fn bounding_box(&self) -> Rect<T> {
360        Rect::new(self.start, self.end)
361    }
362}
363
364impl<T: Copy + PartialOrd> TryBoundingBox<T> for Edge<T> {
365    fn try_bounding_box(&self) -> Option<Rect<T>> {
366        Some(self.bounding_box())
367    }
368}
369
370impl<Src: Copy + NumCast, Dst: Copy + NumCast> Cast<Src, Dst> for Edge<Src> {
371    type Output = Edge<Dst>;
372
373    fn try_cast(&self) -> Option<Self::Output> {
374        match (self.start.try_cast(), self.end.try_cast()) {
375            (Some(s), Some(e)) => Some(Edge::new(s, e)),
376            _ => None,
377        }
378    }
379}
380