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
use mini_math::{Point, Vector};
pub struct Plane {
pub normal: Vector,
pub d: f32,
}
impl Plane {
pub fn new(normal: Vector, d: f32) -> Self {
Self { normal, d }
}
pub fn from_points(p0: Point, p1: Point, p2: Point) -> Self {
let normal = (p1 - p0).cross(p1 - p2).normalized();
let d = -Vector::from(p1).dot(normal);
Self { normal, d }
}
pub fn distance(&self, p: Point) -> f32 {
self.normal.dot(Vector::from(p)) - self.d
}
pub fn point_closest_to(&self, p: Point) -> Point {
let distance = self.distance(p);
p - self.normal * distance
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_distance() {
let plane = Plane::from_points(
Point::new(-1.0, 0.0, -1.0),
Point::new(1.0, 0.0, -1.0),
Point::new(0.0, 0.0, 1.0),
);
let p = Point::new(1.0, 1.0, 1.0);
assert_eq!(plane.distance(p), 1.0);
}
#[test]
fn test_closest_point() {
let plane = Plane::from_points(
Point::new(-1.0, 0.0, -1.0),
Point::new(1.0, 0.0, -1.0),
Point::new(0.0, 0.0, 1.0),
);
let p = Point::new(1.0, 1.0, 1.0);
assert_eq!(plane.point_closest_to(p), Point::new(1.0, 0.0, 1.0));
}
}