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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use super::*;
/// Implements factory constructors and accessors for [`Ray`] and
/// [`Occluder`].
impl Ray {
/// Creates a new ray starting at `origin` pointing in `direction`.
///
/// `t_min` and `t_max` default to [`RAYTRACE_DEFAULT_T_MIN`] and
/// [`RAYTRACE_DEFAULT_T_MAX`]. `depth` defaults to 0.
///
/// # Arguments
///
/// - `Vector3D` - The ray origin.
/// - `Vector3D` - The unit direction.
///
/// # Returns
///
/// - `Ray` - The new ray.
pub fn new(origin: Vector3D, direction: Vector3D) -> Ray {
Ray {
origin,
direction,
t_min: RAYTRACE_DEFAULT_T_MIN,
t_max: RAYTRACE_DEFAULT_T_MAX,
depth: 0,
}
}
/// Computes the world-space point at distance `t` along this ray.
///
/// # Arguments
///
/// - `f64` - The ray parameter.
///
/// # Returns
///
/// - `Vector3D` - `origin + direction * t`.
pub fn at(&self, t: f64) -> Vector3D {
self.get_origin() + self.get_direction().scaled(t)
}
/// Returns a clone of this ray with `depth` replaced by `depth`.
///
/// # Arguments
///
/// - `u32` - The new recursion depth.
///
/// # Returns
///
/// - `Ray` - The cloned ray with updated depth.
pub fn with_depth(&self, depth: u32) -> Ray {
Ray {
origin: self.get_origin(),
direction: self.get_direction(),
t_min: self.get_t_min(),
t_max: self.get_t_max(),
depth,
}
}
/// Returns a clone of this ray with its parameter range replaced.
///
/// The new bounds are taken as given, so an inverted or non-finite
/// range is representable; both query entry points reject such a ray
/// as untraceable rather than letting `NaN` comparisons decide the
/// outcome.
///
/// # Arguments
///
/// - `f64` - The minimum accepted hit parameter.
/// - `f64` - The maximum accepted hit parameter.
///
/// # Returns
///
/// - `Ray` - The cloned ray with the new range.
pub fn with_range(&self, t_min: f64, t_max: f64) -> Ray {
Ray {
origin: self.get_origin(),
direction: self.get_direction(),
t_min,
t_max,
depth: self.get_depth(),
}
}
/// Intersects this ray with a triangle using the Moller-Trumbore
/// algorithm, keeping only hits inside this ray's `t_min`..=`t_max`
/// range.
///
/// The test is two-sided: a hit from either face counts, and the
/// returned normal always faces against the ray direction. This is the
/// range-clamped counterpart of the free
/// [`intersect_triangle`](crate::intersect_triangle), which reports the
/// raw distance however far away the triangle is.
///
/// # Arguments
///
/// - `[Vector3D; 3]` - The three triangle vertices in winding order.
///
/// # Returns
///
/// - `Option<(f64, Vector3D)>` - The hit distance along the ray and the
/// unit normal oriented against the ray direction, or `None` on miss.
pub fn intersect_triangle(&self, vertices: [Vector3D; 3]) -> Option<(f64, Vector3D)> {
let (t, normal): (f64, Vector3D) = intersect_triangle(self, vertices)?;
if t < self.get_t_min() || t > self.get_t_max() {
return None;
}
Some((t, normal))
}
}
/// Implements factory constructors for [`Occluder`].
impl Occluder {
/// Creates a spherical occluder centered at `center` with `radius`.
///
/// # Arguments
///
/// - `Vector3D` - The sphere center.
/// - `f64` - The sphere radius.
/// - `Material` - The surface material.
///
/// # Returns
///
/// - `Occluder` - The new sphere occluder.
pub fn sphere(center: Vector3D, radius: f64, material: Material) -> Occluder {
Occluder {
kind: OccluderKind::Sphere,
center,
extent: Vector3D::new(radius, radius, radius),
vertices: [center; 3],
material,
}
}
/// Creates an axis-aligned bounding-box occluder from `min` to `max`.
///
/// # Arguments
///
/// - `Vector3D` - The AABB minimum corner.
/// - `Vector3D` - The AABB maximum corner.
/// - `Material` - The surface material.
///
/// # Returns
///
/// - `Occluder` - The new AABB occluder.
pub fn aabb(min: Vector3D, max: Vector3D, material: Material) -> Occluder {
Occluder {
kind: OccluderKind::Aabb,
center: min,
extent: max,
vertices: [min; 3],
material,
}
}
/// Creates a triangular occluder from its three vertices.
///
/// The vertex order fixes the geometric winding; because the
/// intersection test is two-sided the winding does not affect which
/// faces produce hits, only the raw cross-product normal before it is
/// oriented against the incoming ray.
///
/// # Arguments
///
/// - `Vector3D` - The first triangle vertex.
/// - `Vector3D` - The second triangle vertex.
/// - `Vector3D` - The third triangle vertex.
/// - `Material` - The surface material.
///
/// # Returns
///
/// - `Occluder` - The new triangle occluder.
pub fn triangle(v0: Vector3D, v1: Vector3D, v2: Vector3D, material: Material) -> Occluder {
Occluder {
kind: OccluderKind::Triangle,
center: Vector3D::zero(),
extent: Vector3D::zero(),
vertices: [v0, v1, v2],
material,
}
}
/// Returns a list of `(center, radius)` sphere tuples approximating
/// this occluder, suitable for [`soft_shadow_factor`].
///
/// For sphere occluders this returns `(center, radius)`. For AABB
/// occluders the bounding sphere is computed conservatively from the
/// AABB extents.
///
/// # Returns
///
/// - `Vec<(Vector3D, f64)>` - One bounding sphere per occluder.
pub fn occluder_points(&self) -> Vec<(Vector3D, f64)> {
collect_occluder_points(from_ref(self))
}
}
/// Implements the constructor and zero-allocation tracing entry points for
/// [`RayTraceScene`].
impl RayTraceScene {
/// Creates a new scene taking ownership of `occluders` and precomputing
/// both the bounding volume hierarchy and the `(center, radius)` shadow
/// bounding spheres used by [`soft_shadow_factor`].
///
/// The hierarchy is built once here; every later query reuses it, so
/// the cost of the BVH never appears in a per-ray measurement. The
/// public surface is unchanged from the pre-BVH constructor, which
/// takes the occluder list by value.
///
/// # Arguments
///
/// - `Vec<Occluder>` - All occluding surfaces in the scene.
///
/// # Returns
///
/// - `RayTraceScene` - The new scene with precomputed shadow data.
pub fn new(occluders: Vec<Occluder>) -> RayTraceScene {
let shadow_points: Vec<(Vector3D, f64)> = collect_occluder_points(&occluders);
let (nodes, indices): (Vec<RayTraceNode>, Vec<usize>) = build_bvh(&occluders);
RayTraceScene {
occluders,
nodes,
indices,
shadow_points,
}
}
/// Iteratively traces a ray through the scene and returns the final
/// shaded color, using the [`RAYTRACE_DEFAULT_MAX_BOUNCES`] constant as
/// the bounce limit.
///
/// Performs no heap allocation per ray or per bounce: the shadow
/// bounding spheres precomputed at construction are reused, and no
/// [`Material`] is cloned. Use [`RayTraceScene::trace_with_bounces`] to
/// override the bounce limit.
///
/// # Arguments
///
/// - `Ray` - The ray to trace.
/// - `&LightingUniforms` - Lighting parameters used during shading.
///
/// # Returns
///
/// - `Vector3D` - The final traced color.
pub fn trace(&self, ray: Ray, lights: &LightingUniforms) -> Vector3D {
self.trace_with_bounces(ray, lights, RAYTRACE_DEFAULT_MAX_BOUNCES)
}
/// Iteratively traces a ray through the scene with an explicit bounce
/// limit and returns the final shaded color.
///
/// On a miss the ambient color scaled by the accumulated specular
/// throughput is added. On a hit the surface material is evaluated with
/// [`LightingUniforms::shade`] and, when the hit material has a
/// non-zero specular component, the trace continues with a reflected
/// ray up to `max_bounces` times (incrementing the ray's `depth` field
/// per bounce).
///
/// # Arguments
///
/// - `Ray` - The ray to trace.
/// - `&LightingUniforms` - Lighting parameters used during shading.
/// - `u32` - The maximum number of bounces allowed for this ray.
///
/// # Returns
///
/// - `Vector3D` - The final traced color.
pub fn trace_with_bounces(
&self,
ray: Ray,
lights: &LightingUniforms,
max_bounces: u32,
) -> Vector3D {
trace_bounces(ray, self, lights, max_bounces)
}
/// Finds the closest intersection between a ray and the scene
/// occluders.
///
/// The winning occluder's [`Material`] is cloned exactly once, when the
/// returned [`Hit`] is constructed; losing candidates are never cloned.
/// Traversal itself resolves every candidate through the scene's
/// bounding volume hierarchy, so the cost scales with the parts of the
/// hierarchy the ray actually crosses rather than with the occluder
/// count.
///
/// # Arguments
///
/// - `&Ray` - The ray to test.
///
/// # Returns
///
/// - `Option<Hit>` - The closest hit, or `None` if the ray misses.
pub fn closest_hit(&self, ray: &Ray) -> Option<Hit> {
let occluders: &[Occluder] = self.get_occluders();
closest_hit_indexed(ray, self).map(
|(index, t, position, normal): (usize, f64, Vector3D, Vector3D)| Hit {
t,
position,
normal,
material: occluders[index].get_material().clone(),
},
)
}
/// Reports whether anything in the scene blocks the ray's parameter
/// range.
///
/// This is the any-hit counterpart to [`RayTraceScene::closest_hit`],
/// built for shadow segments: it stops at the first blocker instead of
/// resolving the whole hierarchy, so a fully occluded light costs less
/// than a fully visible one. An empty scene reports `false`, and a ray
/// with an inverted or non-finite range reports `false` rather than
/// inventing a hit.
///
/// # Arguments
///
/// - `&Ray` - The ray to test.
///
/// # Returns
///
/// - `bool` - `true` when at least one occluder intersects the range.
pub fn occluded(&self, ray: &Ray) -> bool {
occluded_indexed(ray, self)
}
}