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
use crate::Distance;
use mini_math::Point;
#[derive(Debug)]
pub struct LineSegment {
pub start: Point,
pub end: Point,
}
impl LineSegment {
pub fn new(start: Point, end: Point) -> Self {
Self { start, end }
}
}
impl Distance<Point> for LineSegment {
fn distance(&self, p: Point) -> f32 {
let mut direction = self.end - self.start;
let length = direction.magnitude();
direction /= length;
let diff = p - self.start;
let dot = direction.dot(diff);
if dot < 0.0 {
return diff.magnitude();
}
if dot > length {
return (p - self.end).magnitude();
}
let cross = direction.cross(diff);
cross.magnitude()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_distance() {
let line = LineSegment::new(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), 5.0);
let p = Point::new(0.0, 0.0, 15.0);
assert_eq!(line.distance(p), 5.0);
let p = Point::new(0.0, 5.0, 5.0);
assert_eq!(line.distance(p), 5.0);
}
}