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
use euclid::{Length, Point2D, Vector2D};
#[derive(Debug, Default, PartialEq)]
pub struct Line<S> {
pub start: Point2D<f64, S>,
pub end: Point2D<f64, S>,
}
impl<S> Line<S> {
pub const fn new(start: Point2D<f64, S>, end: Point2D<f64, S>) -> Self {
Line { start, end }
}
pub fn displacement(&self) -> Vector2D<f64, S> { self.end - self.start }
pub fn direction(&self) -> Vector2D<f64, S> {
self.displacement().normalize()
}
pub fn length(self) -> f64 { self.displacement().length() }
pub fn perpendicular_distance_to(
self,
point: Point2D<f64, S>,
) -> Length<f64, S> {
const SOME_SMALL_NUMBER: f64 = std::f64::EPSILON * 100.0;
let side_a = self.start - point;
let side_b = self.end - point;
let area = Vector2D::cross(side_a, side_b) / 2.0;
let base_length = self.length();
Length::new(if base_length.abs() < SOME_SMALL_NUMBER {
side_a.length()
} else {
area.abs() * 2.0 / base_length
})
}
}
impl<S> Copy for Line<S> {}
impl<S> Clone for Line<S> {
fn clone(&self) -> Self { *self }
}
#[cfg(test)]
mod tests {
use super::*;
type Point = euclid::default::Point2D<f64>;
type Vector = euclid::default::Vector2D<f64>;
#[test]
fn calculate_length() {
let start = Point::new(1.0, 1.0);
let displacement = Vector::new(3.0, 4.0);
let v = Line::new(start, start + displacement);
assert_eq!(v.length(), 5.0);
assert_eq!(v.displacement(), displacement);
}
}