crcbl_render/cull.rs
1//! Frustum culling: an axis-aligned box, six half-spaces, and the reference
2//! implementation `cull.slang` is checked against.
3//!
4//! ```text
5//! camera.view_projection(aspect) ──▶ Frustum::from_view_projection
6//! │ six planes, unnormalized
7//! ▼
8//! GpuMesh::bounds_* ──▶ Aabb ──transformed by GpuInstance::transform──▶ Aabb
9//! │
10//! Frustum::intersects
11//! ▼
12//! visible_instances
13//! ```
14//!
15//! Topic 03 §3.3: "Compute pass: frustum cull
16//! against instance AABBs → compacted visible instance list". The compute pass
17//! is `crcbl-shaders`' `cull.slang`; **everything in this module is ordinary
18//! Rust**, and it exists for two reasons that are not the same reason:
19//!
20//! * [`Frustum::from_view_projection`] is what fills the shader's uniform block.
21//! Nothing on the GPU can extract planes from a matrix it is never handed.
22//! * [`visible_instances`] is the **oracle**. A dispatch that runs and writes a
23//! buffer nobody reads is indistinguishable from one that does nothing, so
24//! `crcbl-vk`'s `cull` e2e reads the list back and compares it against this,
25//! over instances placed inside, outside each plane, and straddling.
26//!
27//! [`crate::draw_gen`] is what consumes the visible list: it turns the survivors
28//! into per-bucket indirect draw arguments, which [`crate::forward`] draws from.
29//! This module stays the *proof* rather than the path — nothing in a frame calls
30//! [`visible_instances`], and that is the point of an oracle.
31//!
32//! # And the same again, one layer down
33//!
34//! [`cluster_survives_cull`] is §3.5's per-cluster rejection: the frustum
35//! against a cluster's bounding **sphere**, and its normal cone against the
36//! camera. It is the second oracle here for the first one's reason — the rule
37//! it mirrors runs in `mesh_cluster.slang`'s amplification stage, where the
38//! only observable is a counter, and a rule stated in Rust is a rule a test can
39//! state the answer to by hand.
40//!
41//! The instance cull above it is unchanged and still runs first. Cluster
42//! rejection happens *inside* a surviving instance; neither replaces the other.
43//!
44//! # A rotated box is not a box
45//!
46//! [`Aabb::transformed`] uses the standard conservative method — the
47//! **absolute-value matrix** — and its docs carry the derivation. The result
48//! contains the rotated box and is usually larger, which is the direction a cull
49//! must err in: a false survivor costs a draw, a false rejection is a hole in
50//! the picture.
51//!
52//! # The planes are not normalized
53//!
54//! [`Frustum::intersects`] scales linearly with each plane's normal, so
55//! normalizing changes no answer — and under the engine's reversed-Z
56//! **infinite** perspective one of the six planes comes out with a zero normal,
57//! because the far plane is at infinity and rejects nothing. Normalizing would
58//! divide that one by zero and make every comparison against it `NaN`, which is
59//! false, which reads as "outside" — every instance culled, an empty screen, and
60//! no error anywhere. [`Frustum::from_view_projection`] therefore hands the
61//! planes over exactly as extracted, and this module's
62//! `the_infinite_far_plane_is_degenerate_and_rejects_nothing` is what says so.
63
64mod occlusion;
65
66pub use occlusion::{
67 DepthPyramid, EarlyInputs, FacePlanes, PyramidFootprint, Reduction, ScreenBounds,
68 early_entries, face_entries, face_planes, face_tags, footprint, late_entry, occluded,
69 project_box, small_feature, world_box,
70};
71
72use crcbl_core::bounds::{max_lanes, min_lanes};
73use crcbl_shaders::mesh::{GpuInstance, GpuMaterial, GpuMesh};
74use crcbl_shaders::meshlet::ClusterBounds;
75use glam::{Mat3, Mat4, Vec3, Vec4};
76
77/// An axis-aligned bounding box.
78///
79/// Used for a mesh's **local-space** bounds — the box around its vertices as
80/// they sit in the pool, before any instance transform — and for the world-space
81/// box [`Aabb::transformed`] produces from one.
82#[derive(Clone, Copy, Debug, Default, PartialEq)]
83pub struct Aabb {
84 /// Lowest corner.
85 pub min: Vec3,
86 /// Highest corner.
87 pub max: Vec3,
88}
89
90impl Aabb {
91 /// The box containing every point, or `None` for an empty iterator.
92 ///
93 /// `None` rather than an empty-box sentinel: there is no box containing
94 /// nothing, and the usual encoding for one — `min` at `+INFINITY`, `max` at
95 /// `-INFINITY` — is a pair of values that survive into a buffer and turn
96 /// every later comparison into a `NaN`.
97 ///
98 /// # A `NaN` lane is skipped, so this is not a validity check
99 ///
100 /// The fold goes through `f32::min`/`f32::max` per lane, which return the
101 /// **other** operand when one side is `NaN`. An unusable coordinate is
102 /// therefore ignored and the box still contains every finite point. Only a
103 /// lane with no finite value at all comes out `NaN`, so a wholly degenerate
104 /// mesh is still visible as one. An infinity has a defined ordering, is
105 /// real data, and is kept.
106 ///
107 /// **It is deliberately not [`Vec3::min`]/[`Vec3::max`]**, and the
108 /// difference was a bug rather than a preference. glam 0.33 writes those as
109 /// a bare `if self.x < rhs.x { self.x } else { rhs.x }`; every comparison
110 /// against `NaN` is false, so they yield the *incoming* point and discard
111 /// the accumulator. One `NaN` vertex followed by one finite vertex produced
112 /// a **finite box that did not contain the geometry** — which culls what is
113 /// on screen, the direction this module's header says a cull must never err
114 /// in. `a_nan_is_skipped_from_every_position_and_never_shrinks_the_box`
115 /// covers every position because the defect was positional, and it fails
116 /// against the glam form.
117 ///
118 /// What this costs callers is detection: `from_points(…).is_some()`, and
119 /// equally a finiteness test on the box that comes out, cannot tell you the
120 /// points were finite. A caller needing that must test the points
121 /// themselves before folding — `apps/viewer`'s `model` module does.
122 #[must_use]
123 pub fn from_points(points: impl IntoIterator<Item = Vec3>) -> Option<Self> {
124 let mut points = points.into_iter();
125 let first = points.next()?;
126 let mut bounds = Self {
127 min: first,
128 max: first,
129 };
130 for point in points {
131 bounds.min = min_lanes(bounds.min, point);
132 bounds.max = max_lanes(bounds.max, point);
133 }
134 Some(bounds)
135 }
136
137 /// The box's centre.
138 #[must_use]
139 pub fn center(&self) -> Vec3 {
140 (self.max + self.min) * 0.5
141 }
142
143 /// Half the box's size along each axis.
144 #[must_use]
145 pub fn half_extent(&self) -> Vec3 {
146 (self.max - self.min) * 0.5
147 }
148
149 /// The smallest *axis-aligned* box this module will claim contains
150 /// `transform` applied to this one.
151 ///
152 /// **A rotated box is not a box**, so this is the standard conservative
153 /// construction (Ericson, *Real-Time Collision Detection* §4.2.6): the new
154 /// centre is the transform applied to the old centre, and the new
155 /// half-extent is the *element-wise absolute value* of the transform's 3×3
156 /// part applied to the old half-extent. Along world axis `i` the box reaches
157 /// `Σⱼ |m[i][j]| · e[j]`, which is the furthest any corner can get once every
158 /// combination of `±e` is allowed — so the result contains the rotated box,
159 /// and for a rotation that is not a multiple of a quarter turn it is
160 /// strictly larger.
161 ///
162 /// `cull.slang` performs exactly this arithmetic, which is why a rotated
163 /// instance is one of the cases the e2e places deliberately.
164 #[must_use]
165 pub fn transformed(&self, transform: Mat4) -> Self {
166 let center = transform.transform_point3(self.center());
167 let basis = Mat3::from_mat4(transform);
168 // `abs` element-wise, then the ordinary matrix-vector product. Built
169 // column by column because that is how `glam` stores a `Mat3`; the
170 // product is the same either way, since every entry is non-negative.
171 let absolute = Mat3::from_cols(basis.x_axis.abs(), basis.y_axis.abs(), basis.z_axis.abs());
172 let extent = absolute * self.half_extent();
173 Self {
174 min: center - extent,
175 max: center + extent,
176 }
177 }
178}
179
180/// Planes in a [`Frustum`].
181pub const PLANE_COUNT: usize = crcbl_shaders::cull::PLANE_COUNT;
182
183/// A view frustum, as six half-spaces.
184///
185/// Each plane is `[nx, ny, nz, d]` and a point `p` is inside it when
186/// `n · p + d >= 0`. The normals point *inward*, and none of them is unit
187/// length — see the [module docs](self) for why normalizing them would be a
188/// bug rather than a tidy-up.
189#[derive(Clone, Copy, Debug, PartialEq)]
190pub struct Frustum {
191 /// The six half-spaces, in the order
192 /// [`from_view_projection`](Frustum::from_view_projection) extracts them.
193 pub planes: [Vec4; PLANE_COUNT],
194}
195
196impl Frustum {
197 /// The frustum of a world → clip matrix.
198 ///
199 /// **Gribb-Hartmann**: each clip-space inequality is a linear function of
200 /// the world position, so the plane is a sum or difference of two *rows* of
201 /// the matrix. For the `0..w` depth range every backend here uses, the six
202 /// are `x ≥ -w`, `x ≤ w`, `y ≥ -w`, `y ≤ w`, `z ≥ 0`, `z ≤ w`, giving
203 /// `row3 ± row0`, `row3 ± row1`, `row2`, and `row3 - row2`.
204 ///
205 /// The last two are named by their clip-space inequality rather than as
206 /// "near" and "far", because under this engine's reversed-Z they are the
207 /// other way round from the usual reading: `z ≥ 0` is the *far* plane and
208 /// `z ≤ w` is the near one. Under the infinite perspective projection the
209 /// far plane is degenerate — a zero normal and a positive offset, so every
210 /// point passes it — which is correct and is also why nothing here divides
211 /// by a normal's length.
212 #[must_use]
213 pub fn from_view_projection(view_projection: Mat4) -> Self {
214 let row = |index: usize| view_projection.row(index);
215 let (x, y, z, w) = (row(0), row(1), row(2), row(3));
216 Self {
217 planes: [w + x, w - x, w + y, w - y, z, w - z],
218 }
219 }
220
221 /// Whether `bounds` is on the inside of every plane, and so must be drawn.
222 ///
223 /// Conservative in the safe direction: a box outside the frustum but inside
224 /// each of its planes taken alone — the corner case every plane-by-plane
225 /// test has — answers `true`. The alternative rejects geometry that is on
226 /// screen.
227 #[must_use]
228 pub fn intersects(&self, bounds: &Aabb) -> bool {
229 let center = bounds.center();
230 let extent = bounds.half_extent();
231 self.planes.iter().all(|plane| {
232 let normal = plane.truncate();
233 // How far the box reaches from its centre towards this plane, along
234 // the plane's own normal. `abs` on the normal rather than a corner
235 // selection: same number, no branch, and it is what the shader does.
236 let radius = normal.abs().dot(extent);
237 normal.dot(center) + plane.w >= -radius
238 })
239 }
240
241 /// Whether the sphere of `radius` about `center` reaches inside every
242 /// plane. Conservative on [`Frustum::intersects`]' terms exactly.
243 ///
244 /// The **radius** is scaled by each plane normal's length rather than the
245 /// plane divided by it, which is the same inequality and the only form that
246 /// survives an unnormalized plane: the infinite reversed-Z projection's far
247 /// plane has a zero normal, and dividing by it would make every comparison
248 /// against it `NaN` — which is false, which reads as "outside". See the
249 /// module docs, and `cluster_survives`' loop in `mesh_cluster.slang`, which
250 /// is this arithmetic.
251 ///
252 /// A sphere rather than the box [`Frustum::intersects`] takes, because a
253 /// cluster's bound *is* a sphere: [`ClusterBounds::radius`] is the distance
254 /// to its furthest vertex, and boxing it up again would widen the bound by
255 /// up to a factor of √3 for nothing.
256 #[must_use]
257 pub fn intersects_sphere(&self, center: Vec3, radius: f32) -> bool {
258 self.planes.iter().all(|plane| {
259 let normal = plane.truncate();
260 normal.dot(center) + plane.w >= -radius * normal.length()
261 })
262 }
263}
264
265/// Which of the per-cluster cull's two tests rejected a cluster, or that neither
266/// did — the outcomes `mesh_cluster.slang`'s `cluster_survives` answers with.
267///
268/// The counters the amplification stage keeps are per outcome, so this is what
269/// [`cluster_cull_verdict`] has to answer for a test to be able to say *which*
270/// test removed a cluster. A survivor count on its own cannot: "27 of 338
271/// survived" is equally consistent with the normal cone doing all of the work
272/// and with it doing none.
273#[derive(Clone, Copy, Debug, PartialEq, Eq)]
274pub enum ClusterVerdict {
275 /// Both tests kept it, so it reaches the mesh stage.
276 Kept,
277 /// Its bounding sphere is entirely outside one of the frustum's six planes.
278 RejectedByFrustum,
279 /// Every triangle of it faces away from the camera.
280 ///
281 /// **Reached only by a cluster the frustum kept**, because the two tests are
282 /// asked in that order — so a cluster that is both behind the camera and
283 /// facing away is the frustum's, here and in the shader.
284 RejectedByCone,
285}
286
287/// Whether a cluster of an instance may contribute a pixel — **the reference
288/// implementation of §3.5's per-cluster cull**, and the rule
289/// `mesh_cluster.slang`'s amplification stage runs.
290///
291/// [`cluster_cull_verdict`] is the same rule with the cause of a rejection kept;
292/// this is written in terms of it so the two cannot answer differently.
293///
294/// `transform` is the instance's model → world matrix and `camera` its
295/// world-space eye position, so this is the cull in **world space**: the same
296/// space `frustum` is already in, because it comes from the same
297/// [`Frustum::from_view_projection`] the instance cull is handed. `bounds` is
298/// in the mesh's own space, which is what makes the transform necessary at all.
299///
300/// **The sphere is moved by the whole transform, scale included.** The centre
301/// goes through the matrix, the radius is multiplied by the largest factor the
302/// 3×3 can stretch a length by, and the cone axis is the 3×3 applied to it and
303/// then made a unit vector again — which is the world-space form of the rule for
304/// any transform that preserves angles, and **wrong** for one that does not, so
305/// the cone half is skipped there. A cone is a set of *normals*, and a
306/// non-uniform scale moves a normal one way and the surface it belongs to the
307/// other: neither the axis nor the half angle survives, and the widened angle
308/// has no bound this code could state and defend. The sphere still culls, so
309/// what a scaled instance costs is a cluster kept, never one dropped.
310/// [`ClusterBounds::SIMILARITY_TOLERANCE`] is where the number that decides it
311/// lives.
312/// This used to take the radius across unchanged and lean on
313/// [`GpuInstance::transform`] being rigid; the engine's own scenes are not —
314/// `crcbl::screenshot`'s trough is the open box scaled by `6 × 2 × 1.6` — and an
315/// instance-sized sphere standing in for a scene-sized one rejects clusters that
316/// fill half the frame.
317///
318/// # The two halves
319///
320/// Frustum first, against the bounding sphere, then the normal cone. The cone
321/// rule and the derivation that makes it safe are
322/// [`ClusterBounds::cone_cutoff`]'s docs; the short version is that the
323/// [`radius`](ClusterBounds::radius) term is what stops it rejecting a cluster
324/// that has a front-facing triangle.
325///
326/// **`material_mode` decides whether the second half runs at all** — see
327/// [`cone_may_reject`], which is where the argument lives. It is the instance's
328/// own [`GpuInstance::material_mode`], the same two bits the draw-argument pass
329/// keys buckets on.
330///
331/// **This is the oracle, not the path.** Nothing in a frame calls it — the
332/// amplification stage is what culls — and it exists so a test can state the
333/// answer for a case a picture cannot show, exactly as [`visible_instances`]
334/// does for the instance cull one layer up.
335///
336/// [`GpuInstance::transform`]: crcbl_shaders::mesh::GpuInstance::transform
337#[must_use]
338pub fn cluster_survives_cull(
339 frustum: &Frustum,
340 camera: Vec3,
341 transform: Mat4,
342 material_mode: u32,
343 bounds: &ClusterBounds,
344) -> bool {
345 cluster_cull_verdict(frustum, camera, transform, material_mode, bounds) == ClusterVerdict::Kept
346}
347
348/// The same rule as [`cluster_survives_cull`], answering **which test** refused.
349///
350/// Every word of that function's header applies here — it is the one that runs
351/// the rule, and the bool is a reading of this answer. What this adds is the
352/// only thing the counters need and a bool cannot carry: the frame's three
353/// per-cluster numbers are survivors, frustum rejections and cone rejections,
354/// and a test that could only say "something rejected it" would pass just as
355/// well with the two buckets swapped.
356///
357/// The order is the shader's: frustum first against the bounding sphere, then
358/// the cone. A cluster that fails both is [`ClusterVerdict::RejectedByFrustum`]
359/// on both sides, and a double-sided instance — [`cone_may_reject`] — has no
360/// second half, so it answers [`ClusterVerdict::Kept`] or
361/// [`ClusterVerdict::RejectedByFrustum`] and never
362/// [`ClusterVerdict::RejectedByCone`].
363#[must_use]
364pub fn cluster_cull_verdict(
365 frustum: &Frustum,
366 camera: Vec3,
367 transform: Mat4,
368 material_mode: u32,
369 bounds: &ClusterBounds,
370) -> ClusterVerdict {
371 let basis = Mat3::from_mat4(transform);
372 let center = transform.transform_point3(Vec3::from_array(bounds.center));
373 let radius = bounds.radius * max_stretch(basis);
374 if !frustum.intersects_sphere(center, radius) {
375 return ClusterVerdict::RejectedByFrustum;
376 }
377 // A unit axis, so the two sides of the cone inequality below are in the same
378 // units: the left is a length along the axis and the right is a length in
379 // world space. Left unnormalised, a transform that scales by `s` multiplies
380 // one side and not the other, which is a cone test that answers differently
381 // for the same shape at two sizes.
382 let axis = (basis * Vec3::from_array(bounds.cone_axis)).normalize_or_zero();
383 let to_center = center - camera;
384 let sine = (1.0 - bounds.cone_cutoff * bounds.cone_cutoff)
385 .max(0.0)
386 .sqrt();
387 let faces_away = cone_may_reject(material_mode)
388 && preserves_angles(basis)
389 && bounds.cone_cutoff > 0.0
390 && axis.dot(to_center) > sine.mul_add(to_center.length(), radius);
391 if faces_away {
392 ClusterVerdict::RejectedByCone
393 } else {
394 ClusterVerdict::Kept
395 }
396}
397
398/// Whether a cluster of an instance in this **material mode** may be rejected
399/// by its normal cone.
400///
401/// **Which way a surface faces is the material's business, not the geometry's.**
402/// A cluster's cone is a statement about where its triangles' normals point, and
403/// it is *true* whatever material draws them. What turns it into a rejection is
404/// a second claim — that a triangle seen from behind puts nothing on the screen
405/// — and that claim is the back-face cull, which glTF 2.0 §3.9.6's
406/// `doubleSided` switches off. So for a double-sided instance the cone's
407/// arithmetic is still right and the conclusion drawn from it is not: an open
408/// surface with one flat cluster carries `cone_cutoff == 1.0` and an axis
409/// pointing away from the camera, and every pixel of it is visible.
410///
411/// **Only the cone.** The frustum half and the `+ radius` conservatism are about
412/// where the geometry *is*, which no material moves, so they are unchanged for a
413/// double-sided instance — a back-facing cluster off the side of the screen is
414/// still rejected, by the test that was always the right one for that.
415///
416/// `mesh_cluster.slang`'s `cone_may_reject` is this same predicate in the
417/// amplification stage, and `material_mode` is
418/// [`GpuInstance::material_mode`]'s value on both sides — two bits, of which
419/// [`GpuMaterial::DOUBLE_SIDED`] is the one read here.
420#[must_use]
421pub const fn cone_may_reject(material_mode: u32) -> bool {
422 material_mode & GpuMaterial::DOUBLE_SIDED == 0
423}
424
425/// Whether `basis` carries every angle across unchanged — a rotation, a uniform
426/// scale, a reflection, or those composed.
427///
428/// **What the cone test needs and the radius does not.** A cluster's cone is a
429/// set of *normals*, and a transform that stretches one axis moves a normal one
430/// way and the surface it belongs to the other: the cone's axis is no longer the
431/// image of the axis under the 3×3, and its half-angle is no longer its own.
432/// Both would have to move together, and the widened angle has no bound this
433/// code could state and defend — so a cluster of a non-similarity instance is
434/// **kept**, and the frustum is what culls it. Fewer clusters rejected, never a
435/// visible one dropped. `docs/backlog.md` carries what a tighter answer needs.
436///
437/// `BᵀB` is `s²I` exactly when `basis` is `s` times an orthogonal matrix, which
438/// is the definition being tested: every column has the same length and no two
439/// are oblique. Tested relative to the largest diagonal, so it holds at any
440/// scale, against [`ClusterBounds::SIMILARITY_TOLERANCE`] — which carries the
441/// measurements behind the number, and which `mesh_cluster.slang`'s own
442/// `preserves_angles` reads too.
443///
444/// A degenerate basis — a zero scale, which draws nothing — answers `false`, so
445/// its clusters are kept rather than culled by a rule that has no angles left to
446/// read.
447fn preserves_angles(basis: Mat3) -> bool {
448 let gram = basis.transpose() * basis;
449 let diagonal = [gram.x_axis.x, gram.y_axis.y, gram.z_axis.z];
450 let largest = diagonal.iter().copied().fold(0.0f32, f32::max);
451 if largest <= 0.0 {
452 return false;
453 }
454 let slack = ClusterBounds::SIMILARITY_TOLERANCE * largest;
455 let off_diagonal = [gram.x_axis.y, gram.x_axis.z, gram.y_axis.z];
456 off_diagonal.iter().all(|value| value.abs() <= slack)
457 && diagonal.iter().all(|value| (largest - value) <= slack)
458}
459
460/// The largest factor by which `basis` can grow a vector's length, bounded from
461/// above — what a bounding *sphere*'s radius has to be multiplied by to still
462/// bound the transformed cluster.
463///
464/// That factor is `basis`' largest singular value, and this bounds it rather
465/// than computing it: `σ_max² = λ_max(BᵀB)`, and a symmetric matrix's spectral
466/// radius is at most any induced norm of it, so the largest absolute row sum of
467/// `BᵀB` is an upper bound on `σ_max²`. Bounding is the safe direction for a
468/// cull, and the bound is **exact** whenever `basis`' columns are orthogonal —
469/// every rotation-then-scale, which is every transform this engine builds —
470/// because `BᵀB` is then diagonal and its rows are the columns' squared lengths.
471///
472/// The alternative, `max` over the columns' lengths, is exact on the same
473/// matrices and *under*-estimates on a sheared one, which is the direction that
474/// drops geometry. This form needs no contract about what a caller may pass.
475///
476/// `1.0` for a rotation or a translation, so nothing that was already correct
477/// moves.
478fn max_stretch(basis: Mat3) -> f32 {
479 let gram = basis.transpose() * basis;
480 let row_sum = |row: usize| {
481 (0..3)
482 .map(|column| gram.col(column)[row].abs())
483 .sum::<f32>()
484 };
485 (0..3).map(row_sum).fold(0.0f32, f32::max).sqrt()
486}
487
488/// The instances `frustum` keeps, as indices into `instances`.
489///
490/// **The reference implementation, and the oracle `cull.slang` is checked
491/// against.** It resolves each instance's mesh exactly as the shader does —
492/// `GpuInstance::mesh` indexes `meshes`, the entry carries the local-space
493/// bounds, the instance transform makes them world-space — and applies the same
494/// rejections in the same order.
495///
496/// An instance without
497/// [`GpuInstance::LIVE`](crcbl_shaders::mesh::GpuInstance::LIVE) in its
498/// [`flags`](GpuInstance::flags) is **not** visible, and that is asked first:
499/// the array is a pool, so an element between two live instances may be a slot
500/// [`InstancePool::remove`](crate::instance_pool::InstancePool::remove) freed,
501/// still holding the transform and mesh id it had when it was live. Nothing
502/// else in the record is looked at until that bit says it means anything.
503///
504/// An instance whose mesh entry has a zero
505/// [`index_count`](GpuMesh::index_count) is **not** visible: that is the
506/// all-zero record [`MeshPool::free`](crate::mesh_pool::MeshPool::free) leaves
507/// behind, whose bounds are a degenerate point box at the origin, and treating
508/// it as geometry would put a mesh that does not exist on screen whenever the
509/// origin is. An instance naming an entry past the end of `meshes` is not
510/// visible either — the shader has no such guard, because a bind group's buffer
511/// bound whole is exactly the table and reading past it is a validation error
512/// the caller must not create. The box tested is
513/// [`GpuInstance::cull_bounds`]: the record's own under
514/// [`GpuInstance::OWNS_BOUNDS`](crcbl_shaders::mesh::GpuInstance::OWNS_BOUNDS),
515/// the mesh entry's otherwise — and a live instance with
516/// [`GpuInstance::BASE_VERTEX_OVERRIDE`] and no box of its own is kept after
517/// that empty-mesh check, because its source mesh bounds do not describe its
518/// skinned vertex region.
519///
520/// An instance whose [`flags`](GpuInstance::flags) carry `hidden_view` is **not**
521/// visible, asked straight after the live bit: it is the view's own bit of
522/// [`GpuInstance::HIDDEN_VIEWS_MASK`](crcbl_shaders::mesh::GpuInstance::HIDDEN_VIEWS_MASK),
523/// and a cull that is no view's passes zero and rejects nothing on it.
524///
525/// The order is ascending. **The GPU's is not**, because slots come from an
526/// atomic, so a comparison between the two sorts first.
527#[must_use]
528pub fn visible_instances(
529 frustum: &Frustum,
530 instances: &[GpuInstance],
531 meshes: &[GpuMesh],
532 hidden_view: u32,
533) -> Vec<u32> {
534 let mut visible = Vec::new();
535 for (index, instance) in instances.iter().enumerate() {
536 if instance.flags & GpuInstance::LIVE == 0 {
537 continue;
538 }
539 if instance.flags & hidden_view != 0 {
540 continue;
541 }
542 let Some(mesh) = meshes.get(instance.mesh as usize) else {
543 continue;
544 };
545 if mesh.index_count == 0 {
546 continue;
547 }
548 let kept = instance.cull_bounds(mesh).is_none_or(|(min, max)| {
549 let bounds = Aabb {
550 min: Vec3::from_array(min),
551 max: Vec3::from_array(max),
552 };
553 frustum.intersects(&bounds.transformed(Mat4::from_cols_array(&instance.transform)))
554 });
555 if kept {
556 visible.push(u32::try_from(index).unwrap_or_else(|_| {
557 unreachable!("an instance array is indexed by u32 everywhere else")
558 }));
559 }
560 }
561 visible
562}
563
564#[cfg(test)]
565mod tests {
566 use super::*;
567 use crate::camera::{Camera, Projection};
568 use core::f32::consts::FRAC_PI_2;
569
570 /// The camera every test below culls against: two metres back along +Z,
571 /// looking at the origin, default 45° perspective.
572 fn frustum() -> Frustum {
573 Frustum::from_view_projection(Camera::default().view_projection(1.0))
574 }
575
576 /// A unit cube centred on the origin, as a mesh-table entry.
577 fn unit_cube() -> GpuMesh {
578 GpuMesh {
579 base_vertex: 0,
580 base_index: 0,
581 index_count: 36,
582 bounds_min: [-0.5, -0.5, -0.5],
583 bounds_max: [0.5, 0.5, 0.5],
584 // Read by nothing here: this pass resolves boxes, and the range is
585 // the vertex stage's.
586 uv_range: crcbl_shaders::vertex::UvRange::default(),
587 // Read by nothing here either, and for the same reason: the tangent
588 // frame is the raster stages'.
589 flags: 0,
590 }
591 }
592
593 /// Where a `NaN` sits decides whether [`Aabb::from_points`] keeps it, and
594 /// the deciding line is in `glam` rather than here.
595 ///
596 /// `Vec3::min` is not `f32::min`. glam 0.33 writes it as
597 /// `if self.x < rhs.x { self.x } else { rhs.x }`, and every comparison
598 /// against `NaN` is false, so the expression returns **`rhs`** whichever
599 /// side is unusable. The fold seeds the box with the first point and makes
600 /// each later point the `rhs`, so a `NaN` that arrives later overwrites a
601 /// finite accumulator, while a `NaN` seeded into the accumulator is
602 /// overwritten by the first finite point after it.
603 ///
604 /// This is asserted because the behaviour was previously recorded the other
605 /// way round — as `f32::min`'s absorb-everywhere rule — and a caller
606 /// deciding whether to validate its own points will act on which one is
607 /// true. A `glam` upgrade that switched to `f32::min` would silently make
608 /// the common case absorb, so this test is the thing that would notice.
609 #[test]
610 fn a_nan_is_skipped_from_every_position_and_never_shrinks_the_box() {
611 let nan = Vec3::new(f32::NAN, 0.0, 0.0);
612 let low = Vec3::new(-1.0, -1.0, -1.0);
613 let high = Vec3::new(1.0, 1.0, 1.0);
614 let want = Aabb {
615 min: low,
616 max: high,
617 };
618
619 // Every position, because the defect this replaced was positional: the
620 // bare comparison yielded the incoming point, so a NaN anywhere but
621 // last threw away the extent gathered before it and still came back
622 // finite. Leading, middle and trailing all have to hold.
623 for (label, points) in [
624 ("leading", vec![nan, low, high]),
625 ("middle", vec![low, nan, high]),
626 ("trailing", vec![low, high, nan]),
627 ("before a finite point", vec![low, high, nan, low]),
628 ] {
629 let box_ = Aabb::from_points(points).expect("not empty");
630 assert_eq!(
631 box_, want,
632 "a NaN {label} must be skipped, leaving exactly the box the finite points make"
633 );
634 }
635
636 let infinite = Aabb::from_points([low, Vec3::new(f32::INFINITY, 0.0, 0.0), high])
637 .expect("three points is not empty");
638 assert_eq!(
639 infinite.max.x,
640 f32::INFINITY,
641 "an infinity has a defined ordering, so it is real data and is kept — only the \
642 unorderable value is skipped"
643 );
644
645 let all_nan = Aabb::from_points([nan, nan]).expect("two points is not empty");
646 assert!(
647 all_nan.min.x.is_nan() && all_nan.max.x.is_nan(),
648 "with nothing finite to fall back to in that lane the NaN is all there is, so a wholly \
649 degenerate mesh still reports as non-finite rather than as a plausible box"
650 );
651 }
652
653 /// A **live** instance of mesh 0 at `translation`.
654 ///
655 /// Live rather than default, because a default record is dead — see
656 /// [`GpuInstance::LIVE`] — and a test scene built from dead instances would
657 /// cull everything and assert nothing.
658 fn at(translation: Vec3) -> GpuInstance {
659 GpuInstance {
660 transform: Mat4::from_translation(translation).to_cols_array(),
661 flags: GpuInstance::LIVE,
662 ..GpuInstance::default()
663 }
664 }
665
666 #[test]
667 fn a_box_at_the_origin_is_inside_the_default_camera() {
668 let bounds = Aabb {
669 min: Vec3::splat(-0.5),
670 max: Vec3::splat(0.5),
671 };
672 assert!(frustum().intersects(&bounds));
673 }
674
675 /// One case per plane, each moved just past it, so a frustum missing a
676 /// plane — or carrying the same plane twice — fails on the direction it
677 /// stopped covering rather than passing everything.
678 #[test]
679 fn a_box_pushed_past_any_one_plane_is_outside() {
680 let frustum = frustum();
681 let unit = Aabb {
682 min: Vec3::splat(-0.5),
683 max: Vec3::splat(0.5),
684 };
685 // Right/left/top/bottom are far enough sideways to leave a 45° cone;
686 // `behind` is past the eye at z = 2, which is the near plane's side.
687 for (what, translation) in [
688 ("right", Vec3::new(20.0, 0.0, 0.0)),
689 ("left", Vec3::new(-20.0, 0.0, 0.0)),
690 ("top", Vec3::new(0.0, 20.0, 0.0)),
691 ("bottom", Vec3::new(0.0, -20.0, 0.0)),
692 ("behind", Vec3::new(0.0, 0.0, 20.0)),
693 ] {
694 let moved = unit.transformed(Mat4::from_translation(translation));
695 assert!(
696 !frustum.intersects(&moved),
697 "a box {what} of the frustum was not culled: {moved:?}"
698 );
699 }
700 }
701
702 /// The reversed-Z infinite projection has no far plane, and this is where
703 /// that stops being prose. A normalization pass over these planes would
704 /// divide this one by zero.
705 #[test]
706 fn the_infinite_far_plane_is_degenerate_and_rejects_nothing() {
707 let frustum = frustum();
708 // `z >= 0` — the far plane under reversed-Z; see
709 // `Frustum::from_view_projection`.
710 let far = frustum.planes[4];
711 assert_eq!(far.truncate(), Vec3::ZERO, "{far:?}");
712 assert!(far.w > 0.0, "so every point is on its inside: {far:?}");
713
714 // Ten kilometres away along the view direction, and still visible.
715 let distant = Aabb {
716 min: Vec3::new(-0.5, -0.5, -10_000.5),
717 max: Vec3::new(0.5, 0.5, -9_999.5),
718 };
719 assert!(frustum.intersects(&distant));
720
721 // An orthographic camera has a finite far plane, so the same slot is a
722 // real one there — which is what says the degeneracy is the projection's
723 // and not this extraction's.
724 let ortho = Frustum::from_view_projection(
725 Camera::default()
726 .with_projection(Projection::Orthographic {
727 half_height: 1.0,
728 near: 0.1,
729 far: 10.0,
730 })
731 .view_projection(1.0),
732 );
733 assert_ne!(ortho.planes[4].truncate(), Vec3::ZERO);
734 assert!(!ortho.intersects(&distant));
735 }
736
737 /// The conservative transform, on the case that distinguishes it from
738 /// transforming the two corners: a 45° rotation about Z grows a unit square
739 /// by √2, and rotating `min` and `max` alone would leave it the same size.
740 #[test]
741 fn a_rotated_box_grows() {
742 let unit = Aabb {
743 min: Vec3::new(-0.5, -0.5, -0.5),
744 max: Vec3::new(0.5, 0.5, 0.5),
745 };
746 let rotated = unit.transformed(Mat4::from_rotation_z(core::f32::consts::FRAC_PI_4));
747 let half = rotated.half_extent();
748 let expected = core::f32::consts::SQRT_2 / 2.0;
749 assert!(
750 (half.x - expected).abs() < 1e-5 && (half.y - expected).abs() < 1e-5,
751 "a 45° rotation of a unit box has half-extent {expected} in x and y, got {half:?}"
752 );
753 assert!(
754 (half.z - 0.5).abs() < 1e-6,
755 "the rotation axis is untouched: {half:?}"
756 );
757
758 // A quarter turn is the case where the bound is exact rather than
759 // conservative, so it must *not* grow — an implementation that added a
760 // slack term would pass the assertion above and fail this one.
761 let quarter = unit.transformed(Mat4::from_rotation_z(FRAC_PI_2));
762 assert!(
763 (quarter.half_extent() - Vec3::splat(0.5))
764 .abs()
765 .max_element()
766 < 1e-6,
767 "{:?}",
768 quarter.half_extent()
769 );
770 }
771
772 /// The rotation the conservative bound exists for, seen through the cull:
773 /// a tall thin bar off to the right of the frustum, then laid on its side so
774 /// it reaches back in. Same centre, same mesh, opposite answers — which is
775 /// what an implementation that transformed only `min` and `max` would get
776 /// wrong.
777 #[test]
778 fn a_rotation_can_bring_a_box_back_into_the_frustum() {
779 let frustum = frustum();
780 let bar = Aabb {
781 min: Vec3::new(-0.02, -1.0, -0.02),
782 max: Vec3::new(0.02, 1.0, 0.02),
783 };
784 // The default camera sees roughly |x| < 0.83 at z = 0, so a 4 cm wide
785 // bar centred at x = 1.5 is outside; a metre of it either side is not.
786 let offset = Vec3::new(1.5, 0.0, 0.0);
787 let upright = bar.transformed(Mat4::from_translation(offset));
788 assert!(!frustum.intersects(&upright), "{upright:?}");
789
790 let laid_down =
791 bar.transformed(Mat4::from_translation(offset) * Mat4::from_rotation_z(FRAC_PI_2));
792 assert!(frustum.intersects(&laid_down), "{laid_down:?}");
793 }
794
795 /// **A removed instance is not visible**, whatever the frustum says about
796 /// where it last was.
797 ///
798 /// The instance is at the origin, which the camera is pointed at, and it is
799 /// the same record as the live one beside it in every respect but the bit —
800 /// so the only thing that can be deciding this is the bit.
801 #[test]
802 fn an_instance_without_the_live_bit_is_not_visible() {
803 let frustum = frustum();
804 let meshes = [unit_cube()];
805 let live = at(Vec3::ZERO);
806 let removed = GpuInstance {
807 flags: live.flags & !GpuInstance::LIVE,
808 ..live
809 };
810 assert_eq!(
811 visible_instances(&frustum, &[live, removed], &meshes, 0),
812 vec![0],
813 "the live instance survives and its dead twin does not"
814 );
815 // And the other order, so this is the flag and not the index.
816 assert_eq!(
817 visible_instances(&frustum, &[removed, live], &meshes, 0),
818 vec![1]
819 );
820 // A record that is all zeroes is dead too — that is the slot a pool
821 // hands out before anything writes it.
822 assert!(
823 visible_instances(&frustum, &[GpuInstance::default()], &meshes, 0).is_empty(),
824 "a default instance is not live"
825 );
826 }
827
828 /// The reference's other two rejections, neither of which is the frustum
829 /// test.
830 #[test]
831 fn an_instance_whose_mesh_entry_is_empty_is_not_visible() {
832 let frustum = frustum();
833 let meshes = [unit_cube(), GpuMesh::default()];
834 let instances = [
835 at(Vec3::ZERO),
836 GpuInstance {
837 mesh: 1,
838 ..at(Vec3::ZERO)
839 },
840 GpuInstance {
841 mesh: 7,
842 ..at(Vec3::ZERO)
843 },
844 ];
845 assert_eq!(visible_instances(&frustum, &instances, &meshes, 0), vec![0]);
846 }
847
848 #[test]
849 fn a_skinned_instance_survives_when_its_source_bounds_are_outside() {
850 let source_outside = at(Vec3::X * 8.0);
851 assert!(
852 visible_instances(&frustum(), &[source_outside], &[unit_cube()], 0).is_empty(),
853 "the unskinned source bounds are outside the camera"
854 );
855 let skinned = GpuInstance {
856 flags: source_outside.flags | GpuInstance::BASE_VERTEX_OVERRIDE,
857 ..source_outside
858 };
859 assert_eq!(
860 visible_instances(&frustum(), &[skinned], &[unit_cube()], 0),
861 vec![0],
862 "a palette may have moved the skinned vertices into view"
863 );
864 }
865
866 /// A skinned instance with a box of its own is culled by that box: outside
867 /// is rejected even where its source box is in view, and a box inside or
868 /// straddling a plane is kept even where its source box is outside.
869 #[test]
870 fn a_skinned_instance_with_its_own_box_is_culled_by_it() {
871 let skinned = |at_x: f32, bounds_min: [f32; 3], bounds_max: [f32; 3]| {
872 let record = at(Vec3::X * at_x);
873 GpuInstance {
874 flags: record.flags | GpuInstance::BASE_VERTEX_OVERRIDE | GpuInstance::OWNS_BOUNDS,
875 bounds_min,
876 bounds_max,
877 ..record
878 }
879 };
880 let instances = [
881 // 0: source box at the origin, in view; own box eight metres right.
882 skinned(0.0, [7.5, -0.5, -0.5], [8.5, 0.5, 0.5]),
883 // 1: source box eight metres right; own box back at the origin.
884 skinned(8.0, [-8.5, -0.5, -0.5], [-7.5, 0.5, 0.5]),
885 // 2: source box eight metres right; own box reaching from inside the
886 // view to well past its right-hand plane.
887 skinned(8.0, [-8.5, -0.5, -0.5], [0.0, 0.5, 0.5]),
888 ];
889 assert_eq!(
890 visible_instances(&frustum(), &instances, &[unit_cube()], 0),
891 vec![1, 2]
892 );
893 }
894
895 /// An instance hidden from a view is rejected by that view's cull and by no
896 /// other: not by a second view's, and not by a cull that is no view's.
897 #[test]
898 fn a_hidden_instance_is_rejected_by_its_own_view_alone() {
899 let first = 1 << GpuInstance::HIDDEN_VIEWS_SHIFT;
900 let second = 1 << (GpuInstance::HIDDEN_VIEWS_SHIFT + 1);
901 let shown = at(Vec3::ZERO);
902 let hidden = GpuInstance {
903 flags: shown.flags | first,
904 ..shown
905 };
906 let instances = [shown, hidden];
907 let meshes = [unit_cube()];
908 assert_eq!(
909 visible_instances(&frustum(), &instances, &meshes, first),
910 vec![0],
911 "the first view skips the instance hidden from it"
912 );
913 assert_eq!(
914 visible_instances(&frustum(), &instances, &meshes, second),
915 vec![0, 1],
916 "the second view still draws both"
917 );
918 assert_eq!(
919 visible_instances(&frustum(), &instances, &meshes, 0),
920 vec![0, 1],
921 "and a cull that is no view's rejects nothing on the mask"
922 );
923 }
924
925 /// The list is the instances the frustum keeps, in ascending order, and it
926 /// changes when the camera does — which is the assertion a cull test that
927 /// never rejects anything would be missing.
928 #[test]
929 fn the_visible_set_follows_the_camera() {
930 let meshes = [unit_cube()];
931 let instances = [at(Vec3::ZERO), at(Vec3::new(6.0, 0.0, 0.0))];
932
933 let ahead = Frustum::from_view_projection(Camera::default().view_projection(1.0));
934 assert_eq!(visible_instances(&ahead, &instances, &meshes, 0), vec![0]);
935
936 // The same scene from a camera looking at the *other* cube: now it is
937 // the one that survives and the origin is behind the eye.
938 let turned = Camera {
939 eye: Vec3::new(6.0, 0.0, 2.0),
940 target: Vec3::new(6.0, 0.0, 0.0),
941 ..Camera::default()
942 };
943 assert_eq!(
944 visible_instances(
945 &Frustum::from_view_projection(turned.view_projection(1.0)),
946 &instances,
947 &meshes,
948 0
949 ),
950 vec![1]
951 );
952 }
953
954 // -----------------------------------------------------------------------
955 // §3.5's per-cluster cull
956 // -----------------------------------------------------------------------
957
958 /// A cluster ten units down `-Z` — straight ahead of [`frustum`]'s camera,
959 /// which sits at `+Z` looking at the origin — with the cone `axis` and
960 /// half-angle cosine `cutoff` the case wants.
961 ///
962 /// Ten units away and not one, so the sphere is small against the distance
963 /// and every answer below is the *cone*'s rather than the frustum's.
964 fn ahead(axis: Vec3, cutoff: f32, radius: f32) -> ClusterBounds {
965 ClusterBounds {
966 center: [0.0, 0.0, -10.0],
967 radius,
968 cone_axis: axis.normalize().to_array(),
969 cone_cutoff: cutoff,
970 }
971 }
972
973 /// glTF's default material mode: single-sided, so the cone test runs. What
974 /// every case below is about unless it says otherwise.
975 const SINGLE_SIDED: u32 = 0;
976
977 /// The cull as [`ahead`]'s clusters see it, for an instance in
978 /// `material_mode`: identity transform, and the camera [`frustum`] was built
979 /// from.
980 fn survives_as(material_mode: u32, bounds: &ClusterBounds) -> bool {
981 cluster_survives_cull(
982 &frustum(),
983 Camera::default().eye,
984 Mat4::IDENTITY,
985 material_mode,
986 bounds,
987 )
988 }
989
990 /// [`survives_as`] for the single-sided instance most of these cases place.
991 fn survives(bounds: &ClusterBounds) -> bool {
992 survives_as(SINGLE_SIDED, bounds)
993 }
994
995 /// A flat cluster whose normals point at the camera is drawn, and the same
996 /// cluster turned around is not.
997 ///
998 /// The two answers are stated before the arithmetic: the camera is at `+Z`,
999 /// so a `+Z` axis faces it and a `-Z` axis faces away, and a cluster of one
1000 /// flat face has `cone_cutoff == 1.0` and therefore no half-angle to soften
1001 /// either answer.
1002 #[test]
1003 fn a_cluster_is_kept_facing_the_camera_and_rejected_facing_away() {
1004 assert!(
1005 survives(&ahead(Vec3::Z, 1.0, 0.5)),
1006 "a face turned towards the camera is what the cull must never reject"
1007 );
1008 assert!(
1009 !survives(&ahead(Vec3::NEG_Z, 1.0, 0.5)),
1010 "a face turned away is the whole point of the cone test"
1011 );
1012 }
1013
1014 /// **A cluster facing away is kept when its instance is double-sided and
1015 /// rejected when it is not**, which is the whole of what [`cone_may_reject`]
1016 /// changes.
1017 ///
1018 /// Both directions, because either on its own passes for a wrong reason: a
1019 /// predicate stuck at `false` drops the cone test for every material in the
1020 /// tree, and one stuck at `true` is the code as it stood before
1021 /// double-sided materials existed.
1022 ///
1023 /// The bit is read and not the whole mode, so an alpha-masked single-sided
1024 /// row is still single-sided and a row carrying both modes is still
1025 /// double-sided.
1026 ///
1027 /// The last case is the one the predicate must **not** reach. A
1028 /// double-sided instance off the side of the screen is still rejected — by
1029 /// the frustum, which is about where the geometry is rather than which way
1030 /// it faces — so what this buys is a cluster kept in front of the camera and
1031 /// no work anywhere else.
1032 #[test]
1033 fn a_double_sided_instance_keeps_the_cluster_that_faces_away() {
1034 let away = ahead(Vec3::NEG_Z, 1.0, 0.5);
1035 assert!(
1036 !survives_as(SINGLE_SIDED, &away),
1037 "a single-sided face turned away puts nothing on the screen, so the cone is \
1038 right to reject it"
1039 );
1040 assert!(
1041 survives_as(GpuMaterial::DOUBLE_SIDED, &away),
1042 "glTF 2.0 §3.9.6 draws the back face, so the cluster carrying it has to reach \
1043 the mesh stage"
1044 );
1045 assert!(
1046 !survives_as(GpuMaterial::ALPHA_MODE_MASK, &away),
1047 "the alpha-mask bit says nothing about which sides are drawn"
1048 );
1049 assert!(
1050 survives_as(GpuMaterial::MODE_MASK, &away),
1051 "a cutout material may also be double-sided, and then it is double-sided"
1052 );
1053
1054 let frustum = frustum();
1055 let camera = Camera::default().eye;
1056 assert_eq!(
1057 cluster_cull_verdict(
1058 &frustum,
1059 camera,
1060 Mat4::IDENTITY,
1061 GpuMaterial::DOUBLE_SIDED,
1062 &away
1063 ),
1064 ClusterVerdict::Kept,
1065 "a double-sided instance never answers RejectedByCone"
1066 );
1067 assert_eq!(
1068 cluster_cull_verdict(
1069 &frustum,
1070 camera,
1071 Mat4::from_translation(Vec3::new(40.0, 0.0, 0.0)),
1072 GpuMaterial::DOUBLE_SIDED,
1073 &away
1074 ),
1075 ClusterVerdict::RejectedByFrustum,
1076 "the frustum half is not the material's business and still culls"
1077 );
1078 }
1079
1080 /// **A cluster at [`ClusterBounds::OMNIDIRECTIONAL_CUTOFF`] is never
1081 /// rejected by the cone**, whatever its axis and whichever way it points.
1082 ///
1083 /// That value is what a closed shape's cancelled normals produce — the cube
1084 /// and the pyramid both carry it — so a cull that honoured the axis anyway
1085 /// would drop whole meshes. `OMNIDIRECTIONAL_AXIS` is a unit vector rather
1086 /// than a zero one precisely so that the arithmetic here still runs, which
1087 /// is why the axis being *meaningless* has to be caught by the cutoff test
1088 /// and by nothing else.
1089 #[test]
1090 fn an_omnidirectional_cluster_is_never_cone_culled() {
1091 for axis in [Vec3::Z, Vec3::NEG_Z, Vec3::X, Vec3::new(1.0, 2.0, -3.0)] {
1092 assert!(
1093 survives(&ahead(axis, ClusterBounds::OMNIDIRECTIONAL_CUTOFF, 0.5)),
1094 "a cone spanning every direction holds a front-facing normal for \
1095 every view, and {axis} is one of them"
1096 );
1097 }
1098 // And a cone spanning exactly a hemisphere is the boundary of that, so
1099 // it is rejected by nothing either.
1100 assert!(survives(&ahead(Vec3::NEG_Z, 0.0, 0.5)));
1101 }
1102
1103 /// **The radius term, which is the correction this rule needed.**
1104 ///
1105 /// Every number here is chosen so the answer can be stated before the code
1106 /// runs. The camera is at the origin's `+Z` side and the cluster's centre is
1107 /// ten units away, so `length(d)` is a little over ten; `cone_cutoff` is
1108 /// `0.6`, so `sqrt(1 - cutoff²)` is `0.8` and the radius-free rule rejects
1109 /// as soon as `dot(axis, d)` exceeds `8`. The axis is tilted to put that dot
1110 /// product at about `8.5` — past the radius-free threshold — and the radius
1111 /// is `2.0`, well past the `0.5` the correction needs to keep it.
1112 ///
1113 /// It **must** be kept: at a half-angle of `acos(0.6)` and a centre-to-axis
1114 /// angle of `acos(0.85)` the cone's leading edge is still about five degrees
1115 /// off the perpendicular, so the cluster's near side carries triangles that
1116 /// face the camera. The radius-free form draws a hole there.
1117 #[test]
1118 fn a_cluster_the_point_form_would_reject_survives_the_conservative_one() {
1119 // dot(axis, center) = -10 * axis.z, so axis.z = -0.85 puts
1120 // dot(axis, d) at 8.5 once the camera's own +Z offset is folded in.
1121 let axis = Vec3::new(0.526_782_7, 0.0, -0.85);
1122 let cutoff = 0.6f32;
1123 let bounds = ahead(axis, cutoff, 2.0);
1124
1125 // The radius-free rule, spelled out here rather than referenced, so
1126 // this test states what it is contrasting against.
1127 let camera = Camera::default().eye;
1128 let to_center = Vec3::from_array(bounds.center) - camera;
1129 let sine = (1.0 - cutoff * cutoff).sqrt();
1130 let projected = Vec3::from_array(bounds.cone_axis).dot(to_center);
1131 assert!(
1132 projected > sine * to_center.length(),
1133 "the point-form rule must reject this cluster, or the contrast below \
1134 is vacuous: {projected} against {}",
1135 sine * to_center.length()
1136 );
1137
1138 assert!(
1139 survives(&bounds),
1140 "the conservative rule must keep it — the radius term is the whole \
1141 difference, and without it this cluster's front-facing triangles are \
1142 a hole in the picture"
1143 );
1144
1145 // And the term is not simply "keep everything": the same cone at a
1146 // radius small enough to matter is rejected, which is what says the
1147 // radius is doing the work rather than the cutoff.
1148 assert!(!survives(&ahead(axis, cutoff, 0.1)));
1149 }
1150
1151 /// The frustum half, against the sphere rather than a box.
1152 ///
1153 /// Behind the eye and far off to the side are the two rejections a
1154 /// per-cluster frustum test has to make; the same sphere in front of the
1155 /// camera is the anti-vacuity half.
1156 #[test]
1157 fn a_cluster_outside_the_frustum_is_rejected_whichever_way_it_faces() {
1158 let frustum = frustum();
1159 let camera = Camera::default().eye;
1160 // Facing the camera throughout, so nothing below can pass by the cone.
1161 let at = |center: [f32; 3]| ClusterBounds {
1162 center,
1163 radius: 0.5,
1164 cone_axis: Vec3::Z.to_array(),
1165 cone_cutoff: 1.0,
1166 };
1167 let survives = |bounds: &ClusterBounds| {
1168 cluster_survives_cull(&frustum, camera, Mat4::IDENTITY, SINGLE_SIDED, bounds)
1169 };
1170 assert!(survives(&at([0.0, 0.0, -10.0])), "straight ahead");
1171 assert!(
1172 !survives(&at([0.0, 0.0, 20.0])),
1173 "twenty units behind the eye is past the near plane"
1174 );
1175 assert!(
1176 !survives(&at([40.0, 0.0, -10.0])),
1177 "forty units to the right of a 45° frustum ten units deep is outside it"
1178 );
1179 }
1180
1181 /// **Which test rejected the cluster, not merely that something did.**
1182 ///
1183 /// The counters the amplification stage keeps are one per cause, so an
1184 /// oracle that could only say "rejected" would agree with a shader that had
1185 /// the two buckets swapped. Each case here is one the pair of tests above
1186 /// already builds, asked for its cause instead of for a bool.
1187 ///
1188 /// The last case is the one neither of those covers and the one the ordering
1189 /// decides: a cluster that is **both** outside the frustum and facing away
1190 /// belongs to the frustum, because that test is asked first and the shader
1191 /// returns at the first refusal.
1192 #[test]
1193 fn the_verdict_names_the_test_that_rejected_the_cluster() {
1194 let frustum = frustum();
1195 let camera = Camera::default().eye;
1196 // Facing the camera, so the cone has no opinion about it at all.
1197 let facing = |center: [f32; 3]| ClusterBounds {
1198 center,
1199 radius: 0.5,
1200 cone_axis: Vec3::Z.to_array(),
1201 cone_cutoff: 1.0,
1202 };
1203 // The same sphere at the mesh's origin, facing -Z — away from a +Z
1204 // camera. `the_instance_transform_moves_the_sphere_and_turns_the_cone`
1205 // builds this one and asserts it is rejected; this says by what.
1206 let away = ClusterBounds {
1207 center: [0.0, 0.0, 0.0],
1208 radius: 0.5,
1209 cone_axis: [0.0, 0.0, -1.0],
1210 cone_cutoff: 1.0,
1211 };
1212 let ahead = Mat4::from_translation(Vec3::new(0.0, 0.0, -10.0));
1213 let aside = Mat4::from_translation(Vec3::new(40.0, 0.0, -10.0));
1214
1215 for (case, transform, bounds, expected) in [
1216 (
1217 "straight ahead and facing the camera",
1218 Mat4::IDENTITY,
1219 facing([0.0, 0.0, -10.0]),
1220 ClusterVerdict::Kept,
1221 ),
1222 (
1223 "twenty units behind the eye, facing the camera",
1224 Mat4::IDENTITY,
1225 facing([0.0, 0.0, 20.0]),
1226 ClusterVerdict::RejectedByFrustum,
1227 ),
1228 (
1229 "inside the frustum, facing away",
1230 ahead,
1231 away,
1232 ClusterVerdict::RejectedByCone,
1233 ),
1234 (
1235 "outside the frustum and facing away — the frustum is asked first",
1236 aside,
1237 away,
1238 ClusterVerdict::RejectedByFrustum,
1239 ),
1240 ] {
1241 let verdict = cluster_cull_verdict(&frustum, camera, transform, SINGLE_SIDED, &bounds);
1242 assert_eq!(verdict, expected, "{case}");
1243 // And the bool every existing caller reads is this answer and not a
1244 // second rule beside it.
1245 assert_eq!(
1246 cluster_survives_cull(&frustum, camera, transform, SINGLE_SIDED, &bounds),
1247 verdict == ClusterVerdict::Kept,
1248 "{case}: the bool and the verdict disagree",
1249 );
1250 }
1251 }
1252
1253 /// The cull is in **world space**, so the instance transform is what puts a
1254 /// cluster there — and a rotation turns a cone round with it.
1255 ///
1256 /// Without the transform on the axis, a mesh authored facing `-Z` would be
1257 /// rejected however its instance is turned, which is a whole object missing
1258 /// from the frame for as long as it faces the camera.
1259 #[test]
1260 fn the_instance_transform_moves_the_sphere_and_turns_the_cone() {
1261 let frustum = frustum();
1262 let camera = Camera::default().eye;
1263 // In the mesh's own space this cluster sits at the origin facing -Z,
1264 // which from a +Z camera is away.
1265 let bounds = ClusterBounds {
1266 center: [0.0, 0.0, 0.0],
1267 radius: 0.5,
1268 cone_axis: [0.0, 0.0, -1.0],
1269 cone_cutoff: 1.0,
1270 };
1271 let back = Mat4::from_translation(Vec3::new(0.0, 0.0, -10.0));
1272 assert!(
1273 !cluster_survives_cull(&frustum, camera, back, SINGLE_SIDED, &bounds),
1274 "translation alone leaves it facing away"
1275 );
1276
1277 // Turned half a turn about Y, the same cluster faces the camera.
1278 let turned = back * Mat4::from_rotation_y(core::f32::consts::PI);
1279 assert!(
1280 cluster_survives_cull(&frustum, camera, turned, SINGLE_SIDED, &bounds),
1281 "the cone axis must be transformed with the instance"
1282 );
1283
1284 // And moved out of the frustum it is rejected wherever it points, which
1285 // is the half the translation is responsible for.
1286 let aside = Mat4::from_translation(Vec3::new(40.0, 0.0, -10.0))
1287 * Mat4::from_rotation_y(core::f32::consts::PI);
1288 assert!(!cluster_survives_cull(
1289 &frustum,
1290 camera,
1291 aside,
1292 SINGLE_SIDED,
1293 &bounds
1294 ));
1295 }
1296
1297 /// **Which of the open box's five clusters survive from each of the three
1298 /// cameras `crcbl-vk`'s cluster-count end-to-end renders from**, worked out
1299 /// here where the answer is arithmetic rather than a number read out of a
1300 /// buffer.
1301 ///
1302 /// The GPU can only report a *total*, so a count on its own says nothing
1303 /// about which clusters went. This says which, on the same geometry, the
1304 /// same instance transform and the same aspect ratio — so the numbers that
1305 /// test asserts have a statement behind them and a change to either side
1306 /// shows up without a GPU.
1307 ///
1308 /// The three cases are the three the slice owes:
1309 ///
1310 /// * **Nothing rejected.** The box's faces point *inward*, so a camera
1311 /// above it and between its walls sees every one of them front-on. This
1312 /// is what an over-eager cone test fails, and the case a picture cannot
1313 /// show — a cluster wrongly rejected here draws nothing, and the wall it
1314 /// would have drawn is behind the camera's own viewpoint anyway.
1315 /// * **The cone rejects two.** From the golden's camera, out beyond `+X`
1316 /// and `+Z`, the two walls carrying those inward normals are seen from
1317 /// behind.
1318 /// * **The frustum rejects two.** From inside the box looking level at the
1319 /// `-Z` wall, the floor's bounding sphere is entirely below the bottom
1320 /// plane and the `+Z` wall's is entirely behind the eye — and every
1321 /// cluster still faces the camera, so nothing here is the cone's doing.
1322 #[test]
1323 fn the_open_box_loses_the_clusters_each_of_the_three_test_cameras_hides() {
1324 let clusters = crcbl_shaders::meshlet::open_box_clusters();
1325 assert_eq!(
1326 clusters.clusters.len(),
1327 crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
1328 "one cluster per face is what makes the counts below mean anything"
1329 );
1330 // Where `crcbl-vk`'s mesh suite puts the box, and the aspect its 256×192
1331 // frame has. Both matter: the frustum answers below are this shape's.
1332 let at = Vec3::new(-2.0, 0.0, 0.0);
1333 let transform = Mat4::from_translation(at);
1334 let aspect = 256.0 / 192.0;
1335
1336 let kept = |eye: Vec3, target: Vec3| -> Vec<&'static str> {
1337 let look = Camera {
1338 eye,
1339 target,
1340 ..Camera::default()
1341 };
1342 let frustum = Frustum::from_view_projection(look.view_projection(aspect));
1343 clusters
1344 .clusters
1345 .iter()
1346 .zip(crcbl_shaders::mesh::OPEN_BOX_FACES)
1347 .filter(|(cluster, _)| {
1348 cluster_survives_cull(&frustum, eye, transform, SINGLE_SIDED, &cluster.bounds)
1349 })
1350 .map(|(_, face)| face.name)
1351 .collect()
1352 };
1353
1354 assert_eq!(
1355 kept(at + Vec3::new(0.2, 3.2, 0.3), at).len(),
1356 crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
1357 "from above and between the walls every face is front-facing, so a \
1358 correct cull rejects none of them"
1359 );
1360 assert_eq!(
1361 kept(Vec3::new(1.6, 1.2, 2.2) * 1.7, Vec3::ZERO),
1362 vec!["floor", "-X wall", "-Z wall"],
1363 "the two walls whose inward normals point away from the golden's \
1364 camera are the ones the cone must reject, and no others"
1365 );
1366 assert_eq!(
1367 kept(
1368 at + Vec3::new(0.0, 0.4, -0.3),
1369 at + Vec3::new(0.0, 0.4, -1.0)
1370 ),
1371 vec!["-X wall", "+X wall", "-Z wall"],
1372 "from inside, looking level, the floor is under the frame and the +Z \
1373 wall is behind the eye"
1374 );
1375 }
1376
1377 /// **The radius term, on the real mesh and from the camera the end-to-end
1378 /// renders it from.**
1379 ///
1380 /// [`a_cluster_the_point_form_would_reject_survives_the_conservative_one`]
1381 /// is the correctness case — a partial cone whose near side genuinely faces
1382 /// the camera — and it is a constructed one, because **no mesh this engine
1383 /// ships has a `cone_cutoff` strictly between zero and one**: a flat face
1384 /// gets `1.0` and a closed shape gets
1385 /// [`ClusterBounds::OMNIDIRECTIONAL_CUTOFF`]. At a cutoff of exactly `1.0`
1386 /// the two forms differ only where the camera is already past the face's own
1387 /// plane, so what the term buys on *this* geometry is slack rather than a
1388 /// pixel.
1389 ///
1390 /// It is still worth pinning, and this is why: this is the only place the
1391 /// radius term reaches a number the GPU produces, so without it a shader
1392 /// that dropped `+ radius` would pass every count in `crcbl-vk`'s suite. The
1393 /// camera is above the box and just outside two of its walls, so those two
1394 /// are the pair the forms disagree about — five kept against three.
1395 #[test]
1396 fn the_radius_term_keeps_two_clusters_the_point_form_drops() {
1397 let clusters = crcbl_shaders::meshlet::open_box_clusters();
1398 let at = Vec3::new(-2.0, 0.0, 0.0);
1399 let transform = Mat4::from_translation(at);
1400 let eye = at + Vec3::new(0.8, 3.0, 0.8);
1401 let look = Camera {
1402 eye,
1403 target: at,
1404 ..Camera::default()
1405 };
1406 let frustum = Frustum::from_view_projection(look.view_projection(256.0 / 192.0));
1407
1408 // The rule as documented, which is what `cluster_survives_cull` runs.
1409 let conservative = clusters
1410 .clusters
1411 .iter()
1412 .filter(|cluster| {
1413 cluster_survives_cull(&frustum, eye, transform, SINGLE_SIDED, &cluster.bounds)
1414 })
1415 .count();
1416 assert_eq!(
1417 conservative,
1418 crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
1419 "the documented rule keeps every cluster from here"
1420 );
1421
1422 // And the radius-free form, written out so this states what it is
1423 // contrasting against rather than referring to it.
1424 let point_form = clusters
1425 .clusters
1426 .iter()
1427 .filter(|cluster| {
1428 let bounds = &cluster.bounds;
1429 let center = transform.transform_point3(Vec3::from_array(bounds.center));
1430 if !frustum.intersects_sphere(center, bounds.radius) {
1431 return false;
1432 }
1433 let axis = Mat3::from_mat4(transform) * Vec3::from_array(bounds.cone_axis);
1434 let to_center = center - eye;
1435 let sine = (1.0 - bounds.cone_cutoff * bounds.cone_cutoff)
1436 .max(0.0)
1437 .sqrt();
1438 !(bounds.cone_cutoff > 0.0 && axis.dot(to_center) > sine * to_center.length())
1439 })
1440 .count();
1441 assert_eq!(
1442 point_form, 3,
1443 "the radius-free form drops the two walls whose planes this camera has \
1444 crossed, which is the difference the term exists to make"
1445 );
1446 }
1447
1448 // -----------------------------------------------------------------------
1449 // A cluster's sphere under a scaled instance
1450 // -----------------------------------------------------------------------
1451
1452 /// `crcbl::screenshot`'s trough: the open box scaled into a long narrow room
1453 /// and lifted so its floor is the plane `y = 0`.
1454 ///
1455 /// The engine's own non-rigid instance, copied here rather than referred to
1456 /// because `crcbl-render` cannot depend on `crcbl` — and the numbers are what
1457 /// the two tests below are about, so a trough of some other size would not be
1458 /// evidence about the scene that found this.
1459 fn trough(offset: Vec3) -> Mat4 {
1460 Mat4::from_translation(Vec3::new(0.0, 1.0, 0.0) + offset)
1461 * Mat4::from_scale(Vec3::new(6.0, 2.0, 1.6))
1462 }
1463
1464 /// The camera that scene is drawn with: straight down into the trough from
1465 /// just above its walls, `+Z` up because the view direction is `Y`.
1466 fn trough_camera() -> Camera {
1467 Camera {
1468 eye: Vec3::new(0.0, 2.2, 0.0),
1469 target: Vec3::ZERO,
1470 up: Vec3::Z,
1471 projection: Projection::Perspective {
1472 fov_y: core::f32::consts::FRAC_PI_3,
1473 near: 0.01,
1474 },
1475 }
1476 }
1477
1478 /// **A non-uniformly scaled instance does not lose clusters that face the
1479 /// camera**, which is what the cone test did to them.
1480 ///
1481 /// The cone axis is an averaged *normal*, and the rule carries it across
1482 /// with the bare 3×3 — the transform a tangent takes. Under a rotation with
1483 /// a non-uniform scale the two are a long way apart: the case below has them
1484 /// 56° apart, which is enough to put the camera in front of the surface and
1485 /// behind the axis the test reads. Silent, and geometry rather than shading:
1486 /// the cluster is never drawn.
1487 ///
1488 /// The three assertions are one each: the cluster really does face the
1489 /// camera, the old rule really would have rejected it — without which the
1490 /// third asserts nothing — and it survives now.
1491 ///
1492 /// [`preserves_angles`] is what makes the difference, so the second half of
1493 /// this test is the other side of that gate: the *same* geometry under a
1494 /// uniform scale, genuinely facing away, is still rejected by the cone. A
1495 /// fix that simply stopped culling would pass the first half and fail here.
1496 #[test]
1497 fn a_scaled_instance_keeps_a_cluster_whose_surface_faces_the_camera() {
1498 let turn = glam::Quat::from_axis_angle(Vec3::new(0.3, 0.8, 0.5).normalize(), 0.7);
1499 let cone_axis = Vec3::new(0.9, 0.8, 0.9).normalize();
1500 let bounds = ClusterBounds {
1501 center: [0.0, 0.0, 0.0],
1502 radius: 0.5,
1503 cone_axis: cone_axis.to_array(),
1504 cone_cutoff: 20.0f32.to_radians().cos(),
1505 };
1506
1507 // Both cases are rejected by the old rule; only one of them deserves
1508 // it. `view_degrees` is the angle between the surface's true facing
1509 // direction and the direction the camera looks along.
1510 for (case, scale, view_degrees, faces_camera, kept) in [
1511 (
1512 "a non-uniform scale",
1513 Vec3::new(6.0, 2.0, 1.6),
1514 100.0f32,
1515 true,
1516 true,
1517 ),
1518 (
1519 "the same shape uniformly scaled",
1520 Vec3::splat(6.0),
1521 0.0f32,
1522 false,
1523 false,
1524 ),
1525 ] {
1526 let transform = Mat4::from_quat(turn) * Mat4::from_scale(scale);
1527 let basis = Mat3::from_mat4(transform);
1528 // Where the surface actually faces: a normal goes through the
1529 // cofactor matrix, which is what `mesh.slang` shades with.
1530 let cofactor = basis.inverse().transpose() * basis.determinant();
1531 let facing = (cofactor * cone_axis).normalize();
1532 let read = (basis * cone_axis).normalize();
1533 assert_eq!(
1534 facing.dot(read) < 0.9,
1535 faces_camera,
1536 "{case}: the two axes differ exactly where the scale is non-uniform",
1537 );
1538
1539 // The direction the camera looks along, tilted off the surface's
1540 // true facing direction towards the one the old rule reads. Past 90°
1541 // every normal in the cone is on the camera's side; at 0° none is.
1542 let sideways = (read - facing * facing.dot(read)).normalize_or_zero();
1543 let view = facing * view_degrees.to_radians().cos()
1544 + sideways * view_degrees.to_radians().sin();
1545 let eye = Vec3::from_array(bounds.center) - view * 100.0;
1546 let camera = Camera {
1547 eye,
1548 target: Vec3::from_array(bounds.center),
1549 up: Vec3::Y,
1550 projection: Projection::Perspective {
1551 fov_y: core::f32::consts::FRAC_PI_3,
1552 near: 0.01,
1553 },
1554 };
1555 let frustum = Frustum::from_view_projection(camera.view_projection(1.0));
1556 let to_center = Vec3::from_array(bounds.center) - eye;
1557
1558 assert_eq!(
1559 facing.dot(to_center) < 0.0,
1560 faces_camera,
1561 "{case}: which side of the surface the camera is on",
1562 );
1563 let sine = (1.0 - bounds.cone_cutoff * bounds.cone_cutoff).sqrt();
1564 let rejected_by_the_old_rule = read.dot(to_center)
1565 > sine.mul_add(to_center.length(), bounds.radius * max_stretch(basis));
1566 assert!(
1567 rejected_by_the_old_rule,
1568 "{case}: the old rule rejected both of these, which is the point",
1569 );
1570
1571 assert_eq!(
1572 cluster_cull_verdict(&frustum, eye, transform, SINGLE_SIDED, &bounds)
1573 == ClusterVerdict::Kept,
1574 kept,
1575 "{case}: a cluster facing the camera must survive, and one facing away \
1576 under a transform the cone can be trusted through must not",
1577 );
1578 }
1579 }
1580
1581 /// **A cluster's bounding sphere has to bound the cluster after the instance
1582 /// transform, and a scaled instance is where that stops being free.**
1583 ///
1584 /// [`ClusterBounds::radius`] is a distance in the *mesh's* own space. The
1585 /// cull needs one in world space, and the two are the same number only for a
1586 /// transform that preserves length. This walks the open box's real vertices
1587 /// through the trough's transform and measures how far each cluster's
1588 /// furthest one actually gets from its transformed centre.
1589 ///
1590 /// Both halves are asserted, and the second is what makes the first mean
1591 /// something:
1592 ///
1593 /// * the scaled radius **contains** every vertex, which is the property a
1594 /// bounding sphere is; and
1595 /// * the unscaled radius **does not** — by more than a factor of four on the
1596 /// floor — so a test that passed with the scaling removed would be
1597 /// asserting nothing.
1598 ///
1599 /// A wrongly small sphere is not a slightly worse cull. It is a cluster that
1600 /// covers half the frame reported as entirely outside a plane it straddles,
1601 /// which is the frame `docs/backlog.md` recorded as coming back clear.
1602 #[test]
1603 fn a_scaled_instances_cluster_sphere_still_contains_its_geometry() {
1604 let clusters = crcbl_shaders::meshlet::open_box_clusters();
1605 let vertices = crcbl_shaders::mesh::open_box_vertices();
1606 let transform = trough(Vec3::ZERO);
1607 let stretch = max_stretch(Mat3::from_mat4(transform));
1608 assert_eq!(
1609 stretch, 6.0,
1610 "the trough's longest axis is its run, and the bound is exact for an \
1611 axis-aligned scale"
1612 );
1613
1614 let mut escaped_the_local_radius = 0usize;
1615 for cluster in &clusters.clusters {
1616 let bounds = &cluster.bounds;
1617 let center = transform.transform_point3(Vec3::from_array(bounds.center));
1618 let run = cluster.vertex_offset as usize;
1619 let furthest = clusters.vertices[run..run + cluster.vertex_count as usize]
1620 .iter()
1621 .map(|&vertex| {
1622 let position = vertices[vertex as usize].position;
1623 let world = transform.transform_point3(Vec3::new(
1624 position[0],
1625 position[1],
1626 position[2],
1627 ));
1628 (world - center).length()
1629 })
1630 .fold(0.0f32, f32::max);
1631 assert!(
1632 furthest <= bounds.radius * stretch,
1633 "the scaled radius must bound the transformed cluster: {furthest} \
1634 reached against {}",
1635 bounds.radius * stretch
1636 );
1637 if furthest > bounds.radius {
1638 escaped_the_local_radius += 1;
1639 }
1640 }
1641 assert_eq!(
1642 escaped_the_local_radius,
1643 clusters.clusters.len(),
1644 "every cluster of a trough this size outgrows its mesh-space radius, so \
1645 a cull carrying that radius across is testing a sphere that contains \
1646 none of them"
1647 );
1648 }
1649
1650 /// **The trough slid along its own run keeps the floor that is still on
1651 /// screen** — the defect `docs/backlog.md` recorded as "a large open box
1652 /// offset laterally from the camera stops drawing entirely".
1653 ///
1654 /// Three units along `+X`, the trough spans `x = 0..6` and the camera looks
1655 /// straight down at the origin, so the near half of its floor fills a good
1656 /// part of the frame — which this states by projecting the floor cluster's
1657 /// own vertices rather than by asserting it. The cull must therefore keep
1658 /// that cluster, and with a mesh-space radius it does not: `0.71` against the
1659 /// `3.10` the floor actually reaches, which puts its whole sphere outside the
1660 /// left plane.
1661 ///
1662 /// The instance cull one layer up keeps this instance from every offset here
1663 /// — [`visible_instances`] works on the mesh's *box*, which the transform
1664 /// scales correctly — so nothing before the amplification stage notices, and
1665 /// the frame comes back as clear colour with the counters reporting a draw.
1666 #[test]
1667 fn a_scaled_trough_slid_across_the_camera_keeps_the_floor_it_still_shows() {
1668 let clusters = crcbl_shaders::meshlet::open_box_clusters();
1669 let vertices = crcbl_shaders::mesh::open_box_vertices();
1670 let camera = trough_camera();
1671 let view_projection = camera.view_projection(256.0 / 192.0);
1672 let frustum = Frustum::from_view_projection(view_projection);
1673 let floor = &clusters.clusters[0];
1674 assert_eq!(
1675 crcbl_shaders::mesh::OPEN_BOX_FACES[0].name,
1676 "floor",
1677 "cluster zero is the face this test is about"
1678 );
1679
1680 for offset in [2.6f32, 3.0, 4.0] {
1681 let transform = trough(Vec3::X * offset);
1682 // The floor is on screen, and this is the measurement that says so:
1683 // at least one of its vertices lands inside the unit clip box in
1684 // front of the eye.
1685 let run = floor.vertex_offset as usize;
1686 let on_screen = clusters.vertices[run..run + floor.vertex_count as usize]
1687 .iter()
1688 .filter(|&&vertex| {
1689 let position = vertices[vertex as usize].position;
1690 let clip = view_projection
1691 * (transform
1692 * Vec3::new(position[0], position[1], position[2]).extend(1.0));
1693 clip.w > 0.0
1694 && (clip.x / clip.w).abs() <= 1.0
1695 && (clip.y / clip.w).abs() <= 1.0
1696 && clip.z / clip.w >= 0.0
1697 })
1698 .count();
1699 assert!(
1700 on_screen > 0,
1701 "the trough {offset} units along its run must still show floor, or \
1702 there is nothing here for a cull to wrongly reject"
1703 );
1704 assert!(
1705 cluster_survives_cull(&frustum, camera.eye, transform, SINGLE_SIDED, &floor.bounds),
1706 "the floor puts {on_screen} of its vertices in the frame from {offset} \
1707 units out and the cull rejected it — that is the box that stops \
1708 drawing"
1709 );
1710 }
1711
1712 // And the cull still rejects: the same trough far enough out is gone, so
1713 // the assertions above are not satisfied by a rule that keeps everything.
1714 let away = trough(Vec3::X * 40.0);
1715 assert!(
1716 !clusters
1717 .clusters
1718 .iter()
1719 .any(|cluster| cluster_survives_cull(
1720 &frustum,
1721 camera.eye,
1722 away,
1723 SINGLE_SIDED,
1724 &cluster.bounds
1725 )),
1726 "forty units out the whole trough is outside the frustum, radius and all"
1727 );
1728 }
1729}