Skip to main content

geop_core_math/primitives/
line.rs

1use crate::{
2    geop_error::{GeopError, GeopResult},
3    scalars::Scalar,
4    vector::Vector3,
5};
6
7pub struct Line<S: Scalar> {
8    start: Vector3<S>,
9    end: Vector3<S>,
10}
11
12impl<S: Scalar> core::fmt::Debug for Line<S> {
13    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
14        write!(f, "Line({:?} → {:?})", self.start, self.end)
15    }
16}
17
18impl<S: Scalar> Line<S> {
19    /// Fails if `start` and `end` could be equal (zero-length segment uncertain).
20    pub fn try_new(start: Vector3<S>, end: Vector3<S>) -> GeopResult<Self> {
21        let d = end.sub(&start);
22        if d.norm_sq().could_be_equal(S::ZERO) {
23            return Err(GeopError::new(
24                "Line::try_new: start and end could be equal (degenerate segment)",
25            ));
26        }
27        Ok(Self { start, end })
28    }
29
30    pub fn start(&self) -> &Vector3<S> {
31        &self.start
32    }
33    pub fn end(&self) -> &Vector3<S> {
34        &self.end
35    }
36
37    pub fn direction(&self) -> Vector3<S> {
38        self.end.sub(&self.start)
39    }
40
41    pub fn length_sq(&self) -> S {
42        let d = self.direction();
43        d.norm_sq()
44    }
45}