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
79
80
81
82
83
84
use crate::Distance;
use mini_math::{Point, Vector3};
#[derive(Debug)]
pub struct Line {
pub point: Point,
pub direction: Vector3,
}
impl Line {
pub fn new(point: Point, direction: Vector3) -> Self {
Self { point, direction }
}
pub fn from_points(start: Point, end: Point) -> Self {
Self {
point: start,
direction: (end - start).normalized(),
}
}
}
impl Distance<Point> for Line {
fn distance(&self, p: Point) -> f32 {
let cross = self.direction.cross(p - self.point);
cross.magnitude()
}
}
impl Distance<&Line> for Line {
fn distance(&self, line: &Line) -> f32 {
let w = self.point - line.point;
let b = self.direction.dot(line.direction);
let d = self.direction.dot(w);
let e = line.direction.dot(w);
let d_p = 1.0 - b * b;
let (sc, tc) = if d_p < std::f32::EPSILON {
(0.0, if b > 1.0 { d / b } else { e })
} else {
((b * e - d) / d_p, (e - b * d) / d_p)
};
let p = w + (self.direction * sc) - (line.direction * tc);
p.magnitude()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_distance_point() {
let line = Line::from_points(Point::new(0.0, 0.0, 0.0), Point::new(0.0, 0.0, 10.0));
let p = Point::new(0.0, 0.0, -5.0);
assert_eq!(line.distance(p), 0.0);
let p = Point::new(0.0, 5.0, 25.0);
assert_eq!(line.distance(p), 5.0);
}
#[test]
fn test_distance() {
let line = Line::from_points(Point::new(0.0, 0.0, 0.0), Point::new(0.0, 0.0, 10.0));
let l = Line::from_points(Point::new(0.0, 0.0, 1.0), Point::new(0.0, 10.0, 10.0));
assert_eq!(line.distance(&l), 0.0);
let l = Line::from_points(Point::new(0.0, 5.0, 5.0), Point::new(0.0, 5.0, 15.0));
assert_eq!(line.distance(&l), 5.0);
let l = Line::from_points(Point::new(0.0, 5.0, 0.0), Point::new(25.0, 5.0, 0.0));
assert_eq!(line.distance(&l), 5.0);
}
}