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
use crate::{F32Ext, Point, Transform, Transformation};
use std::cmp::Ordering;

/// A quadratic bezier curve segment in 2-dimensional Euclidian space.
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(C)]
pub struct LineSegment {
    pub p0: Point,
    pub p1: Point,
}

impl LineSegment {
    /// Creates a new line segment with the given endpoints.
    pub fn new(p0: Point, p1: Point) -> LineSegment {
        LineSegment { p0, p1 }
    }

    /// Compares `self` to the point `p`.
    ///
    /// Returns `Ordering::Less` if `self` lies below `p`, `Ordering::Greater` if `self` lies
    /// above `p`, and `Ordering::Equal` if `self` is incident to `p`.
    pub fn compare_to_point(self, p: Point) -> Option<Ordering> {
        // Compute the signed area of the triangle with vertices `p`, `p0`, and `p1`.
        (p - self.p0).cross(self.p1 - p).partial_cmp(&0.0)
    }

    /// Returns the intersection point of the supporting line of `self` with the vertical line
    /// through `x`, or None if these lines are coincident.
    pub fn intersect_with_vertical_line(self, x: f32) -> Option<Point> {
        let dx = self.p1.x - self.p0.x;
        if dx == 0.0 {
            return None;
        }
        let dx1 = x - self.p0.x;
        let dx2 = self.p1.x - x;
        Some(Point {
            x,
            y: if dx1 <= dx2 {
                self.p0.y.lerp(self.p1.y, dx1 / dx)
            } else {
                self.p1.y.lerp(self.p0.y, dx2 / dx)
            },
        })
    }
}

impl Transform for LineSegment {
    fn transform<T>(self, t: &T) -> LineSegment
    where
        T: Transformation,
    {
        LineSegment::new(self.p0.transform(t), self.p1.transform(t))
    }

    fn transform_mut<T>(&mut self, t: &T)
    where
        T: Transformation,
    {
        *self = self.transform(t);
    }
}