-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbvh.rs
209 lines (194 loc) · 6.31 KB
/
bvh.rs
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use std::cmp::Ordering;
use std::error::Error;
use std::fmt;
use crate::hit::{Hit, HitRecord};
use crate::math::float::{self, Float};
use crate::math::{partial_max, partial_min};
use crate::ray::Ray;
use crate::vec3::Vec3;
use crate::Rng;
#[derive(Debug)]
pub enum BvhError {
MissingBoundingBox,
InvalidBoundingBox,
TooFewElements(u8),
}
impl fmt::Display for BvhError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BvhError::MissingBoundingBox => write!(
f,
"Encountered object without bounding box during BVH construction"
),
BvhError::InvalidBoundingBox => write!(
f,
"Encountered object with an invalid bounding box during BVH construction"
),
BvhError::TooFewElements(n) => write!(
f,
"Bvh::new was called with {} objects but at least two objects are required",
n
),
}
}
}
impl Error for BvhError {}
#[derive(Debug)]
pub struct Bvh<R: Rng> {
left: Box<dyn Hit<R>>,
right: Box<dyn Hit<R>>,
aabb: Aabb,
}
impl<R: Rng> Bvh<R> {
pub fn new(
mut hit_list: Vec<Box<dyn Hit<R>>>,
time_start: Float,
time_end: Float,
rng: &mut R,
) -> Result<Bvh<R>, BvhError> {
let axis = rng.gen_range(0, 3);
let mut error = None;
hit_list.sort_unstable_by(|a, b| {
// The error handling is a bit awkward here because this is a closure.
// We don't really care about performance issues here as the BVH will only be
// constructed once anyways.
let result = a
.bounding_box(time_start, time_end)
.ok_or(BvhError::MissingBoundingBox)
.and_then(|a_aabb| {
Ok((
a_aabb,
b.bounding_box(time_start, time_end)
.ok_or(BvhError::MissingBoundingBox)?,
))
})
.and_then(|(a_aabb, b_aabb)| {
a_aabb.min[axis]
.partial_cmp(&b_aabb.min[axis])
.ok_or(BvhError::InvalidBoundingBox)
});
match result {
Ok(cmp) => cmp,
Err(e) => {
if error.is_none() {
error = Some(e);
}
// Just return any Ordering as we'll exit anyways.
Ordering::Less
}
}
});
if let Some(error) = error {
return Err(error);
}
let (left, right) = match hit_list.len() {
0 => return Err(BvhError::TooFewElements(0)),
1 => return Err(BvhError::TooFewElements(1)),
2 => {
let right = hit_list.pop().unwrap();
let left = hit_list.pop().unwrap();
(left, right)
}
3 => {
let right = hit_list.pop().unwrap();
let left =
Box::new(Bvh::new(hit_list, time_start, time_end, rng)?) as Box<dyn Hit<R>>;
(left, right)
}
_ => {
let hit_list_len = hit_list.len();
let right_half = hit_list.split_off(hit_list_len / 2);
let left =
Box::new(Bvh::new(hit_list, time_start, time_end, rng)?) as Box<dyn Hit<R>>;
let right =
Box::new(Bvh::new(right_half, time_start, time_end, rng)?) as Box<dyn Hit<R>>;
(left, right)
}
};
// The `unwrap()`s are safe as we'll only reach this part if all AABBs are valid.
Ok(Bvh {
aabb: left
.bounding_box(time_start, time_end)
.unwrap()
.union(&right.bounding_box(time_start, time_end).unwrap()),
left,
right,
})
}
}
impl<R: Rng> Hit<R> for Bvh<R> {
fn hit(&self, ray: &Ray, t_min: Float, t_max: Float, rng: &mut R) -> Option<HitRecord<'_>> {
if self.aabb.hit(ray, t_min, t_max) {
match (
self.left.hit(ray, t_min, t_max, rng),
self.right.hit(ray, t_min, t_max, rng),
) {
(Some(l), Some(r)) => {
if l.t < r.t {
Some(l)
} else {
Some(r)
}
}
(Some(h), None) | (None, Some(h)) => Some(h),
(None, None) => None,
}
} else {
None
}
}
fn bounding_box(&self, _: Float, _: Float) -> Option<Aabb> {
Some(self.aabb)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Aabb {
pub min: Vec3,
pub max: Vec3,
}
impl Aabb {
pub fn new(min: Vec3, max: Vec3) -> Aabb {
Aabb { min, max }
}
pub fn empty() -> Aabb {
Aabb {
min: Vec3::new(float::MAX, float::MAX, float::MAX),
max: Vec3::new(float::MIN, float::MIN, float::MIN),
}
}
pub fn hit(&self, ray: &Ray, mut t_min: Float, mut t_max: Float) -> bool {
// Slab method to compute whether the ray intersects with the AABB.
for a in 0..3 {
let inv_d = 1.0 / ray.direction()[a];
let mut t0 = (self.min[a] - ray.origin()[a]) * inv_d;
let mut t1 = (self.max[a] - ray.origin()[a]) * inv_d;
if inv_d < 0.0 {
std::mem::swap(&mut t0, &mut t1);
}
if t0 > t_min {
t_min = t0;
}
if t1 < t_max {
t_max = t1;
}
if t_max <= t_min {
return false;
}
}
true
}
pub fn union(&self, other: &Aabb) -> Aabb {
Aabb::new(
Vec3::new(
partial_min(self.min.x(), other.min.x()),
partial_min(self.min.y(), other.min.y()),
partial_min(self.min.z(), other.min.z()),
),
Vec3::new(
partial_max(self.max.x(), other.max.x()),
partial_max(self.max.y(), other.max.y()),
partial_max(self.max.z(), other.max.z()),
),
)
}
}