1use super::*;
2
3impl RtTriangle {
5 #[must_use]
18 pub fn from_vertices(
19 positions: [Vec3; 3],
20 normals: [Vec3; 3],
21 uvs: [Vec2; 3],
22 material_slot: u16,
23 ) -> Self {
24 let v0: Vec3 = positions[0];
25 let v1: Vec3 = positions[1];
26 let v2: Vec3 = positions[2];
27 let edge1: Vec3 = v1.sub(v0);
28 let edge2: Vec3 = v2.sub(v0);
29 let geometric_normal: Vec3 = edge1.cross(edge2).normalize();
30 let mut bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
31 bounds.expand_point(v0);
32 bounds.expand_point(v1);
33 bounds.expand_point(v2);
34 let centroid: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
35 Self {
36 v0,
37 edge1,
38 edge2,
39 n0: if normals[0].length_sq() > RT_EPSILON {
40 normals[0].normalize()
41 } else {
42 geometric_normal
43 },
44 n1: if normals[1].length_sq() > RT_EPSILON {
45 normals[1].normalize()
46 } else {
47 geometric_normal
48 },
49 n2: if normals[2].length_sq() > RT_EPSILON {
50 normals[2].normalize()
51 } else {
52 geometric_normal
53 },
54 uv0: uvs[0],
55 uv1: uvs[1],
56 uv2: uvs[2],
57 geometric_normal,
58 bounds,
59 centroid,
60 material_slot,
61 }
62 }
63
64 #[must_use]
76 pub fn from_positions(v0: Vec3, v1: Vec3, v2: Vec3) -> Self {
77 let face_normal: Vec3 = v1.sub(v0).cross(v2.sub(v0)).normalize();
78 Self::from_vertices(
79 [v0, v1, v2],
80 [face_normal, face_normal, face_normal],
81 [
82 Vec2::new(0.0, 0.0),
83 Vec2::new(1.0, 0.0),
84 Vec2::new(0.0, 1.0),
85 ],
86 0,
87 )
88 }
89
90 #[must_use]
102 pub fn interpolate_normal(&self, bary_u: f32, bary_v: f32) -> Vec3 {
103 let w: f32 = (1.0 - bary_u - bary_v).max(0.0);
104 let blended: Vec3 = self
105 .get_n0()
106 .scale(w)
107 .add(self.get_n1().scale(bary_u))
108 .add(self.get_n2().scale(bary_v));
109 if blended.length_sq() > RT_EPSILON {
110 blended.normalize()
111 } else {
112 self.get_geometric_normal()
113 }
114 }
115
116 #[must_use]
128 pub fn interpolate_uv(&self, bary_u: f32, bary_v: f32) -> Vec2 {
129 let w: f32 = (1.0 - bary_u - bary_v).max(0.0);
130 let uv0: Vec2 = self.get_uv0();
131 let uv1: Vec2 = self.get_uv1();
132 let uv2: Vec2 = self.get_uv2();
133 Vec2::new(
134 uv0.get_x() * w + uv1.get_x() * bary_u + uv2.get_x() * bary_v,
135 uv0.get_y() * w + uv1.get_y() * bary_u + uv2.get_y() * bary_v,
136 )
137 }
138}
139
140impl Default for SahBin {
142 fn default() -> Self {
148 Self {
149 bounds: AxisAlignedBox3D::empty(),
150 count: 0,
151 }
152 }
153}
154
155impl Default for Blas3D {
157 fn default() -> Self {
163 Self {
164 nodes: Vec::new(),
165 triangles: Vec::new(),
166 bounds: AxisAlignedBox3D::empty(),
167 }
168 }
169}
170
171impl Blas3D {
173 #[must_use]
183 pub fn from_triangles(mut triangles: Vec<RtTriangle>) -> Self {
184 if triangles.is_empty() {
185 return Self {
186 nodes: Vec::new(),
187 triangles,
188 bounds: AxisAlignedBox3D::empty(),
189 };
190 }
191 let tri_count: usize = triangles.len();
192 let mut nodes: Vec<BlasNode3D> = Vec::with_capacity(tri_count * 2);
193 let root_idx: u32 = Self::build_recursive(&mut nodes, &mut triangles, 0, tri_count);
194 let root_bounds: AxisAlignedBox3D = nodes
195 .get(root_idx as usize)
196 .map_or(AxisAlignedBox3D::empty(), |node: &BlasNode3D| {
197 node.get_bounds()
198 });
199 Self {
200 nodes,
201 triangles,
202 bounds: root_bounds,
203 }
204 }
205
206 #[must_use]
216 pub fn from_mesh(mesh: &Mesh3D) -> Self {
217 let vertices: &[Vertex3D] = mesh.get_vertices().as_slice();
218 let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
219 let tri_mats: &[u16] = mesh.get_tri_materials().as_slice();
220 let mut triangles: Vec<RtTriangle> = Vec::with_capacity(indices.len());
221 for (tri_idx, tri) in indices.iter().enumerate() {
222 let i0: usize = tri[0] as usize;
223 let i1: usize = tri[1] as usize;
224 let i2: usize = tri[2] as usize;
225 if i0 >= vertices.len() || i1 >= vertices.len() || i2 >= vertices.len() {
226 continue;
227 }
228 let vert0: Vertex3D = vertices[i0];
229 let vert1: Vertex3D = vertices[i1];
230 let vert2: Vertex3D = vertices[i2];
231 let slot: u16 = tri_mats.get(tri_idx).copied().unwrap_or(0);
232 let uv0_arr: [f32; 2] = vert0.get_uv0();
233 let uv1_arr: [f32; 2] = vert1.get_uv0();
234 let uv2_arr: [f32; 2] = vert2.get_uv0();
235 triangles.push(RtTriangle::from_vertices(
236 [
237 vert0.get_position(),
238 vert1.get_position(),
239 vert2.get_position(),
240 ],
241 [vert0.get_normal(), vert1.get_normal(), vert2.get_normal()],
242 [
243 Vec2::new(uv0_arr[0], uv0_arr[1]),
244 Vec2::new(uv1_arr[0], uv1_arr[1]),
245 Vec2::new(uv2_arr[0], uv2_arr[1]),
246 ],
247 slot,
248 ));
249 }
250 Self::from_triangles(triangles)
251 }
252
253 fn build_recursive(
266 nodes: &mut Vec<BlasNode3D>,
267 triangles: &mut [RtTriangle],
268 start: usize,
269 end: usize,
270 ) -> u32 {
271 let mut node_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
272 let mut centroid_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
273 for tri in &triangles[start..end] {
274 node_bounds.expand_box(tri.get_bounds());
275 centroid_bounds.expand_point(tri.get_centroid());
276 }
277 let node_idx: u32 = nodes.len() as u32;
278 let count: usize = end - start;
279 nodes.push(BlasNode3D {
280 bounds: node_bounds,
281 left: 0,
282 right: 0,
283 first_tri: start as u32,
284 tri_count: count as u32,
285 });
286 if count <= RT_BLAS_LEAF_MAX_TRIS {
287 return node_idx;
288 }
289 let parent_area: f32 = node_bounds.surface_area().max(RT_EPSILON);
290 let leaf_cost: f32 = count as f32;
291 let mut best_cost: f32 = f32::INFINITY;
292 let mut best_axis: usize = 0;
293 let mut best_split_pos: f32 = 0.0;
294 let mut found_sah_split: bool = false;
295 for axis in 0..3 {
296 let c_min: f32 = vec3_axis(centroid_bounds.get_min(), axis);
297 let c_max: f32 = vec3_axis(centroid_bounds.get_max(), axis);
298 let span: f32 = c_max - c_min;
299 if span <= RT_EPSILON {
300 continue;
301 }
302 let mut bins: [SahBin; RT_SAH_BIN_COUNT] = [SahBin::default(); RT_SAH_BIN_COUNT];
303 let scale: f32 = (RT_SAH_BIN_COUNT as f32) / span;
304 for tri in &triangles[start..end] {
305 let raw_bin: usize =
306 ((vec3_axis(tri.get_centroid(), axis) - c_min) * scale) as usize;
307 let bin_idx: usize = raw_bin.min(RT_SAH_BIN_COUNT - 1);
308 let mut bin_bounds: AxisAlignedBox3D = bins[bin_idx].get_bounds();
309 bin_bounds.expand_box(tri.get_bounds());
310 bins[bin_idx].set_bounds(bin_bounds);
311 let next_count: u32 = bins[bin_idx].get_count() + 1;
312 bins[bin_idx].set_count(next_count);
313 }
314 let mut left_area: [f32; RT_SAH_BIN_COUNT - 1] = [0.0; RT_SAH_BIN_COUNT - 1];
315 let mut left_count: [u32; RT_SAH_BIN_COUNT - 1] = [0; RT_SAH_BIN_COUNT - 1];
316 let mut acc_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
317 let mut acc_count: u32 = 0;
318 for split_idx in 0..(RT_SAH_BIN_COUNT - 1) {
319 acc_bounds.expand_box(bins[split_idx].get_bounds());
320 acc_count += bins[split_idx].get_count();
321 left_area[split_idx] = acc_bounds.surface_area();
322 left_count[split_idx] = acc_count;
323 }
324 let mut right_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
325 let mut right_count: u32 = 0;
326 for split_idx in (0..(RT_SAH_BIN_COUNT - 1)).rev() {
327 right_bounds.expand_box(bins[split_idx + 1].get_bounds());
328 right_count += bins[split_idx + 1].get_count();
329 let l_cnt: u32 = left_count[split_idx];
330 if l_cnt == 0 || right_count == 0 {
331 continue;
332 }
333 let cost: f32 = 0.5
334 + ((left_area[split_idx] * (l_cnt as f32))
335 + (right_bounds.surface_area() * (right_count as f32)))
336 / parent_area;
337 if cost < best_cost {
338 best_cost = cost;
339 best_axis = axis;
340 best_split_pos =
341 c_min + ((split_idx + 1) as f32) * (span / (RT_SAH_BIN_COUNT as f32));
342 found_sah_split = true;
343 }
344 }
345 }
346 let mut mid: usize = if found_sah_split && best_cost < leaf_cost {
347 Self::partition_triangles(triangles, start, end, best_axis, best_split_pos)
348 } else {
349 let extent: Vec3 = centroid_bounds.get_max().sub(centroid_bounds.get_min());
350 let fallback_axis: usize =
351 if extent.get_x() >= extent.get_y() && extent.get_x() >= extent.get_z() {
352 0
353 } else if extent.get_y() >= extent.get_z() {
354 1
355 } else {
356 2
357 };
358 let split_mid: f32 = (vec3_axis(centroid_bounds.get_min(), fallback_axis)
359 + vec3_axis(centroid_bounds.get_max(), fallback_axis))
360 * 0.5;
361 Self::partition_triangles(triangles, start, end, fallback_axis, split_mid)
362 };
363 if mid == start || mid == end {
364 mid = start + count / 2;
365 }
366 let left_idx: u32 = Self::build_recursive(nodes, triangles, start, mid);
367 let right_idx: u32 = Self::build_recursive(nodes, triangles, mid, end);
368 if let Some(node_ref) = nodes.get_mut(node_idx as usize) {
369 node_ref.set_left(left_idx);
370 node_ref.set_right(right_idx);
371 node_ref.set_tri_count(0);
372 }
373 node_idx
374 }
375
376 fn partition_triangles(
390 triangles: &mut [RtTriangle],
391 start: usize,
392 end: usize,
393 axis: usize,
394 split_pos: f32,
395 ) -> usize {
396 let mut left: usize = start;
397 let mut right: usize = end;
398 while left < right {
399 if vec3_axis(triangles[left].get_centroid(), axis) < split_pos {
400 left += 1;
401 } else {
402 right -= 1;
403 triangles.swap(left, right);
404 }
405 }
406 left
407 }
408
409 #[must_use]
419 pub fn triangle_count(&self) -> usize {
420 self.get_triangles().len()
421 }
422
423 #[must_use]
433 pub fn node_count(&self) -> usize {
434 self.get_nodes().len()
435 }
436
437 #[must_use]
447 pub fn is_empty(&self) -> bool {
448 self.get_triangles().is_empty()
449 }
450
451 #[must_use]
464 pub fn trace_closest(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<RtLocalHit> {
465 self.trace_closest_unnormalized(
466 ray.get_origin(),
467 ray.get_direction(),
468 ray.get_inv_direction(),
469 t_min,
470 t_max,
471 )
472 }
473
474 #[must_use]
489 pub fn trace_closest_unnormalized(
490 &self,
491 origin: Vec3,
492 direction: Vec3,
493 inv_dir: Vec3,
494 t_min: f32,
495 t_max: f32,
496 ) -> Option<RtLocalHit> {
497 let nodes: &[BlasNode3D] = self.get_nodes().as_slice();
498 let triangles: &[RtTriangle] = self.get_triangles().as_slice();
499 if nodes.is_empty() {
500 return None;
501 }
502 let root_near: f32 = nodes[0]
503 .get_bounds()
504 .intersect_ray_near(origin, inv_dir, t_min, t_max);
505 if !root_near.is_finite() {
506 return None;
507 }
508 let mut stack: [u32; RT_BVH_STACK_CAPACITY] = [0; RT_BVH_STACK_CAPACITY];
509 let mut stack_len: usize = 1;
510 let mut best_t: f32 = t_max;
511 let mut best_tri_idx: u32 = u32::MAX;
512 let mut best_u: f32 = 0.0;
513 let mut best_v: f32 = 0.0;
514 while stack_len > 0 {
515 stack_len -= 1;
516 let node: BlasNode3D = nodes[stack[stack_len] as usize];
517 let tri_count: u32 = node.get_tri_count();
518 if tri_count > 0 {
519 let first: usize = node.get_first_tri() as usize;
520 let last: usize = first + (tri_count as usize);
521 for (offset, tri) in triangles[first..last].iter().enumerate() {
522 if let Some((hit_t, bary_u, bary_v)) =
523 intersect_triangle_moller_trumbore(origin, direction, tri, t_min, best_t)
524 {
525 best_t = hit_t;
526 best_tri_idx = (first + offset) as u32;
527 best_u = bary_u;
528 best_v = bary_v;
529 }
530 }
531 } else {
532 let left_idx: u32 = node.get_left();
533 let right_idx: u32 = node.get_right();
534 let t_left: f32 = nodes[left_idx as usize]
535 .get_bounds()
536 .intersect_ray_near(origin, inv_dir, t_min, best_t);
537 let t_right: f32 = nodes[right_idx as usize]
538 .get_bounds()
539 .intersect_ray_near(origin, inv_dir, t_min, best_t);
540 let hit_left: bool = t_left.is_finite() && t_left <= best_t;
541 let hit_right: bool = t_right.is_finite() && t_right <= best_t;
542 if hit_left && hit_right {
543 let (near_idx, far_idx): (u32, u32) = if t_left <= t_right {
544 (left_idx, right_idx)
545 } else {
546 (right_idx, left_idx)
547 };
548 if stack_len + 2 <= RT_BVH_STACK_CAPACITY {
549 stack[stack_len] = far_idx;
550 stack[stack_len + 1] = near_idx;
551 stack_len += 2;
552 }
553 } else if hit_left && stack_len < RT_BVH_STACK_CAPACITY {
554 stack[stack_len] = left_idx;
555 stack_len += 1;
556 } else if hit_right && stack_len < RT_BVH_STACK_CAPACITY {
557 stack[stack_len] = right_idx;
558 stack_len += 1;
559 }
560 }
561 }
562 if best_tri_idx == u32::MAX {
563 return None;
564 }
565 let tri: RtTriangle = triangles[best_tri_idx as usize];
566 let position: Vec3 = origin.add(direction.scale(best_t));
567 Some(RtLocalHit {
568 distance: best_t,
569 barycentric_u: best_u,
570 barycentric_v: best_v,
571 position,
572 geometric_normal: tri.get_geometric_normal(),
573 shading_normal: tri.interpolate_normal(best_u, best_v),
574 uv: tri.interpolate_uv(best_u, best_v),
575 triangle_index: best_tri_idx,
576 material_slot: tri.get_material_slot(),
577 })
578 }
579
580 #[must_use]
593 pub fn trace_any_hit(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
594 self.trace_any_hit_unnormalized(
595 ray.get_origin(),
596 ray.get_direction(),
597 ray.get_inv_direction(),
598 t_min,
599 t_max,
600 )
601 }
602
603 #[must_use]
618 pub fn trace_any_hit_unnormalized(
619 &self,
620 origin: Vec3,
621 direction: Vec3,
622 inv_dir: Vec3,
623 t_min: f32,
624 t_max: f32,
625 ) -> bool {
626 let nodes: &[BlasNode3D] = self.get_nodes().as_slice();
627 let triangles: &[RtTriangle] = self.get_triangles().as_slice();
628 if nodes.is_empty() {
629 return false;
630 }
631 if !nodes[0]
632 .get_bounds()
633 .intersect_ray_near(origin, inv_dir, t_min, t_max)
634 .is_finite()
635 {
636 return false;
637 }
638 let mut stack: [u32; RT_BVH_STACK_CAPACITY] = [0; RT_BVH_STACK_CAPACITY];
639 let mut stack_len: usize = 1;
640 while stack_len > 0 {
641 stack_len -= 1;
642 let node: BlasNode3D = nodes[stack[stack_len] as usize];
643 let tri_count: u32 = node.get_tri_count();
644 if tri_count > 0 {
645 let first: usize = node.get_first_tri() as usize;
646 let last: usize = first + (tri_count as usize);
647 for tri in &triangles[first..last] {
648 if intersect_triangle_moller_trumbore(origin, direction, tri, t_min, t_max)
649 .is_some()
650 {
651 return true;
652 }
653 }
654 } else {
655 let left_idx: u32 = node.get_left();
656 let right_idx: u32 = node.get_right();
657 if nodes[left_idx as usize]
658 .get_bounds()
659 .intersect_ray_near(origin, inv_dir, t_min, t_max)
660 .is_finite()
661 && stack_len < RT_BVH_STACK_CAPACITY
662 {
663 stack[stack_len] = left_idx;
664 stack_len += 1;
665 }
666 if nodes[right_idx as usize]
667 .get_bounds()
668 .intersect_ray_near(origin, inv_dir, t_min, t_max)
669 .is_finite()
670 && stack_len < RT_BVH_STACK_CAPACITY
671 {
672 stack[stack_len] = right_idx;
673 stack_len += 1;
674 }
675 }
676 }
677 false
678 }
679
680 #[must_use]
693 pub fn trace_closest_brute_force(
694 &self,
695 ray: &Ray3D,
696 t_min: f32,
697 t_max: f32,
698 ) -> Option<RtLocalHit> {
699 self.trace_closest_brute_force_unnormalized(
700 ray.get_origin(),
701 ray.get_direction(),
702 t_min,
703 t_max,
704 )
705 }
706
707 #[must_use]
721 pub fn trace_closest_brute_force_unnormalized(
722 &self,
723 origin: Vec3,
724 direction: Vec3,
725 t_min: f32,
726 t_max: f32,
727 ) -> Option<RtLocalHit> {
728 let triangles: &[RtTriangle] = self.get_triangles().as_slice();
729 let mut best_t: f32 = t_max;
730 let mut best_tri_idx: u32 = u32::MAX;
731 let mut best_u: f32 = 0.0;
732 let mut best_v: f32 = 0.0;
733 for (idx, tri) in triangles.iter().enumerate() {
734 if let Some((hit_t, bary_u, bary_v)) =
735 intersect_triangle_moller_trumbore(origin, direction, tri, t_min, best_t)
736 {
737 best_t = hit_t;
738 best_tri_idx = idx as u32;
739 best_u = bary_u;
740 best_v = bary_v;
741 }
742 }
743 if best_tri_idx == u32::MAX {
744 return None;
745 }
746 let tri: RtTriangle = triangles[best_tri_idx as usize];
747 let position: Vec3 = origin.add(direction.scale(best_t));
748 Some(RtLocalHit {
749 distance: best_t,
750 barycentric_u: best_u,
751 barycentric_v: best_v,
752 position,
753 geometric_normal: tri.get_geometric_normal(),
754 shading_normal: tri.interpolate_normal(best_u, best_v),
755 uv: tri.interpolate_uv(best_u, best_v),
756 triangle_index: best_tri_idx,
757 material_slot: tri.get_material_slot(),
758 })
759 }
760}
761
762impl RtInstance {
764 #[must_use]
777 pub fn new(
778 blas_id: u32,
779 transform: Mat4,
780 material_id: u32,
781 local_bounds: AxisAlignedBox3D,
782 ) -> Self {
783 let inv_transform: Mat4 = transform.inverse().unwrap_or(Mat4::identity());
784 let normal_matrix: [Vec3; 3] = transform.normal_matrix_3x3();
785 let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
786 let det: f32 = mat4_linear_determinant(&transform);
787 let determinant_sign: f32 = if det < 0.0 { -1.0 } else { 1.0 };
788 Self {
789 blas_id,
790 transform,
791 inv_transform,
792 normal_matrix,
793 material_id,
794 world_bounds,
795 visible: true,
796 determinant_sign,
797 }
798 }
799
800 pub fn update_transform(&mut self, transform: Mat4, local_bounds: AxisAlignedBox3D) {
808 let inv_transform: Mat4 = transform.inverse().unwrap_or(Mat4::identity());
809 let normal_matrix: [Vec3; 3] = transform.normal_matrix_3x3();
810 let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
811 let det: f32 = mat4_linear_determinant(&transform);
812 self.set_transform(transform);
813 self.set_inv_transform(inv_transform);
814 self.set_normal_matrix(normal_matrix);
815 self.set_world_bounds(world_bounds);
816 self.set_determinant_sign(if det < 0.0 { -1.0 } else { 1.0 });
817 }
818}
819
820impl Default for Tlas3D {
822 fn default() -> Self {
828 Self::new()
829 }
830}
831
832impl Tlas3D {
834 #[must_use]
840 pub fn new() -> Self {
841 Self {
842 nodes: Vec::new(),
843 instances: Vec::new(),
844 instance_order: Vec::new(),
845 bounds: AxisAlignedBox3D::empty(),
846 refit_count: 0,
847 rebuild_count: 0,
848 }
849 }
850
851 pub fn add_instance(&mut self, instance: RtInstance) -> usize {
862 let id: usize = self.get_instances().len();
863 self.get_mut_instances().push(instance);
864 id
865 }
866
867 pub fn update_instance_transform(
880 &mut self,
881 instance_id: usize,
882 transform: Mat4,
883 local_bounds: AxisAlignedBox3D,
884 ) -> bool {
885 if let Some(instance) = self.get_mut_instances().get_mut(instance_id) {
886 instance.update_transform(transform, local_bounds);
887 true
888 } else {
889 false
890 }
891 }
892
893 #[must_use]
903 pub fn instance_count(&self) -> usize {
904 self.get_instances().len()
905 }
906
907 #[must_use]
917 pub fn node_count(&self) -> usize {
918 self.get_nodes().len()
919 }
920
921 #[must_use]
931 pub fn is_empty(&self) -> bool {
932 self.get_nodes().is_empty()
933 }
934
935 pub fn rebuild(&mut self) {
941 let Self {
942 nodes,
943 instances,
944 instance_order,
945 bounds,
946 rebuild_count,
947 ..
948 } = self;
949 nodes.clear();
950 instance_order.clear();
951 for (idx, inst) in instances.iter().enumerate() {
952 if inst.get_visible() {
953 instance_order.push(idx as u32);
954 }
955 }
956 if instance_order.is_empty() {
957 *bounds = AxisAlignedBox3D::empty();
958 *rebuild_count += 1;
959 return;
960 }
961 let order_len: usize = instance_order.len();
962 nodes.reserve(order_len * 2);
963 let root_idx: u32 =
964 Self::build_tlas_recursive(nodes, instances, instance_order, 0, order_len);
965 *bounds = nodes
966 .get(root_idx as usize)
967 .map_or(AxisAlignedBox3D::empty(), |node: &TlasNode3D| {
968 node.get_bounds()
969 });
970 *rebuild_count += 1;
971 }
972
973 pub fn refit(&mut self) {
979 let visible_count: usize = self
980 .get_instances()
981 .iter()
982 .filter(|inst: &&RtInstance| inst.get_visible())
983 .count();
984 if self.get_nodes().is_empty() || self.get_instance_order().len() != visible_count {
985 self.rebuild();
986 return;
987 }
988 let Self {
989 nodes,
990 instances,
991 instance_order,
992 bounds,
993 refit_count,
994 ..
995 } = self;
996 let node_count: usize = nodes.len();
997 for idx in (0..node_count).rev() {
998 let inst_count: u32 = nodes[idx].get_instance_count();
999 if inst_count > 0 {
1000 let first: usize = nodes[idx].get_first_instance() as usize;
1001 let last: usize = first + (inst_count as usize);
1002 let mut leaf_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1003 for &inst_id in &instance_order[first..last] {
1004 leaf_bounds.expand_box(instances[inst_id as usize].get_world_bounds());
1005 }
1006 nodes[idx].set_bounds(leaf_bounds);
1007 } else {
1008 let left_idx: usize = nodes[idx].get_left() as usize;
1009 let right_idx: usize = nodes[idx].get_right() as usize;
1010 let mut merged: AxisAlignedBox3D = nodes[left_idx].get_bounds();
1011 merged.expand_box(nodes[right_idx].get_bounds());
1012 nodes[idx].set_bounds(merged);
1013 }
1014 }
1015 *bounds = nodes[0].get_bounds();
1016 *refit_count += 1;
1017 }
1018
1019 fn build_tlas_recursive(
1033 nodes: &mut Vec<TlasNode3D>,
1034 instances: &[RtInstance],
1035 instance_order: &mut [u32],
1036 start: usize,
1037 end: usize,
1038 ) -> u32 {
1039 let mut node_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1040 let mut centroid_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1041 for &inst_id in &instance_order[start..end] {
1042 let wb: AxisAlignedBox3D = instances[inst_id as usize].get_world_bounds();
1043 node_bounds.expand_box(wb);
1044 centroid_bounds.expand_point(wb.center());
1045 }
1046 let node_idx: u32 = nodes.len() as u32;
1047 let count: usize = end - start;
1048 nodes.push(TlasNode3D {
1049 bounds: node_bounds,
1050 left: 0,
1051 right: 0,
1052 first_instance: start as u32,
1053 instance_count: count as u32,
1054 });
1055 if count <= RT_TLAS_LEAF_MAX_INSTANCES {
1056 return node_idx;
1057 }
1058 let parent_area: f32 = node_bounds.surface_area().max(RT_EPSILON);
1059 let leaf_cost: f32 = count as f32;
1060 let mut best_cost: f32 = f32::INFINITY;
1061 let mut best_axis: usize = 0;
1062 let mut best_split_pos: f32 = 0.0;
1063 let mut found_sah: bool = false;
1064 for axis in 0..3 {
1065 let c_min: f32 = vec3_axis(centroid_bounds.get_min(), axis);
1066 let c_max: f32 = vec3_axis(centroid_bounds.get_max(), axis);
1067 let span: f32 = c_max - c_min;
1068 if span <= RT_EPSILON {
1069 continue;
1070 }
1071 let mut bins: [SahBin; RT_SAH_BIN_COUNT] = [SahBin::default(); RT_SAH_BIN_COUNT];
1072 let scale: f32 = (RT_SAH_BIN_COUNT as f32) / span;
1073 for &inst_id in &instance_order[start..end] {
1074 let wb: AxisAlignedBox3D = instances[inst_id as usize].get_world_bounds();
1075 let raw_bin: usize = ((vec3_axis(wb.center(), axis) - c_min) * scale) as usize;
1076 let bin_idx: usize = raw_bin.min(RT_SAH_BIN_COUNT - 1);
1077 let mut bin_bounds: AxisAlignedBox3D = bins[bin_idx].get_bounds();
1078 bin_bounds.expand_box(wb);
1079 bins[bin_idx].set_bounds(bin_bounds);
1080 let next_count: u32 = bins[bin_idx].get_count() + 1;
1081 bins[bin_idx].set_count(next_count);
1082 }
1083 let mut left_area: [f32; RT_SAH_BIN_COUNT - 1] = [0.0; RT_SAH_BIN_COUNT - 1];
1084 let mut left_count: [u32; RT_SAH_BIN_COUNT - 1] = [0; RT_SAH_BIN_COUNT - 1];
1085 let mut acc_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1086 let mut acc_count: u32 = 0;
1087 for split_idx in 0..(RT_SAH_BIN_COUNT - 1) {
1088 acc_bounds.expand_box(bins[split_idx].get_bounds());
1089 acc_count += bins[split_idx].get_count();
1090 left_area[split_idx] = acc_bounds.surface_area();
1091 left_count[split_idx] = acc_count;
1092 }
1093 let mut right_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1094 let mut right_count: u32 = 0;
1095 for split_idx in (0..(RT_SAH_BIN_COUNT - 1)).rev() {
1096 right_bounds.expand_box(bins[split_idx + 1].get_bounds());
1097 right_count += bins[split_idx + 1].get_count();
1098 let l_cnt: u32 = left_count[split_idx];
1099 if l_cnt == 0 || right_count == 0 {
1100 continue;
1101 }
1102 let cost: f32 = 0.5
1103 + ((left_area[split_idx] * (l_cnt as f32))
1104 + (right_bounds.surface_area() * (right_count as f32)))
1105 / parent_area;
1106 if cost < best_cost {
1107 best_cost = cost;
1108 best_axis = axis;
1109 best_split_pos =
1110 c_min + ((split_idx + 1) as f32) * (span / (RT_SAH_BIN_COUNT as f32));
1111 found_sah = true;
1112 }
1113 }
1114 }
1115 let mut mid: usize = if found_sah && best_cost < leaf_cost {
1116 Self::partition_instances(
1117 instances,
1118 instance_order,
1119 start,
1120 end,
1121 best_axis,
1122 best_split_pos,
1123 )
1124 } else {
1125 let extent: Vec3 = centroid_bounds.get_max().sub(centroid_bounds.get_min());
1126 let fallback_axis: usize =
1127 if extent.get_x() >= extent.get_y() && extent.get_x() >= extent.get_z() {
1128 0
1129 } else if extent.get_y() >= extent.get_z() {
1130 1
1131 } else {
1132 2
1133 };
1134 let split_mid: f32 = (vec3_axis(centroid_bounds.get_min(), fallback_axis)
1135 + vec3_axis(centroid_bounds.get_max(), fallback_axis))
1136 * 0.5;
1137 Self::partition_instances(
1138 instances,
1139 instance_order,
1140 start,
1141 end,
1142 fallback_axis,
1143 split_mid,
1144 )
1145 };
1146 if mid == start || mid == end {
1147 mid = start + count / 2;
1148 }
1149 let left_idx: u32 =
1150 Self::build_tlas_recursive(nodes, instances, instance_order, start, mid);
1151 let right_idx: u32 = Self::build_tlas_recursive(nodes, instances, instance_order, mid, end);
1152 if let Some(node_ref) = nodes.get_mut(node_idx as usize) {
1153 node_ref.set_left(left_idx);
1154 node_ref.set_right(right_idx);
1155 node_ref.set_instance_count(0);
1156 }
1157 node_idx
1158 }
1159
1160 fn partition_instances(
1175 instances: &[RtInstance],
1176 instance_order: &mut [u32],
1177 start: usize,
1178 end: usize,
1179 axis: usize,
1180 split_pos: f32,
1181 ) -> usize {
1182 let mut left: usize = start;
1183 let mut right: usize = end;
1184 while left < right {
1185 let center: Vec3 = instances[instance_order[left] as usize]
1186 .get_world_bounds()
1187 .center();
1188 if vec3_axis(center, axis) < split_pos {
1189 left += 1;
1190 } else {
1191 right -= 1;
1192 instance_order.swap(left, right);
1193 }
1194 }
1195 left
1196 }
1197
1198 fn intersect_instance(
1213 instance_id: u32,
1214 instance: RtInstance,
1215 blas_list: &[Blas3D],
1216 ray: &Ray3D,
1217 t_min: f32,
1218 t_max: f32,
1219 ) -> Option<RtHit> {
1220 if !instance.get_visible() {
1221 return None;
1222 }
1223 let blas: &Blas3D = blas_list.get(instance.get_blas_id() as usize)?;
1224 let inv: Mat4 = instance.get_inv_transform();
1225 let local_origin: Vec3 = inv.mul_point3(ray.get_origin());
1226 let local_dir: Vec3 = inv.mul_vec3(ray.get_direction());
1227 let local_inv_dir: Vec3 = Ray3D::safe_inv_vec(local_dir);
1228 let local_hit: RtLocalHit =
1229 blas.trace_closest_unnormalized(local_origin, local_dir, local_inv_dir, t_min, t_max)?;
1230 let normal_mat: [Vec3; 3] = instance.get_normal_matrix();
1231 let world_geom_n: Vec3 =
1232 Mat4::transform_normal_with_basis(local_hit.get_geometric_normal(), normal_mat);
1233 let world_shade_n: Vec3 =
1234 Mat4::transform_normal_with_basis(local_hit.get_shading_normal(), normal_mat);
1235 let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1236 orient_hit_normals(ray.get_direction(), world_geom_n, world_shade_n);
1237 let world_point: Vec3 = ray
1238 .get_origin()
1239 .add(ray.get_direction().scale(local_hit.get_distance()));
1240 Some(RtHit {
1241 distance: local_hit.get_distance(),
1242 point: world_point,
1243 geometric_normal: geom_n,
1244 shading_normal: shade_n,
1245 uv: local_hit.get_uv(),
1246 material_id: instance.get_material_id(),
1247 instance_id,
1248 primitive_index: local_hit.get_triangle_index(),
1249 front_face,
1250 })
1251 }
1252
1253 #[must_use]
1267 pub fn trace_closest(
1268 &self,
1269 blas_list: &[Blas3D],
1270 ray: &Ray3D,
1271 t_min: f32,
1272 t_max: f32,
1273 ) -> Option<RtHit> {
1274 let nodes: &[TlasNode3D] = self.get_nodes().as_slice();
1275 let instances: &[RtInstance] = self.get_instances().as_slice();
1276 let order: &[u32] = self.get_instance_order().as_slice();
1277 if nodes.is_empty() {
1278 return None;
1279 }
1280 let origin: Vec3 = ray.get_origin();
1281 let inv_dir: Vec3 = ray.get_inv_direction();
1282 if !nodes[0]
1283 .get_bounds()
1284 .intersect_ray_near(origin, inv_dir, t_min, t_max)
1285 .is_finite()
1286 {
1287 return None;
1288 }
1289 let mut stack: [u32; RT_BVH_STACK_CAPACITY] = [0; RT_BVH_STACK_CAPACITY];
1290 let mut stack_len: usize = 1;
1291 let mut best_t: f32 = t_max;
1292 let mut best_hit: Option<RtHit> = None;
1293 while stack_len > 0 {
1294 stack_len -= 1;
1295 let node: TlasNode3D = nodes[stack[stack_len] as usize];
1296 let inst_count: u32 = node.get_instance_count();
1297 if inst_count > 0 {
1298 let first: usize = node.get_first_instance() as usize;
1299 let last: usize = first + (inst_count as usize);
1300 for &inst_id in &order[first..last] {
1301 let inst: RtInstance = instances[inst_id as usize];
1302 if !inst
1303 .get_world_bounds()
1304 .intersect_ray_near(origin, inv_dir, t_min, best_t)
1305 .is_finite()
1306 {
1307 continue;
1308 }
1309 if let Some(hit) =
1310 Self::intersect_instance(inst_id, inst, blas_list, ray, t_min, best_t)
1311 {
1312 best_t = hit.get_distance();
1313 best_hit = Some(hit);
1314 }
1315 }
1316 } else {
1317 let left_idx: u32 = node.get_left();
1318 let right_idx: u32 = node.get_right();
1319 let t_left: f32 = nodes[left_idx as usize]
1320 .get_bounds()
1321 .intersect_ray_near(origin, inv_dir, t_min, best_t);
1322 let t_right: f32 = nodes[right_idx as usize]
1323 .get_bounds()
1324 .intersect_ray_near(origin, inv_dir, t_min, best_t);
1325 let hit_left: bool = t_left.is_finite() && t_left <= best_t;
1326 let hit_right: bool = t_right.is_finite() && t_right <= best_t;
1327 if hit_left && hit_right {
1328 let (near_idx, far_idx): (u32, u32) = if t_left <= t_right {
1329 (left_idx, right_idx)
1330 } else {
1331 (right_idx, left_idx)
1332 };
1333 if stack_len + 2 <= RT_BVH_STACK_CAPACITY {
1334 stack[stack_len] = far_idx;
1335 stack[stack_len + 1] = near_idx;
1336 stack_len += 2;
1337 }
1338 } else if hit_left && stack_len < RT_BVH_STACK_CAPACITY {
1339 stack[stack_len] = left_idx;
1340 stack_len += 1;
1341 } else if hit_right && stack_len < RT_BVH_STACK_CAPACITY {
1342 stack[stack_len] = right_idx;
1343 stack_len += 1;
1344 }
1345 }
1346 }
1347 best_hit
1348 }
1349
1350 #[must_use]
1364 pub fn trace_any_hit(&self, blas_list: &[Blas3D], ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1365 let nodes: &[TlasNode3D] = self.get_nodes().as_slice();
1366 let instances: &[RtInstance] = self.get_instances().as_slice();
1367 let order: &[u32] = self.get_instance_order().as_slice();
1368 if nodes.is_empty() {
1369 return false;
1370 }
1371 let origin: Vec3 = ray.get_origin();
1372 let inv_dir: Vec3 = ray.get_inv_direction();
1373 if !nodes[0]
1374 .get_bounds()
1375 .intersect_ray_near(origin, inv_dir, t_min, t_max)
1376 .is_finite()
1377 {
1378 return false;
1379 }
1380 let mut stack: [u32; RT_BVH_STACK_CAPACITY] = [0; RT_BVH_STACK_CAPACITY];
1381 let mut stack_len: usize = 1;
1382 while stack_len > 0 {
1383 stack_len -= 1;
1384 let node: TlasNode3D = nodes[stack[stack_len] as usize];
1385 let inst_count: u32 = node.get_instance_count();
1386 if inst_count > 0 {
1387 let first: usize = node.get_first_instance() as usize;
1388 let last: usize = first + (inst_count as usize);
1389 for &inst_id in &order[first..last] {
1390 let inst: RtInstance = instances[inst_id as usize];
1391 if !inst.get_visible() {
1392 continue;
1393 }
1394 if !inst
1395 .get_world_bounds()
1396 .intersect_ray_near(origin, inv_dir, t_min, t_max)
1397 .is_finite()
1398 {
1399 continue;
1400 }
1401 if let Some(blas) = blas_list.get(inst.get_blas_id() as usize) {
1402 let inv: Mat4 = inst.get_inv_transform();
1403 let local_origin: Vec3 = inv.mul_point3(origin);
1404 let local_dir: Vec3 = inv.mul_vec3(ray.get_direction());
1405 let local_inv_dir: Vec3 = Ray3D::safe_inv_vec(local_dir);
1406 if blas.trace_any_hit_unnormalized(
1407 local_origin,
1408 local_dir,
1409 local_inv_dir,
1410 t_min,
1411 t_max,
1412 ) {
1413 return true;
1414 }
1415 }
1416 }
1417 } else {
1418 let left_idx: u32 = node.get_left();
1419 let right_idx: u32 = node.get_right();
1420 if nodes[left_idx as usize]
1421 .get_bounds()
1422 .intersect_ray_near(origin, inv_dir, t_min, t_max)
1423 .is_finite()
1424 && stack_len < RT_BVH_STACK_CAPACITY
1425 {
1426 stack[stack_len] = left_idx;
1427 stack_len += 1;
1428 }
1429 if nodes[right_idx as usize]
1430 .get_bounds()
1431 .intersect_ray_near(origin, inv_dir, t_min, t_max)
1432 .is_finite()
1433 && stack_len < RT_BVH_STACK_CAPACITY
1434 {
1435 stack[stack_len] = right_idx;
1436 stack_len += 1;
1437 }
1438 }
1439 }
1440 false
1441 }
1442
1443 #[must_use]
1457 pub fn trace_closest_brute_force(
1458 &self,
1459 blas_list: &[Blas3D],
1460 ray: &Ray3D,
1461 t_min: f32,
1462 t_max: f32,
1463 ) -> Option<RtHit> {
1464 let mut best_t: f32 = t_max;
1465 let mut best_hit: Option<RtHit> = None;
1466 for (inst_idx, &inst) in self.get_instances().iter().enumerate() {
1467 if !inst.get_visible() {
1468 continue;
1469 }
1470 let blas: &Blas3D = match blas_list.get(inst.get_blas_id() as usize) {
1471 Some(b) => b,
1472 None => continue,
1473 };
1474 let inv: Mat4 = inst.get_inv_transform();
1475 let local_origin: Vec3 = inv.mul_point3(ray.get_origin());
1476 let local_dir: Vec3 = inv.mul_vec3(ray.get_direction());
1477 if let Some(local_hit) =
1478 blas.trace_closest_brute_force_unnormalized(local_origin, local_dir, t_min, best_t)
1479 {
1480 let normal_mat: [Vec3; 3] = inst.get_normal_matrix();
1481 let world_geom_n: Vec3 =
1482 Mat4::transform_normal_with_basis(local_hit.get_geometric_normal(), normal_mat);
1483 let world_shade_n: Vec3 =
1484 Mat4::transform_normal_with_basis(local_hit.get_shading_normal(), normal_mat);
1485 let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1486 orient_hit_normals(ray.get_direction(), world_geom_n, world_shade_n);
1487 let world_point: Vec3 = ray
1488 .get_origin()
1489 .add(ray.get_direction().scale(local_hit.get_distance()));
1490 best_t = local_hit.get_distance();
1491 best_hit = Some(RtHit {
1492 distance: local_hit.get_distance(),
1493 point: world_point,
1494 geometric_normal: geom_n,
1495 shading_normal: shade_n,
1496 uv: local_hit.get_uv(),
1497 material_id: inst.get_material_id(),
1498 instance_id: inst_idx as u32,
1499 primitive_index: local_hit.get_triangle_index(),
1500 front_face,
1501 });
1502 }
1503 }
1504 best_hit
1505 }
1506}
1507
1508impl RtPrimitive {
1510 #[must_use]
1524 pub fn intersect(
1525 &self,
1526 ray: &Ray3D,
1527 t_min: f32,
1528 t_max: f32,
1529 primitive_index: u32,
1530 ) -> Option<RtHit> {
1531 let origin: Vec3 = ray.get_origin();
1532 let dir: Vec3 = ray.get_direction();
1533 let mat_id: u32 = self.get_material_id();
1534 match self.get_shape() {
1535 RtPrimitiveShape::Sphere { center, radius } => {
1536 let r: f32 = radius.abs();
1537 if r <= RT_EPSILON {
1538 return None;
1539 }
1540 let oc: Vec3 = origin.sub(center);
1541 let b: f32 = oc.dot(dir);
1542 let c: f32 = oc.dot(oc) - r * r;
1543 let disc: f32 = b * b - c;
1544 if disc < 0.0 {
1545 return None;
1546 }
1547 let sqrt_d: f32 = disc.sqrt();
1548 let mut root: f32 = -b - sqrt_d;
1549 if root < t_min || root > t_max {
1550 root = -b + sqrt_d;
1551 if root < t_min || root > t_max {
1552 return None;
1553 }
1554 }
1555 let point: Vec3 = origin.add(dir.scale(root));
1556 let outward: Vec3 = point.sub(center).scale(1.0 / r).normalize();
1557 let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1558 orient_hit_normals(dir, outward, outward);
1559 let u: f32 = 0.5 + outward.get_z().atan2(outward.get_x()) / TAU;
1560 let v: f32 = 0.5 - outward.get_y().clamp(-1.0, 1.0).asin() / PI;
1561 Some(RtHit {
1562 distance: root,
1563 point,
1564 geometric_normal: geom_n,
1565 shading_normal: shade_n,
1566 uv: Vec2::new(u, v),
1567 material_id: mat_id,
1568 instance_id: RT_PRIMITIVE_INSTANCE_ID,
1569 primitive_index,
1570 front_face,
1571 })
1572 }
1573 RtPrimitiveShape::Plane {
1574 point: plane_pt,
1575 normal,
1576 } => {
1577 let n: Vec3 = normal.normalize();
1578 let denom: f32 = n.dot(dir);
1579 if denom.abs() < RT_EPSILON {
1580 return None;
1581 }
1582 let dist: f32 = plane_pt.sub(origin).dot(n) / denom;
1583 if !dist.is_finite() {
1584 return None;
1585 }
1586 if dist < t_min || dist > t_max {
1587 return None;
1588 }
1589 let hit_pt: Vec3 = origin.add(dir.scale(dist));
1590 let (tangent, bitangent): (Vec3, Vec3) = build_orthonormal_basis(n);
1591 let rel: Vec3 = hit_pt.sub(plane_pt);
1592 let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1593 orient_hit_normals(dir, n, n);
1594 Some(RtHit {
1595 distance: dist,
1596 point: hit_pt,
1597 geometric_normal: geom_n,
1598 shading_normal: shade_n,
1599 uv: Vec2::new(rel.dot(tangent), rel.dot(bitangent)),
1600 material_id: mat_id,
1601 instance_id: RT_PRIMITIVE_INSTANCE_ID,
1602 primitive_index,
1603 front_face,
1604 })
1605 }
1606 RtPrimitiveShape::Box { min, max } => {
1607 let inv: Vec3 = ray.get_inv_direction();
1608 let tx1: f32 = (min.get_x() - origin.get_x()) * inv.get_x();
1609 let tx2: f32 = (max.get_x() - origin.get_x()) * inv.get_x();
1610 let tx_min: f32 = tx1.min(tx2);
1611 let tx_max: f32 = tx1.max(tx2);
1612 let ty1: f32 = (min.get_y() - origin.get_y()) * inv.get_y();
1613 let ty2: f32 = (max.get_y() - origin.get_y()) * inv.get_y();
1614 let ty_min: f32 = ty1.min(ty2);
1615 let ty_max: f32 = ty1.max(ty2);
1616 let tz1: f32 = (min.get_z() - origin.get_z()) * inv.get_z();
1617 let tz2: f32 = (max.get_z() - origin.get_z()) * inv.get_z();
1618 let tz_min: f32 = tz1.min(tz2);
1619 let tz_max: f32 = tz1.max(tz2);
1620 let t_enter: f32 = tx_min.max(ty_min).max(tz_min);
1621 let t_exit: f32 = tx_max.min(ty_max).min(tz_max);
1622 if t_exit < t_enter {
1623 return None;
1624 }
1625 if t_exit < t_min || t_enter > t_max {
1626 return None;
1627 }
1628 let (hit_t, is_enter): (f32, bool) = if t_enter >= t_min {
1629 (t_enter, true)
1630 } else if t_exit <= t_max {
1631 (t_exit, false)
1632 } else {
1633 return None;
1634 };
1635 let hit_pt: Vec3 = origin.add(dir.scale(hit_t));
1636 let size: Vec3 = max.sub(min);
1637 let sx: f32 = size.get_x().max(RT_EPSILON);
1638 let sy: f32 = size.get_y().max(RT_EPSILON);
1639 let sz: f32 = size.get_z().max(RT_EPSILON);
1640 let outward: Vec3 = if is_enter {
1641 if t_enter == tx_min {
1642 Vec3::new(if dir.get_x() > 0.0 { -1.0 } else { 1.0 }, 0.0, 0.0)
1643 } else if t_enter == ty_min {
1644 Vec3::new(0.0, if dir.get_y() > 0.0 { -1.0 } else { 1.0 }, 0.0)
1645 } else {
1646 Vec3::new(0.0, 0.0, if dir.get_z() > 0.0 { -1.0 } else { 1.0 })
1647 }
1648 } else if t_exit == tx_max {
1649 Vec3::new(if dir.get_x() > 0.0 { 1.0 } else { -1.0 }, 0.0, 0.0)
1650 } else if t_exit == ty_max {
1651 Vec3::new(0.0, if dir.get_y() > 0.0 { 1.0 } else { -1.0 }, 0.0)
1652 } else {
1653 Vec3::new(0.0, 0.0, if dir.get_z() > 0.0 { 1.0 } else { -1.0 })
1654 };
1655 let (u, v): (f32, f32) = if outward.get_x().abs() > 0.5 {
1656 (
1657 (hit_pt.get_z() - min.get_z()) / sz,
1658 (hit_pt.get_y() - min.get_y()) / sy,
1659 )
1660 } else if outward.get_y().abs() > 0.5 {
1661 (
1662 (hit_pt.get_x() - min.get_x()) / sx,
1663 (hit_pt.get_z() - min.get_z()) / sz,
1664 )
1665 } else {
1666 (
1667 (hit_pt.get_x() - min.get_x()) / sx,
1668 (hit_pt.get_y() - min.get_y()) / sy,
1669 )
1670 };
1671 let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1672 orient_hit_normals(dir, outward, outward);
1673 Some(RtHit {
1674 distance: hit_t,
1675 point: hit_pt,
1676 geometric_normal: geom_n,
1677 shading_normal: shade_n,
1678 uv: Vec2::new(u.clamp(0.0, 1.0), v.clamp(0.0, 1.0)),
1679 material_id: mat_id,
1680 instance_id: RT_PRIMITIVE_INSTANCE_ID,
1681 primitive_index,
1682 front_face,
1683 })
1684 }
1685 RtPrimitiveShape::Disk {
1686 center,
1687 normal,
1688 radius,
1689 } => {
1690 let r: f32 = radius.abs();
1691 if r <= RT_EPSILON {
1692 return None;
1693 }
1694 let n: Vec3 = normal.normalize();
1695 let denom: f32 = n.dot(dir);
1696 if denom.abs() < RT_EPSILON {
1697 return None;
1698 }
1699 let dist: f32 = center.sub(origin).dot(n) / denom;
1700 if !dist.is_finite() {
1701 return None;
1702 }
1703 if dist < t_min || dist > t_max {
1704 return None;
1705 }
1706 let hit_pt: Vec3 = origin.add(dir.scale(dist));
1707 let offset: Vec3 = hit_pt.sub(center);
1708 if offset.length_sq() > r * r {
1709 return None;
1710 }
1711 let (tangent, bitangent): (Vec3, Vec3) = build_orthonormal_basis(n);
1712 let u: f32 = (offset.dot(tangent) / (2.0 * r) + 0.5).clamp(0.0, 1.0);
1713 let v: f32 = (offset.dot(bitangent) / (2.0 * r) + 0.5).clamp(0.0, 1.0);
1714 let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1715 orient_hit_normals(dir, n, n);
1716 Some(RtHit {
1717 distance: dist,
1718 point: hit_pt,
1719 geometric_normal: geom_n,
1720 shading_normal: shade_n,
1721 uv: Vec2::new(u, v),
1722 material_id: mat_id,
1723 instance_id: RT_PRIMITIVE_INSTANCE_ID,
1724 primitive_index,
1725 front_face,
1726 })
1727 }
1728 RtPrimitiveShape::Quad {
1729 corner,
1730 edge_u,
1731 edge_v,
1732 } => {
1733 let cross_uv: Vec3 = edge_u.cross(edge_v);
1734 let area_sq: f32 = cross_uv.length_sq();
1735 if area_sq <= RT_EPSILON * RT_EPSILON {
1736 return None;
1737 }
1738 let n: Vec3 = cross_uv.scale(1.0 / area_sq.sqrt());
1739 let denom: f32 = n.dot(dir);
1740 if denom.abs() < RT_EPSILON {
1741 return None;
1742 }
1743 let dist: f32 = corner.sub(origin).dot(n) / denom;
1744 if !dist.is_finite() {
1745 return None;
1746 }
1747 if dist < t_min || dist > t_max {
1748 return None;
1749 }
1750 let hit_pt: Vec3 = origin.add(dir.scale(dist));
1751 let rel: Vec3 = hit_pt.sub(corner);
1752 let w_vec: Vec3 = cross_uv.scale(1.0 / area_sq);
1753 let alpha: f32 = w_vec.dot(rel.cross(edge_v));
1754 let beta: f32 = w_vec.dot(edge_u.cross(rel));
1755 if !(0.0..=1.0).contains(&alpha) || !(0.0..=1.0).contains(&beta) {
1756 return None;
1757 }
1758 let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1759 orient_hit_normals(dir, n, n);
1760 Some(RtHit {
1761 distance: dist,
1762 point: hit_pt,
1763 geometric_normal: geom_n,
1764 shading_normal: shade_n,
1765 uv: Vec2::new(alpha, beta),
1766 material_id: mat_id,
1767 instance_id: RT_PRIMITIVE_INSTANCE_ID,
1768 primitive_index,
1769 front_face,
1770 })
1771 }
1772 RtPrimitiveShape::Cylinder {
1773 center,
1774 radius,
1775 half_height,
1776 capped,
1777 } => {
1778 let r: f32 = radius.abs();
1779 let hh: f32 = half_height.abs();
1780 if r <= RT_EPSILON || hh <= RT_EPSILON {
1781 return None;
1782 }
1783 let rel_o: Vec3 = origin.sub(center);
1784 let ox: f32 = rel_o.get_x();
1785 let oy: f32 = rel_o.get_y();
1786 let oz: f32 = rel_o.get_z();
1787 let dx: f32 = dir.get_x();
1788 let dy: f32 = dir.get_y();
1789 let dz: f32 = dir.get_z();
1790 let mut best_t: f32 = t_max;
1791 let mut best_outward: Vec3 = Vec3::new(0.0, 1.0, 0.0);
1792 let mut best_uv: Vec2 = Vec2::zero();
1793 let mut found: bool = false;
1794 let a: f32 = dx * dx + dz * dz;
1795 if a > RT_EPSILON {
1796 let half_b: f32 = ox * dx + oz * dz;
1797 let c: f32 = ox * ox + oz * oz - r * r;
1798 let disc: f32 = half_b * half_b - a * c;
1799 if disc >= 0.0 {
1800 let sqrt_d: f32 = disc.sqrt();
1801 let roots: [f32; 2] = [(-half_b - sqrt_d) / a, (-half_b + sqrt_d) / a];
1802 for root in roots {
1803 if root >= t_min && root < best_t {
1804 let y_local: f32 = oy + root * dy;
1805 if y_local >= -hh && y_local <= hh {
1806 let hx: f32 = ox + root * dx;
1807 let hz: f32 = oz + root * dz;
1808 best_t = root;
1809 best_outward = Vec3::new(hx / r, 0.0, hz / r).normalize();
1810 let u: f32 = 0.5 + hz.atan2(hx) / TAU;
1811 let v: f32 = ((y_local + hh) / (2.0 * hh)).clamp(0.0, 1.0);
1812 best_uv = Vec2::new(u, v);
1813 found = true;
1814 }
1815 }
1816 }
1817 }
1818 }
1819 if capped && dy.abs() > RT_EPSILON {
1820 let cap_planes: [(f32, f32); 2] = [(hh, 1.0), (-hh, -1.0)];
1821 for (cap_y, sign_y) in cap_planes {
1822 let cap_t: f32 = (cap_y - oy) / dy;
1823 if cap_t >= t_min && cap_t < best_t {
1824 let hx: f32 = ox + cap_t * dx;
1825 let hz: f32 = oz + cap_t * dz;
1826 if hx * hx + hz * hz <= r * r {
1827 best_t = cap_t;
1828 best_outward = Vec3::new(0.0, sign_y, 0.0);
1829 best_uv = Vec2::new(
1830 (hx / (2.0 * r) + 0.5).clamp(0.0, 1.0),
1831 (hz / (2.0 * r) + 0.5).clamp(0.0, 1.0),
1832 );
1833 found = true;
1834 }
1835 }
1836 }
1837 }
1838 if !found {
1839 return None;
1840 }
1841 let hit_pt: Vec3 = origin.add(dir.scale(best_t));
1842 let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1843 orient_hit_normals(dir, best_outward, best_outward);
1844 Some(RtHit {
1845 distance: best_t,
1846 point: hit_pt,
1847 geometric_normal: geom_n,
1848 shading_normal: shade_n,
1849 uv: best_uv,
1850 material_id: mat_id,
1851 instance_id: RT_PRIMITIVE_INSTANCE_ID,
1852 primitive_index,
1853 front_face,
1854 })
1855 }
1856 }
1857 }
1858
1859 #[must_use]
1872 pub fn any_hit(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1873 self.intersect(ray, t_min, t_max, 0).is_some()
1874 }
1875
1876 #[must_use]
1886 pub fn bounds(&self) -> AxisAlignedBox3D {
1887 match self.get_shape() {
1888 RtPrimitiveShape::Sphere { center, radius } => {
1889 let r: Vec3 = Vec3::splat(radius.abs());
1890 AxisAlignedBox3D::new(center.sub(r), center.add(r))
1891 }
1892 RtPrimitiveShape::Plane { .. } => {
1893 AxisAlignedBox3D::new(Vec3::splat(-1e5), Vec3::splat(1e5))
1894 }
1895 RtPrimitiveShape::Box { min, max } => AxisAlignedBox3D::new(min.min(max), min.max(max)),
1896 RtPrimitiveShape::Disk { center, radius, .. } => {
1897 let r: Vec3 = Vec3::splat(radius.abs());
1898 AxisAlignedBox3D::new(center.sub(r), center.add(r))
1899 }
1900 RtPrimitiveShape::Quad {
1901 corner,
1902 edge_u,
1903 edge_v,
1904 } => {
1905 let mut bbox: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1906 bbox.expand_point(corner);
1907 bbox.expand_point(corner.add(edge_u));
1908 bbox.expand_point(corner.add(edge_v));
1909 bbox.expand_point(corner.add(edge_u).add(edge_v));
1910 bbox
1911 }
1912 RtPrimitiveShape::Cylinder {
1913 center,
1914 radius,
1915 half_height,
1916 ..
1917 } => {
1918 let r: f32 = radius.abs();
1919 let hh: f32 = half_height.abs();
1920 let ext: Vec3 = Vec3::new(r, hh, r);
1921 AxisAlignedBox3D::new(center.sub(ext), center.add(ext))
1922 }
1923 }
1924 }
1925}
1926
1927impl Default for SdfSphereTracer {
1929 fn default() -> Self {
1935 Self::new(0, AxisAlignedBox3D::empty())
1936 }
1937}
1938
1939impl SdfSphereTracer {
1941 #[must_use]
1952 pub fn new(material_id: u32, bounds: AxisAlignedBox3D) -> Self {
1953 Self {
1954 ops: Vec::new(),
1955 root_index: 0,
1956 material_id,
1957 bounds,
1958 max_steps: RT_SDF_DEFAULT_MAX_STEPS,
1959 hit_epsilon: RT_SDF_DEFAULT_EPSILON,
1960 normal_epsilon: RT_SDF_NORMAL_EPSILON,
1961 max_distance: RT_SDF_DEFAULT_MAX_DISTANCE,
1962 lipschitz_factor: 1.0,
1963 }
1964 }
1965
1966 pub fn push_op(&mut self, op: RtSdfOp) -> u32 {
1977 let idx: u32 = self.get_ops().len() as u32;
1978 self.get_mut_ops().push(op);
1979 self.set_root_index(idx);
1980 idx
1981 }
1982
1983 #[must_use]
1994 pub fn evaluate_distance(&self, point: Vec3) -> f32 {
1995 let ops: &[RtSdfOp] = self.get_ops().as_slice();
1996 let root: usize = self.get_root_index() as usize;
1997 if root >= ops.len() {
1998 return f32::INFINITY;
1999 }
2000 let mut visit_stack: [(u32, bool); RT_SDF_EVAL_STACK_CAPACITY] =
2001 [(0, false); RT_SDF_EVAL_STACK_CAPACITY];
2002 let mut visit_len: usize = 1;
2003 visit_stack[0] = (root as u32, false);
2004 let mut val_stack: [f32; RT_SDF_EVAL_STACK_CAPACITY] = [0.0; RT_SDF_EVAL_STACK_CAPACITY];
2005 let mut val_len: usize = 0;
2006 while visit_len > 0 {
2007 visit_len -= 1;
2008 let (node_idx, expanded): (u32, bool) = visit_stack[visit_len];
2009 let op: RtSdfOp = match ops.get(node_idx as usize) {
2010 Some(&found) => found,
2011 None => return f32::INFINITY,
2012 };
2013 match op {
2014 RtSdfOp::Sphere { center, radius } => {
2015 if val_len < RT_SDF_EVAL_STACK_CAPACITY {
2016 val_stack[val_len] = point.sub(center).length() - radius.abs();
2017 val_len += 1;
2018 }
2019 }
2020 RtSdfOp::Box {
2021 center,
2022 half_extents,
2023 rounding,
2024 } => {
2025 let rel: Vec3 = point.sub(center);
2026 let qx: f32 = rel.get_x().abs() - half_extents.get_x().abs();
2027 let qy: f32 = rel.get_y().abs() - half_extents.get_y().abs();
2028 let qz: f32 = rel.get_z().abs() - half_extents.get_z().abs();
2029 let out_len: f32 = Vec3::new(qx.max(0.0), qy.max(0.0), qz.max(0.0)).length();
2030 let in_dist: f32 = qx.max(qy.max(qz)).min(0.0);
2031 if val_len < RT_SDF_EVAL_STACK_CAPACITY {
2032 val_stack[val_len] = out_len + in_dist - rounding.max(0.0);
2033 val_len += 1;
2034 }
2035 }
2036 RtSdfOp::Torus {
2037 center,
2038 major_radius,
2039 minor_radius,
2040 } => {
2041 let rel: Vec3 = point.sub(center);
2042 let qx: f32 = (rel.get_x() * rel.get_x() + rel.get_z() * rel.get_z()).sqrt()
2043 - major_radius.abs();
2044 let qy: f32 = rel.get_y();
2045 if val_len < RT_SDF_EVAL_STACK_CAPACITY {
2046 val_stack[val_len] = (qx * qx + qy * qy).sqrt() - minor_radius.abs();
2047 val_len += 1;
2048 }
2049 }
2050 RtSdfOp::Capsule { start, end, radius } => {
2051 let pa: Vec3 = point.sub(start);
2052 let ba: Vec3 = end.sub(start);
2053 let denom: f32 = ba.dot(ba).max(RT_EPSILON);
2054 let h: f32 = (pa.dot(ba) / denom).clamp(0.0, 1.0);
2055 if val_len < RT_SDF_EVAL_STACK_CAPACITY {
2056 val_stack[val_len] = pa.sub(ba.scale(h)).length() - radius.abs();
2057 val_len += 1;
2058 }
2059 }
2060 RtSdfOp::Union { left, right }
2061 | RtSdfOp::Subtract {
2062 base: left,
2063 cutout: right,
2064 }
2065 | RtSdfOp::Intersect { left, right }
2066 | RtSdfOp::SmoothUnion { left, right, .. }
2067 | RtSdfOp::SmoothSubtract {
2068 base: left,
2069 cutout: right,
2070 ..
2071 } => {
2072 if !expanded {
2073 if visit_len + 3 <= RT_SDF_EVAL_STACK_CAPACITY {
2074 visit_stack[visit_len] = (node_idx, true);
2075 visit_stack[visit_len + 1] = (right, false);
2076 visit_stack[visit_len + 2] = (left, false);
2077 visit_len += 3;
2078 }
2079 } else if val_len >= 2 {
2080 let rhs_val: f32 = val_stack[val_len - 1];
2081 let lhs_val: f32 = val_stack[val_len - 2];
2082 val_len -= 1;
2083 let combined: f32 = match op {
2084 RtSdfOp::Union { .. } => lhs_val.min(rhs_val),
2085 RtSdfOp::Subtract { .. } => lhs_val.max(-rhs_val),
2086 RtSdfOp::Intersect { .. } => lhs_val.max(rhs_val),
2087 RtSdfOp::SmoothUnion { smoothness, .. } => {
2088 sdf_smooth_min(lhs_val, rhs_val, smoothness)
2089 }
2090 RtSdfOp::SmoothSubtract { smoothness, .. } => {
2091 sdf_smooth_subtract(lhs_val, rhs_val, smoothness)
2092 }
2093 _ => lhs_val,
2094 };
2095 val_stack[val_len - 1] = combined;
2096 }
2097 }
2098 }
2099 }
2100 if val_len > 0 {
2101 val_stack[val_len - 1]
2102 } else {
2103 f32::INFINITY
2104 }
2105 }
2106
2107 #[must_use]
2118 pub fn evaluate_normal(&self, point: Vec3) -> Vec3 {
2119 let eps: f32 = self.get_normal_epsilon().max(1e-5);
2120 let k0: Vec3 = Vec3::new(1.0, -1.0, -1.0);
2121 let k1: Vec3 = Vec3::new(-1.0, -1.0, 1.0);
2122 let k2: Vec3 = Vec3::new(-1.0, 1.0, -1.0);
2123 let k3: Vec3 = Vec3::new(1.0, 1.0, 1.0);
2124 let d0: f32 = self.evaluate_distance(point.add(k0.scale(eps)));
2125 let d1: f32 = self.evaluate_distance(point.add(k1.scale(eps)));
2126 let d2: f32 = self.evaluate_distance(point.add(k2.scale(eps)));
2127 let d3: f32 = self.evaluate_distance(point.add(k3.scale(eps)));
2128 k0.scale(d0)
2129 .add(k1.scale(d1))
2130 .add(k2.scale(d2))
2131 .add(k3.scale(d3))
2132 .normalize()
2133 }
2134
2135 #[must_use]
2149 pub fn trace(
2150 &self,
2151 ray: &Ray3D,
2152 t_min: f32,
2153 t_max: f32,
2154 primitive_index: u32,
2155 ) -> Option<RtHit> {
2156 if self.get_ops().is_empty() {
2157 return None;
2158 }
2159 let bounds: AxisAlignedBox3D = self.get_bounds();
2160 let origin: Vec3 = ray.get_origin();
2161 let dir: Vec3 = ray.get_direction();
2162 let inv_dir: Vec3 = ray.get_inv_direction();
2163 let tx1: f32 = (bounds.get_min().get_x() - origin.get_x()) * inv_dir.get_x();
2164 let tx2: f32 = (bounds.get_max().get_x() - origin.get_x()) * inv_dir.get_x();
2165 let ty1: f32 = (bounds.get_min().get_y() - origin.get_y()) * inv_dir.get_y();
2166 let ty2: f32 = (bounds.get_max().get_y() - origin.get_y()) * inv_dir.get_y();
2167 let tz1: f32 = (bounds.get_min().get_z() - origin.get_z()) * inv_dir.get_z();
2168 let tz2: f32 = (bounds.get_max().get_z() - origin.get_z()) * inv_dir.get_z();
2169 let march_start: f32 = t_min.max(tx1.min(tx2).max(ty1.min(ty2)).max(tz1.min(tz2)));
2170 let march_end: f32 = t_max
2171 .min(self.get_max_distance())
2172 .min(tx1.max(tx2).min(ty1.max(ty2)).min(tz1.max(tz2)));
2173 if march_end < march_start {
2174 return None;
2175 }
2176 let max_steps: u32 = self.get_max_steps().max(1);
2177 let hit_eps: f32 = self.get_hit_epsilon().max(1e-6);
2178 let lip: f32 = self.get_lipschitz_factor().clamp(0.1, 1.0);
2179 let mut t: f32 = march_start;
2180 for _ in 0..max_steps {
2181 if t > march_end {
2182 break;
2183 }
2184 let pos: Vec3 = origin.add(dir.scale(t));
2185 let signed_dist: f32 = self.evaluate_distance(pos);
2186 let abs_dist: f32 = signed_dist.abs();
2187 if abs_dist <= hit_eps {
2188 let outward: Vec3 = self.evaluate_normal(pos);
2189 let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
2190 orient_hit_normals(dir, outward, outward);
2191 let rel: Vec3 = pos.sub(bounds.get_min());
2192 let ext: Vec3 = bounds.get_max().sub(bounds.get_min());
2193 let uv: Vec2 = Vec2::new(
2194 (rel.get_x() / ext.get_x().max(RT_EPSILON)).clamp(0.0, 1.0),
2195 (rel.get_z() / ext.get_z().max(RT_EPSILON)).clamp(0.0, 1.0),
2196 );
2197 return Some(RtHit {
2198 distance: t,
2199 point: pos,
2200 geometric_normal: geom_n,
2201 shading_normal: shade_n,
2202 uv,
2203 material_id: self.get_material_id(),
2204 instance_id: RT_PRIMITIVE_INSTANCE_ID,
2205 primitive_index,
2206 front_face,
2207 });
2208 }
2209 t += abs_dist * lip;
2210 }
2211 None
2212 }
2213
2214 #[must_use]
2227 pub fn any_hit(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
2228 self.trace(ray, t_min, t_max, 0).is_some()
2229 }
2230}