Skip to main content

shape_core/elements/lines/line_2d/
mod.rs

1use num_traits::{Num, One};
2
3use super::*;
4
5mod constructors;
6mod convert;
7
8/// represents an infinitely long lines segment
9#[cfg_attr(feature = "serde", repr(C), derive(Serialize, Deserialize))]
10#[derive(Copy, Clone, PartialEq, Eq, Hash)]
11pub struct Vector<T> {
12    /// x component of the vector
13    pub dx: T,
14    /// y component of the vector
15    pub dy: T,
16}
17
18/// A lines segment of finite length, determined by a starting points and an ending points.
19#[cfg_attr(feature = "serde", repr(C), derive(Serialize, Deserialize))]
20#[derive(Copy, Clone, PartialEq, Eq, Hash)]
21pub struct Line<T> {
22    /// Start points of the lines segment.
23    pub s: Point<T>,
24    /// End points of the lines segment.
25    pub e: Point<T>,
26}
27
28impl<T> Line<T>
29    where
30        T: Clone + Num,
31{
32    /// Get the length of the line
33    pub fn length(&self) -> T
34        where
35            T: Real,
36    {
37        self.s.euclidean_distance(&self.e)
38    }
39    #[inline(always)]
40    pub fn as_vector(&self) -> Vector<T> {
41        let new = self.e.clone() - &self.s;
42        Vector { dx: new.x, dy: new.y }
43    }
44    /// Check if two line is parallel
45    pub fn is_parallel(&self, rhs: &Self) -> bool {
46        let a = self.as_vector();
47        let b = rhs.as_vector();
48        a.is_parallel(&b)
49    }
50    /// Check if two line is orthogonal
51    pub fn is_orthogonal(&self, rhs: &Self) -> bool {
52        let a = self.as_vector();
53        let b = rhs.as_vector();
54        a.is_orthogonal(&b)
55    }
56}
57
58impl<T> Vector<T>
59    where
60        T: Clone + Num,
61{
62    pub fn from_2_points<P>(start: P, end: P) -> Self
63        where
64            Point<T>: From<P>,
65    {
66        let Point { x: x1, y: y1 } = start.into();
67        let Point { x: x2, y: y2 } = end.into();
68        Self { dx: x2 - x1, dy: y2 - y1 }
69    }
70}
71
72impl<T> Vector<T>
73    where
74        T: Clone + Num,
75{
76    /// Check if two vector is parallel
77    pub fn is_parallel(&self, rhs: &Self) -> bool {
78        let Vector { dx: x1, dy: y1 } = self.clone();
79        let Vector { dx: x2, dy: y2 } = rhs.clone();
80        x1 * x2 - y1 * y2 == zero()
81    }
82    /// Check if two vector is orthogonal
83    pub fn is_orthogonal(&self, rhs: &Self) -> bool {
84        let Vector { dx: x1, dy: y1 } = self.clone();
85        let Vector { dx: x2, dy: y2 } = rhs.clone();
86        x1 * x2 + y1 * y2 == zero()
87    }
88}