Skip to main content

crcbl_render/scene/
bounds.rs

1//! CPU-side bounds of a set of [`InstanceDesc`]s over a [`SceneDesc`]'s
2//! meshes: one box around the lot under a root transform, or one box per
3//! instance for a rigid compound.
4//!
5//! # Every vertex, not a transformed box
6//!
7//! Each box is folded from the mesh's vertex positions after the transform, so
8//! it is the tightest axis-aligned box around the placed geometry. Transforming
9//! the mesh's own box instead — [`Aabb::transformed`], the absolute-value
10//! matrix method a cull uses — is cheaper and contains the geometry, but is
11//! strictly larger under any rotation that is not a quarter turn: an object
12//! placed on a surface by its box's lowest point would float above it.
13//!
14//! # A non-finite position is refused, not skipped
15//!
16//! [`Aabb::from_points`] skips a `NaN` lane on purpose, because a cull box must
17//! keep containing the finite geometry. A placement or a collision part has the
18//! opposite need: a box that silently leaves a vertex out is wrong without
19//! saying so. So every placed position is checked and the first one that is
20//! `NaN` or infinite fails the call with [`SceneBoundsError::NonFinitePosition`],
21//! naming the instance — whether the vertex, the instance transform or the root
22//! was the poisoned input, and including a finite product that overflowed.
23//!
24//! # `f32` here, `f64` in physics
25//!
26//! The boxes are this crate's `f32` [`Aabb`], in the precision the vertices and
27//! [`InstanceDesc::transform`] are stored in. `crcbl_phys::AabbCompound` takes
28//! `f64` boxes; the widening is the caller's, one `as_dvec3()` per corner, and
29//! is exact, since every `f32` is an `f64`.
30
31use glam::{Mat4, Vec3};
32
33use super::{Geometry, InstanceDesc, SceneDesc};
34use crate::cull::Aabb;
35use crate::mesh_pool::vertex_positions;
36use crcbl_shaders::mesh::VERTEX_STRIDE;
37
38/// Why [`SceneDesc::instance_bounds`] or [`SceneDesc::instance_parts`] refused
39/// a set of instances. Each variant that concerns one instance names its index
40/// in the slice the call was given.
41#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
42pub enum SceneBoundsError {
43    /// The instance names a mesh past the end of [`SceneDesc::meshes`].
44    #[error("instance {instance} names mesh {mesh}, which the scene does not have")]
45    MissingMesh {
46        /// The instance's index.
47        instance: usize,
48        /// The mesh it names.
49        mesh: usize,
50    },
51    /// The instance's mesh is a [`Geometry::Dag`] with no levels, so it has no
52    /// finest level to bound.
53    #[error("instance {instance} names mesh {mesh}, a cluster DAG with no levels")]
54    NoLevels {
55        /// The instance's index.
56        instance: usize,
57        /// The mesh it names.
58        mesh: usize,
59    },
60    /// The mesh's vertex bytes are not a whole number of vertices.
61    #[error("instance {instance} names mesh {mesh}, whose vertex bytes end in a partial vertex")]
62    PartialVertex {
63        /// The instance's index.
64        instance: usize,
65        /// The mesh it names.
66        mesh: usize,
67    },
68    /// A vertex of the instance's mesh, placed by the instance and root
69    /// transforms, has a `NaN` or infinite coordinate.
70    #[error("instance {instance}'s vertex {vertex} is not finite once placed")]
71    NonFinitePosition {
72        /// The instance's index.
73        instance: usize,
74        /// The vertex's index in its mesh (level 0's, for a DAG).
75        vertex: usize,
76    },
77    /// The instance's mesh has no vertices, so there is no part to bound.
78    #[error("instance {instance}'s mesh has no vertices")]
79    EmptyPart {
80        /// The instance's index.
81        instance: usize,
82    },
83    /// No instance contributed a vertex — the set is empty, or every mesh in
84    /// it is.
85    #[error("the instances have no vertices to bound")]
86    Empty,
87}
88
89impl SceneDesc<'_> {
90    /// The box around every vertex of `instances`, each placed by
91    /// `root * instance.transform`.
92    ///
93    /// Folded from the placed vertices, so it is the tightest axis-aligned box
94    /// around them; [`Aabb::transformed`] of the mesh's own box would contain
95    /// them too, but is larger under any rotation that is not a quarter turn.
96    /// A [`Geometry::Dag`] is bounded by level 0, its finest. An instance whose
97    /// mesh has no vertices contributes nothing.
98    ///
99    /// A placed vertex that is `NaN` or infinite fails the call — from a bad
100    /// vertex, a bad instance transform or root, or a finite product that
101    /// overflowed. [`Aabb::from_points`] would skip a `NaN`, which a cull box
102    /// wants and a placement or collision box does not.
103    ///
104    /// # Errors
105    ///
106    /// The first [`SceneBoundsError`] an instance meets, in slice order, and
107    /// [`SceneBoundsError::Empty`] when no instance has a vertex.
108    pub fn instance_bounds(
109        &self,
110        instances: &[InstanceDesc],
111        root: Mat4,
112    ) -> Result<Aabb, SceneBoundsError> {
113        let mut bounds: Option<Aabb> = None;
114        for (index, instance) in instances.iter().enumerate() {
115            if let Some(placed) = self.placed_bounds(index, instance, root)? {
116                bounds = Some(match bounds {
117                    Some(so_far) => Aabb {
118                        min: so_far.min.min(placed.min),
119                        max: so_far.max.max(placed.max),
120                    },
121                    None => placed,
122                });
123            }
124        }
125        bounds.ok_or(SceneBoundsError::Empty)
126    }
127
128    /// One box per instance, in slice order, each around its mesh's vertices
129    /// placed by [`InstanceDesc::transform`] alone — the parts of a rigid
130    /// compound in the frame the instance transforms are written in.
131    ///
132    /// Widened to `f64`, they are what `crcbl_phys::AabbCompound::new` takes:
133    /// every box is finite and none is inverted. A flat part (an axis where
134    /// `min == max`, from planar geometry or a zero scale) is returned as it
135    /// is; a caller wanting a minimum thickness pads it.
136    ///
137    /// # Errors
138    ///
139    /// The first [`SceneBoundsError`] an instance meets, in slice order,
140    /// including [`SceneBoundsError::EmptyPart`] for a mesh with no vertices.
141    /// An empty slice is not an error: it yields no parts.
142    pub fn instance_parts(
143        &self,
144        instances: &[InstanceDesc],
145    ) -> Result<Vec<Aabb>, SceneBoundsError> {
146        instances
147            .iter()
148            .enumerate()
149            .map(|(index, instance)| {
150                self.placed_bounds(index, instance, Mat4::IDENTITY)?
151                    .ok_or(SceneBoundsError::EmptyPart { instance: index })
152            })
153            .collect()
154    }
155
156    /// The box around `instance`'s vertices placed by
157    /// `root * instance.transform`, or `None` when its mesh has none. `index`
158    /// is only what an error names.
159    fn placed_bounds(
160        &self,
161        index: usize,
162        instance: &InstanceDesc,
163        root: Mat4,
164    ) -> Result<Option<Aabb>, SceneBoundsError> {
165        let mesh = instance.mesh;
166        let geometry = &self
167            .meshes
168            .get(mesh)
169            .ok_or(SceneBoundsError::MissingMesh {
170                instance: index,
171                mesh,
172            })?
173            .geometry;
174        let vertices = match geometry {
175            Geometry::Flat { vertices, .. } => vertices.as_ref(),
176            Geometry::Dag { levels, .. } => levels
177                .first()
178                .ok_or(SceneBoundsError::NoLevels {
179                    instance: index,
180                    mesh,
181                })?
182                .as_ref(),
183        };
184        if vertices.len() % VERTEX_STRIDE != 0 {
185            return Err(SceneBoundsError::PartialVertex {
186                instance: index,
187                mesh,
188            });
189        }
190        let transform = root * instance.transform;
191        let mut bounds: Option<Aabb> = None;
192        for (vertex, position) in vertex_positions(vertices).enumerate() {
193            let point: Vec3 = transform.transform_point3(position);
194            if !point.is_finite() {
195                return Err(SceneBoundsError::NonFinitePosition {
196                    instance: index,
197                    vertex,
198                });
199            }
200            // Every point is finite, so `Vec3::min`/`max` cannot meet the `NaN`
201            // that makes them unsafe in `Aabb::from_points`.
202            bounds = Some(match bounds {
203                Some(so_far) => Aabb {
204                    min: so_far.min.min(point),
205                    max: so_far.max.max(point),
206                },
207                None => Aabb {
208                    min: point,
209                    max: point,
210                },
211            });
212        }
213        Ok(bounds)
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use std::borrow::Cow;
220    use std::f32::consts::{FRAC_1_SQRT_2, FRAC_PI_2, FRAC_PI_4};
221
222    use crcbl_phys::{AabbCompound, Ray, Transform};
223    use crcbl_shaders::mesh::{self, MeshVertex};
224    use crcbl_shaders::meshlet::MeshClusters;
225    use crcbl_shaders::vertex::UvRange;
226    use glam::{DQuat, DVec3};
227
228    use super::*;
229    use crate::scene::{DEMO_CUBE, MeshDesc, demo};
230
231    fn cube(transform: Mat4) -> InstanceDesc {
232        InstanceDesc {
233            mesh: DEMO_CUBE,
234            material: 0,
235            transform,
236        }
237    }
238
239    /// The demo scene with one more flat mesh holding `positions`, and that
240    /// mesh's index.
241    fn with_mesh(positions: &[[f32; 3]]) -> (SceneDesc<'static>, usize) {
242        let vertices: Vec<MeshVertex> = positions
243            .iter()
244            .map(|&position| {
245                MeshVertex::from_normal(
246                    position,
247                    [0.0, 1.0, 0.0],
248                    [1.0; 4],
249                    [0.0; 2],
250                    &UvRange::default(),
251                )
252            })
253            .collect();
254        let mut scene = demo();
255        scene.meshes.push(MeshDesc {
256            label: Cow::Borrowed("test mesh"),
257            geometry: Geometry::Flat {
258                vertices: Cow::Owned(mesh::vertex_bytes(&vertices)),
259                uv_range: UvRange::default(),
260                indices: Cow::Owned(Vec::new()),
261                clusters: MeshClusters::default(),
262                flags: 0,
263            },
264        });
265        let index = scene.meshes.len() - 1;
266        (scene, index)
267    }
268
269    fn flat_vertices<'s>(scene: &'s mut SceneDesc<'_>, mesh: usize) -> &'s mut Vec<u8> {
270        let Geometry::Flat { vertices, .. } = &mut scene.meshes[mesh].geometry else {
271            panic!("mesh {mesh} is flat geometry");
272        };
273        vertices.to_mut()
274    }
275
276    fn assert_close(actual: Vec3, expected: Vec3) {
277        assert!(
278            actual.abs_diff_eq(expected, 1e-6),
279            "{actual} is not {expected}"
280        );
281    }
282
283    /// An octahedron with its tips on the axes, turned an eighth about Z: its
284    /// tips go to `(±√½, ±√½, 0)`, so the box reaches `√½` on X and Y. The
285    /// absolute-value box of the unturned `[-1, 1]` box reaches `√2`, which is
286    /// what the second assertion tells apart.
287    #[test]
288    fn a_turned_instance_is_bounded_by_its_vertices() {
289        let (scene, octahedron) = with_mesh(&[
290            [1.0, 0.0, 0.0],
291            [-1.0, 0.0, 0.0],
292            [0.0, 1.0, 0.0],
293            [0.0, -1.0, 0.0],
294            [0.0, 0.0, 1.0],
295            [0.0, 0.0, -1.0],
296        ]);
297        let place = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
298        let instance = InstanceDesc {
299            mesh: octahedron,
300            material: 0,
301            transform: Mat4::from_rotation_z(FRAC_PI_4),
302        };
303        let bounds = scene
304            .instance_bounds(&[instance], place)
305            .expect("finite geometry");
306        assert_close(
307            bounds.min,
308            Vec3::new(1.0 - FRAC_1_SQRT_2, 2.0 - FRAC_1_SQRT_2, 2.0),
309        );
310        assert_close(
311            bounds.max,
312            Vec3::new(1.0 + FRAC_1_SQRT_2, 2.0 + FRAC_1_SQRT_2, 4.0),
313        );
314
315        let loose = Aabb {
316            min: Vec3::splat(-1.0),
317            max: Vec3::ONE,
318        }
319        .transformed(place * instance.transform);
320        assert!(
321            loose.max.x > bounds.max.x + 0.5,
322            "the turned box of the mesh's box is {loose:?}, not the vertex bound"
323        );
324    }
325
326    #[test]
327    fn several_instances_are_bounded_together() {
328        let scene = demo();
329        let bounds = scene
330            .instance_bounds(
331                &[
332                    cube(Mat4::from_translation(Vec3::new(-2.0, 0.0, 0.0))),
333                    cube(
334                        Mat4::from_translation(Vec3::new(3.0, 4.0, 5.0))
335                            * Mat4::from_scale(Vec3::new(2.0, 1.0, 3.0)),
336                    ),
337                ],
338                Mat4::IDENTITY,
339            )
340            .expect("two cubes");
341        assert_eq!(bounds.min, Vec3::new(-2.5, -0.5, -0.5));
342        assert_eq!(bounds.max, Vec3::new(4.0, 4.5, 6.5));
343    }
344
345    /// A `NaN` in the second instance's mesh, at a vertex after finite ones, is
346    /// refused by name on both entry points — where [`Aabb::from_points`] would
347    /// have skipped it and returned a finite box.
348    #[test]
349    fn a_nan_vertex_is_refused_and_names_its_instance() {
350        let (mut scene, poisoned) = with_mesh(&[[0.0; 3], [1.0; 3], [2.0; 3]]);
351        let bytes = flat_vertices(&mut scene, poisoned);
352        bytes[2 * mesh::VERTEX_STRIDE..2 * mesh::VERTEX_STRIDE + 4]
353            .copy_from_slice(&f32::NAN.to_le_bytes());
354        let instances = [
355            cube(Mat4::IDENTITY),
356            InstanceDesc {
357                mesh: poisoned,
358                material: 0,
359                transform: Mat4::IDENTITY,
360            },
361        ];
362        let expected = SceneBoundsError::NonFinitePosition {
363            instance: 1,
364            vertex: 2,
365        };
366        assert_eq!(
367            scene.instance_bounds(&instances, Mat4::IDENTITY),
368            Err(expected)
369        );
370        assert_eq!(scene.instance_parts(&instances), Err(expected));
371        assert_eq!(
372            expected.to_string(),
373            "instance 1's vertex 2 is not finite once placed"
374        );
375    }
376
377    #[test]
378    fn a_non_finite_transform_is_refused() {
379        let scene = demo();
380        let nan = Mat4::from_translation(Vec3::new(f32::NAN, 0.0, 0.0));
381        let expected = SceneBoundsError::NonFinitePosition {
382            instance: 0,
383            vertex: 0,
384        };
385        assert_eq!(
386            scene.instance_bounds(&[cube(nan)], Mat4::IDENTITY),
387            Err(expected)
388        );
389        assert_eq!(
390            scene.instance_bounds(&[cube(Mat4::IDENTITY)], nan),
391            Err(expected)
392        );
393        assert_eq!(scene.instance_parts(&[cube(nan)]), Err(expected));
394        // Finite inputs whose product overflows.
395        let huge = Mat4::from_scale(Vec3::splat(f32::MAX));
396        assert_eq!(
397            scene.instance_bounds(&[cube(huge)], Mat4::from_scale(Vec3::splat(4.0))),
398            Err(expected)
399        );
400    }
401
402    #[test]
403    fn an_empty_set_has_no_bounds_and_no_parts() {
404        let scene = demo();
405        assert_eq!(
406            scene.instance_bounds(&[], Mat4::IDENTITY),
407            Err(SceneBoundsError::Empty)
408        );
409        assert_eq!(scene.instance_parts(&[]), Ok(Vec::new()));
410    }
411
412    /// An instance of a mesh with no vertices is skipped by the set's bounds
413    /// and refused as a part.
414    #[test]
415    fn an_empty_mesh_contributes_nothing_and_is_no_part() {
416        let (scene, empty) = with_mesh(&[]);
417        let hollow = InstanceDesc {
418            mesh: empty,
419            material: 0,
420            transform: Mat4::IDENTITY,
421        };
422        assert_eq!(
423            scene.instance_bounds(&[hollow], Mat4::IDENTITY),
424            Err(SceneBoundsError::Empty)
425        );
426        assert_eq!(
427            scene.instance_bounds(&[hollow, cube(Mat4::IDENTITY)], Mat4::IDENTITY),
428            Ok(Aabb {
429                min: Vec3::splat(-0.5),
430                max: Vec3::splat(0.5),
431            })
432        );
433        assert_eq!(
434            scene.instance_parts(&[cube(Mat4::IDENTITY), hollow]),
435            Err(SceneBoundsError::EmptyPart { instance: 1 })
436        );
437    }
438
439    /// The parts, widened, are accepted by `AabbCompound::new`, and a ray cast
440    /// at a turned pose strikes the part it is aimed at, at the face the
441    /// instance transform put there.
442    #[test]
443    fn the_parts_build_a_compound_a_ray_strikes() {
444        let scene = demo();
445        let parts = scene
446            .instance_parts(&[
447                cube(Mat4::IDENTITY),
448                cube(Mat4::from_translation(Vec3::new(3.0, 0.0, 0.0))),
449            ])
450            .expect("two cubes");
451        let widened: Vec<crcbl_phys::Aabb> = parts
452            .iter()
453            .map(|part| crcbl_phys::Aabb::new(part.min.as_dvec3(), part.max.as_dvec3()))
454            .collect();
455        let compound = AabbCompound::new(&widened).expect("finite, non-inverted parts");
456        // A quarter turn about Z takes the second cube's local +X offset to
457        // world +Y, so its local -X face at x = 2.5 is the world plane y = 12.5.
458        let pose = Transform::new(
459            DVec3::new(0.0, 10.0, 0.0),
460            DQuat::from_rotation_z(core::f64::consts::FRAC_PI_2),
461        );
462        let hit = compound
463            .ray_cast(
464                &pose,
465                &Ray::new(DVec3::new(0.0, 11.75, 0.0), DVec3::new(0.0, 1.0, 0.0)),
466            )
467            .expect("the ray starts between the parts and runs into the second");
468        assert_eq!(hit.part, 1);
469        assert!((hit.hit.point - DVec3::new(0.0, 12.5, 0.0)).length() < 1e-9);
470        assert!((hit.hit.t - 0.75).abs() < 1e-9);
471    }
472
473    // Ported from EW's `asset_placement` tests, with EW's expected values.
474
475    #[test]
476    fn missing_or_malformed_mesh_geometry_is_refused() {
477        let scene = demo();
478        let missing = InstanceDesc {
479            mesh: scene.meshes.len(),
480            ..cube(Mat4::IDENTITY)
481        };
482        assert_eq!(
483            scene.instance_bounds(&[missing], Mat4::IDENTITY),
484            Err(SceneBoundsError::MissingMesh {
485                instance: 0,
486                mesh: scene.meshes.len(),
487            })
488        );
489
490        let mut incomplete = demo();
491        flat_vertices(&mut incomplete, DEMO_CUBE).pop();
492        assert_eq!(
493            incomplete.instance_bounds(&[cube(Mat4::IDENTITY)], Mat4::IDENTITY),
494            Err(SceneBoundsError::PartialVertex {
495                instance: 0,
496                mesh: DEMO_CUBE,
497            })
498        );
499
500        let mut nonfinite = demo();
501        flat_vertices(&mut nonfinite, DEMO_CUBE)[..4].copy_from_slice(&f32::NAN.to_le_bytes());
502        assert_eq!(
503            nonfinite.instance_bounds(&[cube(Mat4::IDENTITY)], Mat4::IDENTITY),
504            Err(SceneBoundsError::NonFinitePosition {
505                instance: 0,
506                vertex: 0,
507            })
508        );
509    }
510
511    #[test]
512    fn a_mesh_with_no_vertices_alone_has_no_bounds() {
513        let mut scene = demo();
514        flat_vertices(&mut scene, DEMO_CUBE).clear();
515        assert_eq!(
516            scene.instance_bounds(&[cube(Mat4::IDENTITY)], Mat4::IDENTITY),
517            Err(SceneBoundsError::Empty)
518        );
519    }
520
521    #[test]
522    fn a_dag_is_bounded_by_its_finest_level_and_transforms_compose() {
523        let mut dag_scene = demo();
524        let dag_mesh = dag_scene
525            .meshes
526            .iter()
527            .position(|mesh| matches!(mesh.geometry, Geometry::Dag { .. }))
528            .expect("the demo includes a DAG mesh");
529        let instance = InstanceDesc {
530            mesh: dag_mesh,
531            material: 0,
532            transform: Mat4::IDENTITY,
533        };
534        let expected = dag_scene
535            .instance_bounds(&[instance], Mat4::IDENTITY)
536            .expect("the dunes have vertices");
537        {
538            let Geometry::Dag { levels, .. } = &mut dag_scene.meshes[dag_mesh].geometry else {
539                panic!("the selected demo mesh is a DAG");
540            };
541            assert!(levels.len() > 1);
542            for vertex in levels[1]
543                .to_mut()
544                .as_chunks_mut::<{ mesh::VERTEX_STRIDE }>()
545                .0
546            {
547                vertex[..12].copy_from_slice(
548                    &[10_000.0_f32, 10_000.0, 10_000.0]
549                        .map(f32::to_le_bytes)
550                        .concat(),
551                );
552            }
553        }
554        assert_eq!(
555            dag_scene.instance_bounds(&[instance], Mat4::IDENTITY),
556            Ok(expected)
557        );
558
559        let Geometry::Dag { levels, .. } = &mut dag_scene.meshes[dag_mesh].geometry else {
560            panic!("the selected demo mesh is a DAG");
561        };
562        levels.clear();
563        assert_eq!(
564            dag_scene.instance_bounds(&[instance], Mat4::IDENTITY),
565            Err(SceneBoundsError::NoLevels {
566                instance: 0,
567                mesh: dag_mesh,
568            })
569        );
570
571        let scene = demo();
572        let root =
573            Mat4::from_translation(Vec3::new(10.0, 20.0, 30.0)) * Mat4::from_rotation_z(FRAC_PI_2);
574        let bounds = scene
575            .instance_bounds(&[cube(Mat4::from_translation(Vec3::X * 2.0))], root)
576            .expect("a cube");
577        assert_eq!(bounds.min, Vec3::new(9.5, 21.5, 29.5));
578        assert_eq!(bounds.max, Vec3::new(10.5, 22.5, 30.5));
579    }
580
581    /// EW's expected values, less EW's own `MIN_HALF_EXTENT_M` padding: the
582    /// last two parts are flat boxes here, which `AabbCompound::new` accepts.
583    #[test]
584    fn parts_follow_each_instance_transform() {
585        let scene = demo();
586        let large_coordinate = f32::MAX * 0.75;
587        let parts = scene
588            .instance_parts(&[
589                cube(Mat4::from_translation(Vec3::new(-2.0, 0.0, 0.0))),
590                cube(
591                    Mat4::from_translation(Vec3::new(3.0, 4.0, 5.0))
592                        * Mat4::from_scale(Vec3::new(2.0, 1.0, 3.0)),
593                ),
594                cube(Mat4::from_translation(Vec3::splat(large_coordinate))),
595                cube(
596                    Mat4::from_translation(Vec3::new(7.0, 8.0, 9.0)) * Mat4::from_scale(Vec3::ZERO),
597                ),
598            ])
599            .expect("four finite cubes");
600        assert_eq!(
601            parts,
602            vec![
603                Aabb {
604                    min: Vec3::new(-2.5, -0.5, -0.5),
605                    max: Vec3::new(-1.5, 0.5, 0.5),
606                },
607                Aabb {
608                    min: Vec3::new(2.0, 3.5, 3.5),
609                    max: Vec3::new(4.0, 4.5, 6.5),
610                },
611                Aabb {
612                    min: Vec3::splat(large_coordinate),
613                    max: Vec3::splat(large_coordinate),
614                },
615                Aabb {
616                    min: Vec3::new(7.0, 8.0, 9.0),
617                    max: Vec3::new(7.0, 8.0, 9.0),
618                },
619            ]
620        );
621    }
622}