kdtree_ray/aabb.rs
1use crate::Point3;
2
3/// Axis-aligned bounding box is defined by two positions.
4///
5/// **Note**: The first position is expected to be the minimum bound and the second
6/// the maximum bound.
7///
8/// The animated GIF below shows a graphic example of an AABB that adapts its
9/// size to fit the rotating entity. The box constantly changes dimensions to
10/// snugly fit the entity contained inside.
11///
12/// 
13#[derive(Clone, Debug)]
14pub struct AABB {
15 /// Minimum position
16 pub min: Point3,
17 /// Maximum position
18 pub max: Point3,
19}
20
21impl Default for AABB {
22 fn default() -> Self {
23 Self::empty()
24 }
25}
26
27impl AABB {
28 /// Create an new AABB from two points.
29 pub fn new(min: Point3, max: Point3) -> Self {
30 Self { min, max }
31 }
32
33 /// Create an empty AABB.
34 pub fn empty() -> Self {
35 Self::new(
36 Point3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY),
37 Point3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY),
38 )
39 }
40
41 /// Compute AABB volume
42 pub fn volume(&self) -> f32 {
43 (self.max.x - self.min.x) * (self.max.y - self.min.y) * (self.max.z - self.min.z)
44 }
45
46 /// Compute AABB surface
47 pub fn surface(&self) -> f32 {
48 let dx = self.max.x - self.min.x;
49 let dy = self.max.y - self.min.y;
50 let dz = self.max.z - self.min.z;
51 2.0 * (dx * dy + dx * dz + dy * dz)
52 }
53
54 /// Merge another AABB into this one.
55 pub fn merge(&mut self, other: &Self) {
56 self.min = Point3::new(
57 self.min.x.min(other.min.x),
58 self.min.y.min(other.min.y),
59 self.min.z.min(other.min.z),
60 );
61 self.max = Point3::new(
62 self.max.x.max(other.max.x),
63 self.max.y.max(other.max.y),
64 self.max.z.max(other.max.z),
65 );
66 }
67}
68
69/// Your shapes needs to implement `Bounded` trait to build a KD-tree around it.
70pub trait Bounded {
71 /// This function return the **Axis-aligned bounding boxes**
72 /// (`AABB`) of the object.
73 ///
74 /// For more information check [AABB](type.AABB.html).
75 fn bound(&self) -> AABB;
76}