Skip to main content

crcbl_render/forward/
shadow_inputs.rs

1//! Complete logical input records for shadow-atlas group reuse.
2
3use super::ForwardRenderer;
4use crate::cull::{Aabb, Frustum};
5use crate::shadow;
6use crcbl_shaders::mesh::{self, GpuInstance, GpuMesh};
7use glam::{Mat4, Vec3};
8
9/// How much wider than its own world box an instance's footprint is taken to
10/// be, relative to the box's size and its distance from the origin, and in
11/// world units on top of that.
12///
13/// **Slack in the safe direction.** `cull.slang` tests the same box against the
14/// same planes in `f32`, and a host and a GPU can round one comparison two ways
15/// for a box that grazes a plane. A footprint that said "outside" where the cull
16/// said "inside" would hold a map the caster is in, so the host's box is the
17/// larger one: a caster grazing a light's frustum redraws that light's map when
18/// the cull may not have drawn it, never the other way round.
19const FOOTPRINT_SLACK: f32 = 1.0e-3;
20
21/// Where one element of the instance array can put depth into a shadow map, as
22/// the shadow culls would decide it.
23///
24/// **The cull's own question, asked on the host and answered conservatively.**
25/// `cull.slang` keeps an instance when it is live and its mesh's box, carried by
26/// its transform, reaches inside every plane of the cull's frustum — and only a
27/// kept instance draws. [`crate::cull::visible_instances`] is the same rule, and
28/// this is it with every doubt resolved towards "it could be anywhere".
29#[derive(Clone, Copy, Debug, Default, PartialEq)]
30pub(super) enum CasterFootprint {
31    /// Draws nothing: a slot no instance holds, or one whose
32    /// [`GpuInstance::LIVE`] bit is clear, which the cull asks before anything.
33    #[default]
34    Nowhere,
35    /// Draws only where this world box reaches, slack included.
36    Within(Aabb),
37    /// Could draw into any map: a skinned instance, whose vertices are not its
38    /// mesh's and so are bounded by nothing the host holds, or a record whose
39    /// mesh or transform gives no finite box.
40    Everywhere,
41}
42
43impl CasterFootprint {
44    /// The footprint of `record`, with its mesh looked up in `meshes`.
45    pub(super) fn of(record: &GpuInstance, meshes: &[GpuMesh]) -> Self {
46        if record.flags & GpuInstance::LIVE == 0 {
47            return Self::Nowhere;
48        }
49        // The cull keeps a skinned instance whatever its box says — see
50        // `crate::cull::visible_instances` — because its box is its source
51        // mesh's and its vertices are a compute pass's.
52        if record.flags & GpuInstance::BASE_VERTEX_OVERRIDE != 0 {
53            return Self::Everywhere;
54        }
55        // A mesh id with no entry, or an entry naming no mesh, is one the cull
56        // rejects; it is taken as everywhere all the same, because the cost of
57        // being wrong about an id nothing should name is a redraw.
58        let Some(mesh) = meshes
59            .get(record.mesh as usize)
60            .filter(|mesh| mesh.index_count > 0)
61        else {
62            return Self::Everywhere;
63        };
64        let world = Aabb {
65            min: Vec3::from_array(mesh.bounds_min),
66            max: Vec3::from_array(mesh.bounds_max),
67        }
68        .transformed(Mat4::from_cols_array(&record.transform));
69        let (center, extent) = (world.center(), world.half_extent());
70        let slack =
71            FOOTPRINT_SLACK * (1.0 + center.abs().max_element() + extent.abs().max_element());
72        if !(center.is_finite() && extent.is_finite() && slack.is_finite()) {
73            // A NaN would make every plane test false, which reads as "outside
74            // every frustum" — the one answer a footprint must never give by
75            // accident.
76            return Self::Everywhere;
77        }
78        Self::Within(Aabb {
79            min: world.min - Vec3::splat(slack),
80            max: world.max + Vec3::splat(slack),
81        })
82    }
83
84    /// Whether a cull against `frustum` could keep this instance.
85    pub(super) fn reaches(&self, frustum: &Frustum) -> bool {
86        match self {
87            Self::Nowhere => false,
88            Self::Within(bounds) => frustum.intersects(bounds),
89            Self::Everywhere => true,
90        }
91    }
92}
93
94/// The part of a shadow view's block the depth pass reads, with every other
95/// field zeroed.
96///
97/// **What the atlas is a function of, read off the shaders** rather than off
98/// the block's declaration. The atlas is drawn by `depth_pipeline` and
99/// `depth_masked_pipeline` alone: `mesh.slang`'s `depthVertexMain`, or its
100/// `vertexMain` ahead of `depthMaskedFragmentMain` for a cutout, or
101/// `mesh_cluster.slang`'s amplification and mesh stages on the mesh path, and
102/// `depthClearVertexMain` for a tile reset. Between them they read
103/// `view_proj`, `previous_view_proj`, `camera_position` — the light, for the
104/// normal-cone test — `lod_params`, `vertex_pool` and the debug view switch in
105/// `ambient.w`, and nothing else of `FrameUniforms`. Every other field is the
106/// colour pass's: the cascades' matrices and reaches, the light tiles', the
107/// froxel grid, the probes, the fog and the sky. Several of them are fitted to
108/// the camera, and carried into a light's record they redrew the light's maps
109/// whenever the camera moved.
110///
111/// A shader change that makes the depth pass read another field has to add it
112/// here, or a map drawn from a stale value of it will be held.
113/// [`FRAME_UNIFORMS_READERS`] is the same split as a table, and the two checks
114/// on it are what hold this function to the shaders: this module's tests hold
115/// the function to the table, and `crcbl`'s `mesh_e2e` `shadow_block_reads`
116/// holds the table to the atlas a device draws.
117fn depth_pass_reads(block: &mesh::FrameUniforms) -> mesh::FrameUniforms {
118    mesh::FrameUniforms {
119        view_proj: block.view_proj,
120        camera_position: block.camera_position,
121        ambient: [0.0, 0.0, 0.0, block.ambient[3]],
122        shadow_view_proj: [[0.0; 16]; mesh::SHADOW_CASCADES],
123        cascade_far: [0.0; 4],
124        shadow_params: [0.0; 4],
125        cluster_grid: [0; 4],
126        light_view_proj: [[0.0; 16]; mesh::SHADOW_LIGHT_TILES],
127        probes: crcbl_shaders::probe::ProbeVolume::default(),
128        lod_params: block.lod_params,
129        fog_params: [0.0; 4],
130        fog_color: [0.0; 4],
131        sky_sh_r: [0.0; 4],
132        sky_sh_g: [0.0; 4],
133        sky_sh_b: [0.0; 4],
134        previous_view_proj: block.previous_view_proj,
135        vertex_pool: block.vertex_pool,
136        shadow_atlas_rect: [[0.0; 4]; mesh::SHADOW_ATLAS_TILES],
137        shadow_filter: [0; 4],
138    }
139}
140
141/// Which pass reads a [`UniformsField`] of a shadow view's block.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub enum UniformsReader {
144    /// The atlas's depth pass reads it, so a held map's group record carries it
145    /// — `depth_pass_reads` keeps it.
146    DepthPass,
147    /// Only the colour pass reads it, so a change to it is no reason to redraw a
148    /// map — `depth_pass_reads` zeroes it.
149    ColourOnly,
150}
151
152/// One field of [`mesh::FrameUniforms`], or the lanes of one field that a
153/// single reader owns, as the shadow atlas's depth pass sees it.
154#[derive(Clone, Copy, Debug)]
155pub struct UniformsField {
156    /// The field's name, with the lanes after a dot where the field is split —
157    /// `ambient.xyz` and `ambient.w`.
158    pub name: &'static str,
159    /// Which pass reads it.
160    pub reader: UniformsReader,
161    /// Overwrites this field's lanes of a block with a value no frame writes
162    /// there, and leaves every other lane alone.
163    ///
164    /// A [`UniformsReader::DepthPass`] entry's overwrite is a *nudge* rather
165    /// than garbage — the view's depth pushed by a fraction, a lane toggled — so
166    /// that a device test perturbing it still draws geometry into the atlas to
167    /// compare.
168    pub perturb: fn(&mut mesh::FrameUniforms),
169}
170
171/// A matrix no view is drawn through: every element distinct, none of them a
172/// value a projection or an identity would hold.
173const GARBAGE_MATRIX: [f32; 16] = [
174    -279.375, 242.125, -204.875, 167.625, -130.375, 93.125, -55.875, 18.625, -18.625, 55.875,
175    -93.125, 130.375, -167.625, 204.875, -242.125, 279.375,
176];
177
178/// **Every field of a shadow view's block, and which pass reads it** — the
179/// split `depth_pass_reads` makes, as data a test can walk.
180///
181/// A test hook rather than anything the renderer runs: the renderer's own
182/// split is `depth_pass_reads`, and nothing in a frame reads this. Two tests
183/// do, and between them they close the loop that function's doc leaves to a
184/// reader of the shaders:
185///
186/// * **This module's tests** hold `depth_pass_reads` to the table — every
187///   depth-read entry moves its output, every colour-only one does not — and
188///   hold the table to the struct: every field is classified, a split field in
189///   every lane, and each entry's perturbation touches its own lanes alone.
190///   Adding a field to [`mesh::FrameUniforms`] stops them compiling until it is
191///   entered here.
192/// * **`crcbl`'s `mesh_e2e` `shadow_block_reads`** holds the table to the
193///   shaders: it draws the atlas on every geometry path with each colour-only
194///   entry perturbed in every block the depth pass is fed, through
195///   [`ForwardRenderer::set_shadow_view_tamper`], and asserts the depth it
196///   reads back is unchanged to the bit.
197///
198/// So a shader that starts reading a field listed as colour-only turns that
199/// device test red, and moving the field to the depth-read side here turns
200/// this module's test red until `depth_pass_reads` keeps it.
201pub const FRAME_UNIFORMS_READERS: &[UniformsField] = &[
202    UniformsField {
203        name: "view_proj",
204        reader: UniformsReader::DepthPass,
205        perturb: |block| block.view_proj[14] += 0.0625,
206    },
207    UniformsField {
208        name: "camera_position",
209        reader: UniformsReader::DepthPass,
210        perturb: |block| block.camera_position[0] += 3.0,
211    },
212    UniformsField {
213        name: "ambient.xyz",
214        reader: UniformsReader::ColourOnly,
215        perturb: |block| {
216            block.ambient[0] = -913.25;
217            block.ambient[1] = 4096.5;
218            block.ambient[2] = 0.007_812_5;
219        },
220    },
221    UniformsField {
222        name: "ambient.w",
223        reader: UniformsReader::DepthPass,
224        perturb: |block| block.ambient[3] = 1.0 - block.ambient[3],
225    },
226    UniformsField {
227        name: "shadow_view_proj",
228        reader: UniformsReader::ColourOnly,
229        perturb: |block| block.shadow_view_proj = [GARBAGE_MATRIX; mesh::SHADOW_CASCADES],
230    },
231    UniformsField {
232        name: "cascade_far",
233        reader: UniformsReader::ColourOnly,
234        perturb: |block| block.cascade_far = [-1.5e6, 3.0e-7, 777.0, -0.0],
235    },
236    UniformsField {
237        name: "shadow_params",
238        reader: UniformsReader::ColourOnly,
239        perturb: |block| block.shadow_params = [123.0, -456.0, 7.0e5, -8.0e-5],
240    },
241    UniformsField {
242        name: "cluster_grid",
243        reader: UniformsReader::ColourOnly,
244        perturb: |block| block.cluster_grid = [0xDEAD_BEEF, 0x0BAD_F00D, 0xFEED_FACE, 0x1234_5678],
245    },
246    UniformsField {
247        name: "light_view_proj",
248        reader: UniformsReader::ColourOnly,
249        perturb: |block| block.light_view_proj = [GARBAGE_MATRIX; mesh::SHADOW_LIGHT_TILES],
250    },
251    UniformsField {
252        name: "probes",
253        reader: UniformsReader::ColourOnly,
254        perturb: |block| {
255            block.probes = crcbl_shaders::probe::ProbeVolume {
256                origin: [-321.5, 654.25, -987.0],
257                inv_spacing: [13.0, -0.5, 1.0e4],
258                counts: [0xDEAD, 3, 0xBEEF],
259                levels: 0xFFFF_FFF0,
260                steps: [[-77_777, 31_337, i32::MIN]; crcbl_shaders::probe::PROBE_LEVELS],
261            };
262        },
263    },
264    UniformsField {
265        name: "lod_params",
266        reader: UniformsReader::DepthPass,
267        perturb: |block| block.lod_params[0] += 1.5,
268    },
269    UniformsField {
270        name: "fog_params",
271        reader: UniformsReader::ColourOnly,
272        perturb: |block| block.fog_params = [65_536.0, -2.5, 0.333, -1.0e-9],
273    },
274    UniformsField {
275        name: "fog_color",
276        reader: UniformsReader::ColourOnly,
277        perturb: |block| block.fog_color = [-4.0, 1.0e5, 0.125, -77.0],
278    },
279    UniformsField {
280        name: "sky_sh_r",
281        reader: UniformsReader::ColourOnly,
282        perturb: |block| block.sky_sh_r = [11.5, -22.5, 33.5, -44.5],
283    },
284    UniformsField {
285        name: "sky_sh_g",
286        reader: UniformsReader::ColourOnly,
287        perturb: |block| block.sky_sh_g = [-55.25, 66.25, -77.25, 88.25],
288    },
289    UniformsField {
290        name: "sky_sh_b",
291        reader: UniformsReader::ColourOnly,
292        perturb: |block| block.sky_sh_b = [99.0, -110.0, 121.0, -132.0],
293    },
294    UniformsField {
295        name: "previous_view_proj",
296        reader: UniformsReader::DepthPass,
297        perturb: |block| block.previous_view_proj[14] += 0.0625,
298    },
299    UniformsField {
300        name: "vertex_pool",
301        reader: UniformsReader::DepthPass,
302        perturb: |block| block.vertex_pool[0] ^= 0x40,
303    },
304    UniformsField {
305        name: "shadow_atlas_rect",
306        reader: UniformsReader::ColourOnly,
307        perturb: |block| {
308            block.shadow_atlas_rect = [[-3.5, 9.25, 1000.0, -0.125]; mesh::SHADOW_ATLAS_TILES]
309        },
310    },
311    UniformsField {
312        name: "shadow_filter",
313        reader: UniformsReader::ColourOnly,
314        perturb: |block| block.shadow_filter = [0xFFFF_FFFF, 0xDEAD_BEEF, 77, 0x8000_0000],
315    },
316];
317
318/// Moves `writes[group]` for every group whose cull any of `moved`'s
319/// footprints, before or after its write, could have been kept by.
320///
321/// Against **this frame's** frustum, and that is enough: a group's record
322/// carries its frustum too, so a group whose frustum moved since its maps were
323/// drawn already differs from them whatever this says. A group that culls
324/// nothing this frame — a free light slot, or every group on a frame with
325/// shadows off — is moved by any write, which costs nothing it had not already
326/// lost.
327///
328/// A function of the three rather than a method, because the frame that calls
329/// it is holding a closure over another of the renderer's fields.
330pub(super) fn shadow_groups_reached(
331    writes: &mut [u64],
332    moved: &[(CasterFootprint, CasterFootprint)],
333    culls: &[(usize, Frustum)],
334) {
335    for (group, count) in writes.iter_mut().enumerate() {
336        let frustum = culls
337            .iter()
338            .find(|(owner, _)| *owner == group)
339            .map(|(_, frustum)| frustum);
340        let reached = moved.iter().any(|(before, after)| {
341            frustum.is_none_or(|frustum| before.reaches(frustum) || after.reaches(frustum))
342        });
343        if reached {
344            *count = count.wrapping_add(1);
345        }
346    }
347}
348
349impl ForwardRenderer {
350    /// Takes the instance elements written since the last frame, and leaves in
351    /// [`ForwardRenderer::shadow_moved`] each one's footprint **before and
352    /// after** the write, for [`shadow_groups_reached`] to test against the
353    /// frame's culls once they are fitted.
354    ///
355    /// Before matters as much as after: a caster that walked out of a light's
356    /// cone leaves a shadow in the held map, and a caster removed from the scene
357    /// has a dead record now and a live one then. The before is the footprint
358    /// this kept in [`ForwardRenderer::shadow_footprints`] when it last ran,
359    /// and the after is the one the element's record gives now.
360    ///
361    /// It also keeps [`ForwardRenderer::shadow_dag_elements`] — the live
362    /// elements whose mesh has a DAG, whose cut the selection eye decides —
363    /// current.
364    pub(super) fn note_caster_writes(&mut self) {
365        let mut written = std::mem::take(&mut self.shadow_written);
366        written.clear();
367        self.shadow_moved.clear();
368        self.instances.take_written(&mut written);
369        if !written.is_empty() {
370            let meshes = self.pool.table_entries();
371            for &element in &written {
372                let index = element as usize;
373                if self.shadow_footprints.len() <= index {
374                    self.shadow_footprints
375                        .resize(index + 1, CasterFootprint::Nowhere);
376                }
377                let before = self.shadow_footprints[index];
378                let record = self.instances.record(element);
379                let after = record.map_or(CasterFootprint::Nowhere, |record| {
380                    CasterFootprint::of(&record, &meshes)
381                });
382                self.shadow_footprints[index] = after;
383                self.shadow_moved.push((before, after));
384                let selects_by_eye = record.is_some_and(|record| {
385                    record.flags & GpuInstance::LIVE != 0 && self.mesh_selects_by_eye(record.mesh)
386                });
387                if selects_by_eye {
388                    self.shadow_dag_elements.insert(element);
389                } else {
390                    self.shadow_dag_elements.remove(&element);
391                }
392            }
393        }
394        self.shadow_written = written;
395    }
396
397    /// Whether an instance naming mesh `mesh` has its level chosen from the
398    /// selection eye: a mesh with a DAG, whose groups `draw_gen.slang`'s
399    /// `select_level` projects from the eye. An id past the table is taken as
400    /// one that does.
401    fn mesh_selects_by_eye(&self, mesh: u32) -> bool {
402        self.draw_tables
403            .mesh_levels
404            .get(mesh as usize)
405            .is_none_or(|levels| levels.group_count > 0)
406    }
407
408    /// Everything one group of the shadow atlas is a function of, as bytes to
409    /// compare with the reading the image was last drawn from.
410    ///
411    /// A **group** is a cascade or a light slot's whole run of tiles — what one
412    /// cull covers and what [`crate::shadow::Cadence`] schedules. Per group rather than
413    /// per atlas since the cadence rung: a lamp that swings makes its own group's
414    /// reading differ and leaves every other group's alone, which is what lets
415    /// the frame redraw its tiles and hold the rest.
416    ///
417    /// # What is in it
418    ///
419    /// * **The group's view blocks, as the depth pass reads them, and its cull's
420    ///   frustum** — the values [`begin_frame_body`](Self::begin_frame_body) is
421    ///   about to write, cut down by [`depth_pass_reads`]. They carry the
422    ///   cascade's or the light's matrices, the light's position and this
423    ///   frame's shadow LOD budgets — so a light that moved, turned, changed
424    ///   radius or angle, or gained or lost a tile is a different reading, and so
425    ///   is a camera that moved *for a cascade*, because a cascade is fitted to
426    ///   it. The atlas rectangles are not in the blocks the depth pass reads;
427    ///   where a map lands is the layout, which is compared on its own and
428    ///   redraws everything when it moves.
429    /// * **The instance count**, which reaches the cull beside the frustum and is
430    ///   in no block.
431    /// * **The selection eye, where the group's cull reads it.** `draw_gen.slang`
432    ///   chooses a DAG mesh's level by projecting its groups' error from the eye,
433    ///   so the eye is an input to every group a DAG instance could be kept by:
434    ///   always for a cascade, and for a light slot when any live DAG element's
435    ///   footprint reaches its frustum. A light whose frustum holds flat meshes
436    ///   alone draws the same maps from any eye, and leaving the eye out is what
437    ///   lets it hold them while the camera moves. Not quantised: any move of the
438    ///   eye can move a group across its budget, and a quantum is a range of eyes
439    ///   over which a held map is a cut the cull would not have chosen.
440    /// * **[`ForwardRenderer::shadow_group_writes`]**, which moves for every
441    ///   instance write whose element's footprint, before or after it, reaches
442    ///   this group's frustum — see [`note_caster_writes`](Self::note_caster_writes) and
443    ///   [`shadow_groups_reached`].
444    ///   A transform, a mesh, a material, a removal or a skinned re-point all
445    ///   pass through [`crate::InstancePool::take_written`], and a write whose
446    ///   element could be kept by this group's cull neither before nor after it
447    ///   draws nothing into this group's maps either way.
448    ///
449    /// The bytes are the blocks' own `to_bytes` — the encoding the GPU reads —
450    /// rather than the objects' memory, so no padding and no `f32` bit pattern
451    /// nobody wrote is in the comparison. Two readings that differ by `-0.0`
452    /// against `0.0` compare unequal and redraw, which is the safe direction.
453    ///
454    /// A skinned frame is **not** in here and is not meant to be: a record that
455    /// merely carried "this frame skins" would still match the last skinned
456    /// frame's and cache. [`ForwardRenderer::frame_skins`] is a separate veto on
457    /// the answer for that reason, and it is where that limit is written down.
458    ///
459    /// # What is deliberately not in it
460    ///
461    /// * **The mesh pool.** Its buffers are written by `build_geometry` and
462    ///   `residents` alone, both of which run inside
463    ///   [`with_scene`](Self::with_scene) before a renderer exists — this type
464    ///   exposes no way to upload or free a mesh afterwards. The one runtime
465    ///   caller of the suballocator is
466    ///   [`reserve_skinned`](Self::reserve_skinned), whose bytes are a skinned
467    ///   region's, and those are `frame_skins`' always-redraw case.
468    /// * **Whether the frame has shadows at all**, which is the atlas's *layout*
469    ///   rather than any group's reading: a frame with shadows off gives every
470    ///   group no views and no cull, so none of them reaches this function, and
471    ///   `begin_frame_body`'s empty layout is what makes such a frame clear the
472    ///   image once and cost nothing after.
473    /// * **Materials, samplers and the colour pipeline.** `depth_pipeline`
474    ///   names no fragment stage, so nothing the atlas holds is a function of
475    ///   them.
476    pub(super) fn shadow_group_record(
477        &self,
478        group: usize,
479        views: &[(usize, usize, mesh::FrameUniforms)],
480        culls: &[(usize, Frustum)],
481        eye: [f32; 3],
482        instance_count: u32,
483    ) -> Vec<u8> {
484        let view_count = views.iter().filter(|(owner, _, _)| *owner == group).count();
485        let cull_count = culls.iter().filter(|(owner, _)| *owner == group).count();
486        let reads_eye = group < shadow::CASCADES
487            || culls
488                .iter()
489                .find(|(owner, _)| *owner == group)
490                .is_none_or(|(_, frustum)| {
491                    self.shadow_dag_elements
492                        .iter()
493                        .any(|element| self.shadow_footprints[*element as usize].reaches(frustum))
494                });
495        let capacity = size_of::<u64>()
496            + size_of::<u32>()
497            + size_of::<u8>()
498            + if reads_eye { size_of::<[f32; 3]>() } else { 0 }
499            + view_count * (size_of::<u32>() + mesh::FRAME_UNIFORMS_SIZE)
500            + cull_count * (size_of::<u32>() + crate::cull::PLANE_COUNT * size_of::<[f32; 4]>());
501        let mut record = Vec::with_capacity(capacity);
502        record.extend_from_slice(&self.shadow_group_writes[group].to_le_bytes());
503        record.extend_from_slice(&instance_count.to_le_bytes());
504        record.push(u8::from(reads_eye));
505        if reads_eye {
506            for value in eye {
507                record.extend_from_slice(&value.to_le_bytes());
508            }
509        }
510        for (_, view, block) in views.iter().filter(|(owner, _, _)| *owner == group) {
511            record.extend_from_slice(&(*view as u32).to_le_bytes());
512            record.extend_from_slice(&depth_pass_reads(block).to_bytes());
513        }
514        for (cull, frustum) in culls.iter().filter(|(cull, _)| *cull == group) {
515            record.extend_from_slice(&(*cull as u32).to_le_bytes());
516            for plane in frustum.planes {
517                for value in plane.to_array() {
518                    record.extend_from_slice(&value.to_le_bytes());
519                }
520            }
521        }
522        record
523    }
524}
525
526// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
527#[cfg(all(test, not(target_arch = "wasm32")))]
528mod tests {
529    use super::super::SHADOW_CULLS;
530    use super::*;
531    use crate::scene;
532    use crcbl_hal::null::{NullInstance, Recorder};
533    use crcbl_hal::{AdapterId, DeviceDesc, Format, Instance, QueueKind};
534    use glam::{Vec3, Vec4};
535
536    /// A light group's index: the first light slot, past the cascades.
537    const LIGHT: usize = shadow::CASCADES;
538
539    /// A block whose every field holds something, so a field the record
540    /// dropped and a field it kept are told apart by changing it.
541    fn filled_block(id: usize, owner: usize) -> mesh::FrameUniforms {
542        let matrix = Mat4::from_scale(Vec3::splat(id as f32 + 1.0)).to_cols_array();
543        mesh::FrameUniforms {
544            view_proj: matrix,
545            camera_position: [0.0, 0.0, 2.0, 1.0],
546            ambient: [id as f32, -0.0, owner as f32, 1.0],
547            shadow_view_proj: [Mat4::IDENTITY.to_cols_array(); mesh::SHADOW_CASCADES],
548            cascade_far: [1.0, 2.0, 3.0, 4.0],
549            shadow_params: [0.5, 0.25, 0.0, 0.0],
550            cluster_grid: [1, 2, 3, 0],
551            light_view_proj: [Mat4::IDENTITY.to_cols_array(); mesh::SHADOW_LIGHT_TILES],
552            probes: crcbl_shaders::probe::ProbeVolume::default(),
553            lod_params: [3.0, 4.0, 5.0, 0.0],
554            fog_params: [0.1; 4],
555            fog_color: [0.2; 4],
556            sky_sh_r: [0.3; 4],
557            sky_sh_g: [0.4; 4],
558            sky_sh_b: [0.5; 4],
559            previous_view_proj: matrix,
560            vertex_pool: [11, 12, 13, 14],
561            shadow_atlas_rect: [[0.75; 4]; mesh::SHADOW_ATLAS_TILES],
562            shadow_filter: [1, 2, 3, 4],
563        }
564    }
565
566    #[test]
567    fn group_records_preserve_complete_bytes_and_selected_input_order() {
568        let recorder = Recorder::new();
569        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
570        let device = instance
571            .create_device(&DeviceDesc::for_adapter(AdapterId(0)))
572            .unwrap();
573        let queue = device.queue(QueueKind::Graphics).unwrap();
574        let mut renderer = ForwardRenderer::with_scene(
575            device.as_ref(),
576            queue,
577            Format::Rgba8UnormSrgb,
578            &scene::demo(),
579        )
580        .unwrap();
581        let mut views: Vec<_> = [
582            (LIGHT, 9),
583            (0, 3),
584            (LIGHT, 7),
585            (1, 4),
586            (LIGHT, 1),
587            (LIGHT, 8),
588            (LIGHT, 5),
589            (LIGHT, 6),
590        ]
591        .into_iter()
592        .map(|(owner, id)| (owner, id, filled_block(id, owner)))
593        .collect();
594        let mut culls: Vec<_> = [LIGHT, 0, 1, LIGHT]
595            .into_iter()
596            .map(|owner| {
597                (
598                    owner,
599                    Frustum {
600                        planes: std::array::from_fn(|i| {
601                            Vec4::new(owner as f32, i as f32, -0.0, 1.0)
602                        }),
603                    },
604                )
605            })
606            .collect();
607        let eye = [-0.0, 7.0, -9.0];
608        let count = u32::MAX;
609        renderer.shadow_group_writes = (0..SHADOW_CULLS as u64).map(|n| 40 + n).collect();
610        let expected = |writes: u64,
611                        with_eye: bool,
612                        group: usize,
613                        views: &[(usize, usize, mesh::FrameUniforms)],
614                        culls: &[(usize, Frustum)]| {
615            let mut bytes = Vec::new();
616            bytes.extend(writes.to_le_bytes());
617            bytes.extend(count.to_le_bytes());
618            bytes.push(u8::from(with_eye));
619            if with_eye {
620                bytes.extend(eye.into_iter().flat_map(f32::to_le_bytes));
621            }
622            for (owner, id, block) in views {
623                if *owner == group {
624                    bytes.extend((*id as u32).to_le_bytes());
625                    bytes.extend(depth_pass_reads(block).to_bytes());
626                }
627            }
628            for (owner, frustum) in culls {
629                if *owner == group {
630                    bytes.extend((*owner as u32).to_le_bytes());
631                    bytes.extend(
632                        frustum
633                            .planes
634                            .iter()
635                            .flat_map(|v| v.to_array())
636                            .flat_map(f32::to_le_bytes),
637                    );
638                }
639            }
640            bytes
641        };
642        for group in 0..SHADOW_CULLS {
643            let record = renderer.shadow_group_record(group, &views, &culls, eye, count);
644            // A cascade reads the eye always; a light slot culled against a
645            // frustum no DAG element reaches does not, and one that culls
646            // nothing this frame is taken to.
647            let with_eye = group < shadow::CASCADES || group > LIGHT;
648            assert_eq!(
649                record,
650                expected(40 + group as u64, with_eye, group, &views, &culls),
651                "group {group}"
652            );
653            assert_eq!(record.capacity(), record.len());
654        }
655
656        let original = renderer.shadow_group_record(LIGHT, &views, &culls, eye, count);
657        let cascade = renderer.shadow_group_record(0, &views, &culls, eye, count);
658        // The eye: a cascade's input, and not a flat-only light's.
659        assert_ne!(
660            cascade,
661            renderer.shadow_group_record(0, &views, &culls, [0.0, 7.0, -9.0], count)
662        );
663        assert_eq!(
664            original,
665            renderer.shadow_group_record(LIGHT, &views, &culls, [5.0, 7.0, -9.0], count),
666            "a light whose cull no DAG element reaches drew the same maps from any eye"
667        );
668        assert_ne!(
669            original,
670            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count - 1)
671        );
672
673        // Another group's blocks and culls are not this one's.
674        views[1].2.ambient[3] += 1.0;
675        culls[1].1.planes[0].x += 1.0;
676        assert_eq!(
677            original,
678            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
679        );
680
681        // Every field the depth pass reads is in the record, and none of the
682        // colour pass's is — which is what lets a light hold its maps while the
683        // camera, which several of them follow, moves.
684        for field in FRAME_UNIFORMS_READERS {
685            let saved = views[0].2;
686            (field.perturb)(&mut views[0].2);
687            let record = renderer.shadow_group_record(LIGHT, &views, &culls, eye, count);
688            match field.reader {
689                UniformsReader::DepthPass => assert_ne!(
690                    original, record,
691                    "the depth pass reads `{}` and the record did not change with it",
692                    field.name
693                ),
694                UniformsReader::ColourOnly => assert_eq!(
695                    original, record,
696                    "the depth pass reads nothing of `{}` and the record moved with it",
697                    field.name
698                ),
699            }
700            views[0].2 = saved;
701        }
702        // And every colour-only field at once.
703        let saved = views[0].2;
704        for field in FRAME_UNIFORMS_READERS {
705            if field.reader == UniformsReader::ColourOnly {
706                (field.perturb)(&mut views[0].2);
707            }
708        }
709        assert_eq!(
710            original,
711            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count),
712            "every colour-only field moved at once, and the record moved with them"
713        );
714        views[0].2 = saved;
715
716        views[0].1 += 1;
717        assert_ne!(
718            original,
719            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
720        );
721        views[0].1 -= 1;
722        culls[0].1.planes[0].z = 0.0;
723        assert_ne!(
724            original,
725            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
726        );
727        culls[0].1.planes[0].z = -0.0;
728        views.swap(0, 2);
729        assert_ne!(
730            original,
731            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
732        );
733        views.swap(0, 2);
734
735        // A write this group's cull could see.
736        renderer.shadow_group_writes[LIGHT] += 1;
737        let changed = renderer.shadow_group_record(LIGHT, &views, &culls, eye, count);
738        assert_ne!(original, changed);
739        assert_eq!(&original[size_of::<u64>()..], &changed[size_of::<u64>()..]);
740        renderer.shadow_group_writes[LIGHT] -= 1;
741
742        // A DAG element whose footprint reaches the light's frustum puts the
743        // eye into the light's record; one outside it does not.
744        let frustum = Frustum::from_view_projection(glam::camera::rh::proj::directx::orthographic(
745            -1.0, 1.0, -1.0, 1.0, 0.0, 10.0,
746        ));
747        culls[0].1 = frustum;
748        culls[3].1 = frustum;
749        let light = |renderer: &ForwardRenderer, eye| {
750            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
751        };
752        let far_away = CasterFootprint::Within(Aabb {
753            min: Vec3::splat(100.0),
754            max: Vec3::splat(101.0),
755        });
756        renderer.shadow_footprints = vec![far_away];
757        renderer.shadow_dag_elements.insert(0);
758        assert_eq!(
759            light(&renderer, eye),
760            light(&renderer, [5.0, 7.0, -9.0]),
761            "a DAG element no cull of this light can keep chose no level in its maps"
762        );
763        renderer.shadow_footprints[0] = CasterFootprint::Within(Aabb {
764            min: Vec3::new(-0.5, -0.5, -5.0),
765            max: Vec3::new(0.5, 0.5, -4.0),
766        });
767        assert_ne!(
768            light(&renderer, eye),
769            light(&renderer, [5.0, 7.0, -9.0]),
770            "a DAG element inside the light's frustum has its level chosen from the eye"
771        );
772
773        renderer.destroy(device.as_ref());
774        recorder.assert_valid();
775        assert_eq!(recorder.total_live_objects(), 0);
776    }
777
778    /// Each of a block's fields, or a split field's lanes, by the name
779    /// [`FRAME_UNIFORMS_READERS`] gives it, with its value spelled out.
780    ///
781    /// **Exhaustive on purpose**: the destructure names every field and has no
782    /// `..`, so a field added to [`mesh::FrameUniforms`] stops this compiling
783    /// until it is listed here — and then
784    /// [`every_frame_uniforms_field_is_classified_and_depth_pass_reads_agrees`]
785    /// fails until the table classifies it.
786    fn lanes(block: &mesh::FrameUniforms) -> Vec<(&'static str, String)> {
787        let mesh::FrameUniforms {
788            view_proj,
789            camera_position,
790            ambient,
791            shadow_view_proj,
792            cascade_far,
793            shadow_params,
794            cluster_grid,
795            light_view_proj,
796            probes,
797            lod_params,
798            fog_params,
799            fog_color,
800            sky_sh_r,
801            sky_sh_g,
802            sky_sh_b,
803            previous_view_proj,
804            vertex_pool,
805            shadow_atlas_rect,
806            shadow_filter,
807        } = block;
808        // `Debug` rather than `==`, so a NaN lane equals itself and `-0.0` is
809        // not `0.0`: the question is whether the bits a shader reads moved.
810        vec![
811            ("view_proj", format!("{view_proj:?}")),
812            ("camera_position", format!("{camera_position:?}")),
813            ("ambient.xyz", format!("{:?}", &ambient[..3])),
814            ("ambient.w", format!("{:?}", ambient[3])),
815            ("shadow_view_proj", format!("{shadow_view_proj:?}")),
816            ("cascade_far", format!("{cascade_far:?}")),
817            ("shadow_params", format!("{shadow_params:?}")),
818            ("cluster_grid", format!("{cluster_grid:?}")),
819            ("light_view_proj", format!("{light_view_proj:?}")),
820            ("probes", format!("{probes:?}")),
821            ("lod_params", format!("{lod_params:?}")),
822            ("fog_params", format!("{fog_params:?}")),
823            ("fog_color", format!("{fog_color:?}")),
824            ("sky_sh_r", format!("{sky_sh_r:?}")),
825            ("sky_sh_g", format!("{sky_sh_g:?}")),
826            ("sky_sh_b", format!("{sky_sh_b:?}")),
827            ("previous_view_proj", format!("{previous_view_proj:?}")),
828            ("vertex_pool", format!("{vertex_pool:?}")),
829            ("shadow_atlas_rect", format!("{shadow_atlas_rect:?}")),
830            ("shadow_filter", format!("{shadow_filter:?}")),
831        ]
832    }
833
834    /// **[`FRAME_UNIFORMS_READERS`] classifies every lane of a block exactly
835    /// once, each entry perturbs its own lanes and no others, and
836    /// [`depth_pass_reads`] keeps exactly the depth-read ones.**
837    ///
838    /// The table is what `crcbl`'s `mesh_e2e` `shadow_block_reads` holds to the
839    /// shaders on a device, so this is the half that ties the function the
840    /// record is built from to what that test checked.
841    #[test]
842    fn every_frame_uniforms_field_is_classified_and_depth_pass_reads_agrees() {
843        let block = filled_block(3, LIGHT);
844        let before = lanes(&block);
845        let names: Vec<&str> = before.iter().map(|(name, _)| *name).collect();
846        let mut listed: Vec<&str> = FRAME_UNIFORMS_READERS
847            .iter()
848            .map(|field| field.name)
849            .collect();
850        listed.sort_unstable();
851        let mut expected = names.clone();
852        expected.sort_unstable();
853        assert_eq!(
854            listed, expected,
855            "the table must name every lane group of `FrameUniforms` exactly once"
856        );
857
858        let kept_before = lanes(&depth_pass_reads(&block));
859        for field in FRAME_UNIFORMS_READERS {
860            let mut perturbed = block;
861            (field.perturb)(&mut perturbed);
862            let after = lanes(&perturbed);
863            for ((name, was), (_, is)) in before.iter().zip(&after) {
864                if *name == field.name {
865                    assert_ne!(was, is, "`{name}`'s perturbation left it as it was");
866                } else {
867                    assert_eq!(
868                        was, is,
869                        "`{}`'s perturbation also moved `{name}`, so the device test would \
870                         blame the wrong field",
871                        field.name
872                    );
873                }
874            }
875
876            let kept_after = lanes(&depth_pass_reads(&perturbed));
877            let lane = |of: &[(&str, String)]| {
878                of.iter()
879                    .find(|(name, _)| *name == field.name)
880                    .map(|(_, value)| value.clone())
881                    .expect("every table name is a lane")
882            };
883            match field.reader {
884                UniformsReader::DepthPass => assert_eq!(
885                    lane(&kept_after),
886                    lane(&after),
887                    "`{}` is read by the depth pass and `depth_pass_reads` does not keep it",
888                    field.name
889                ),
890                UniformsReader::ColourOnly => assert_eq!(
891                    kept_before, kept_after,
892                    "`{}` is the colour pass's alone and `depth_pass_reads` keeps it",
893                    field.name
894                ),
895            }
896        }
897    }
898
899    /// A footprint is the cull's own question: dead is nowhere, skinned is
900    /// everywhere, and a live rigid instance is its mesh's box carried by its
901    /// transform, never smaller.
902    #[test]
903    fn a_footprint_is_the_cull_s_box_and_never_smaller() {
904        let cube = GpuMesh {
905            index_count: 36,
906            bounds_min: [-0.5; 3],
907            bounds_max: [0.5; 3],
908            ..GpuMesh::default()
909        };
910        let meshes = [cube, GpuMesh::default()];
911        let at = |x: f32| GpuInstance {
912            transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)).to_cols_array(),
913            flags: GpuInstance::LIVE,
914            ..GpuInstance::default()
915        };
916        let CasterFootprint::Within(bounds) = CasterFootprint::of(&at(10.0), &meshes) else {
917            panic!("a live rigid instance of a real mesh has a box");
918        };
919        assert!(bounds.min.x < 9.5 && bounds.max.x > 10.5);
920        assert!(bounds.max.x < 10.6, "the slack is slack, not a second box");
921
922        let dead = GpuInstance {
923            flags: 0,
924            ..at(0.0)
925        };
926        assert_eq!(
927            CasterFootprint::of(&dead, &meshes),
928            CasterFootprint::Nowhere
929        );
930        let skinned = GpuInstance {
931            flags: GpuInstance::LIVE | GpuInstance::BASE_VERTEX_OVERRIDE,
932            ..at(0.0)
933        };
934        assert_eq!(
935            CasterFootprint::of(&skinned, &meshes),
936            CasterFootprint::Everywhere
937        );
938        for mesh in [1, 7] {
939            let unnamed = GpuInstance { mesh, ..at(0.0) };
940            assert_eq!(
941                CasterFootprint::of(&unnamed, &meshes),
942                CasterFootprint::Everywhere,
943                "mesh {mesh}"
944            );
945        }
946        let nan = GpuInstance {
947            transform: [f32::NAN; 16],
948            ..at(0.0)
949        };
950        assert_eq!(
951            CasterFootprint::of(&nan, &meshes),
952            CasterFootprint::Everywhere,
953            "a box of NaN would read as outside every frustum"
954        );
955    }
956
957    /// **A write reaches a group when its element could be kept by the group's
958    /// cull before the write or after it**, and a group culling nothing this
959    /// frame is reached by any write.
960    #[test]
961    fn a_write_reaches_the_groups_its_old_or_new_box_is_in() {
962        // A box one unit across either side of the origin, looking down -z.
963        let frustum = Frustum::from_view_projection(glam::camera::rh::proj::directx::orthographic(
964            -1.0, 1.0, -1.0, 1.0, 0.0, 10.0,
965        ));
966        let inside = CasterFootprint::Within(Aabb {
967            min: Vec3::new(-0.25, -0.25, -3.0),
968            max: Vec3::new(0.25, 0.25, -2.0),
969        });
970        let outside = CasterFootprint::Within(Aabb {
971            min: Vec3::new(5.0, 5.0, -3.0),
972            max: Vec3::new(6.0, 6.0, -2.0),
973        });
974        assert!(inside.reaches(&frustum) && !outside.reaches(&frustum));
975        let reached = |moved: &[(CasterFootprint, CasterFootprint)]| {
976            let mut writes = [0u64; 2];
977            // Group 0 culls against the box; group 1 culls nothing.
978            shadow_groups_reached(&mut writes, moved, &[(0, frustum)]);
979            writes
980        };
981        assert_eq!(reached(&[]), [0, 0], "no write reaches nothing");
982        assert_eq!(reached(&[(inside, inside)]), [1, 1], "moved inside");
983        assert_eq!(reached(&[(outside, outside)]), [0, 1], "moved outside");
984        assert_eq!(reached(&[(inside, outside)]), [1, 1], "moved out of it");
985        assert_eq!(reached(&[(outside, inside)]), [1, 1], "moved into it");
986        assert_eq!(
987            reached(&[(CasterFootprint::Nowhere, inside)]),
988            [1, 1],
989            "spawned inside"
990        );
991        assert_eq!(
992            reached(&[(inside, CasterFootprint::Nowhere)]),
993            [1, 1],
994            "removed from inside"
995        );
996        assert_eq!(
997            reached(&[
998                (outside, outside),
999                (CasterFootprint::Nowhere, CasterFootprint::Everywhere)
1000            ]),
1001            [1, 1],
1002            "a skinned element reaches every group"
1003        );
1004    }
1005}