Skip to main content

crcbl_render/
forward.rs

1//! The frame milestones 3, 4 and 5 draw: a lit mesh into an HDR target, then a
2//! tonemap into whatever the caller is presenting to.
3//!
4//! ```text
5//! ┌ cull ───────────┐ ┌ draw-args ──────┐ ┌ forward ──────────┐ ┌ tonemap ──────┐
6//! │ instances ─────▶│ │ visible ───────▶│ │ scene-color Clear │ │ reads it      │
7//! │ visible list    │ │ per-bucket runs │ │ scene-depth Clear │ │ writes the    │
8//! │ + a GPU count   │ │ + indirect args │ │ one indirect call │ │ target        │
9//! │                 │ │ + a draw count  │ │ per bucket        │ │               │
10//! └─────────────────┘ └─────────────────┘ └───────────────────┘ └───────────────┘
11//! ```
12//!
13//! Two passes and one graph. Everything that makes them ordered, everything that
14//! transitions `scene-color` from a colour attachment into a sampled texture,
15//! and everything that returns the target to [`ResourceState::Present`] is
16//! computed by [`crate::graph`] — **there is not one hand-written barrier in
17//! this file, or anywhere above the seam.**
18//!
19//! # Scope
20//!
21//! Stage 2's ladder rungs 3–5, and nothing beyond:
22//!
23//! * **3** — depth-tested spinning mesh, perspective camera in a uniform buffer.
24//! * **4** — one directional light (in `mesh.slang`). The rung's own wording is
25//!   "Lambert+Blinn"; what shipped is Lambert plus a Cook-Torrance GGX lobe over
26//!   a glTF metallic-roughness row, which is that rung's "real material model"
27//!   arriving early rather than a different rung.
28//! * **5** — orthographic mode, which is [`Camera::projection`] and *nothing
29//!   else*: no second pipeline, no branch in this file, no shader permutation.
30//!
31//! Explicitly not here: bindless at scale (P3), shadows and real post (P7),
32//! material authoring (topic 37), asset loading (P9). The mesh is a constant in
33//! `crcbl-shaders` because rung 3 says "hardcoded cube/sphere".
34//!
35//! What *is* here since 2026-08 is [`crate::material_table`]: §3.2's material
36//! table, holding **both** halves of "texture indices + factors", with
37//! [`mesh::GpuInstance::material`] selecting a row. Three rows are resident and
38//! two of them exist to be seen: [`scene::DEMO_TINTED`] differs from the default
39//! row in its factor and its roughness, and [`scene::DEMO_TEXTURED`] in its
40//! base-colour page layer alone. Which rows those are is [`crate::scene::demo`]'s
41//! to say, and so is why the shading factor rides on that row rather than on a
42//! fourth.
43//!
44//! The page is the texture side, and it is one `D2Array` image rather than an
45//! array of descriptors — `BindingModel::ArrayPages` rather than `Bindless`.
46//! That is the whole of the binding-model decision §3.2 leaves open, taken
47//! here because a layer index needs nothing of a device where a descriptor
48//! array needs `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws. So
49//! there is one lookup, one layout and one artifact rather than a permutation,
50//! and a device that reports the feature runs the same declaration. What
51//! bindless buys later is capacity, not a second path — see [`crate::scene::PageDesc`]
52//! and the layout entry for binding 7.
53//!
54//! What *was* on that list until 2026-08 is GPU culling and the indirect draw
55//! count, and both are here now: [`crate::draw_gen`] runs `cull.slang` and
56//! `draw_gen.slang` in front of this pass, and the draws below come out of the
57//! arguments they wrote. See that module for what a bucket is and why the
58//! arguments are per bucket rather than per surviving instance.
59//!
60//! # The CPU records a fixed number of draws
61//!
62//! One per bucket, whatever the scene holds — topic 03's
63//! headline goal, "10 objects and 10,000 objects record roughly the same
64//! commands". Adding an object is an instance in the pool and nothing else;
65//! removing one is [`InstancePool::remove`] and nothing else. Neither changes a
66//! single command this file records, because what varies — how many instances a
67//! bucket draws, and which — is written by a compute pass into a buffer the
68//! draw reads.
69//!
70//! Which *call* those draws are is the one branch: [`GeometryPath::IndirectCount`]
71//! takes the count from GPU memory too, and [`GeometryPath::IndirectPerBatch`] —
72//! Metal, whose API has multi-draw-indirect and no GPU-side count — reads each
73//! bucket's one argument structure unconditionally and leans on its instance
74//! count being zero.
75//!
76//! What *is* here, since 2026-08, is [`crate::mesh_pool`]: the cube is the first
77//! resident of the global vertex and index pools rather than owning two buffers
78//! of its own, so it is `{base_vertex, base_index, index_count}` like everything
79//! P7 will draw. Same geometry, different residence.
80//!
81//! And since the same month, [`crate::instance_pool`]: the cube's model matrix
82//! is a `GpuInstance` in a storage buffer rather than a field of the frame's
83//! uniform block, uploaded by delta. It holds the same matrix `begin_frame` used
84//! to write into the uniform, which is why the golden images did not move.
85//!
86//! # A second resident, and how it finds its own vertices
87//!
88//! A pool whose only mesh is at base vertex 0 cannot tell a base vertex that
89//! works from one that is silently cancelled out, and `mesh.slang`'s header
90//! shows the four targets disagreeing about exactly that: the SPIR-V subtracts
91//! `BaseVertex` back out of `SV_VertexID`, so the pool's base — passed through
92//! `draw_indexed`'s own argument — reached the shader as zero, while WGSL and
93//! MSL kept it. The same disagreement covers `SV_InstanceID`, which is what
94//! [`crate::sprite_pass`] paid for first.
95//!
96//! So **every draw this pass records passes zero for both of its bases**, and
97//! the real ones arrive as data. The base vertex comes from
98//! [`MeshPool`]'s mesh table, indexed by the drawn instance's
99//! [`mesh::GpuInstance::mesh`] — so it is resolved per instance, by the GPU,
100//! and one draw could cover instances of different meshes. The instance comes
101//! from the bucket's run of survivors, walked with `SV_InstanceID`, which counts
102//! from zero on every target *because* the first instance is zero. All a draw
103//! says for itself is which word holds its run's start — the start is the GPU's,
104//! per frame — in a [`mesh::DrawConstants`] block reached through a dynamic
105//! offset: one block per bucket, written once at build.
106//!
107//! That is what makes the pool's *second* resident,
108//! [`mesh::pyramid_vertices`], draw its own geometry rather than the cube's.
109//!
110//! The pyramid is in the pools from `new` but has no *instance* until a caller
111//! places one with [`ForwardRenderer::add_instance`] — an instance in the pool
112//! is an object in the scene now that culling decides what draws. The frame the
113//! samples draw is still the cube alone, which is why their golden images did
114//! not move either.
115//!
116//! # A third resident, and how it finds its own clusters
117//!
118//! The same argument one layer down. A mesh that fits **one** cluster cannot
119//! tell a per-cluster offset that works from one that is lost, and the cube and
120//! the pyramid fit one each — 24 and 16 vertices against a bound of 64. So the
121//! pool's third resident is [`mesh::open_box_vertices`], five clusters of one
122//! flat face each, four of them at a `Meshlet::vertex_offset` that is not zero.
123//! It is [`crate::cluster_pool`]'s counterpart to what the pyramid is for
124//! [`crate::mesh_pool`], and it is what §3.5's per-cluster culling will need
125//! before a surviving-cluster count can mean anything.
126//!
127//! It arrives on the pyramid's terms exactly: resident from `new`, in the scene
128//! only when a caller places it, so no golden moved for it either.
129//!
130//! # Uniforms are a ring, and they have to be
131//!
132//! The camera spins, so the uniform block is rewritten every frame — and the
133//! previous frame may still be reading it. One buffer would be a
134//! read-after-write hazard *across* submissions, which is precisely what
135//! `CRCBL_VK_SYNC_VALIDATION=1` exists to find and precisely what
136//! stage 2 called its headline risk. So there
137//! is one uniform buffer and one bind group per frame in flight, and
138//! [`ForwardRenderer::begin_frame`] rotates them.
139
140use crcbl_hal::{
141    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
142    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
143    BufferUsage, ColorTargetState, CompareOp, CullMode, DepthBias, DepthStencilState, Device,
144    DeviceCaps, Features, FilterMode, Format, GeometryPath, GraphicsPipelineDesc,
145    GraphicsPipelineHandle, HalError, ImageDesc, ImageHandle, ImageSubresourceRange, ImageType,
146    ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
147    MeshPipelineDesc, MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PolygonMode,
148    PrimitiveState, QueueHandle, Rect2d, ResourceState, SampleType, SamplerAddressMode,
149    SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc, ShaderModuleHandle, ShaderStages,
150    StoreOp, Viewport, check_portable_storage_buffers,
151};
152use crcbl_shaders::meshlet::MeshClusters;
153use crcbl_shaders::probe_gather::PunctualProducer;
154use crcbl_shaders::{
155    MESH, MESH_CLUSTER, Stage, TONEMAP, contact_shadows, dfg, level_select, ltc, mesh, ssao, ssr,
156    tonemap,
157};
158use glam::{Mat4, Quat, Vec3};
159use std::sync::Arc;
160use std::sync::atomic::{AtomicU64, Ordering};
161
162use crate::camera::{Atmosphere, Camera, DirectionalLight, Fog, Sky};
163use crate::cluster_pool::{ClusterPool, ClusterRange, PooledMesh};
164use crate::contact_shadows::ContactShadows;
165use crate::counters::FrameCounters;
166use crate::cull::Frustum;
167use crate::cull_stats::CullStatsRing;
168use crate::debug_draw::DebugDraw;
169use crate::draw_gen::{DrawGen, DrawGenDesc, FrameCull, GeneratedDraws};
170use crate::effects::{EffectRequest, RenderEffects};
171use crate::graph::{
172    BufferId, ImageId, ImportedBuffer, ImportedImage, InitialClaim, PassBuilder, RenderGraph,
173};
174// Renamed on the way in, because [`crate::light_grid::Grid`] already holds the
175// bare name here and means the froxel grid — the collision [`crate::grid`]'s
176// header predicted.
177use crate::atlas_view::AtlasView;
178use crate::bloom::Bloom;
179use crate::cmaa2::Cmaa2;
180use crate::exposure::{Exposure, ExposureAdaptation, ExposureBuffers};
181use crate::fxaa::Fxaa;
182use crate::grass::{Grass, GrassFrame, GrassScene};
183use crate::grid::{Grid as GroundGrid, GridStyle};
184use crate::hiz::Hiz;
185use crate::instance_pool::{InstanceHandle, InstancePool, InstancePoolDesc, InstancePoolError};
186use crate::light::{Light, sun_row};
187use crate::light_grid::{FROXEL_CAPACITY, FrameView, Grid, LightGrid, LightGridDesc};
188use crate::material_table::{MaterialTable, MaterialTableDesc};
189use crate::mesh_pool::{MeshHandle, MeshPool, MeshPoolDesc, MeshPoolError, MeshUpload};
190use crate::occlusion_cull::{OcclusionCulling, OcclusionPyramid};
191use crate::probe::{ProbeTable, ProbeTableDesc};
192use crate::probe_gather::{ProbeGather, ProbeGatherDesc, RsmImages, RsmTargets};
193use crate::rsm;
194use crate::scene::{self, Geometry, InstanceDesc, PageKind, ProbeUpdate, SceneDesc};
195use crate::shadow::{self, Cascades};
196use crate::skinning::{SkinRange, SkinnedMesh, Skinning, SkinningError};
197use crate::sky_pass::SkyPass;
198use crate::ssao::{Ssao, cached_group};
199use crate::ssr::{Ssr, SsrEnvironment, SsrImages};
200use crate::stack::CameraStack;
201use crate::texture::{
202    UploadedTexture, upload_texture, upload_texture_layers, upload_texture_mip_layers,
203};
204use crate::transient::TransientPool;
205use crate::upscale::Upscale;
206use crate::volumetric::{FroxelBuffers, Medium, Volumetric, VolumetricImages, VolumetricReads};
207use crate::water::{Water, WaterBodies, WaterFrame, WaterImages, WaterInputs};
208use crcbl_shaders::atmosphere::{SKY_VIEW_BUILD_ROWS, SkyView, SkyViewBuild};
209
210mod bucket_draws;
211mod frame_prepare;
212mod pages;
213mod shadow_inputs;
214mod view;
215
216use pages::{PageBindings, RetiredPage, upload_page};
217
218pub use shadow_inputs::{FRAME_UNIFORMS_READERS, UniformsField, UniformsReader};
219
220use bucket_draws::{BucketDraws, EmitTail, RegionStep};
221
222use view::{FramePasses, Overlays, TonemapPipeline, View, ViewInputs, ViewOutput};
223pub use view::{
224    FrameTargets, MAX_VIEWS, ViewBackground, ViewDesc, ViewId, ViewLighting, ViewMask, ViewTarget,
225};
226
227/// The clear behind the mesh, in **linear** light.
228///
229/// The scene target is `Rgba16Float`, so this is a linear value and the tonemap
230/// pass plus the swapchain's sRGB encode are what turn it into pixels. Writing a
231/// display-referred colour here would come out visibly paler, which is the
232/// classic HDR-pipeline mistake and worth a sentence rather than a surprise.
233pub const SCENE_CLEAR: [f32; 4] = [0.012, 0.016, 0.030, 1.0];
234
235/// How many frames of uniform buffers to keep. Matches the frame loop's
236/// frames-in-flight.
237pub const FRAMES_IN_FLIGHT: usize = 2;
238
239// The UI pass this renderer draws its HUD through keeps a ring of its own,
240// built at `crcbl_frame`'s default depth; held equal here, where both are in
241// scope, so the HUD cannot fall a frame behind the ring it shares a submit with.
242const _: () = assert!(crcbl_frame::ui_pass::FRAMES_IN_FLIGHT == FRAMES_IN_FLIGHT);
243
244/// The darkest exposure [`ForwardRenderer::set_exposure`] will accept: **five
245/// stops below** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`].
246///
247/// The floor exists so that the control cannot be driven somewhere it cannot be
248/// driven back from. The operator clamps its own *output* to `[0, 1]`, so an
249/// unclamped input has two dead ends: far enough down and every pixel rounds to
250/// the same black byte, far enough up and every pixel saturates to white — and
251/// in both the picture stops carrying the information a user would need to see
252/// which way to go. Five stops is well inside either: it is a sixteenth of the
253/// scene's brightness, dark but plainly still a picture, and it is the range a
254/// camera's exposure-compensation dial covers.
255pub const EXPOSURE_MIN: f32 = 1.0 / 32.0;
256
257/// The brightest exposure [`ForwardRenderer::set_exposure`] will accept: **five
258/// stops above** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`], for
259/// [`EXPOSURE_MIN`]'s reason.
260pub const EXPOSURE_MAX: f32 = 32.0;
261
262/// The default has to be reachable from both ends of the range, or a control
263/// that steps by a ratio starts somewhere it can only leave in one direction.
264const _: () = assert!(
265    EXPOSURE_MIN > 0.0
266        && EXPOSURE_MIN < crcbl_shaders::tonemap::DEFAULT_EXPOSURE
267        && EXPOSURE_MAX > crcbl_shaders::tonemap::DEFAULT_EXPOSURE
268);
269
270/// The format the frame's depth buffer is created with, taken from the
271/// description that creates it rather than written down a second time.
272///
273/// Read by [`ForwardRenderer::set_ground_grid`], whose pipeline is built for a
274/// depth attachment before there is a frame to ask. The extent is irrelevant to
275/// a format, which is why any is passed.
276pub(crate) const SCENE_DEPTH_FORMAT: Format = crate::targets::scene_depth((1, 1)).format;
277
278/// The format the frame's HDR scene target is created with, taken from the
279/// description that creates it rather than written down a second time.
280///
281/// Read by [`crate::debug_draw`], whose pipeline blends into whichever image the
282/// chain of HDR passes ended with — every one of them is a
283/// [`crate::targets::scene_color`]. The extent is irrelevant to a format,
284/// which is why any is passed.
285pub(crate) const SCENE_COLOR_FORMAT: Format = crate::targets::scene_color((1, 1)).format;
286
287/// The format §3.2's base-colour page is created with.
288///
289/// **`Rgba8UnormSrgb`, and that is the colour-space decision** — the argument
290/// for it is at the `upload_texture_mip_layers` call inside
291/// [`ForwardRenderer::with_scene`]. Named rather than spelled twice because
292/// [`ForwardRenderer::base_color_page_import`] has to declare the same format
293/// the image was created with, and a barrier naming a format the image is not in
294/// picks the wrong aspects.
295const BASE_COLOR_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
296
297/// The format topic 43 §2's **normal** page is
298/// created with.
299///
300/// **`Rgba8Unorm`, and the missing `Srgb` is the whole decision.**
301/// Topic 44's rung 2 argues it: a base-colour texel is a
302/// colour and glTF defines it as sRGB-encoded, so the format above is what makes
303/// the sampler decode it; a normal texel is a *number* — three components of a
304/// direction, stored as `n * 0.5 + 0.5` — and pushing it through the sRGB
305/// transfer curve is wrong by a gamma. What that looks like is not an error but
306/// a surface that leans further off vertical than the author drew, which is why
307/// the mistake survives review everywhere it is made.
308///
309/// `the_page_formats_split_colour_from_number` is the whole guard, and it is
310/// worth having because the four constants sit a few lines apart and the wrong
311/// one compiles.
312const NORMAL_PAGE_FORMAT: Format = Format::Rgba8Unorm;
313
314/// The format topic 43 §2's **metallic-roughness-
315/// occlusion** page is created with.
316///
317/// **`Rgba8Unorm`, and the missing `Srgb` is the same decision
318/// [`NORMAL_PAGE_FORMAT`] argues.** An occlusion, a roughness and a metalness
319/// are numbers rather than colours — glTF 2.0 §3.9.2 and §3.9.5 define them as
320/// linear factors — and a surface shaded through an sRGB decode of them is
321/// smoother and shinier than the author drew, which is a failure that survives
322/// review because it looks like a choice.
323///
324/// A separate constant from [`NORMAL_PAGE_FORMAT`] rather than a reuse of it,
325/// for [`LTC_SIZE_U32`]'s reason: the two stand for different facts, and a day
326/// one of them wanted a different format should be an edit here rather than a
327/// search for which callers of a shared name meant which page.
328const MRO_PAGE_FORMAT: Format = Format::Rgba8Unorm;
329
330/// The format topic 43 §2's **emissive** page is
331/// created with.
332///
333/// **`Rgba8UnormSrgb`, and it is the base-colour page's decision rather than
334/// the normal page's.** An emissive texel is a colour: glTF 2.0 §3.9.4 defines
335/// `emissiveTexture` as sRGB-encoded exactly as it defines `baseColorTexture`,
336/// and `GpuMaterial::emissive` beside it is a linear radiance, so the format is
337/// what puts the two in one space before they are multiplied.
338///
339/// A separate constant from [`BASE_COLOR_PAGE_FORMAT`] for the reason above it,
340/// and `the_page_formats_split_colour_from_number` is the guard that the four
341/// do not drift into one another.
342const EMISSIVE_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
343
344/// What the renderer needs of a [`PageKind`] to create and fill its image.
345///
346/// Written here rather than in [`crate::scene`] because the two answers are the
347/// device's: the format is the one [`base_color_page_import`] and
348/// [`normal_page_import`] have to declare, and the filter is the one
349/// [`crate::mip`] builds the chain with. A kind added by
350/// topic 43 §2's rung 3 is a new arm in each.
351///
352/// [`base_color_page_import`]: ForwardRenderer::base_color_page_import
353/// [`normal_page_import`]: ForwardRenderer::normal_page_import
354impl PageKind {
355    /// The format this kind's image is created with.
356    ///
357    /// The sRGB in one and its absence in the other is the whole colour-space
358    /// decision — see [`BASE_COLOR_PAGE_FORMAT`] and [`NORMAL_PAGE_FORMAT`],
359    /// which is where each is argued.
360    const fn format(self) -> Format {
361        match self {
362            Self::BaseColor => BASE_COLOR_PAGE_FORMAT,
363            Self::Normal => NORMAL_PAGE_FORMAT,
364            Self::MetallicRoughnessOcclusion => MRO_PAGE_FORMAT,
365            Self::Emissive => EMISSIVE_PAGE_FORMAT,
366        }
367    }
368
369    /// Every mip level below `level0`, built on the host with this kind's own
370    /// filter.
371    ///
372    /// [`crate::mip::normal_chain`] averages the decoded vectors plainly and
373    /// renormalises, where [`crate::mip::chain`] decodes an sRGB curve and
374    /// weights by alpha. A normal map mipped through the colour filter leans
375    /// further off vertical at every level than the map it was built from, and
376    /// nothing in a frame reports it.
377    fn chain(self, level0: &[u8], extent: u32) -> Vec<Vec<u8>> {
378        match self {
379            Self::BaseColor | Self::Emissive => crate::mip::chain(level0, extent),
380            Self::Normal => crate::mip::normal_chain(level0, extent),
381            Self::MetallicRoughnessOcclusion => crate::mip::linear_chain(level0, extent),
382        }
383    }
384
385    /// The device label this kind's image is created under.
386    const fn upload_label(self) -> &'static str {
387        match self {
388            Self::BaseColor => "material base colour",
389            Self::Normal => "material normals",
390            Self::MetallicRoughnessOcclusion => "material metallic-roughness-occlusion",
391            Self::Emissive => "material emissive",
392        }
393    }
394}
395
396/// The one texel a page **nothing names** is created with.
397///
398/// [`crate::texture::upload_texture_mip_layers`] refuses a zero-layer image, and
399/// every bind group of the mesh layout has to fill both page bindings whether or
400/// not the description carried either page — so a [`PageKind`] with no layers
401/// gets a 1×1 single-layer image in its own format instead of an `extent²` one
402/// nobody samples. That is the whole of what row (d) bought back:
403/// `apps/alcove`, `apps/sundial` and `apps/quarry` name no page at all, and
404/// every scene in the tree that has no normal map used to carry a full neutral
405/// layer and a third again for its chain.
406///
407/// **Magenta, and it is never sampled for its value.** A material naming no page
408/// carries [`GpuMaterial::NO_PAGE`](mesh::GpuMaterial::NO_PAGE):
409/// `mesh.slang`'s `base_color_texel` discards the fetch with a select and
410/// returns the literal `1.0`, and `shading_normal_of` returns before it fetches
411/// at all. So nothing should ever read this — and the value is chosen so that if
412/// something does, the frame says so in a colour no lit surface in this engine
413/// produces. White would blend into every untextured surface and black would
414/// read as a shadow; both are failures a golden could pass.
415const PAGE_PLACEHOLDER_TEXEL: [u8; 4] = [0xFF, 0x00, 0xFF, 0xFF];
416
417/// The format the motion-vector target is created with: two channels of half
418/// float, topic 43 §9's third colour attachment.
419///
420/// **Named here rather than in [`crate::targets::motion`]**, on
421/// [`crate::graph`]'s other format-owning descriptions' terms: the description
422/// and
423/// [`MeshModules::COLOR_TARGETS`] have to agree, and the pass that builds the
424/// pipeline is the one that owns the answer.
425///
426/// # The convention the target holds, so a consumer never has to guess it
427///
428/// **Current minus previous, in texture coordinates, `+y` down.** A pass
429/// holding the previous frame reads its history at `uv - motion`, and a surface
430/// travelling right and down the screen has both components positive.
431/// `mesh.slang`'s `motion_vector` is where the mapping is written out and this
432/// is the same sentence on the host side, because the first consumer will read
433/// one of the two and not both.
434///
435/// # Two channels and half float
436///
437/// A motion vector is a screen-space offset and has no third component. Half
438/// float rather than a normalised integer because the value is signed and
439/// unbounded — an object crossing the frame in one frame is a motion past `1.0`
440/// — and because the interesting magnitudes are small: a surface moving a
441/// tenth of a pixel is the case a temporal filter is most sensitive to, and
442/// eight or even sixteen unsigned bits over a `-1..1` range would quantise it
443/// into rest. It is also the format `crcbl_hal::Format::Rg16Float`'s own doc
444/// names motion vectors as the use for.
445pub(crate) const MOTION_FORMAT: Format = Format::Rg16Float;
446
447/// Which picture the colour pass draws instead of the shaded one.
448///
449/// The engine's debug views, as one value rather than as independent booleans,
450/// because they are not independent: every one of them rides in a single lane of
451/// the frame's uniform block and the shaders test the thresholds outermost
452/// first, so a renderer with two of them set draws exactly one.
453/// [`ForwardRenderer::debug_view`] is where that order lives, and this is what it
454/// answers with — so a menu row, a debug panel and the picture cannot disagree
455/// about which view is on.
456///
457/// **The declaration order is not the precedence** — each view was appended as
458/// it arrived, and [`ForwardRenderer::debug_view`] is the one place the order is
459/// decided. The sentinels in
460/// [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) ascend with it, though:
461/// see its `HEATMAP_VIEW_ON`, and the shaders test the outermost threshold
462/// first.
463#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
464pub enum DebugView {
465    /// The lit picture. What every frame draws unless a caller asked otherwise.
466    #[default]
467    Shaded,
468    /// Each cluster shaded by the projected screen-space error the LOD
469    /// selection judged it on — [`ForwardRenderer::set_heatmap`].
470    Heatmap,
471    /// Each cluster tinted by the DAG level it was decimated to —
472    /// [`ForwardRenderer::set_lod_view`].
473    LodTint,
474    /// World-space surface normals — [`ForwardRenderer::set_normals_view`].
475    Normals,
476    /// The ambient-occlusion channel alone, as grey —
477    /// [`ForwardRenderer::set_occlusion_view`].
478    AmbientOcclusion,
479    /// The motion vector each fragment wrote, stretched and centred on grey —
480    /// [`ForwardRenderer::set_motion_view`].
481    Motion,
482    /// The bent direction the occlusion channel carries beside its scalar, as
483    /// `n * 0.5 + 0.5` — [`ForwardRenderer::set_bent_normal_view`]. **Wins over
484    /// every other view.**
485    BentNormal,
486    /// The sun's cascades and the lit tiles beside them — the `D32Float` shadow
487    /// atlas itself, letterboxed over the finished frame with a border round
488    /// every occupied slot — [`ForwardRenderer::set_atlas_view`].
489    ///
490    /// **The one view that is a pass rather than a branch in `mesh.slang`**, and
491    /// therefore the one whose lane is the off sentinel: the colour pass draws
492    /// the shaded picture exactly as it always did and `crate::atlas_view`
493    /// replaces it afterwards. That module's header is where the placement is
494    /// argued.
495    ///
496    /// It resolves **below every view above and above [`Self::Cascades`]** — see
497    /// [`ForwardRenderer::debug_view`].
498    ShadowAtlas,
499    /// The shaded picture tinted by the cascade each sun-lit fragment's shadow
500    /// was sampled from, with the cross-fade band drawn as the blend of the two
501    /// — [`ForwardRenderer::set_cascade_view`].
502    ///
503    /// **Loses to every other view**, and it is the only one that does. The views
504    /// above draw something *instead of* the shaded picture; this one draws the
505    /// shaded picture and multiplies it, so there is nothing left for it to
506    /// modulate as soon as one of them is on. See
507    /// [`ForwardRenderer::debug_view`].
508    Cascades,
509}
510
511impl DebugView {
512    /// What a panel row or a summary line calls it.
513    #[must_use]
514    pub const fn label(self) -> &'static str {
515        match self {
516            Self::Shaded => "shaded",
517            Self::Heatmap => "heatmap",
518            Self::LodTint => "lod tint",
519            Self::Normals => "normals",
520            Self::AmbientOcclusion => "ambient occlusion",
521            Self::Motion => "motion",
522            Self::BentNormal => "bent normal",
523            Self::ShadowAtlas => "shadow atlas",
524            Self::Cascades => "cascades",
525        }
526    }
527}
528
529// Mesh-only resources follow the complete common fragment binding range.
530// Metal assigns dense native indices by resource-table order, so inserting a
531// mesh-only buffer before lights/probes would shift the layout away from the
532// independently compiled fragment stage. Sparse logical bindings cost no slots.
533const CLUSTERS_BINDING: u32 = 32;
534const CLUSTER_VERTICES_BINDING: u32 = 33;
535const CLUSTER_CORNERS_BINDING: u32 = 34;
536const CLUSTER_DRAW_ARGS_BINDING: u32 = 35;
537const CLUSTER_CULL_BINDING: u32 = 36;
538const CLUSTER_CULL_STATS_BINDING: u32 = 37;
539const CLUSTER_SELECT_BINDING: u32 = 38;
540const CLUSTER_SELECTION_BINDING: u32 = 39;
541const CLUSTER_GROUP_STATE_BINDING: u32 = 40;
542
543/// The shared fragment shader's shadow atlas slot. Historical logical gaps
544/// remain reserved so the raster shader bindings stay unchanged.
545const SHADOW_ATLAS_BINDING: u32 = 15;
546
547/// The bind-group slot the shadow atlas's **comparison** sampler is bound to.
548const SHADOW_SAMPLER_BINDING: u32 = 16;
549
550/// The bind-group slot the base-colour page is bound to.
551///
552/// Named because [`ForwardRenderer::replace_page`] rewrites it in every group
553/// of the mesh layout, as it does each page's binding — see
554/// `pages::page_binding`.
555const BASE_COLOR_PAGE_BINDING: u32 = 7;
556
557/// The bind-group slot the base-colour page's sampler is bound to.
558///
559/// Named because it is an entry [`ForwardRenderer::set_anisotropy`] rewrites
560/// in every group of the mesh layout: a sampler is a resource a group holds by
561/// handle, so a new sampler is a new group, and the rebuild finds the entry by
562/// this number.
563const PAGE_SAMPLER_BINDING: u32 = 8;
564
565/// The shared fragment shader's light list. Both shader modules declare it
566/// before mesh-only buffers so native buffer index 7 is common to both stages.
567const LIGHT_LIST_BINDING: u32 = 20;
568
569/// The bind-group slot the froxel grid is read through.
570const LIGHT_GRID_BINDING: u32 = 21;
571
572/// The fragment shader's screen-space occlusion texture. Mesh-only additions
573/// are buffers, so this resource does not shift their native argument table.
574const AMBIENT_OCCLUSION_BINDING: u32 = 22;
575
576/// The shared irradiance probe table, native buffer 9 in both shader modules.
577/// `mesh_cluster.slang` mirrors it before its own buffers to preserve the prefix.
578const PROBE_TABLE_BINDING: u32 = 23;
579
580/// The mesh path's packed `DrawGen` table, read for the screen-error heatmap.
581/// Its logical binding stays 24; after the shared fragment buffer prefix it is
582/// native buffer 10. The raster path does not declare this storage buffer.
583const LEVEL_GROUP_TABLE_BINDING: u32 = 24;
584
585/// The bind-group slot the split-sum `DFG` table is fetched through — how much
586/// of the light arriving at a GGX lobe that lobe hands back.
587///
588/// No mirror is needed in `mesh_cluster.slang`: that module adds only buffers
589/// after the shared prefix. The fragment shader's `specular_dfg` remains at
590/// native texture 3, following `ambient_occlusion` at texture 2.
591///
592/// **An image rather than a storage buffer, and that is forced.** The table is
593/// 4096 pairs and a buffer would carry it exactly; but the raster path's layout
594/// is at the WebGPU storage-buffer ceiling in its *vertex* stage, and Slang's
595/// Metal backend materialises every global into every entry point — so a row
596/// bound to the fragment stage alone would be a global the vertex stage names
597/// and nothing fills. See [`crcbl_hal::check_portable_storage_buffers`] and
598/// binding 7's `geometry` visibility.
599const SPECULAR_DFG_BINDING: u32 = 25;
600
601/// The bind-group slot §2's normal page is sampled through.
602///
603/// **Appended past [`SPECULAR_DFG_BINDING`], never inserted**, for
604/// [`PROBE_TABLE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
605/// next index in its Metal argument table by counting the same-table entries of
606/// this layout, and Slang numbers a stage's arguments by declaration order, so
607/// the two agree only while both ascend. No mirror is needed in
608/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
609///
610/// **No sampler of its own.** The page is read through
611/// [`PAGE_SAMPLER_BINDING`]'s sampler, the same trilinear anisotropic one the
612/// base-colour page uses, because it is sampled at the same UV over an image of
613/// the same extent. A second sampler would be a second layout entry, a second
614/// index in Metal's sampler argument table, and a second thing
615/// [`ForwardRenderer::set_anisotropy`] has to rebuild — for a filter that would
616/// be identical.
617const NORMAL_PAGE_BINDING: u32 = 26;
618
619/// The bind-group slot topic 44's rung 5 reads its linearly
620/// transformed cosine table through.
621///
622/// **Appended past [`NORMAL_PAGE_BINDING`], never inserted**, for that
623/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
624/// Metal argument table by counting the same-table entries of this layout, and
625/// Slang numbers a stage's arguments by declaration order, so the two agree only
626/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
627/// needs no mirror there and no index anything already owns moves.
628///
629/// **No sampler**, like the table two rows below it: four `Load`s and a bilinear
630/// blend written out in the shader, because a hardware filter's weights are
631/// fixed-function arithmetic four rasterisers compute independently and these
632/// goldens are compared across all four.
633const LTC_TABLE_BINDING: u32 = 27;
634
635/// The bind-group slot topic 45's contact-shadow channel is
636/// read through.
637///
638/// **Appended past [`LTC_TABLE_BINDING`], never inserted**, for that constant's
639/// reason exactly: `crcbl-mtl` gives a resource the next index in its Metal
640/// argument table by counting the same-table entries of this layout, and Slang
641/// numbers a stage's arguments by declaration order, so the two agree only while
642/// both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it needs
643/// no mirror there and no index anything already owns moves.
644///
645/// **No sampler**, like the occlusion channel: `mesh.slang`'s `contact_at` is a
646/// clamped `Load` at `SV_Position.xy`, and the channel is exactly the size of
647/// the frame on every pass that computed one.
648const CONTACT_SHADOW_BINDING: u32 = 28;
649
650/// The bind-group slot the irradiance probes' per-probe
651/// visibility maps are read through: one `Rg32Float` layer per probe.
652///
653/// **Appended past [`CONTACT_SHADOW_BINDING`], never inserted**, for that
654/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
655/// Metal argument table by counting the same-table entries of this layout, and
656/// Slang numbers a stage's arguments by declaration order, so the two agree only
657/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
658/// needs no mirror there and no index anything already owns moves —
659/// `msl/mesh.metal` puts it at `texture(7)`, the next free index of that table.
660///
661/// **A texture rather than a storage buffer, and that is forced**: the raster
662/// path's vertex stage is already at every storage buffer a WebGPU device
663/// guarantees, which is the same reason [`SPECULAR_DFG_BINDING`] is an image.
664///
665/// **No sampler**, like the occlusion channel and both cooked tables:
666/// `mesh.slang`'s `probe_moments` is four clamped `Load`s and a blend written
667/// out, because a hardware filter's weights are fixed-function arithmetic four
668/// rasterisers compute independently — and because `Rg32Float` is not a
669/// filterable format on WebGPU without an optional feature.
670const PROBE_VISIBILITY_BINDING: u32 = 29;
671
672/// The bind-group slot topic 43 §2's packed
673/// **metallic-roughness-occlusion** page is sampled through.
674///
675/// **Appended past [`PROBE_VISIBILITY_BINDING`], never inserted**, for
676/// [`NORMAL_PAGE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
677/// next index in its Metal argument table by counting the same-table entries of
678/// this layout, and Slang numbers a stage's arguments by declaration order, so
679/// the two agree only while both ascend. No mirror is needed in
680/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
681///
682/// **No sampler of its own**, for [`NORMAL_PAGE_BINDING`]'s reason: the page is
683/// read at the same UV over an image of the same shape as the base-colour one,
684/// so it goes through [`PAGE_SAMPLER_BINDING`]'s sampler and adds no entry to
685/// Metal's sampler argument table.
686const MRO_PAGE_BINDING: u32 = 30;
687
688/// The bind-group slot topic 43 §2's **emissive**
689/// page is sampled through.
690///
691/// **Appended past [`MRO_PAGE_BINDING`], never inserted**, for that constant's
692/// reason exactly, and it shares [`PAGE_SAMPLER_BINDING`]'s sampler on the same
693/// terms. `mesh_cluster.slang` adds only buffers after these textures, so it needs no
694/// mirror there and no index anything already owns moves.
695const EMISSIVE_PAGE_BINDING: u32 = 31;
696
697/// [`crcbl_shaders::dfg::DFG_SIZE`] as an image extent.
698///
699/// The table is square, and its size is a compile-time constant, so the
700/// conversion belongs here rather than as a fallible one at the upload.
701const DFG_SIZE_U32: u32 = dfg::DFG_SIZE as u32;
702
703/// [`crcbl_shaders::ltc::LTC_SIZE`] as an image extent.
704///
705/// The same number as [`DFG_SIZE_U32`], and a separate constant rather than a
706/// reuse of it: `crcbl_shaders::ltc`'s `the_grid_is_the_dfg_table_s_grid` is
707/// what says the two tables are the same square, and each upload naming its own
708/// module is what would make a day they were not into a compile error here
709/// rather than a stretched image.
710const LTC_SIZE_U32: u32 = ltc::LTC_SIZE as u32;
711
712/// The `Rgba8Unorm` texel that occludes nothing and steers nothing.
713///
714/// What [`ForwardRenderer::ambient_occlusion_placeholder`] holds, and therefore
715/// what `mesh.slang` reads on a frame drawing without
716/// [`RenderEffects::AMBIENT_OCCLUSION`].
717///
718/// **`r` is `0xFF`, which is `1.0`**: the shading multiplies its ambient by
719/// this and the term is untouched. Any other value would be a silent global
720/// ambient scale.
721///
722/// **`gba` are [`ssao::BENT_NORMAL_NONE`], which decodes to a zero-length
723/// direction** — the sentinel the occlusion chain writes wherever it has no
724/// bent direction to report, and which `mesh.slang`'s `bent_normal_at` answers
725/// with the fragment's own shading normal. So "no occlusion pass ran" and "no
726/// direction at this pixel" are one case with one answer, and a frame drawn
727/// with the effect off is the frame this renderer drew before the channel was
728/// widened. Encoding a direction here instead would tilt every ambient term in
729/// such a frame towards one world axis.
730const AMBIENT_OCCLUSION_NONE: [u8; 4] = [
731    0xFF,
732    ssao::BENT_NORMAL_NONE,
733    ssao::BENT_NORMAL_NONE,
734    ssao::BENT_NORMAL_NONE,
735];
736
737/// The `R8Unorm` texel the sun reaches unobstructed: `1.0`, which is `0xFF`.
738///
739/// What [`ForwardRenderer::contact_shadow_placeholder`] holds, and therefore
740/// what `mesh.slang` reads on a frame drawing without
741/// [`RenderEffects::CONTACT_SHADOWS`] — it multiplies `sun_visibility` by this
742/// and the cascades have the last word alone. Any other value would be a silent
743/// global scale on the sun.
744///
745/// The same byte as [`AMBIENT_OCCLUSION_NONE`]'s first and a constant of its
746/// own, for the reason [`LTC_SIZE_U32`] is not [`DFG_SIZE_U32`]: the two
747/// placeholders stand for different facts, and a day one of them wanted a
748/// different value should be an edit here rather than a search for which
749/// callers of a shared name meant which thing.
750const CONTACT_SHADOW_NONE: u8 = 0xFF;
751
752/// The one `Rg32Float` texel that occludes nothing: a mean distance of
753/// [`probe_visibility::FAR`](crcbl_shaders::probe_visibility::FAR) and its
754/// square.
755///
756/// What [`ForwardRenderer::probe_visibility_placeholder`] holds, and therefore
757/// what `mesh.slang` reads on a frame drawn before anything was captured or with
758/// `r_probe_visibility` off. No surface in any scene is further away than that,
759/// so `probe_weight` answers one for every probe and every fragment, and the
760/// grid is the unweighted trilinear blend it was before this rung — which is
761/// what makes the off position bit-identical rather than merely close.
762///
763/// Any *smaller* value would be a silent occluder: every probe in every scene
764/// would read as being behind a wall, and the whole grid would collapse onto
765/// `PROBE_OCCLUDED_WEIGHT`.
766fn probe_visibility_none() -> [u8; crcbl_shaders::probe_visibility::TEXEL_BYTES] {
767    let mut texel = [0u8; crcbl_shaders::probe_visibility::TEXEL_BYTES];
768    let far = crcbl_shaders::probe_visibility::FAR;
769    texel[..4].copy_from_slice(&far.to_le_bytes());
770    texel[4..].copy_from_slice(&(far * far).to_le_bytes());
771    texel
772}
773
774/// The reversed-Z far plane, in the two places that have to agree about it.
775///
776/// `ssao.slang` leaves early at exactly this depth because the unprojection there
777/// divides by a `clip.w` an infinite reversed-Z projection takes to zero. The
778/// shader cannot include the seam and `crcbl-shaders` does not depend on it, so
779/// the mirror is checked here — which is the only place both names are in scope.
780const _: () = assert!(crcbl_hal::depth::CLEAR == crcbl_shaders::ssao::DEPTH_FAR);
781
782/// How many buckets a resident mesh occupies, which is **not the same on every
783/// geometry path** — the one place in this renderer the two differ in shape
784/// rather than in the call they record.
785///
786/// A flat mesh is one bucket either way. A DAG is one bucket on
787/// [`EmitTail::Mesh`]: a bucket is a mesh's run of clusters, and the point of
788/// topic 25's per-cluster selection is that one dispatch covers
789/// several levels at once, so the run is every level's clusters end to end and
790/// the bucket's mesh id is level 0's.
791///
792/// On the two indirect tails a DAG is one bucket **per level**, because there
793/// the same plan takes a uniform cut and a level is drawn as an ordinary index
794/// range: a DAG's levels are separate mesh table entries, `draw_gen.slang`
795/// selects one per instance, and a bucket is what an indexed draw of one index
796/// range *is*. See [`ForwardRenderer::level_buckets`].
797const fn buckets_for(levels: usize, emit: EmitTail) -> usize {
798    if emit.is_mesh() { 1 } else { levels }
799}
800
801/// Every material mode this renderer routes a draw by, and the order the bucket
802/// table lays its per-mode runs of every mesh's levels down in.
803///
804/// [`GpuMaterial::mode`](mesh::GpuMaterial::mode)'s whole range, which is why
805/// the routing is total rather than checked: a row's mode is
806/// `flags & GpuMaterial::MODE_MASK`, that mask is the alpha-mask bit and the
807/// double-sided one, and the four combinations of them are these — so no
808/// material can carry a mode that is not in this list and no instance can
809/// scatter into a bucket that does not exist. Widening the mask means adding the
810/// mode here **and** giving it a depth pipeline in
811/// [`ForwardRenderer::depth_partitions`] in the same change — the two are the
812/// producer and the consumer of one list.
813///
814/// **A scene emits a twin per mode its own materials carry**, not one per
815/// entry here: two materials of two modes are two twins whichever two they are,
816/// and only a scene actually holding all four pays for four. The build below is
817/// where that filter is, and this module's
818/// `an_all_opaque_scene_keeps_one_bucket_per_mesh_level` is what holds it.
819const DEPTH_MODES: [u32; 4] = [
820    0,
821    mesh::GpuMaterial::ALPHA_MODE_MASK,
822    mesh::GpuMaterial::DOUBLE_SIDED,
823    mesh::GpuMaterial::ALPHA_MODE_MASK | mesh::GpuMaterial::DOUBLE_SIDED,
824];
825
826/// A pipeline and its [`CullMode::None`] twin: the two objects a pass binds to
827/// draw single-sided and double-sided buckets of one frame.
828///
829/// **A pipeline rather than a per-draw state, because no backend seam exposes
830/// dynamic cull mode** — and `crcbl_hal::CommandEncoder::set_stencil_reference`
831/// is the precedent for why one would not be added: a raster state a recorded
832/// stream carried per draw is a state every backend has to be able to change
833/// between two indirect calls, and the portable answer to "this draw rasterises
834/// differently" is a second pipeline. Which draws take which is
835/// [`ForwardRenderer::sided_partitions`].
836///
837/// Four passes need the pair — the colour pass, the two depth-only ones and the
838/// reflective shadow map — so it is a type rather than eight fields, and the
839/// twins are built together so a renderer can never hold one without the other.
840#[derive(Clone, Copy, Debug, PartialEq, Eq)]
841struct SidedPipelines {
842    /// [`CullMode::Back`]: every bucket whose material is single-sided, which is
843    /// every bucket of every scene that does not use `doubleSided`.
844    single: GraphicsPipelineHandle,
845    /// [`CullMode::None`]: the buckets whose material carries
846    /// [`GpuMaterial::DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED).
847    ///
848    /// Built on every scene rather than only on one that has such a material,
849    /// for [`MeshModules::depth_masked_pipeline`]'s stated reason: the modules
850    /// are released inside `build` and a pipeline built later would need them
851    /// back, which is a second shader compilation.
852    double: GraphicsPipelineHandle,
853}
854
855/// The pixel budget topic 25's descent compares a group's projected
856/// error against, unless a caller sets another with
857/// [`ForwardRenderer::set_lod_error_budget`].
858///
859/// One pixel, because that is what the metric is *for*: a level's error is how
860/// far its simplification may have moved the surface, so a budget of a pixel is
861/// the point at which a level change stops being something a viewer can see.
862/// The plan's "correct thresholds make pops sub-pixel by definition" is this
863/// number.
864const LOD_ERROR_BUDGET: f32 = 1.0;
865
866/// Bytes one bucket's draw-constant block occupies, whichever of the two blocks
867/// it holds.
868///
869/// The larger of [`mesh::DRAW_CONSTANTS_SIZE`] and
870/// [`CLUSTER_DRAW_CONSTANTS_SIZE`](crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE),
871/// because which one a bucket holds is the geometry path's decision and the
872/// buffer, its dynamic stride and the range the bind group names are all fixed
873/// before that decision reaches them.
874///
875/// **The bound range is the half that bites.** A range sized for the smaller
876/// block leaves the larger one's tail outside it, and a uniform read past the
877/// bound range is not a fault — it is a zero. Sized at sixteen bytes, the mesh
878/// path's `group_stride` read back as zero and every instance descended against
879/// instance zero's LOD state.
880const DRAW_CONSTANTS_BLOCK: u64 =
881    if mesh::DRAW_CONSTANTS_SIZE > crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE {
882        mesh::DRAW_CONSTANTS_SIZE as u64
883    } else {
884        crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE as u64
885    };
886
887/// How far below the budget an already-expanded group is held before it
888/// collapses again — topic 25's "switch-up and switch-down differ",
889/// as a fraction of [`LOD_ERROR_BUDGET`].
890///
891/// A ratio and not an offset because the band has to scale with the budget: a
892/// fixed number of pixels is most of a one-pixel budget and none of a fifty-pixel
893/// one. A fifth of the budget is a deadband a camera has to move decisively out
894/// of, and one a camera drifting along a boundary never leaves — which is the
895/// flicker the plan is about. `crcbl_shaders::cluster_select::LodBudgets` is the
896/// pair this produces, and a ratio of one is that type's `sharp`: no band, and
897/// the setting that shows the band is what stops the flicker.
898const LOD_HOLD_RATIO: f32 = 0.8;
899
900/// How much larger than the camera's the pixel budget a shadow cascade selects
901/// under is — topic 25's "**Shadow LOD bias**: shadow-pass culling
902/// selects +1/+2 coarser levels — casters are cheap where it never shows".
903///
904/// # A budget factor, because a level is not a parameter of the rule
905///
906/// The descent compares a group's projected error to a pixel budget; it never
907/// names a level. So "one or two levels coarser" is an *intent*, and the budget
908/// that produces it is the setting — and the two do not convert, because how far
909/// apart two levels' errors are is a property of the mesh. The committed dunes
910/// DAG is the demonstration: the step from one level's error to the next is
911/// several times larger in the middle of that hierarchy than at its base, and
912/// across its top levels there is no step at all — they report one error and are
913/// never separately selected by any budget. A bias expressed in levels would
914/// mean something different at each of those. `cook-clusters` prints the per
915/// level errors it built.
916///
917/// Four, then, is two doublings of the budget: enough that a caster is drawn
918/// coarser than the same object is in the colour pass, and small enough to stay
919/// inside what a shadow hides. What hides it is that a shadow edge is filtered —
920/// the atlas is read through a comparison sampler with linear filtering, so an
921/// edge arrives already spread over neighbouring texels — and that the atlas
922/// quantises every caster to [`shadow::TILE`] texels per cascade before anything
923/// samples it.
924///
925/// # Why one number, applied to the whole pass
926///
927/// **A cut is a cover only while expansion is monotone up the DAG**, and this
928/// scaling is what keeps it so. Multiplying both budgets by one positive
929/// constant leaves the rule in
930/// [`crcbl_shaders::cluster_select`]'s form with different constants in it, and
931/// that module's induction turns on the projected error being monotone up the
932/// DAG rather than on what the constants are — so the shadow pass's cut is a
933/// cover for exactly the reason the camera's is. A bias that varied by cluster,
934/// by group, by level or by cascade would not be: two groups on one branch would
935/// be judged against different budgets, and a child expanding under an
936/// unexpanded parent is a hole.
937///
938/// Being larger than one also makes the shadow pass's expanded set a **subset**
939/// of the colour pass's, since the two now select from one eye at one scale: a
940/// group over `k` times the budget is over the budget. So the shadow cut is
941/// never finer than the camera's anywhere, which is the property
942/// `crcbl-vk`'s `the_shadow_cascades_select_coarser_than_the_camera` reads back
943/// and asserts.
944pub const SHADOW_LOD_BIAS: f32 = 4.0;
945
946/// How many culls the shadow atlas needs: one per cascade and **one per shadowed
947/// light**, whatever kind of light it is.
948///
949/// Topic 18's fourth decision, as a number. A point light's six faces share the
950/// light's sphere — which is what a cull tests against — so they share one
951/// [`DrawGen`] and its visible set, and the six draws differ in a matrix and a
952/// viewport. Six generators per light would be six copies of
953/// [`TileBuffers::group_state`], which is where the cost of one is written down.
954const SHADOW_CULLS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS;
955
956/// How many shadow *views* there are: one per cascade, and one per face of every
957/// light slot.
958///
959/// A view is what has a matrix, so it is what has a frame-block copy, a bind
960/// group and a cut of its own — while a *tile* is where a view lands in the
961/// atlas and a *cull* is which visible set it draws. The three were one number
962/// until a light could own six tiles.
963///
964/// Every slot carries [`shadow::POINT_FACES`] views whether the light in it is a
965/// point or a spot, because a bind group names its buffers when it is created
966/// and the kind of light holding a slot changes per frame. A spot uses face 0's
967/// view and the other five are never recorded — they cost a uniform buffer and a
968/// descriptor each, which is nothing beside the [`DrawGen`] a second *cull*
969/// would cost.
970const SHADOW_VIEWS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS * shadow::POINT_FACES;
971
972/// Cascade 0's view, which is the one the irradiance probes'
973/// reflective shadow map is drawn through.
974///
975/// **A cascade is its own view index**, which is what `add_shadow_pass`'s view
976/// list pushes; [`shadow_view`] numbers a *light slot's* faces and starts past
977/// [`shadow::CASCADES`], so it is not the function to reach for here.
978const CASCADE_ZERO_VIEW: usize = 0;
979
980const _: () = assert!(
981    CASCADE_ZERO_VIEW < shadow::CASCADES,
982    "cascade 0's view has to be one of the cascades' own, not a light slot's"
983);
984
985/// Which view is face `face` of light slot `slot`.
986const fn shadow_view(slot: usize, face: usize) -> usize {
987    shadow::CASCADES + slot * shadow::POINT_FACES + face
988}
989
990/// Which cull light slot `slot` draws from.
991const fn shadow_cull(slot: usize) -> usize {
992    shadow::CASCADES + slot
993}
994
995/// One punctual shadow face this frame draws into the punctual reflective
996/// shadow map, and everything both halves of the updater need of it.
997///
998/// The irradiance probes' punctual producer. It carries no
999/// matrix and no visible set: a face's transform is already in the uniform block
1000/// [`ForwardRenderer::shadow_groups`] binds, and its draws are the ones its
1001/// slot's cull generated for the atlas — which is what makes this rung cost no
1002/// second cull and no second matrix.
1003#[derive(Clone, Copy, Debug)]
1004struct PunctualFace {
1005    /// Which shadow view this face is — [`shadow_view`]'s answer, and the index
1006    /// of the bind group whose block holds that face's own `view_proj`.
1007    view: usize,
1008    /// Which of the frame's shadow culls generated its draws — [`shadow_cull`]'s
1009    /// answer for the slot this face belongs to.
1010    cull: usize,
1011    /// Which face of its light this is, and so — where the light's cull tagged
1012    /// its casters by face — which draw region it draws.
1013    face: usize,
1014    /// Where it lands in the punctual map — [`rsm::punctual_tile`], which is the
1015    /// rectangle the pass sets its viewport to *and* the one the gather reads
1016    /// this face's texels out of.
1017    tile: shadow::TileRect,
1018    /// The light this is a face of, as the gather weighs its texels.
1019    producer: PunctualProducer,
1020}
1021
1022/// The draw region face `face` of a light draws: its own region where the
1023/// light's cull tagged casters by face, and region 0 — every survivor — where it
1024/// did not. See [`crcbl_shaders::draw_gen::FACE_REGION_BASE`].
1025fn face_region(by_face: bool, face: usize) -> u32 {
1026    if by_face {
1027        crcbl_shaders::draw_gen::FACE_REGION_BASE
1028            + u32::try_from(face).unwrap_or_else(|_| unreachable!("a light has six faces"))
1029    } else {
1030        0
1031    }
1032}
1033
1034/// One light's row in the gather's producer table, for the face standing at
1035/// `tile`.
1036///
1037/// **Built out of the light's own row**, which is the one place a light becomes
1038/// numbers — so the falloff, the cone and the colour the bounce is weighed by
1039/// are the very ones `mesh.slang` weighs the same light's direct term by, rather
1040/// than a second reading of the same fields that could round or widen
1041/// differently. [`Light::row`](crate::light::Light::row) is handed [`None`]
1042/// because a producer occludes through nothing: the gather gates a texel with
1043/// the probe's own visibility map, not with the light's.
1044fn producer_row(light: &Light, tile: shadow::TileRect) -> PunctualProducer {
1045    let row = light.row(None);
1046    PunctualProducer {
1047        position: [row.position[0], row.position[1], row.position[2]],
1048        radius: row.position[3],
1049        color: [row.color[0], row.color[1], row.color[2]],
1050        cos_outer: row.direction[3],
1051        axis: [row.direction[0], row.direction[1], row.direction[2]],
1052        cos_inner: row.cos_inner,
1053        origin: [tile.x, tile.y],
1054        side: tile.side,
1055        kind: row.kind,
1056    }
1057}
1058
1059const _: () = assert!(
1060    SHADOW_CULLS == shadow::GROUPS,
1061    "a cull is a cadence group: `shadow::Cadence` schedules what this file \
1062     dispatches, and two different counts would schedule a group nothing draws"
1063);
1064
1065/// Vertices in the over-sized triangle `mesh.slang`'s `depthClearVertexMain`
1066/// generates from `SV_VertexID`. No geometry is bound.
1067const TILE_CLEAR_VERTICES: u32 = 3;
1068
1069const _: () = assert!(
1070    crcbl_shaders::mesh::SHADOW_ATLAS_CLEAR_DEPTH == crcbl_hal::depth::CLEAR,
1071    "the stage that resets one tile writes a depth the attachment's own clear \
1072     does not, so a held tile and a cleared one would answer differently where \
1073     nothing was drawn"
1074);
1075
1076/// Narrows the shadow pass's viewport and scissor to one tile of the atlas.
1077///
1078/// The rectangle the allocator handed out — the same one the fragment stage
1079/// samples through, out of [`shadow::Selection`]. The graph set a viewport over
1080/// the whole atlas before the pass body ran, and this is what narrows it: the
1081/// same clip-space matrix mapped into a different part of the image, and for a
1082/// point light six different matrices into six of them off one visible set.
1083///
1084/// A function rather than the two calls inline, because the tile clear and the
1085/// draws that follow it walk the same tiles and a viewport set one way for one
1086/// of them would clear a rectangle nothing draws into.
1087fn set_shadow_tile(encoder: &mut dyn crcbl_hal::CommandEncoder, tile: shadow::TileRect) {
1088    let rect = Rect2d {
1089        x: i32::try_from(tile.x).unwrap_or(i32::MAX),
1090        y: i32::try_from(tile.y).unwrap_or(i32::MAX),
1091        width: tile.side,
1092        height: tile.side,
1093    };
1094    encoder.set_viewport(&Viewport {
1095        x: rect.x as f32,
1096        y: rect.y as f32,
1097        width: rect.width as f32,
1098        height: rect.height as f32,
1099        ..Viewport::from_size(rect.width, rect.height)
1100    });
1101    encoder.set_scissor(&rect);
1102}
1103
1104/// What the last executed graph left the renderer-owned import `image` in, as an
1105/// [`ImportedImage::initial`].
1106///
1107/// **[`ResourceState::Undefined`] is the answer to an empty ledger, not a
1108/// fallback around one.** The ledger records what a graph *executed*, so nothing
1109/// recorded means nothing has run against this image on this pool — a freshly
1110/// created image before its first frame, and an image whose pool has been
1111/// through [`TransientPool::destroy`] — and `Undefined` is what an image no
1112/// barrier has moved is in. It is also the only declaration that lets the
1113/// incoming barrier hand the image a layout at all: every other state names an
1114/// old layout the image is not in.
1115///
1116/// The reason this is a lookup and not a field the renderer advances: a graph is
1117/// built, then compiled, and [`RenderGraph::compile`] can refuse it. A field
1118/// stepped forward while the passes were declared would have moved for a frame
1119/// that never reached the GPU, and the next frame's declaration — now wrong —
1120/// has no ledger entry to contradict it, so [`InitialClaim::Tracked`] would pass
1121/// it through. One source of truth is what removes that gap rather than
1122/// narrowing it.
1123fn imported_state(pool: &TransientPool, image: ImageHandle) -> ResourceState {
1124    pool.imported_image_use(image)
1125        .unwrap_or(ResourceState::Undefined)
1126}
1127
1128/// The passes [`ForwardRenderer::add_passes`] records itself: the shadow
1129/// atlas's, the two reflective shadow maps, the depth prepass, the forward pass,
1130/// the debug draw layer, the tonemap, the ground grid and the
1131/// culling-statistics copy — plus [`Ssao::MAX_PASSES`], [`Ssr::PASSES`],
1132/// [`ProbeGather::PASSES`], [`Bloom::MAX_PASSES`], [`Exposure::PASSES`],
1133/// [`POST_TONEMAP_PASSES`] and [`Upscale::PASSES`] beside them.
1134///
1135/// [`AtlasView::PASSES`] has no term of its own and is inside
1136/// [`POST_TONEMAP_PASSES`] instead, which is where that is argued: the atlas
1137/// viewer and the resolve are never both recorded.
1138///
1139/// The reflective shadow maps and [`ProbeGather::PASSES`] are counted on the
1140/// ground grid's terms: all three are off unless a scene's
1141/// [`ProbeUpdate`] asks for them, and a bound short
1142/// of the frame that does ask would silently stop timing its last pass. The
1143/// punctual map is a pass whether or not the frame has a punctual light to draw
1144/// into it — see `ForwardRenderer::add_shadow_pass`, where the clear is what the
1145/// gather reads on a frame that lights none.
1146///
1147/// Every other pass in the frame belongs to a [`DrawGen`] or to the
1148/// [`LightGrid`], which is why this is the only count written here rather than
1149/// derived — see [`ForwardRenderer::MAX_PASSES`]. The copy is counted even
1150/// though a device that refused the readback records one fewer: this is a
1151/// ceiling, and one that came up short would silently stop timing the last pass
1152/// of every frame. It is the **all-effects-on** count for the same reason: a
1153/// frame that switched one off records fewer, and a bound that tracked the
1154/// toggles would have to be re-sized whenever they moved.
1155///
1156/// The ground grid is counted on the same terms, even though it is off by
1157/// default and is not a [`RenderEffects`] bit: a caller that switches it on
1158/// records one more pass, and a bound short of that would silently stop timing
1159/// the last pass of every frame it drew. The render-scale upscale is the second
1160/// of those — see [`ForwardRenderer::set_render_scale`], which is `1.0` and
1161/// therefore absent until a caller moves it. The debug draw layer is the third,
1162/// and [`DebugDraw::MAX_PASSES`] is its own ceiling.
1163///
1164/// **The bloom, Hi-Z and occlusion terms are ceilings where the others are
1165/// counts**: a chain's length is a function of the target's extent — see
1166/// [`crate::bloom`] and [`crate::hiz`] — and the occlusion pair's is a function
1167/// of [`crate::ssao::r_ssao_blur_passes`], while this constant is read before
1168/// either an extent or a console is known. The frame that lands on
1169/// it is a large one with bloom switched on; every smaller frame records fewer,
1170/// exactly as a frame with a free shadow slot does.
1171const RENDER_PASSES: u32 = 8
1172    // The occlusion cull's late depth prepass and its farthest pyramid, on the
1173    // ground grid's terms: off unless a caller switches the cull on.
1174    + 1
1175    + OcclusionPyramid::PASSES
1176    + DebugDraw::MAX_PASSES
1177    + ProbeGather::PASSES
1178    + Ssao::MAX_PASSES
1179    + ContactShadows::PASSES
1180    + Hiz::PASSES
1181    + Ssr::PASSES
1182    + Volumetric::PASSES
1183    + Water::PASSES
1184    + Grass::PASSES
1185    + Exposure::PASSES
1186    + Bloom::MAX_PASSES
1187    + POST_TONEMAP_PASSES
1188    + Upscale::PASSES;
1189
1190/// What the frame's one resolve slot costs at its widest: the larger of the two
1191/// antialiasing tiers.
1192///
1193/// **The larger and not the sum**, because the two are never both recorded —
1194/// [`RenderEffects::CMAA2`] carries that in writing and
1195/// [`ForwardRenderer::add_passes`] is where the choice is made. So this is the
1196/// all-effects-on count as well as the ceiling, which is the property
1197/// [`RENDER_PASSES`] needs from every term it adds up.
1198///
1199/// [`ForwardRenderer::add_passes`]: ForwardRenderer::add_passes
1200const RESOLVE_PASSES: u32 = if Fxaa::PASSES > Cmaa2::PASSES {
1201    Fxaa::PASSES
1202} else {
1203    Cmaa2::PASSES
1204};
1205
1206/// What the frame's one **post-tonemap** slot costs at its widest: the resolve
1207/// above, or [`crate::atlas_view`]'s pass, which replaces the picture instead of
1208/// filtering it.
1209///
1210/// **The larger and not the sum**, on [`RESOLVE_PASSES`]' terms and for a
1211/// reason of the same shape: [`ForwardRenderer::resolved_effects`] takes *both*
1212/// antialiasing tiers off for every debug view, and the atlas viewer records
1213/// only on the frame [`ForwardRenderer::debug_view`] resolved to
1214/// [`DebugView::ShadowAtlas`] — which is a debug view. So a frame that draws the
1215/// atlas resolves nothing, a frame that resolves is not drawing the atlas, and
1216/// neither can be short of this. `the_pass_bound_is_the_widest_frame_the_renderer_records`
1217/// is what holds the arithmetic to a frame that was actually recorded.
1218const POST_TONEMAP_PASSES: u32 = if RESOLVE_PASSES > AtlasView::PASSES {
1219    RESOLVE_PASSES
1220} else {
1221    AtlasView::PASSES
1222};
1223
1224/// Draws a full-screen pass records: the over-sized triangle, drawn once.
1225///
1226/// The smallest fraction of the target extent a frame may be drawn at.
1227///
1228/// A quarter in each dimension, which is a sixteenth of the pixels — below that
1229/// the internal frame is small enough that a Catmull-Rom reconstruction of it
1230/// stops being a picture of the scene and starts being a picture of the filter,
1231/// and the Hi-Z pyramid and the bloom chain both run out of levels. Every
1232/// engine's resolution slider bottoms out somewhere; this is where this one
1233/// does, and [`ForwardRenderer::set_render_scale`] clamps to it rather than
1234/// refusing, so a settings slider cannot hand the renderer a frame it cannot
1235/// draw.
1236pub const MIN_RENDER_SCALE: f32 = 0.25;
1237
1238/// The anisotropy the base-colour page is sampled with where the device grants
1239/// [`Features::SAMPLER_ANISOTROPY`].
1240///
1241/// Eight, which is topic 43's filtering rung's
1242/// default and the figure current engines default their own slider to: past it
1243/// the footprint's long axis is already sampled finely enough that sixteen is
1244/// invisible at a grazing angle and costs the same again in fetches. A device
1245/// whose [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) is lower gets
1246/// that limit instead — [`ForwardRenderer::anisotropy_for`] is the clamp — and a
1247/// device without the feature gets one, which is the value that turns it off.
1248pub const DEFAULT_ANISOTROPY: f32 = 8.0;
1249
1250/// Named rather than written into [`ForwardRenderer::counters`]'s arithmetic,
1251/// because these are the only draws in this file whose instance and triangle
1252/// counts the CPU knows exactly — everything else here goes through an indirect
1253/// call.
1254const FULLSCREEN_DRAWS: u64 = 1;
1255
1256/// How many full-screen passes a frame drawing `effects` at `extent` records:
1257/// the tonemap, always, and each switched-on effect's passes beside it.
1258///
1259/// **A function of the frame rather than a constant**, since
1260/// topic 48's toggles: it was the tonemap alone, then
1261/// five, and either written down is a number that stops matching the frame. The
1262/// tonemap is the one that is not conditional — a frame has to reach the
1263/// swapchain.
1264///
1265/// **`extent` is here because the bloom chain's length depends on it** — see
1266/// [`crate::bloom`] — where the two pairs above are the same two passes at every
1267/// size. A frame too small for even one chain level records none of them, which
1268/// is the same arithmetic as the toggle being off. It is the **internal** render
1269/// extent for the same reason: that is the extent every one of these passes runs
1270/// at.
1271///
1272/// `upscaling` is not a [`RenderEffects`] bit and could not be one — it is a
1273/// resolution, not an effect — so it arrives as its own argument, on the ground
1274/// grid's terms. It is false on every frame at full render scale, which is the
1275/// frame this function counted before the knob existed.
1276///
1277/// `ssao_blurs` arrives the same way and for the same reason: it is a console
1278/// variable rather than an effect bit, and it is the caller's job to read it
1279/// **once** for the frame. Reading it here as well would be a second read that
1280/// a command landing between the two could disagree with, and the disagreement
1281/// would be a counter describing a frame that was not recorded.
1282fn fullscreen_passes(
1283    effects: RenderEffects,
1284    extent: (u32, u32),
1285    upscaling: bool,
1286    ssao_blurs: u32,
1287) -> u64 {
1288    let mut passes = 1;
1289    if upscaling {
1290        passes += Upscale::PASSES as u64;
1291    }
1292    if effects.contains(RenderEffects::AMBIENT_OCCLUSION) {
1293        passes += u64::from(Ssao::passes(ssao_blurs));
1294    }
1295    if effects.contains(RenderEffects::CONTACT_SHADOWS) {
1296        passes += u64::from(ContactShadows::PASSES);
1297    }
1298    if effects.contains(RenderEffects::REFLECTIONS) {
1299        // The march's pair, and the pyramid it climbs — which is as long as the
1300        // extent allows and is zero on a frame too small to halve once, so this
1301        // term is the only one here that is not a constant per effect.
1302        passes += Ssr::PASSES as u64 + u64::from(crate::hiz::levels_for(extent));
1303    }
1304    if effects.contains(RenderEffects::BLOOM) {
1305        passes += u64::from(Bloom::passes_for(extent));
1306    }
1307    // **One resolve slot, and the higher tier takes it.** Both bits set is a
1308    // frame with CMAA2's passes and no FXAA pass at all, which is what
1309    // [`RenderEffects::CMAA2`] means by the two never both running — so this is
1310    // an `else if` rather than two independent terms.
1311    //
1312    // **[`Cmaa2::FULLSCREEN_PASSES`] and not [`Cmaa2::PASSES`]**: what this
1313    // function counts is full-screen *draws*, and two of that tier's three
1314    // passes are compute dispatches. [`crate::exposure`]'s three are left out
1315    // of this arithmetic for the same reason.
1316    if effects.contains(RenderEffects::CMAA2) {
1317        passes += Cmaa2::FULLSCREEN_PASSES;
1318    } else if effects.contains(RenderEffects::ANTIALIASING) {
1319        passes += Fxaa::PASSES as u64;
1320    }
1321    if effects.contains(RenderEffects::VOLUMETRIC_FOG) {
1322        // **[`Volumetric::COMPOSITE_PASSES`], not [`Volumetric::PASSES`].** The
1323        // scatter and the column scan are compute dispatches; what this
1324        // function counts is full-screen *draws*, and only the composite is
1325        // one. An atmosphere runs the composite without the effect, and the
1326        // caller adds that one — it is not an effect bit.
1327        passes += u64::from(Volumetric::COMPOSITE_PASSES);
1328    }
1329    // [`RenderEffects::AUTO_EXPOSURE`] adds none, and that is the whole of its
1330    // entry here: all three of its passes are compute dispatches, and the
1331    // exposure they measure reaches the picture through the tonemap's own draw.
1332    passes
1333}
1334
1335/// The budget an **orthographic** camera selects under: one no group satisfies,
1336/// so every group expands and the base level is drawn whole.
1337///
1338/// The metric divides a projected error by the distance to the group's sphere,
1339/// and an orthographic projection has no such falloff — see
1340/// [`Projection::pixels_per_unit`], which is where the trade is written down.
1341/// Drawing the finest level is the conservative answer and the honest one; a
1342/// distance term invented for a projection that has none would be neither.
1343///
1344/// [`Projection::pixels_per_unit`]: crate::camera::Projection::pixels_per_unit
1345const LOD_BUDGET_NONE: f32 = f32::NEG_INFINITY;
1346
1347/// Where a skinned object is, and what it draws: [`InstanceDesc`] with a
1348/// [`SkinnedMesh`] where the description's mesh index would be.
1349///
1350/// The mesh is a reservation rather than an index because a skinned draw is not
1351/// only a mesh — it also names a *run of the vertex pool* the skinning dispatch
1352/// fills, and which of the reservation's two runs that is changes every frame.
1353/// [`ForwardRenderer::begin_skinned_frame`] is what keeps it current, so nothing
1354/// here carries a parity.
1355#[derive(Clone, Copy, Debug)]
1356pub struct SkinnedInstanceDesc<'a> {
1357    /// The region this object is drawn out of, from
1358    /// [`ForwardRenderer::reserve_skinned`].
1359    pub mesh: &'a SkinnedMesh,
1360    /// Which [`SceneDesc::materials`] row it shades through, exactly as
1361    /// [`InstanceDesc::material`].
1362    pub material: usize,
1363    /// Where it is: a model matrix, on [`InstanceDesc::transform`]'s terms.
1364    ///
1365    /// The joints are **not** in it — a palette carries each joint's global
1366    /// transform times its inverse bind matrix, and this is what puts the
1367    /// deformed mesh in the world. See
1368    /// [`SkinRange::palette`](crate::skinning::SkinRange::palette).
1369    pub transform: Mat4,
1370}
1371
1372/// The sky-view LUT a frame is drawn from, and everything taken out of it.
1373///
1374/// **The two projections are cached beside the LUT rather than taken per
1375/// frame**, which is what makes a frame under a sun that has not moved do no
1376/// host LUT work at all: both are functions of the LUT alone, and the LUT only
1377/// changes when [`ForwardRenderer::refresh_sky_view`] swaps a finished build
1378/// in. [`crate::sky_pass`] still encodes [`SkyView::rows`] and its aerial LUT's
1379/// rows per frame, because those are writes into the frame's own ring slots
1380/// rather than projections.
1381#[derive(Clone, Debug)]
1382struct PresentedSky {
1383    /// The normalised sun and viewpoint the LUT was marched for, which is what
1384    /// [`ForwardRenderer::refresh_sky_view`] compares this frame's atmosphere
1385    /// against.
1386    parameters: crcbl_shaders::atmosphere::Atmosphere,
1387    /// The marched LUT: what [`crate::sky_pass`] uploads and the background
1388    /// samples.
1389    view: SkyView,
1390    /// [`SkyView::gradient_fit`], which `ssr.slang` reflects with and the sky
1391    /// pass's block carries.
1392    gradient: crcbl_shaders::sky::SkyGradient,
1393    /// [`SkyView::irradiance`], which is the frame block's L1 ambient term.
1394    irradiance: crcbl_shaders::probe::GpuProbe,
1395}
1396
1397impl PresentedSky {
1398    /// Takes both projections from a LUT that has just been marched.
1399    fn new(parameters: crcbl_shaders::atmosphere::Atmosphere, view: SkyView) -> Self {
1400        Self {
1401            parameters,
1402            gradient: view.gradient_fit(),
1403            irradiance: view.irradiance(),
1404            view,
1405        }
1406    }
1407}
1408
1409/// What [`ForwardRenderer::begin_frame`] fitted for the whole frame, kept so a
1410/// secondary view begun after it writes its blocks against the same sun, light
1411/// rows and shadow matrices the primary camera's were written against.
1412///
1413/// Everything here is decided by the primary camera and drawn once: the rows
1414/// carry the shadow tiles the primary camera's selection handed out, and the
1415/// cascades are fitted to its frustum. A secondary view samples the maps those
1416/// passes drew — `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
1417#[derive(Clone, Debug)]
1418struct FrameScene {
1419    light: DirectionalLight,
1420    rows: Vec<crcbl_shaders::light::GpuLight>,
1421    cascades: Cascades,
1422    shadow_view_proj: [[f32; 16]; shadow::CASCADES],
1423    light_view_proj: [[f32; 16]; shadow::LIGHT_TILES],
1424    atlas_rects: [[f32; 4]; shadow::TILES],
1425}
1426
1427/// The bucket and level tables a scene's generators are all built from, kept
1428/// so [`ForwardRenderer::create_view`] can build one more after `build` has
1429/// returned.
1430#[derive(Debug)]
1431struct DrawTables {
1432    bucket_meshes: Vec<u32>,
1433    bucket_clusters: Vec<u32>,
1434    bucket_cluster_bases: Vec<u32>,
1435    mesh_levels: Vec<level_select::MeshLevels>,
1436    level_groups: Vec<level_select::LevelGroup>,
1437    level_meshes: Vec<u32>,
1438    instance_capacity: u32,
1439    light_capacity: u32,
1440}
1441
1442/// The primary frame attachments an overlay may use before antialiasing and
1443/// render-scale reconstruction.
1444///
1445/// `display` is the display-space image the tonemap and post-tonemap overlays
1446/// have written. `depth` is the matching internal scene depth image, retained
1447/// as a read-only attachment for depth-tested overlays. Both have
1448/// `internal_extent` dimensions.
1449#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1450pub struct ForwardOverlayTargets {
1451    pub display: ImageId,
1452    pub depth: ImageId,
1453    pub internal_extent: (u32, u32),
1454}
1455
1456/// Everything the forward frame owns, created once.
1457#[derive(Debug)]
1458pub struct ForwardRenderer {
1459    // Geometry: the global pools, and the meshes resident in them. Each
1460    // range is resolved once, at build, and `MeshPool::mesh` only hands one out
1461    // for a mesh whose upload has completed — so there is no way to reach a
1462    // draw below with a mesh the GPU has not received.
1463    pool: MeshPool,
1464    /// The dynamic offset of each bucket's [`mesh::DrawConstants`] block, in
1465    /// [`SceneDesc::meshes`] order. Its length is the bucket count, which
1466    /// [`buckets_for`] says is a property of the path as well as of the scene.
1467    ///
1468    /// **The whole of what the CPU still says per draw.** Everything else a
1469    /// draw needs — how many instances, which indices, which vertices — is in
1470    /// the arguments the GPU wrote or in a table it resolves them through.
1471    bucket_constants: Vec<u32>,
1472    /// What one draw region adds to a bucket's offsets — the same for every
1473    /// generator this renderer built, because they share one bucket table.
1474    region_step: RegionStep,
1475    /// The material mode of each bucket, in the same order — the copy the
1476    /// **passes** read, where `DrawGen`'s copy is the one the GPU scatters
1477    /// against.
1478    ///
1479    /// What it is for: the depth prepass and the shadow atlas partition their
1480    /// call list on it and bind a pipeline per partition, so an opaque mesh in a
1481    /// scene with a cutout in it keeps the vertex-only stage. See
1482    /// [`ForwardRenderer::depth_partitions`].
1483    ///
1484    /// All zeroes for a scene whose materials are all opaque — every demo and
1485    /// every golden in this tree — which is exactly one bucket per mesh and one
1486    /// partition, byte for byte the stream they recorded before modes existed.
1487    bucket_modes: Vec<u32>,
1488
1489    // The instance array, and the objects' places in it. Nothing here is
1490    // rewritten per frame: the pool uploads what a caller changed and nothing
1491    // else, so a scene nobody moved costs no transfer at all.
1492    instances: InstancePool,
1493    /// The mesh table id of each description mesh's **level 0**, in
1494    /// [`SceneDesc::meshes`] order — what an [`InstanceDesc::mesh`] index
1495    /// resolves through.
1496    ///
1497    /// Level 0's and not the whole run, because that is the entry an instance
1498    /// carries: `cull.slang` reads a bounding box out of it and a DAG's coarser
1499    /// levels approximate the same surface inside the same box. The coarser
1500    /// entries are resident and no instance names one — a cluster reaches its
1501    /// own level's vertices through
1502    /// [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`], and the
1503    /// uniform cut reaches them through the bucket table.
1504    ///
1505    /// Kept rather than resolved per call because every write of an instance
1506    /// writes the whole record, and an instance that lost its mesh id would
1507    /// resolve to entry 0 — which is a mesh, and the wrong one.
1508    mesh_ids: Vec<u32>,
1509    /// Level 0's pool handle for each description mesh that can be skinned, in
1510    /// [`SceneDesc::meshes`] order, and [`None`] for the ones that cannot — see
1511    /// [`ResidentMesh::skinnable`].
1512    ///
1513    /// What [`ForwardRenderer::reserve_skinned`] resolves an
1514    /// [`InstanceDesc::mesh`] index through. Kept rather than looked up, because
1515    /// there is no way back from a table id to the handle that owns it: an id is
1516    /// a bare index and a [`MeshHandle`] is generational.
1517    skinnable_meshes: Vec<Option<MeshHandle>>,
1518    /// Every object [`ForwardRenderer::add_skinned_instance`] placed, with the
1519    /// two base vertices it alternates between.
1520    ///
1521    /// The list [`ForwardRenderer::begin_skinned_frame`] walks to point each one
1522    /// at the half of its region *this* frame's dispatch fills. Entries whose
1523    /// instance has gone stale are dropped as it walks, so
1524    /// [`ForwardRenderer::remove_instance`] needs to know nothing about
1525    /// skinning.
1526    skinned_instances: Vec<SkinnedInstance>,
1527
1528    /// §3.2's material table, and the rows in it.
1529    ///
1530    /// One buffer shared by every frame's bind group, not a ring — see
1531    /// [`crate::material_table`], which is where that decision lives.
1532    materials: MaterialTable,
1533    /// The table row of each description material, in [`SceneDesc::materials`]
1534    /// order — what an [`InstanceDesc::material`] index resolves through.
1535    ///
1536    /// Kept for the reason [`ForwardRenderer::mesh_ids`] is: a `set` writes the
1537    /// whole record, and an instance that lost its material id would name row 0
1538    /// by accident, which is a material and only *happens* to be the untinted
1539    /// one.
1540    material_ids: Vec<u32>,
1541    /// Topic 50's irradiance grid, row by row.
1542    ///
1543    /// One buffer shared by every frame's bind group, like the material table
1544    /// and for a stronger version of its reason: a probe is written when the
1545    /// scene is made resident and there is no call that rewrites one. See
1546    /// [`crate::probe`].
1547    probes: ProbeTable,
1548    /// Where those rows are, which rides in the frame block rather than in a
1549    /// buffer of its own — a fragment needs it before it knows which row to
1550    /// fetch.
1551    ///
1552    /// Kept rather than re-derived because [`SceneDesc`] is read once, at build.
1553    /// [`ProbeVolume::default`](crcbl_shaders::probe::ProbeVolume::default) is a
1554    /// grid of nothing, which is what a description with no probes leaves here
1555    /// and what makes the whole feature add zero.
1556    probe_volume: crcbl_shaders::probe::ProbeVolume,
1557    /// §3.2's texture side: one `D2Array` image whose layers the material rows
1558    /// index. One page, bound once, for every material — see the module docs on
1559    /// why this is [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) and not
1560    /// a bindless descriptor array.
1561    base_color_page: UploadedTexture,
1562    /// §2's second page: one `D2Array` image of tangent-space normals, whose
1563    /// layers [`GpuMaterial::normal_texture`](mesh::GpuMaterial::normal_texture)
1564    /// indexes.
1565    ///
1566    /// The base-colour page's own shape at [`NORMAL_PAGE_BINDING`], sampled
1567    /// through the same UV and the same sampler, and **created linear** — see
1568    /// [`NORMAL_PAGE_FORMAT`]. Its extent is its own: a description sizes each
1569    /// [`PageKind`] separately, so a 512² normal page beside a 2048²
1570    /// base-colour one is what the caller wrote and what this holds.
1571    normal_page: UploadedTexture,
1572    /// §2's third page: one `D2Array` image of glTF's packed occlusion,
1573    /// roughness and metallic, whose layers
1574    /// [`metallic_roughness_occlusion_texture`](mesh::GpuMaterial::metallic_roughness_occlusion_texture)
1575    /// indexes.
1576    ///
1577    /// The normal page's own shape at [`MRO_PAGE_BINDING`], sampled through the
1578    /// same UV and the same sampler, and **created linear** — see
1579    /// [`MRO_PAGE_FORMAT`].
1580    mro_page: UploadedTexture,
1581    /// §2's fourth page: one `D2Array` image of emitted radiance, whose layers
1582    /// [`emissive_texture`](mesh::GpuMaterial::emissive_texture) indexes.
1583    ///
1584    /// The base-colour page's own shape at [`EMISSIVE_PAGE_BINDING`], and
1585    /// **created sRGB** rather than linear, because an emissive texel is a
1586    /// colour — see [`EMISSIVE_PAGE_FORMAT`].
1587    emissive_page: UploadedTexture,
1588    /// Each [`PageKind`]'s image size in texels, as a width and a height,
1589    /// indexed by [`PageKind::index`].
1590    ///
1591    /// Square, because [`PageDesc`](crate::scene::PageDesc) carries one extent
1592    /// per kind rather than a rectangle. `(1, 1)` for a kind the description
1593    /// named no layer of, which is the placeholder's extent and not the
1594    /// description's — see [`PAGE_PLACEHOLDER_TEXEL`]. Kept rather than
1595    /// re-derived because [`add_passes`](Self::add_passes) declares both pages
1596    /// to the graph and an [`ImportedImage`] names an extent, and the
1597    /// description they came from is the caller's, read once at build.
1598    page_extents: [(u32, u32); PageKind::ALL.len()],
1599    /// The sampler the page is read through.
1600    base_color_sampler: SamplerHandle,
1601    /// The anisotropy [`ForwardRenderer::base_color_sampler`] was created
1602    /// with, after [`set_anisotropy`](ForwardRenderer::set_anisotropy)'s clamp.
1603    anisotropy: f32,
1604    /// How many layers each [`PageKind`]'s page holds, indexed by
1605    /// [`PageKind::index`] — zero for a kind the description named none of.
1606    ///
1607    /// What [`replace_page`](ForwardRenderer::replace_page) holds a
1608    /// replacement to, so every material row's layer number goes on naming the
1609    /// same texture.
1610    page_layers: [usize; PageKind::ALL.len()],
1611    /// `[frame]`: the page sampler and the four page views that slot's
1612    /// mesh-layout groups name.
1613    ///
1614    /// A slot moves onto [`ForwardRenderer::page_bindings`] at its own
1615    /// `begin_frame` and not before — see [`ForwardRenderer::adopt_pages`] —
1616    /// so this is what says which slots still name a sampler
1617    /// [`set_anisotropy`](ForwardRenderer::set_anisotropy) replaced or a page
1618    /// [`replace_page`](ForwardRenderer::replace_page) did.
1619    slot_pages: Vec<PageBindings>,
1620    /// Page samplers and pages replaced while some slot may still name them.
1621    /// Each is destroyed as the last slot naming it moves off, or at
1622    /// [`destroy`](ForwardRenderer::destroy).
1623    retired_pages: Vec<RetiredPage>,
1624
1625    /// Draw calls the last [`ForwardRenderer::add_passes`] recorded — see
1626    /// [`ForwardRenderer::counters`], which is the only thing that reads it.
1627    ///
1628    /// Kept rather than recomputed because the shadow pass's share is the number
1629    /// of **occupied** tiles, which [`ForwardRenderer::add_shadow_pass`] works
1630    /// out from topic 45's tile allocation and nothing outside
1631    /// it can restate without becoming the second copy that drifts.
1632    recorded_draws: u64,
1633    /// Which call the forward pass records — the device's [`GeometryPath`],
1634    /// resolved once.
1635    emit: EmitTail,
1636    /// The most buckets one call of the geometry passes draws, or `None` where
1637    /// they record a call per bucket — [`EmitTail::range_limit`], resolved at
1638    /// build with [`emit`](Self::emit) and for its reason.
1639    range_limit: Option<u32>,
1640    /// §3.5's clusters, and **only on [`EmitTail::Mesh`]**: the two indirect
1641    /// tails draw the same geometry out of the index pool and read none of
1642    /// this. `None` is therefore the ordinary state on most devices rather than
1643    /// a failure, and it is also what makes a fall-through impossible — see
1644    /// [`ForwardRenderer::geometry_path`].
1645    clusters: Option<ClusterPool>,
1646    /// Whether the mesh pipeline was built with §3.5's amplification stage in
1647    /// front of it — see [`ForwardRenderer::culls_clusters`], which is where
1648    /// what it means is written down.
1649    culls_clusters: bool,
1650    /// Where each description mesh's clusters are in
1651    /// [`ForwardRenderer::clusters`] — every level of it, as one run, in
1652    /// [`SceneDesc::meshes`] order. Empty off the mesh path, where there is no
1653    /// cluster pool at all. See [`ForwardRenderer::cluster_range`].
1654    mesh_clusters: Vec<ClusterRange>,
1655    /// The bucket each level of each description mesh draws through, finest
1656    /// first, in [`SceneDesc::meshes`] order — and empty on the mesh path. See
1657    /// [`ForwardRenderer::level_buckets`].
1658    ///
1659    /// **The run for the scene's first material mode**, which is `OPAQUE`
1660    /// wherever the scene has an opaque material at all: the table is every
1661    /// mesh's levels once per mode the scene holds, mode by mode, and this
1662    /// names a mesh's levels in the first of those runs. See
1663    /// [`ForwardRenderer::bucket_modes`].
1664    mesh_level_buckets: Vec<Vec<u32>>,
1665    /// The pixel budget topic 25's descent compares a group's
1666    /// projected error against. [`LOD_ERROR_BUDGET`] until
1667    /// [`ForwardRenderer::set_lod_error_budget`] says otherwise.
1668    lod_error_budget: f32,
1669    /// How far below that an expanded group is held before it collapses again.
1670    /// [`LOD_HOLD_RATIO`] until
1671    /// [`ForwardRenderer::set_lod_hold_ratio`] says otherwise.
1672    lod_hold_ratio: f32,
1673    /// The same three numbers the shadow cascades selected under, which is
1674    /// [`ForwardRenderer::lod_params`] with both budgets scaled by
1675    /// [`SHADOW_LOD_BIAS`] and the same pixels-per-unit.
1676    ///
1677    /// Kept beside the camera's for its reason: a reader comparing the two cuts
1678    /// takes both pairs from here rather than re-deriving the bias, which would
1679    /// be comparing two copies of one arithmetic instead of two selections.
1680    shadow_lod_params: [f32; 3],
1681
1682    /// The lights a caller set beside the sun, as
1683    /// [`ForwardRenderer::set_lights`] was handed them.
1684    ///
1685    /// Kept rather than converted on the way in, because a row is the *frame's*
1686    /// artefact: the sun arrives per frame at
1687    /// [`begin_frame`](ForwardRenderer::begin_frame) and is row 0, so the list a
1688    /// frame uploads cannot be assembled until then.
1689    extra_lights: Vec<Light>,
1690
1691    /// One [`mesh::DrawConstants`] block per draw, a device dynamic-offset
1692    /// alignment apart. Shared by every frame's bind group rather than ringed,
1693    /// because nothing rewrites it after `build`: a mesh's base vertex and an
1694    /// object's instance index are decided when the pools allocate them.
1695    draw_constants: BufferHandle,
1696    /// The camera's resources and history — see [`view`], which is where the
1697    /// line between a camera's state and the scene's is drawn.
1698    primary: View,
1699    /// Every secondary view [`ForwardRenderer::create_view`] built, indexed by
1700    /// [`ViewId::index`] less one — a free id is `None`.
1701    views: Vec<Option<View>>,
1702    /// The tables a view's generator is built from — see [`DrawTables`].
1703    draw_tables: DrawTables,
1704    /// Counts every [`begin_frame`](ForwardRenderer::begin_frame), so a view can
1705    /// say which frame it was last begun for — see [`View::begun`].
1706    frame_serial: u64,
1707    /// The frame the last `begin_frame` opened, for
1708    /// [`begin_view`](ForwardRenderer::begin_view). `None` before the first.
1709    frame_scene: Option<FrameScene>,
1710    /// Which frame-in-flight slot is current. Set from
1711    /// [`InstancePool::begin_frame`]'s return rather than counted here, so the
1712    /// uniform ring and the instance ring cannot drift apart.
1713    frame: usize,
1714
1715    mesh_layout: BindGroupLayoutHandle,
1716    mesh_pipeline_layout: PipelineLayoutHandle,
1717    mesh_pipeline: SidedPipelines,
1718    /// [`ForwardRenderer::mesh_pipeline`] again in
1719    /// [`PolygonMode::Line`], for
1720    /// [`set_wireframe`](ForwardRenderer::set_wireframe).
1721    ///
1722    /// [`None`] until a caller first switches the view on — the ground grid's
1723    /// arrangement exactly, and for its reason: a second pipeline compiled at
1724    /// build would be paid for by every sample, golden and headless run that
1725    /// never asks for a wireframe, which is all of them. Once built it is kept,
1726    /// because switching the view off is
1727    /// [`ForwardRenderer::wireframe_on`] and not a release.
1728    ///
1729    /// **A pair, like the pipeline it replaces**, because [`PolygonMode::Line`]
1730    /// does not disable culling: a single-sided wireframe drawn over a
1731    /// double-sided bucket would leave a surface out of the debug view that the
1732    /// shaded frame beside it draws, which is a view of the document that
1733    /// disagrees with the document.
1734    wireframe_pipeline: Option<SidedPipelines>,
1735    /// Whether [`add_passes`](ForwardRenderer::add_passes) drives the forward
1736    /// pass through [`ForwardRenderer::wireframe_pipeline`]. **`false` by
1737    /// default**: a wireframe is a tool's view of a document, and every sample
1738    /// and every golden image predates it.
1739    wireframe_on: bool,
1740    /// The occlusion and small-feature culls a caller asked for — see
1741    /// [`set_occlusion_culling`](ForwardRenderer::set_occlusion_culling).
1742    occlusion_culling: OcclusionCulling,
1743    /// Whether a point light's six faces cull separately — see
1744    /// [`set_point_face_culls`](ForwardRenderer::set_point_face_culls).
1745    point_face_culls: bool,
1746    /// What a test asked every shadow view's uploaded block to be rewritten
1747    /// with — see
1748    /// [`set_shadow_view_tamper`](ForwardRenderer::set_shadow_view_tamper).
1749    /// [`None`] outside a test.
1750    shadow_view_tamper: Option<fn(&mut mesh::FrameUniforms)>,
1751    /// Whether [`begin_frame`](ForwardRenderer::begin_frame) writes
1752    /// [`FrameUniforms::NORMALS_VIEW_ON`] into the frame block, which makes
1753    /// `mesh.slang`'s fragment stage draw world-space normals instead of shading
1754    /// — see [`set_normals_view`](ForwardRenderer::set_normals_view).
1755    ///
1756    /// **`false` by default**, on [`ForwardRenderer::wireframe_on`]'s terms
1757    /// exactly: it is a tool's view of a document, and every sample and every
1758    /// golden image predates it.
1759    ///
1760    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
1761    normals_view: bool,
1762
1763    /// The exponential height fog the colour pass composites over its
1764    /// radiance — see [`set_fog`](ForwardRenderer::set_fog).
1765    ///
1766    /// **[`Fog::NONE`] by default**, on [`normals_view`](Self::normals_view)'s
1767    /// terms: a caller who never asks for fog draws the frame this renderer
1768    /// drew before the feature existed, and exactly that frame — the shader's
1769    /// composite is an identity at zero density rather than an interpolation
1770    /// that nearly is.
1771    fog: Fog,
1772
1773    /// The gradient sky whose irradiance the colour pass adds to the ambient
1774    /// term — see [`set_sky`](ForwardRenderer::set_sky).
1775    ///
1776    /// **[`Sky::NONE`] by default**, on [`fog`](Self::fog)'s terms: a black
1777    /// gradient projects to coefficients that are all zero, so the three dot
1778    /// products the fragment stage adds are zero and no frame drawn before a
1779    /// sky existed moves.
1780    sky: Sky,
1781    /// The atmosphere that **replaces** [`Self::sky`] when a caller sets one —
1782    /// see [`set_atmosphere`](ForwardRenderer::set_atmosphere).
1783    ///
1784    /// `None` by default, so a renderer nobody calls that on is the renderer it
1785    /// was.
1786    atmosphere: Option<Atmosphere>,
1787    /// The marched sky-view LUT this renderer is drawing, with the parameters
1788    /// it was marched for and the projections taken from it.
1789    ///
1790    /// **Cached against the parameters rather than rebuilt per frame**, because
1791    /// the march is tens of milliseconds of CPU and the sun in most frames has
1792    /// not moved. The stored parameters are the *normalised* ones the shader
1793    /// crate takes, so a caller handing over the same sun spelled two lengths
1794    /// does not force a rebuild.
1795    ///
1796    /// This is the LUT a frame is **drawn from**, which is not the one being
1797    /// marched: see [`Self::sky_view_build`].
1798    sky_view: Option<PresentedSky>,
1799    /// The march in flight, when the sun has moved away from
1800    /// [`Self::sky_view`]'s.
1801    ///
1802    /// [`ForwardRenderer::refresh_sky_view`] steps it
1803    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame and swaps it into
1804    /// [`Self::sky_view`] when it finishes.
1805    ///
1806    /// **The host side is where the double buffer is**: the LUT being drawn and
1807    /// the LUT being marched are these two fields, and [`crate::sky_pass`]'s
1808    /// device ring is untouched. Putting the stripe on the device instead would
1809    /// mean writing part of a ring slot per frame, and that ring's slots are
1810    /// written whole precisely because each is a frame in flight — a partial
1811    /// write would have to track, per slot, which rows of *which* sun that slot
1812    /// already holds, which is bookkeeping the host copy does not need at all.
1813    sky_view_build: Option<SkyViewBuild>,
1814
1815    /// Whether the colour pass tints each cluster by its DAG level instead of
1816    /// shading — see [`set_lod_view`](ForwardRenderer::set_lod_view).
1817    ///
1818    /// **Wins over [`normals_view`](Self::normals_view) when both are set**,
1819    /// because one uniform lane carries both switches and the fragment stage
1820    /// tests the LOD threshold first. `crcbl_shaders`'
1821    /// `the_lod_view_threshold_lies_above_the_normals_view` is what keeps that
1822    /// order true.
1823    lod_view: bool,
1824
1825    /// Whether the colour pass shades each cluster by the projected error the
1826    /// LOD selection judged it on, instead of shading it or tinting it — see
1827    /// [`set_heatmap`](ForwardRenderer::set_heatmap).
1828    ///
1829    /// **Wins over both [`lod_view`](Self::lod_view) and
1830    /// [`normals_view`](Self::normals_view)**, on the same terms and for the same
1831    /// reason: one uniform lane carries all three switches and the shaders test
1832    /// the outermost threshold first. `crcbl_shaders`'
1833    /// `the_heatmap_view_threshold_lies_above_the_lod_view` is what keeps that
1834    /// order true, and
1835    /// `the_three_debug_views_resolve_in_one_order_however_they_are_set` is what
1836    /// holds this side to it.
1837    heatmap: bool,
1838
1839    /// Whether the colour pass draws the ambient-occlusion channel as grey
1840    /// instead of shading — see
1841    /// [`set_occlusion_view`](ForwardRenderer::set_occlusion_view).
1842    ///
1843    /// **Wins over every other view**, on [`heatmap`](Self::heatmap)'s terms and
1844    /// for its reason: one uniform lane, outermost threshold first.
1845    /// `crcbl_shaders`' `the_occlusion_view_threshold_lies_above_the_heatmap` is
1846    /// what keeps that order true, and
1847    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1848    /// this side to it.
1849    occlusion_view: bool,
1850
1851    /// Whether the colour pass draws the motion vector instead of shading — see
1852    /// [`set_motion_view`](ForwardRenderer::set_motion_view).
1853    ///
1854    /// **Wins over every other view**, on [`occlusion_view`](Self::occlusion_view)'s
1855    /// terms and for its reason: one uniform lane, outermost threshold first.
1856    /// `crcbl_shaders`' `the_motion_view_threshold_lies_above_the_occlusion_view`
1857    /// is what keeps that order true, and
1858    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1859    /// this side to it.
1860    motion_view: bool,
1861    /// Whether the colour pass draws the occlusion channel's bent direction
1862    /// instead of shading — see
1863    /// [`set_bent_normal_view`](ForwardRenderer::set_bent_normal_view).
1864    ///
1865    /// **Wins over every other view**, on [`motion_view`](Self::motion_view)'s
1866    /// terms: it is the outermost sentinel in the lane, and
1867    /// `crcbl_shaders`' `the_bent_normal_view_threshold_lies_above_the_motion_view`
1868    /// is what holds the shader's branch order to it.
1869    bent_normal_view: bool,
1870
1871    /// Whether the colour pass tints the shaded picture by the cascade each
1872    /// sun-lit fragment's shadow was sampled from — see
1873    /// [`set_cascade_view`](ForwardRenderer::set_cascade_view).
1874    ///
1875    /// **Loses to every other view**, which is the opposite of every field
1876    /// above and for the reason [`DebugView::Cascades`] carries: every one of them
1877    /// replaces the shaded picture and this one multiplies it, so a frame drawing
1878    /// any of them has nothing for this tint to reach. `crcbl_shaders`'
1879    /// `the_cascade_view_threshold_lies_below_every_replacing_view` is what
1880    /// holds the shader to the same order, from the other end of the lane.
1881    cascade_view: bool,
1882
1883    /// Whether the frame draws the shadow atlas over the finished picture — see
1884    /// [`set_atlas_view`](ForwardRenderer::set_atlas_view).
1885    ///
1886    /// **Not a lane of the frame block**, unlike every field above: this view is
1887    /// a pass rather than a branch in `mesh.slang`, so what reads this is
1888    /// [`ForwardRenderer::add_passes`] deciding whether to record
1889    /// [`crate::atlas_view`]'s. It resolves below every replacing view and above
1890    /// [`cascade_view`](Self::cascade_view) — see
1891    /// [`ForwardRenderer::debug_view`].
1892    atlas_view: bool,
1893
1894    /// Where [`begin_frame`](ForwardRenderer::begin_frame) projects
1895    /// topic 25's selection from, when that is not the camera's own
1896    /// eye — see
1897    /// [`set_frozen_selection_eye`](ForwardRenderer::set_frozen_selection_eye).
1898    ///
1899    /// **[`None`] is not a position, it is "follow the camera"**, and it is what
1900    /// every frame the engine has drawn so far did: the eye handed to
1901    /// [`DrawGen::begin_frame`] is `camera.eye`, byte for byte, so a caller that
1902    /// never sets this writes the parameter block it wrote before this field
1903    /// existed.
1904    ///
1905    /// **Not a [`DebugView`]**, and deliberately: the three views are one
1906    /// picture chosen between, while this is a change to what the *selection*
1907    /// answers and leaves the picture's choice alone. A reviewer freezing the
1908    /// cut and then reading it off the LOD tint is the combination the feature
1909    /// exists for, so the two cannot be alternatives.
1910    frozen_selection_eye: Option<Vec3>,
1911
1912    /// Topic 18's shadow atlas: one `D32Float` image holding
1913    /// [`shadow::TILES`] square tiles in a fixed grid — the sun's cascades
1914    /// first, then one per shadowed light.
1915    ///
1916    /// Owned here rather than created by the graph per frame, because its
1917    /// extent is a **quality setting and not a window size** — nothing about it
1918    /// changes on a resize, so a transient would be re-created for no reason
1919    /// and could not be read back by a test that does not own the graph.
1920    shadow_atlas: ImageHandle,
1921    shadow_atlas_view: ImageViewHandle,
1922    /// A 1×1 depth image that exists so the depth-only pipeline's bind group can
1923    /// fill [`SHADOW_ATLAS_BINDING`] without naming the atlas it is writing.
1924    ///
1925    /// Both halves of that sentence are forced:
1926    ///
1927    /// * **The slot has to be filled.** Slang's Metal backend materialises every
1928    ///   global into every entry point — `msl/mesh.metal`'s `vertexMain` takes
1929    ///   `shadow_atlas [[texture(1)]]` whether it reads it or not — so a
1930    ///   depth-only pipeline sharing this layout still declares the argument. A
1931    ///   layout with the slot removed would break Metal alone, on a runner this
1932    ///   team cannot debug on, which is the trap binding 6's comment already
1933    ///   records.
1934    /// * **It cannot be the atlas.** WebGPU refuses a texture that is a render
1935    ///   attachment and a bind-group resource in the same pass, and the shadow
1936    ///   pass is exactly that pass.
1937    ///
1938    /// Nothing samples it: the shadow pipeline has no fragment stage. It is
1939    /// brought into the graph beside the atlas so its layout transition is the
1940    /// graph's like every other, rather than a hand-written barrier.
1941    shadow_placeholder: ImageHandle,
1942    shadow_placeholder_view: ImageViewHandle,
1943    /// The **comparison** sampler the atlas is read through — hardware PCF.
1944    shadow_sampler: SamplerHandle,
1945    /// The depth-only pipeline every tile is rendered with — and, driven with
1946    /// the camera's own draws, the depth prepass's: `mesh.slang`'s
1947    /// `depthVertexMain` where the geometry comes from a vertex stage, the same
1948    /// geometry stage as [`ForwardRenderer::mesh_pipeline`] where it comes from
1949    /// a mesh one, and no fragment stage in either case.
1950    shadow_pipeline: SidedPipelines,
1951    /// The same two passes' pipeline for the buckets whose material mode cuts
1952    /// an alpha mask: `vertexMain` and `depthMaskedFragmentMain` — see
1953    /// [`MeshModules::depth_masked_pipeline`].
1954    ///
1955    /// Built on every scene rather than only on one that has a masked material,
1956    /// for [`ForwardRenderer::rsm_pipeline`]'s reason: the modules are released
1957    /// inside `build` and a pipeline built later would need them back, which is
1958    /// a second shader compilation. Which buckets are drawn with it is
1959    /// [`ForwardRenderer::depth_partitions`], and it is a **partition of one
1960    /// frame's draws** rather than a choice for the whole frame.
1961    depth_masked_pipeline: SidedPipelines,
1962    /// The pipeline that resets one tile of the atlas before it is redrawn, on a
1963    /// frame that is keeping some of the others — see
1964    /// [`MeshModules::depth_clear_pipeline`], which is where the whole argument
1965    /// for it lives.
1966    shadow_clear_pipeline: GraphicsPipelineHandle,
1967    /// The irradiance probes' reflective shadow map — see
1968    /// [`MeshModules::rsm_pipeline`]. Built on every scene and bound only by a
1969    /// frame whose volume asked for [`ProbeUpdate::EveryFrame`].
1970    rsm_pipeline: SidedPipelines,
1971    /// The compute pass that reads that map into the probe rows, and [`None`]
1972    /// for every scene whose volume is [`ProbeUpdate::Authored`] — which is the
1973    /// whole of what the default costs such a scene: no pipeline, no buffers, no
1974    /// pass and no frame time.
1975    probe_gather: Option<ProbeGather>,
1976    /// Whether cascade 0's view block and cull parameters were written for the
1977    /// frame being recorded, so the reflective shadow map can be drawn from
1978    /// them.
1979    ///
1980    /// Not [`ForwardRenderer::shadow_group_redrawn`], which is a claim about the
1981    /// *atlas*: a frame drawing without
1982    /// [`RenderEffects::SHADOWS`](crate::effects::RenderEffects::SHADOWS) fits
1983    /// cascade 0 for the map and writes no tile, and overloading that flag would
1984    /// report a cascade as redrawn when nothing drew it.
1985    rsm_cull_ready: bool,
1986    /// What the scene said fills the probe rows.
1987    ///
1988    /// Read by [`ForwardRenderer::begin_frame`] — which keeps cascade 0 off the
1989    /// shadow atlas's static-cache hold when the updater is on, because the map
1990    /// is that cascade's own draws — and by the pass recording below.
1991    probe_update: ProbeUpdate,
1992    /// How far cascade 0 reached on the frame being recorded, which is the
1993    /// radius of the sphere it was fitted to — `crate::rsm::texel_area` is what
1994    /// reads it.
1995    ///
1996    /// Written by [`ForwardRenderer::begin_frame`] beside the cascade matrices
1997    /// themselves, rather than recomputed at pass-record time: a frame that
1998    /// scaled its gather by one cascade's footprint while drawing the map
1999    /// through another's would be a bounce that is uniformly wrong, and nothing
2000    /// in the frame could see it.
2001    cascade_reach: f32,
2002    /// The sun's colour premultiplied by its intensity, this frame.
2003    ///
2004    /// The reflective shadow map holds albedo rather than flux — `RsmOutput` in
2005    /// `mesh.slang` argues why — so this is what the gather multiplies by, and it
2006    /// is read off the same [`DirectionalLight`] the cascades were fitted to.
2007    /// The sun's *direction* is not carried beside it: the gather needs none, on
2008    /// `probe_gather.slang`'s own derivation.
2009    sun_color: Vec3,
2010    /// One cull and draw-argument pass **per cascade and per shadowed light**,
2011    /// which is topic 18's "one cull dispatch per cascade against the same
2012    /// instance/geometry pools" with a shadowed light counting as a cascade does.
2013    ///
2014    /// A whole [`DrawGen`] rather than just its cull half: the shadow pass emits
2015    /// the same indirect call the colour pass does, so it needs the same
2016    /// arguments, and there is no "cull only" constructor to reach for. The cost
2017    /// is that each duplicates the clear and draw-argument pipelines and
2018    /// [`DrawGen`]'s own per-instance state — see
2019    /// [`TileBuffers::group_state`], which is where that price is written down,
2020    /// and [`SHADOW_CULLS`], which is why a point light has one of these rather
2021    /// than six.
2022    ///
2023    /// **Indexed by cull**: `0..shadow::CASCADES` are the sun's and
2024    /// [`shadow_cull`] is where a light slot's is.
2025    shadow_draws: Vec<DrawGen>,
2026    /// `[frame][view]`: a copy of the frame block whose `view_proj` **is** that
2027    /// view's matrix, so the depth-only pipeline runs the unmodified vertex and
2028    /// mesh stages rather than a second transform path.
2029    shadow_uniforms: Vec<Vec<BufferHandle>>,
2030    /// Empty between frame preparations, with capacity retained for assembly.
2031    shadow_prepare_views: Vec<(usize, usize, mesh::FrameUniforms)>,
2032    /// Empty between frame preparations, with capacity retained for frusta.
2033    shadow_prepare_culls: Vec<(usize, Frustum)>,
2034    /// `[frame][view]`: the mesh layout again, reading that view's uniforms and
2035    /// the survivors of the cull its slot owns.
2036    shadow_groups: Vec<Vec<BindGroupHandle>>,
2037    /// `[frame][view]`: the cut that view's amplification stage chose, one word
2038    /// per resident cluster — and empty where there is no such stage.
2039    ///
2040    /// **A buffer per view rather than the camera's**, unlike every other
2041    /// resource these passes share: the colour pass is recorded last and writes
2042    /// [`ForwardRenderer::cluster_selection`] over whatever a view left in it,
2043    /// so a view writing there leaves nothing behind to read. Without one of
2044    /// these the shadow pass's descent is unobservable — which is the state
2045    /// [`SHADOW_LOD_BIAS`] arrived in, and it is what a bias nothing can measure
2046    /// would have stayed in.
2047    shadow_selection: Vec<Vec<BufferHandle>>,
2048    /// Which of [`ForwardRenderer::extra_lights`] holds each shadow slot, where
2049    /// in the atlas's light region its tiles are, and the memory that keeps that
2050    /// answer from flickering.
2051    ///
2052    /// Re-run every [`ForwardRenderer::begin_frame`] and read by
2053    /// [`ForwardRenderer::add_shadow_pass`], which records a cull for each
2054    /// occupied slot and a viewport per face it has, and nothing at all for the
2055    /// free ones — so an unheld tile keeps the reversed-Z clear, which reads as
2056    /// "nothing stored, fully lit" wherever anything did sample it.
2057    shadow_lights: shadow::Selection,
2058    /// `[group]`: everything that group's maps would be drawn from, as
2059    /// [`ForwardRenderer::shadow_group_record`] spells it.
2060    ///
2061    /// Kept only to tell one frame's answer from the last one's: it is compared
2062    /// and then replaced, and what travels from there is the number below.
2063    ///
2064    /// **Per group rather than per atlas**, since the cadence rung: a group is a
2065    /// cascade or a light slot's whole run of tiles, and holding one map while
2066    /// redrawing another is the whole of what that rung buys.
2067    shadow_group_inputs: Vec<Vec<u8>>,
2068    /// `[group]`: a number that moves whenever that group's entry of
2069    /// [`ForwardRenderer::shadow_group_inputs`] does, and never comes back to a
2070    /// value it has had.
2071    ///
2072    /// So "the image already holds this" is one integer comparison, which is
2073    /// what lets the pass body below carry the answer out of the graph.
2074    shadow_group_id: Vec<u64>,
2075    /// `[group]`: how many instance writes that group's cull could have seen,
2076    /// over the renderer's life — the per-group stand-in for
2077    /// [`InstancePool::revision`] in
2078    /// [`ForwardRenderer::shadow_group_record`], moved by
2079    /// [`ForwardRenderer::note_caster_writes`].
2080    shadow_group_writes: Vec<u64>,
2081    /// `[element]`: where each element of the instance array could draw into a
2082    /// shadow map, as of the last [`ForwardRenderer::note_caster_writes`] —
2083    /// which is what a write's *before* is read from. Grows to the highest
2084    /// element written; an element past its end has never been written and is
2085    /// [`shadow_inputs::CasterFootprint::Nowhere`].
2086    shadow_footprints: Vec<shadow_inputs::CasterFootprint>,
2087    /// The live elements whose mesh has a DAG, and so whose level the selection
2088    /// eye chooses — the ones that put the eye into a light group's record.
2089    shadow_dag_elements: std::collections::BTreeSet<u32>,
2090    /// Scratch for [`InstancePool::take_written`], kept so a frame that moved
2091    /// an instance does not allocate its list.
2092    shadow_written: Vec<u32>,
2093    /// This frame's written elements' footprints, before and after the write,
2094    /// from [`ForwardRenderer::note_caster_writes`] for
2095    /// [`shadow_inputs::shadow_groups_reached`]. Empty on a frame nothing was
2096    /// written in.
2097    shadow_moved: Vec<(
2098        shadow_inputs::CasterFootprint,
2099        shadow_inputs::CasterFootprint,
2100    )>,
2101    /// The number given to the shadow pass this renderer recorded last.
2102    ///
2103    /// Moves once per recorded pass, so the body below can say *which* pass ran
2104    /// with one integer.
2105    shadow_pass_id: u64,
2106    /// The [`ForwardRenderer::shadow_pass_id`] of the last shadow pass that
2107    /// **ran**, written by that pass's own body.
2108    ///
2109    /// By the body rather than by the call that recorded it, and that is the
2110    /// whole of why this is shared state rather than a plain field: a frame
2111    /// whose graph was refused — or built and dropped — recorded a pass that
2112    /// never executed, so the image still holds whatever the frame before it
2113    /// left there. `a_refused_frame_leaves_the_shadow_atlas_where_it_was` is
2114    /// that case, and it is the same boundary [`TransientPool`]'s ledger of
2115    /// imported images uses for the same reason.
2116    ///
2117    /// Zero until a pass has run, and the ids start above it, so the first frame
2118    /// of all draws.
2119    shadow_pass_ran: Arc<AtomicU64>,
2120    /// What the shadow pass recorded last would leave the image holding, if its
2121    /// body ran.
2122    ///
2123    /// Taken and applied by the next [`ForwardRenderer::begin_frame`], which is
2124    /// the only place that can tell whether it did — see
2125    /// [`ForwardRenderer::shadow_pass_ran`].
2126    shadow_pending: Option<ShadowCommit>,
2127    /// `[group]`: the id, the centre that group's maps were projected from and
2128    /// how far they reach, as the record the **image** holds describes them.
2129    ///
2130    /// The id is what says a map is out of date. The centre and reach are what
2131    /// say it is about somewhere else: a map whose own centre has moved further
2132    /// than its own reach covers ground it was never drawn for, and holding
2133    /// that is worse than a shadow that lags — see
2134    /// [`ForwardRenderer::shadow_cadence_reset`].
2135    shadow_group_held: Vec<(u64, Vec3, f32)>,
2136    /// `[group]`: whether this frame redraws that group's maps.
2137    ///
2138    /// Frozen by [`ForwardRenderer::begin_frame`] for
2139    /// [`ForwardRenderer::frame_effects`]' reason: this call decides it and
2140    /// `add_passes` acts on it, and a value that moved between them would skip
2141    /// a cull whose draws were recorded, or the other way about.
2142    shadow_group_redrawn: Vec<bool>,
2143    /// Where every atlas slot's map was laid out on the frame the **image** was
2144    /// drawn from, so a frame can tell whether the texels it is keeping still
2145    /// describe the layout it is about to sample through.
2146    ///
2147    /// A layout that has moved is what makes a frame clear the whole attachment
2148    /// and redraw every group: a tile left over from a different layout is
2149    /// texels nothing this frame can account for. Promoted beside
2150    /// [`ForwardRenderer::shadow_group_held`].
2151    ///
2152    /// [`None`] until a pass has drawn, which is **not** the layout a frame
2153    /// with shadows off produces: an image no pass has touched holds undefined
2154    /// memory rather than a clear, so the first frame of all has to write one
2155    /// whatever it is asked for.
2156    shadow_atlas_layout: Option<Vec<shadow::TileRect>>,
2157    /// Whether any map this frame samples is one an earlier frame drew, rather
2158    /// than one this frame did.
2159    ///
2160    /// The cadence's own readback — see
2161    /// [`ForwardRenderer::shadow_atlas_cached`], which is this for the whole
2162    /// atlas.
2163    shadow_atlas_cached: bool,
2164    /// Whether this frame ignored the cadence because some map's region moved
2165    /// out from under it — see [`ForwardRenderer::shadow_cadence_reset`].
2166    shadow_cadence_reset: bool,
2167    /// How many tiles this frame redraws — see
2168    /// [`ForwardRenderer::shadow_faces_redrawn`].
2169    shadow_faces_redrawn: u32,
2170    /// A shadow cadence the caller pinned, or [`None`] to take the console's.
2171    ///
2172    /// [`ForwardRenderer::set_effect_request`]'s shape at this knob and for its
2173    /// reason: `shadow::r_shadow_cadence` and `shadow::r_shadow_faces` are
2174    /// process-global, and an application that wants a tier's own pair — or a
2175    /// test that wants a frame nothing else in the process can move — needs one
2176    /// that is not.
2177    shadow_cadence_request: Option<shadow::Cadence>,
2178    /// Whether this frame's shadow pass clears the whole attachment, rather
2179    /// than loading it and resetting only the tiles it redraws.
2180    ///
2181    /// Frozen beside [`ForwardRenderer::shadow_group_redrawn`] and for its
2182    /// reason: the decision is `begin_frame`'s and the recording is
2183    /// `add_shadow_pass`'s, and a value that moved between them would load an
2184    /// attachment whose tiles nothing had reset.
2185    shadow_atlas_clears: bool,
2186    /// How many frames have been opened, which is what the cadence is keyed to.
2187    ///
2188    /// **Monotonic, unlike [`ForwardRenderer::frame`]**, which is the index of
2189    /// the frame in flight and wraps every [`FRAMES_IN_FLIGHT`]. A schedule
2190    /// keyed to that would repeat every few frames and bound nothing.
2191    shadow_frame: u64,
2192    /// Whether this frame dispatches skinning, and so rewrites part of the
2193    /// vertex pool the shadow pass draws from.
2194    ///
2195    /// The atlas's one **always redraw**: a skinned caster's vertices are
2196    /// produced by a compute pass into the pool, so there is nothing on the
2197    /// host to compare a frame's geometry against — the palette a caller hands
2198    /// over is not the vertices, and the vertices are never read back. Set by
2199    /// [`ForwardRenderer::begin_skinned_frame`], which is the only call that
2200    /// can make it true, and cleared by [`ForwardRenderer::begin_frame`], which
2201    /// dispatches none.
2202    frame_skins: bool,
2203
2204    /// Topic 03 §3.6's one permitted readback: the camera cull's statistics, on
2205    /// a delayed ring — see [`crate::cull_stats`], which is where the shape and
2206    /// the latency are argued.
2207    ///
2208    /// **The camera's cull only.** [`ForwardRenderer::shadow_draws`] each have a
2209    /// statistics buffer of their own and none of them is read: a cascade's
2210    /// survivor count is a different question about a different frustum, and
2211    /// added into this one it would produce a number larger than the pool holds.
2212    ///
2213    /// [`None`] on a device that would not give out the buffers, which is what
2214    /// makes the counters row degrade to `indirect` rather than fail.
2215    cull_stats: Option<CullStatsRing>,
2216
2217    tonemap_layout: BindGroupLayoutHandle,
2218    tonemap_pipeline_layout: PipelineLayoutHandle,
2219    tonemap_pipeline: GraphicsPipelineHandle,
2220    sampler: SamplerHandle,
2221    /// The multiplier the tonemap pass applies before its clamp — see
2222    /// [`set_exposure`](ForwardRenderer::set_exposure).
2223    ///
2224    /// Always within [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`], because the setter is
2225    /// the only thing that writes it and it clamps.
2226    exposure: f32,
2227    /// How far auto-exposure may move in one frame — see
2228    /// [`set_exposure_adaptation`](ForwardRenderer::set_exposure_adaptation).
2229    ///
2230    /// [`None`] until a caller says otherwise, and that is the whole distance in
2231    /// one frame: the picture the pass drew before adaptation existed.
2232    exposure_adaptation: Option<ExposureAdaptation>,
2233    /// Which operator the tonemap pass runs — see
2234    /// [`set_tonemap_curve`](ForwardRenderer::set_tonemap_curve).
2235    ///
2236    /// [`TonemapCurve::Aces`](crcbl_shaders::tonemap::TonemapCurve::Aces) until
2237    /// a caller says otherwise: this renderer shades in linear HDR, so the
2238    /// filmic roll-off is what a view that has said nothing wants. A
2239    /// display-referred view — a 2D sample, or a fixture whose assertions
2240    /// predict a code value — asks for
2241    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp),
2242    /// which is the identity on `0..=1`.
2243    tonemap_curve: tonemap::TonemapCurve,
2244
2245    /// The format the tonemap pipeline was built for. A swapchain format change
2246    /// needs a new pipeline, which is why it is remembered rather than assumed.
2247    target_format: Format,
2248
2249    /// A 1×1 `R8Unorm` image holding [`AMBIENT_OCCLUSION_NONE`], so a group of
2250    /// the mesh layout can fill [`AMBIENT_OCCLUSION_BINDING`] without naming an
2251    /// occlusion image that does not exist yet.
2252    ///
2253    /// [`ForwardRenderer::shadow_placeholder`]'s argument, one binding along.
2254    /// The shadow pass and the depth prepass name it and never sample it — a
2255    /// depth-only pipeline has no fragment stage — and **the forward pass names
2256    /// it too on a frame drawing without [`RenderEffects::AMBIENT_OCCLUSION`]**,
2257    /// where it is the whole of that effect's off-switch. An AO-on frame binds
2258    /// the occlusion pair's blurred output instead.
2259    ///
2260    /// **It is white because that is the value that occludes nothing**, which is
2261    /// what makes it an honest stand-in for "no occlusion was computed" rather
2262    /// than decoration. That it *reads* as white is `mesh.slang`'s doing: the
2263    /// binding is fetched with a `Load`, and a `Load` past a 1×1 image's one
2264    /// texel is zero on every backend, so the shader clamps the coordinate to the
2265    /// image's extent. See [`add_passes`](ForwardRenderer::add_passes).
2266    ///
2267    /// It is uploaded rather than cleared, so it is in
2268    /// [`ResourceState::ShaderRead`] from the moment it exists and no pass has to
2269    /// declare it to give it a layout.
2270    ambient_occlusion_placeholder: UploadedTexture,
2271    /// A 1×1 `R8Unorm` image holding [`CONTACT_SHADOW_NONE`], so a group of the
2272    /// mesh layout can fill [`CONTACT_SHADOW_BINDING`] without naming a
2273    /// contact-shadow image that does not exist yet.
2274    ///
2275    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, one
2276    /// binding along and with one difference worth stating: an unclamped `Load`
2277    /// past this one's single texel would cost the frame its **sun**, not its
2278    /// ambient. `mesh.slang`'s `contact_at` is what clamps it.
2279    contact_shadow_placeholder: UploadedTexture,
2280    /// A 1×1×1 `Rg32Float` image holding [`probe_visibility_none`], so a group
2281    /// of the mesh layout can fill [`PROBE_VISIBILITY_BINDING`] before anything
2282    /// has been captured — and so the console switch has something to name when
2283    /// the maps are turned off.
2284    ///
2285    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, with the
2286    /// same clamp on the shader's side: `mesh.slang`'s `probe_moments` clamps
2287    /// against `GetDimensions`, so all four of its taps land on this image's one
2288    /// texel and every probe reads as unobstructed.
2289    probe_visibility_placeholder: UploadedTexture,
2290    /// The captured maps, one `Rg32Float` layer per probe — `None` until
2291    /// [`ForwardRenderer::capture_probe_visibility`] has run, which is every
2292    /// frame drawn by a caller that never calls it.
2293    probe_visibility: Option<UploadedTexture>,
2294    /// The scene's static triangles, kept for that capture and for nothing else.
2295    ///
2296    /// Empty for a description that reserved no probes, which is what makes the
2297    /// retention cost of this rung zero for every caller that does not use it —
2298    /// see [`crate::probe_visibility`].
2299    probe_occluders: crate::probe_visibility::Occluders,
2300    /// The split-sum `DFG` table as an `Rgba8Unorm` image — binding
2301    /// [`SPECULAR_DFG_BINDING`], read by multi-scatter energy compensation and
2302    /// by every area light's specular term.
2303    ///
2304    /// Uploaded once from `crcbl_shaders::dfg::pair_texels` and never written
2305    /// again: it is a property of the GGX lobe rather than of a scene, a view or
2306    /// a frame. Unlike [`ForwardRenderer::ambient_occlusion_placeholder`] beside
2307    /// it this is not a stand-in for anything — there is no path on which the
2308    /// table is absent, because there is no path on which the lobe is.
2309    specular_dfg: UploadedTexture,
2310    /// The linearly transformed cosine fit as an `Rgba16Float` image — binding
2311    /// [`LTC_TABLE_BINDING`], and the whole of an area light's specular shape.
2312    ///
2313    /// Uploaded once from `crcbl_shaders::ltc::texels`, on the table above it's
2314    /// terms exactly and for the same reason: it is a property of the lobe, and
2315    /// it is bound on every path because Slang's Metal backend materialises
2316    /// every global into every entry point.
2317    ltc_table: UploadedTexture,
2318    /// `[frame][view]`: the entries [`ForwardRenderer::shadow_groups`] was built
2319    /// from.
2320    ///
2321    /// Kept for one rebuild only: the pages' and their sampler's, which
2322    /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
2323    /// layout a slot holds — [`View::prepass_group_entries`]' reason.
2324    shadow_group_entries: Vec<Vec<Vec<BindGroupEntry>>>,
2325
2326    /// The ground grid's pipeline and uniform ring — see [`crate::grid`].
2327    ///
2328    /// [`None`] until a caller first switches it on with
2329    /// [`set_ground_grid`](ForwardRenderer::set_ground_grid), which is what
2330    /// keeps a sample that never asks for a grid from building a pipeline and a
2331    /// ring of blocks for a pass it does not record. Once built it is kept —
2332    /// switching the grid off is [`ForwardRenderer::ground_grid_on`] and not a
2333    /// release, because releasing a uniform ring the frames in flight may still
2334    /// be reading is exactly what the ring exists to prevent.
2335    ground_grid: Option<GroundGrid>,
2336    /// Whether [`add_passes`](ForwardRenderer::add_passes) records the ground
2337    /// grid's pass. **`false` by default**: the grid is a tool's chrome, and
2338    /// every sample and every golden image predates it.
2339    ground_grid_on: bool,
2340
2341    /// The debug draw layer's immediate-mode buffer and its pass — see
2342    /// [`crate::debug_draw`].
2343    ///
2344    /// Always present and empty by default, because appending to it is what a
2345    /// system does and the buffer is a `Vec`; the pipeline and the rings inside
2346    /// it are what stay unbuilt until a frame has both a segment and
2347    /// [`crate::debug_draw::r_debug_draw`] switched on.
2348    debug_draw: DebugDraw,
2349
2350    /// The shadow atlas viewer — see [`crate::atlas_view`]. It draws on no frame
2351    /// but the one [`debug_view`](Self::debug_view) resolved to
2352    /// [`DebugView::ShadowAtlas`], which is none until a caller calls
2353    /// [`set_atlas_view`](Self::set_atlas_view).
2354    atlas_viewer: AtlasView,
2355    /// How large the internal render target is as a fraction of the extent a
2356    /// caller hands `begin_frame` — see [`set_render_scale`](Self::set_render_scale).
2357    render_scale: f32,
2358
2359    /// The three layers a caller supplies — see [`crate::effects`].
2360    effect_request: EffectRequest,
2361    /// The fourth layer: what this device can draw, which clamps last and
2362    /// absolutely.
2363    ///
2364    /// **Every effect, and that is a fact about the effects rather than an
2365    /// unfinished clamp.** Topic 18 says so of the occlusion pair in as many
2366    /// words — "there is no device fact to gate on … inventing a capability that
2367    /// is really a performance opinion is what topic 39 exists to prevent" — and
2368    /// the reflection pair's module says it of itself. The shadow atlas is a
2369    /// `D32Float` image and a depth-only pass, which is not something a device
2370    /// that got this far can be missing either: one too small for the atlas
2371    /// fails to *build* this renderer rather than degrading past it.
2372    ///
2373    /// So the clamp is real and its rule set is empty. The first rule arrives
2374    /// with the ray-traced variants of these same three effects, which
2375    /// [`LightingPath`](crcbl_hal::LightingPath) selects and which nothing
2376    /// builds yet.
2377    device_effects: RenderEffects,
2378    /// What the frame [`begin_frame`](ForwardRenderer::begin_frame) opened
2379    /// draws, resolved once there.
2380    ///
2381    /// **Frozen for the frame on purpose.** `begin_frame` skips a shadow cull's
2382    /// parameter write when shadows are off and
2383    /// [`add_passes`](ForwardRenderer::add_passes) skips its dispatch; a request
2384    /// changed between the two would dispatch a cull whose counters nothing
2385    /// zeroed, which is a plausible frame drawn off last frame's numbers.
2386    frame_effects: RenderEffects,
2387    /// How many blur passes the frame [`begin_frame`](ForwardRenderer::begin_frame)
2388    /// opened runs over the raw occlusion channel — [`crate::ssao::blur_passes`],
2389    /// read once there.
2390    ///
2391    /// **Frozen for the frame on [`ForwardRenderer::frame_effects`]'s terms.**
2392    /// [`add_passes`](ForwardRenderer::add_passes) both counts the frame's
2393    /// full-screen triangles and records its passes, and a console command
2394    /// landing between the two reads would leave `counters` describing a frame
2395    /// that was never submitted.
2396    frame_ssao_blurs: u32,
2397    /// Full-screen passes the last [`add_passes`](ForwardRenderer::add_passes)
2398    /// recorded, which is what [`counters`](ForwardRenderer::counters) reports
2399    /// as submitted beside the pool's instances.
2400    ///
2401    /// Stored rather than re-derived from [`ForwardRenderer::frame_effects`]:
2402    /// `counters` describes the frame that *was* recorded, and a request set
2403    /// after it would otherwise change the count of a frame already submitted.
2404    recorded_fullscreen: u64,
2405
2406    /// Whether the last [`add_passes`](ForwardRenderer::add_passes) recorded the
2407    /// debug draw layer's pass, as the one direct draw it costs.
2408    ///
2409    /// Separate from [`ForwardRenderer::recorded_fullscreen`] because it is not
2410    /// a full-screen triangle: it is one line-list draw of every segment this
2411    /// frame appended. Both are direct draws of one instance, which is what
2412    /// [`ForwardRenderer::direct_draws`] adds up.
2413    recorded_debug_draw: u64,
2414    /// How many tiles of the shadow atlas the last
2415    /// [`add_passes`](ForwardRenderer::add_passes) reset with a draw rather
2416    /// than with the attachment's own clear.
2417    ///
2418    /// Zero on every frame that clears the whole attachment, which is every
2419    /// frame until the cadence is switched on — see
2420    /// [`MeshModules::depth_clear_pipeline`]. One over-sized triangle of one
2421    /// instance each, so it joins the full-screen draws rather than the
2422    /// indirect ones.
2423    recorded_tile_clears: u64,
2424    /// `docs/plan/55-water.md`'s bodies of water, meshed, and the ring of
2425    /// buffers every view draws them from — see [`crate::water`]. Empty until
2426    /// [`set_water`](ForwardRenderer::set_water), and an empty set records no
2427    /// pass.
2428    water: WaterBodies,
2429    /// The surface draws the last [`add_passes`](ForwardRenderer::add_passes)
2430    /// recorded for the primary camera: one indexed draw per body, each of one
2431    /// instance, so they join the direct draws on the debug draw layer's terms.
2432    recorded_water_draws: u64,
2433    /// `docs/plan/57-grass.md`'s field, its device resources and the ring of
2434    /// retirements a replaced one leaves — see [`crate::grass`]. Empty until
2435    /// [`set_grass`](ForwardRenderer::set_grass), and an empty field records no
2436    /// pass.
2437    grass: GrassScene,
2438    /// The wind block every view writes into its own ring — see
2439    /// [`set_wind`](ForwardRenderer::set_wind). Calm until a caller sets one.
2440    wind: crcbl_shaders::wind::WindParams,
2441    /// The grass draws the last [`add_passes`](ForwardRenderer::add_passes)
2442    /// recorded for the primary camera: one per tile slot per look the field
2443    /// draws.
2444    ///
2445    /// **Not among the direct draws**, unlike the water surface's: every one of
2446    /// them is an indirect call whose instance count lives in a buffer a
2447    /// dispatch wrote, so the CPU knows how many *calls* it submitted and
2448    /// nothing about how many blades came out of them.
2449    recorded_grass_draws: u64,
2450}
2451
2452/// What a partly-built [`ForwardRenderer`] has to give back.
2453///
2454/// `new` creates a dozen objects with `?` between them, and the seam's
2455/// `destroy_*` is explicit — so a failure half way through used to leak
2456/// everything created before it. The recorder's leak assertions cover the happy
2457/// path; this covers the other one.
2458#[derive(Debug, Default)]
2459struct Rollback {
2460    buffers: Vec<BufferHandle>,
2461    bind_groups: Vec<BindGroupHandle>,
2462    bind_group_layouts: Vec<BindGroupLayoutHandle>,
2463    pipeline_layouts: Vec<PipelineLayoutHandle>,
2464    pipelines: Vec<GraphicsPipelineHandle>,
2465    samplers: Vec<SamplerHandle>,
2466    /// The shadow atlas and its placeholder, which are created here rather than
2467    /// uploaded — so unlike [`Rollback::textures`] they are a plain handle each,
2468    /// with their views beside them.
2469    images: Vec<ImageHandle>,
2470    image_views: Vec<ImageViewHandle>,
2471    /// Uploaded images, which own a view each and so cannot be rolled back as
2472    /// one list of handles.
2473    textures: Vec<UploadedTexture>,
2474    /// The geometry pool, which owns two buffers, a semaphore and anything
2475    /// still staged — so it cannot be rolled back as a list of handles.
2476    pool: Option<MeshPool>,
2477    /// The instance pool, which owns one buffer per frame in flight.
2478    instances: Option<InstancePool>,
2479    /// The material table, which owns one buffer.
2480    materials: Option<MaterialTable>,
2481    /// The irradiance probe table, which owns one buffer.
2482    probes: Option<ProbeTable>,
2483    /// The irradiance probes' updater, which owns one pipeline,
2484    /// one layout and a ring of blocks — and only exists for a scene whose
2485    /// volume asked to be updated.
2486    probe_gather: Option<ProbeGather>,
2487    /// The cull and draw-argument passes, which own two pipelines and a ring of
2488    /// buffers each — and which clean themselves up on their own failure path,
2489    /// so this only carries one that was built.
2490    draws: Option<DrawGen>,
2491    /// One more of the same per shadow-atlas tile — a `Vec` rather than an
2492    /// `Option`, because a failure part way through the tiles has to release the
2493    /// ones already built.
2494    shadow_draws: Vec<DrawGen>,
2495    /// The cluster buffers, which own three buffers and are built on the
2496    /// mesh-shader path alone.
2497    clusters: Option<ClusterPool>,
2498    /// Topic 18's light list and froxel grid, which own a pipeline and a ring of
2499    /// three buffers — and which clean themselves up on their own failure path,
2500    /// so this only carries one that was built.
2501    lights: Option<LightGrid>,
2502    /// Topic 46's occlusion pair, which owns two
2503    /// pipelines, two layouts and a ring of blocks.
2504    ssao: Option<Ssao>,
2505    /// Topic 45's contact-shadow march, which owns one
2506    /// pipeline, one layout and a ring of blocks.
2507    contact_shadows: Option<ContactShadows>,
2508    /// Topic 47's depth pyramid, which owns one
2509    /// pipeline, one layout and a ring of blocks per level.
2510    hiz: Option<Hiz>,
2511    /// Topic 03 §3.3's farthest-depth pyramid,
2512    /// which owns one pipeline, one layout and — once a frame culled — a chain
2513    /// of level images.
2514    occlusion_pyramid: Option<OcclusionPyramid>,
2515    /// Topic 47's reflection march, which owns one
2516    /// pipeline, one layout and a ring of blocks.
2517    ssr: Option<Ssr>,
2518    /// The froxel volume, which owns three
2519    /// pipelines, two layouts and two rings of buffers.
2520    volumetric: Option<Volumetric>,
2521    /// Topic 43 §6's auto-exposure, which owns three
2522    /// pipelines, one layout and three rings of buffers.
2523    exposure: Option<Exposure>,
2524    /// Topic 48's bloom chain, which owns three
2525    /// pipelines, two layouts, a sampler and a ring of blocks.
2526    bloom: Option<Bloom>,
2527    /// The cheap antialiasing tier, which owns one
2528    /// pipeline, one layout, a sampler and a ring of blocks.
2529    fxaa: Option<Fxaa>,
2530    /// The higher antialiasing tier, which owns
2531    /// four compute pipelines, one graphics pipeline, two layouts and a ring of
2532    /// blocks.
2533    cmaa2: Option<Cmaa2>,
2534    upscale: Option<Upscale>,
2535    /// The background pass, which owns one pipeline, one layout and a ring of
2536    /// blocks and groups.
2537    sky_pass: Option<SkyPass>,
2538    /// The water surface's two pipelines, their layouts and a ring of blocks.
2539    water: Option<Water>,
2540    /// The grass passes' pipelines, their layouts and their rings of
2541    /// blocks.
2542    grass: Option<Grass>,
2543    /// The shadow atlas viewer, which owns one pipeline, one layout and a ring
2544    /// of blocks and groups.
2545    atlas_viewer: Option<AtlasView>,
2546    /// The camera, once [`View::build`] has made it whole — released as one,
2547    /// by [`View::destroy`].
2548    primary: Option<View>,
2549}
2550
2551impl Rollback {
2552    /// Releases everything, in the same dependency order as
2553    /// [`ForwardRenderer::destroy`].
2554    fn run(self, device: &dyn Device) {
2555        if let Some(view) = self.primary {
2556            view.destroy(device);
2557        }
2558        for texture in self.textures {
2559            texture.destroy(device);
2560        }
2561        for handle in self.samplers {
2562            device.destroy_sampler(handle);
2563        }
2564        for handle in self.image_views {
2565            device.destroy_image_view(handle);
2566        }
2567        for handle in self.images {
2568            device.destroy_image(handle);
2569        }
2570        for handle in self.pipelines {
2571            device.destroy_graphics_pipeline(handle);
2572        }
2573        for handle in self.pipeline_layouts {
2574            device.destroy_pipeline_layout(handle);
2575        }
2576        for handle in self.bind_groups {
2577            device.destroy_bind_group(handle);
2578        }
2579        for handle in self.bind_group_layouts {
2580            device.destroy_bind_group_layout(handle);
2581        }
2582        for handle in self.buffers {
2583            device.destroy_buffer(handle);
2584        }
2585        if let Some(clusters) = self.clusters {
2586            clusters.destroy(device);
2587        }
2588        for draws in self.shadow_draws {
2589            draws.destroy(device);
2590        }
2591        if let Some(lights) = self.lights {
2592            lights.destroy(device);
2593        }
2594        if let Some(atlas_viewer) = self.atlas_viewer {
2595            atlas_viewer.destroy(device);
2596        }
2597        if let Some(grass) = self.grass {
2598            grass.destroy(device);
2599        }
2600        if let Some(water) = self.water {
2601            water.destroy(device);
2602        }
2603        if let Some(sky_pass) = self.sky_pass {
2604            sky_pass.destroy(device);
2605        }
2606        if let Some(upscale) = self.upscale {
2607            upscale.destroy(device);
2608        }
2609        if let Some(cmaa2) = self.cmaa2 {
2610            cmaa2.destroy(device);
2611        }
2612        if let Some(fxaa) = self.fxaa {
2613            fxaa.destroy(device);
2614        }
2615        if let Some(bloom) = self.bloom {
2616            bloom.destroy(device);
2617        }
2618        if let Some(exposure) = self.exposure {
2619            exposure.destroy(device);
2620        }
2621        if let Some(volumetric) = self.volumetric {
2622            volumetric.destroy(device);
2623        }
2624        if let Some(ssr) = self.ssr {
2625            ssr.destroy(device);
2626        }
2627        if let Some(occlusion_pyramid) = self.occlusion_pyramid {
2628            occlusion_pyramid.destroy(device);
2629        }
2630        if let Some(hiz) = self.hiz {
2631            hiz.destroy(device);
2632        }
2633        if let Some(contact_shadows) = self.contact_shadows {
2634            contact_shadows.destroy(device);
2635        }
2636        if let Some(ssao) = self.ssao {
2637            ssao.destroy(device);
2638        }
2639        if let Some(draws) = self.draws {
2640            draws.destroy(device);
2641        }
2642        // Before the table, because its bind groups name that table's rows.
2643        if let Some(gather) = self.probe_gather {
2644            gather.destroy(device);
2645        }
2646        if let Some(table) = self.probes {
2647            table.destroy(device);
2648        }
2649        if let Some(table) = self.materials {
2650            table.destroy(device);
2651        }
2652        if let Some(pool) = self.instances {
2653            pool.destroy(device);
2654        }
2655        if let Some(pool) = self.pool {
2656            pool.destroy(device);
2657        }
2658    }
2659}
2660
2661/// What every bind group of the mesh layout names identically.
2662///
2663/// Split from [`MeshGroup`] rather than folded into it because the split *is*
2664/// the claim: a resource here cannot differ between the colour pass's group and
2665/// a cascade's, and one there must be looked at.
2666struct SharedBindings<'a> {
2667    vertices: BufferHandle,
2668    draw_constants: BufferHandle,
2669    mesh_table: BufferHandle,
2670    materials: BufferHandle,
2671    /// Bindings [`BASE_COLOR_PAGE_BINDING`], [`NORMAL_PAGE_BINDING`],
2672    /// [`MRO_PAGE_BINDING`] and [`EMISSIVE_PAGE_BINDING`] — the four material
2673    /// pages, every one read through the sampler at [`PAGE_SAMPLER_BINDING`]
2674    /// beside them — as this frame slot names them, which is what
2675    /// [`ForwardRenderer::adopt_pages`] moves one slot at a time.
2676    pages: PageBindings,
2677    /// `Some` on [`GeometryPath::MeshShader`] and on no other path, which is
2678    /// what decides whether the mesh-only bindings exist at all.
2679    clusters: Option<&'a ClusterPool>,
2680    shadow_sampler: SamplerHandle,
2681    /// Bindings [`LIGHT_LIST_BINDING`] and [`LIGHT_GRID_BINDING`], this frame's
2682    /// slots of the light ring.
2683    ///
2684    /// Shared rather than per-group, unlike the instance array beside them, and
2685    /// that is the claim: **a cascade shades nothing**, so it reads the same
2686    /// list and the same grid the colour pass does — the depth-only pipeline
2687    /// simply never looks. Two buffers per pass would be two clustering
2688    /// dispatches for one camera.
2689    lights: BufferHandle,
2690    light_grid: BufferHandle,
2691    /// Binding [`PROBE_TABLE_BINDING`], **this frame's slot** of the irradiance
2692    /// grid's ring.
2693    ///
2694    /// Shared across the *groups of one frame* rather than across frames, which
2695    /// is the light list's arrangement exactly: a cascade shades nothing, so it
2696    /// reads the same rows the colour pass does and the depth-only pipeline
2697    /// simply never looks. What it is not is shared across the ring — see
2698    /// [`crate::probe`] for why the table is per-frame at all.
2699    probes: BufferHandle,
2700    /// Binding [`LEVEL_GROUP_TABLE_BINDING`], `DrawGen`'s packed table buffer.
2701    ///
2702    /// Shared rather than per-group for the probe grid's reason exactly: the
2703    /// regions are written when a mesh becomes resident and never per frame, so
2704    /// a cascade and the colour pass read the same words. What varies between
2705    /// them is the *budget* the mesh stage projects against, and that rides in
2706    /// each pass's own frame block.
2707    tables: BufferHandle,
2708    /// Binding [`SPECULAR_DFG_BINDING`], the split-sum `DFG` pair — see
2709    /// [`ForwardRenderer::specular_dfg`].
2710    ///
2711    /// Shared rather than per-group for the probe grid's reason and more
2712    /// strongly: it is cooked into the binary, uploaded once at build and
2713    /// identical for every view this engine will ever draw. A cascade names it
2714    /// and never looks.
2715    specular_dfg: ImageViewHandle,
2716    /// Binding [`LTC_TABLE_BINDING`], the area lights' fit — see
2717    /// [`ForwardRenderer::ltc_table`]. Shared for the table above it's reason.
2718    ltc_table: ImageViewHandle,
2719}
2720
2721/// The half of a mesh-layout bind group that differs between the colour pass and
2722/// each shadow cascade.
2723///
2724/// One description for both, so the two cannot drift: a cascade's group is the
2725/// colour pass's with six resources swapped, and swapping the wrong five of them
2726/// is a shadow map rendered from the camera — which looks like a shadow map.
2727struct MeshGroup {
2728    /// Binding 0. The colour pass's frame block, or a cascade's copy whose
2729    /// `view_proj` is that cascade's matrix.
2730    uniforms: BufferHandle,
2731    /// Binding 2. This frame's slot of the instance ring.
2732    instances: BufferHandle,
2733    /// Binding 5. Whose survivors this group draws.
2734    runs: BufferHandle,
2735    /// Binding 12, on the mesh path: the same survivors' indirect arguments,
2736    /// read as data.
2737    args: BufferHandle,
2738    /// Binding 13, where there is an amplification stage: the frustum it culls
2739    /// clusters against.
2740    cull_params: BufferHandle,
2741    /// Binding 14, likewise: what it counts survivors into.
2742    cull_stats: BufferHandle,
2743    /// Binding 18, likewise: the cut the descent chose, one word per resident
2744    /// cluster. `None` exactly where there is no amplification stage, which is
2745    /// where the layout has no CLUSTER_SELECTION_BINDING either.
2746    ///
2747    /// **A buffer per pass**, not one shared: the colour pass is recorded last,
2748    /// so a cascade writing the camera's would leave nothing of its own to read.
2749    /// See [`ForwardRenderer::shadow_selection`].
2750    cluster_selection: Option<BufferHandle>,
2751    /// Binding 19, likewise: topic 25's hysteresis state, which the
2752    /// draw-argument pass wrote this frame and this one only reads.
2753    ///
2754    /// **A buffer per pass** as well, because the colour pass and a cascade
2755    /// judge the same groups under different budgets — see
2756    /// [`TileBuffers::group_state`].
2757    group_state: Option<BufferHandle>,
2758    /// Binding [`SHADOW_ATLAS_BINDING`]. The atlas for the pass that reads it,
2759    /// and the placeholder for the pass that writes it — see
2760    /// [`ForwardRenderer::shadow_placeholder`], which is where that is argued.
2761    shadow_map: ImageViewHandle,
2762    /// Binding [`AMBIENT_OCCLUSION_BINDING`]. The blurred occlusion channel for
2763    /// a forward pass that computed one, and the white placeholder everywhere
2764    /// else — see [`ForwardRenderer::ambient_occlusion_placeholder`].
2765    ///
2766    /// **Every group built at `build` names the placeholder**, including the
2767    /// camera's: the occlusion image may be a graph transient whose view exists
2768    /// only at execute time, so the camera's group is rebuilt against whatever
2769    /// the frame bound inside the forward pass and cached — the shape
2770    /// [`View::tonemap_groups`] already has.
2771    ambient_occlusion: ImageViewHandle,
2772    /// Binding [`CONTACT_SHADOW_BINDING`]. The contact-shadow channel for a
2773    /// forward pass that marched one, and the white placeholder everywhere else
2774    /// — see [`ForwardRenderer::contact_shadow_placeholder`].
2775    ///
2776    /// [`MeshGroup::ambient_occlusion`]'s terms exactly, including that every
2777    /// group built at `build` names the placeholder.
2778    contact_shadow: ImageViewHandle,
2779    /// Binding [`PROBE_VISIBILITY_BINDING`]. The captured per-probe visibility
2780    /// maps for the camera's pass, and the one-texel placeholder everywhere
2781    /// else — see [`ForwardRenderer::probe_visibility_placeholder`].
2782    ///
2783    /// [`MeshGroup::ambient_occlusion`]'s terms, with one difference: the image
2784    /// is not a graph transient but an ordinary uploaded texture, so what makes
2785    /// this a per-frame swap is the console switch and whether a capture has
2786    /// happened yet — neither of which is known at `build`.
2787    probe_visibility: ImageViewHandle,
2788}
2789
2790impl MeshGroup {
2791    fn entries(&self, shared: &SharedBindings<'_>) -> Vec<BindGroupEntry> {
2792        let mut entries = vec![
2793            BindGroupEntry {
2794                binding: 0,
2795                array_index: 0,
2796                resource: BindingResource::whole_buffer(self.uniforms),
2797            },
2798            BindGroupEntry {
2799                binding: 1,
2800                array_index: 0,
2801                resource: BindingResource::whole_buffer(shared.vertices),
2802            },
2803            BindGroupEntry {
2804                binding: 2,
2805                array_index: 0,
2806                // **This frame's slot of the instance ring, not a shared
2807                // buffer.** Binding one buffer here for every group would undo
2808                // the ring and reintroduce the cross-submission
2809                // read-after-write hazard it exists to prevent.
2810                resource: BindingResource::whole_buffer(self.instances),
2811            },
2812            BindGroupEntry {
2813                binding: 3,
2814                array_index: 0,
2815                // **One block, not the whole buffer.** The binding is dynamic,
2816                // so the bind's offset is added on top of this one and both
2817                // Vulkan and WebGPU require `offset + dynamic + size` to stay
2818                // inside the buffer — bound whole, the very first non-zero
2819                // dynamic offset would be out of range.
2820                resource: BindingResource::Buffer {
2821                    buffer: shared.draw_constants,
2822                    offset: 0,
2823                    size: DRAW_CONSTANTS_BLOCK,
2824                },
2825            },
2826            BindGroupEntry {
2827                binding: 4,
2828                array_index: 0,
2829                // The same table in every group, unlike the instance array
2830                // above it: the pool writes an entry when a mesh is uploaded or
2831                // freed, neither of which happens between frames here.
2832                resource: BindingResource::whole_buffer(shared.mesh_table),
2833            },
2834            BindGroupEntry {
2835                binding: 5,
2836                array_index: 0,
2837                // Whose cull this group draws from. This is the binding a
2838                // cascade's group differs in most consequentially: it is what
2839                // makes the shadow pass draw what the *light* can see rather
2840                // than what the camera can.
2841                resource: BindingResource::whole_buffer(self.runs),
2842            },
2843            BindGroupEntry {
2844                binding: 6,
2845                array_index: 0,
2846                resource: BindingResource::whole_buffer(shared.materials),
2847            },
2848            BindGroupEntry {
2849                binding: BASE_COLOR_PAGE_BINDING,
2850                array_index: 0,
2851                // **One entry, `array_index: 0`**, because the page is one
2852                // image and the layer is chosen in the shader. A bindless array
2853                // would be one entry per texture at ascending array indices,
2854                // which is the write path `BindGroupEntry`'s own docs describe
2855                // and the one this pass does not take.
2856                resource: BindingResource::ImageView(
2857                    shared.pages.views[PageKind::BaseColor.index()],
2858                ),
2859            },
2860            BindGroupEntry {
2861                binding: PAGE_SAMPLER_BINDING,
2862                array_index: 0,
2863                resource: BindingResource::Sampler(shared.pages.sampler),
2864            },
2865        ];
2866        if let Some(clusters) = shared.clusters {
2867            entries.extend([
2868                BindGroupEntry {
2869                    binding: CLUSTERS_BINDING,
2870                    array_index: 0,
2871                    // The same three buffers in every group, on the mesh table's
2872                    // terms: clusters are written when the pool is built and
2873                    // never again.
2874                    resource: BindingResource::whole_buffer(clusters.clusters()),
2875                },
2876                BindGroupEntry {
2877                    binding: CLUSTER_VERTICES_BINDING,
2878                    array_index: 0,
2879                    resource: BindingResource::whole_buffer(clusters.vertices()),
2880                },
2881                BindGroupEntry {
2882                    binding: CLUSTER_CORNERS_BINDING,
2883                    array_index: 0,
2884                    resource: BindingResource::whole_buffer(clusters.corners()),
2885                },
2886                BindGroupEntry {
2887                    binding: CLUSTER_DRAW_ARGS_BINDING,
2888                    array_index: 0,
2889                    // **Arguments read as data.** The mesh path records no
2890                    // indirect draw at all; what it wants out of this buffer is
2891                    // the one word only the GPU knows — how many instances
2892                    // survived into each bucket.
2893                    resource: BindingResource::whole_buffer(self.args),
2894                },
2895            ]);
2896        }
2897        // Both mesh entry points retain these native buffer arguments even
2898        // when no amplification stage reads them.
2899        if shared.clusters.is_some() {
2900            entries.extend([
2901                BindGroupEntry {
2902                    binding: CLUSTER_CULL_BINDING,
2903                    array_index: 0,
2904                    resource: BindingResource::whole_buffer(self.cull_params),
2905                },
2906                BindGroupEntry {
2907                    binding: CLUSTER_CULL_STATS_BINDING,
2908                    array_index: 0,
2909                    resource: BindingResource::whole_buffer(self.cull_stats),
2910                },
2911            ]);
2912        }
2913        entries.push(BindGroupEntry {
2914            binding: SHADOW_ATLAS_BINDING,
2915            array_index: 0,
2916            resource: BindingResource::ImageView(self.shadow_map),
2917        });
2918        entries.push(BindGroupEntry {
2919            binding: SHADOW_SAMPLER_BINDING,
2920            array_index: 0,
2921            resource: BindingResource::Sampler(shared.shadow_sampler),
2922        });
2923        // Mesh-only buffers are sorted after the common fragment prefix below.
2924        if let Some(clusters) = shared.clusters {
2925            entries.push(BindGroupEntry {
2926                binding: CLUSTER_SELECT_BINDING,
2927                array_index: 0,
2928                // Bound with the geometry rather than with the cull, because
2929                // `vertex_base` *is* geometry: it is which level of a DAG a
2930                // cluster's vertices live in, and both mesh entry points resolve
2931                // a vertex through it.
2932                resource: BindingResource::whole_buffer(clusters.selection()),
2933            });
2934        }
2935        if let Some(selection) = self.cluster_selection {
2936            entries.push(BindGroupEntry {
2937                binding: CLUSTER_SELECTION_BINDING,
2938                array_index: 0,
2939                resource: BindingResource::whole_buffer(selection),
2940            });
2941        }
2942        if let Some(state) = self.group_state {
2943            entries.push(BindGroupEntry {
2944                binding: CLUSTER_GROUP_STATE_BINDING,
2945                array_index: 0,
2946                resource: BindingResource::whole_buffer(state),
2947            });
2948        }
2949        // Topic 18's pair, on every path and in every group — see the layout,
2950        // which has no configuration that omits them either.
2951        entries.push(BindGroupEntry {
2952            binding: LIGHT_LIST_BINDING,
2953            array_index: 0,
2954            resource: BindingResource::whole_buffer(shared.lights),
2955        });
2956        entries.push(BindGroupEntry {
2957            binding: LIGHT_GRID_BINDING,
2958            array_index: 0,
2959            resource: BindingResource::whole_buffer(shared.light_grid),
2960        });
2961        // Shared fragment textures and probes retain their raster bindings.
2962        entries.push(BindGroupEntry {
2963            binding: AMBIENT_OCCLUSION_BINDING,
2964            array_index: 0,
2965            resource: BindingResource::ImageView(self.ambient_occlusion),
2966        });
2967        // And the irradiance grid past it — see [`PROBE_TABLE_BINDING`].
2968        entries.push(BindGroupEntry {
2969            binding: PROBE_TABLE_BINDING,
2970            array_index: 0,
2971            resource: BindingResource::whole_buffer(shared.probes),
2972        });
2973        // Group records are present on both mesh paths, matching the layout.
2974        if shared.clusters.is_some() {
2975            entries.push(BindGroupEntry {
2976                binding: LEVEL_GROUP_TABLE_BINDING,
2977                array_index: 0,
2978                resource: BindingResource::whole_buffer(shared.tables),
2979            });
2980        }
2981        // The DFG texture is read by the fragment stage of every path.
2982        entries.push(BindGroupEntry {
2983            binding: SPECULAR_DFG_BINDING,
2984            array_index: 0,
2985            resource: BindingResource::ImageView(shared.specular_dfg),
2986        });
2987        // And §2's normal page above that, on the same ascending terms — see
2988        // [`NORMAL_PAGE_BINDING`]. Unconditional and `array_index: 0` for
2989        // binding 7's reason: one image, and the layer is chosen in the shader.
2990        entries.push(BindGroupEntry {
2991            binding: NORMAL_PAGE_BINDING,
2992            array_index: 0,
2993            resource: BindingResource::ImageView(shared.pages.views[PageKind::Normal.index()]),
2994        });
2995        // And the area lights' table above that, on the same ascending terms —
2996        // see [`LTC_TABLE_BINDING`].
2997        entries.push(BindGroupEntry {
2998            binding: LTC_TABLE_BINDING,
2999            array_index: 0,
3000            resource: BindingResource::ImageView(shared.ltc_table),
3001        });
3002        // And the contact-shadow channel above that, last of the set and on the
3003        // same ascending terms — see [`CONTACT_SHADOW_BINDING`].
3004        entries.push(BindGroupEntry {
3005            binding: CONTACT_SHADOW_BINDING,
3006            array_index: 0,
3007            resource: BindingResource::ImageView(self.contact_shadow),
3008        });
3009        // And the probe visibility maps above that, on the same ascending terms
3010        // — see [`PROBE_VISIBILITY_BINDING`].
3011        entries.push(BindGroupEntry {
3012            binding: PROBE_VISIBILITY_BINDING,
3013            array_index: 0,
3014            resource: BindingResource::ImageView(self.probe_visibility),
3015        });
3016        // And §2's other two pages above that, last of the set and on the same
3017        // ascending terms — see [`MRO_PAGE_BINDING`] and
3018        // [`EMISSIVE_PAGE_BINDING`]. Unconditional and `array_index: 0` for the
3019        // normal page's reason: one image apiece, and the layer is chosen in
3020        // the shader.
3021        entries.push(BindGroupEntry {
3022            binding: MRO_PAGE_BINDING,
3023            array_index: 0,
3024            resource: BindingResource::ImageView(
3025                shared.pages.views[PageKind::MetallicRoughnessOcclusion.index()],
3026            ),
3027        });
3028        entries.push(BindGroupEntry {
3029            binding: EMISSIVE_PAGE_BINDING,
3030            array_index: 0,
3031            resource: BindingResource::ImageView(shared.pages.views[PageKind::Emissive.index()]),
3032        });
3033        entries.sort_by_key(|entry| entry.binding);
3034        entries
3035    }
3036}
3037
3038/// The two `ArrayPages` images every group of the mesh layout names, as the
3039/// graph knows them.
3040///
3041/// One value rather than two arguments because the two travel together
3042/// everywhere: every pass that declares one declares the other, and a pass
3043/// handed them the wrong way round would order a caller's copy into the wrong
3044/// image — which is a barrier bug, and therefore one that reproduces on one
3045/// backend and not the others.
3046#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3047struct MaterialPages {
3048    /// §3.2's base-colour page — [`ForwardRenderer::base_color_page_import`].
3049    base_color: ImageId,
3050    /// §2's normal page — [`ForwardRenderer::normal_page_import`].
3051    normal: ImageId,
3052    /// §2's metallic-roughness-occlusion page —
3053    /// [`ForwardRenderer::mro_page_import`].
3054    mro: ImageId,
3055    /// §2's emissive page — [`ForwardRenderer::emissive_page_import`].
3056    emissive: ImageId,
3057}
3058
3059/// Everything [`ForwardRenderer::add_shadow_pass`] declares and does not write,
3060/// as the graph knows it.
3061///
3062/// One value rather than an argument apiece for [`MaterialPages`]' reason, and
3063/// the list grew past what an argument list should be the moment the probe rows
3064/// joined it: each of these is in every cascade's bind group and read by no
3065/// cascade, so what the pass does with them is one thing — declare them, so the
3066/// graph can order whoever writes them against these draws.
3067#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3068struct ShadowReads {
3069    /// The occlusion placeholder every cascade's group stands the real channel
3070    /// in for — [`ForwardRenderer::ambient_occlusion_placeholder`].
3071    occlusion_placeholder: ImageId,
3072    /// §3.2's and §2's pages, which the cascades name and never sample.
3073    pages: MaterialPages,
3074    /// The skinned vertex region, where a frame has one — the cascades pull the
3075    /// same geometry the colour pass does.
3076    skinned: Option<BufferId>,
3077    /// This frame's slot of the probe ring — see [`crate::probe`].
3078    probes: BufferId,
3079}
3080
3081/// What the mesh pass's bind-group layout is called.
3082///
3083/// Named rather than written twice because a test asserts on it: the layout's
3084/// *binding numbers* are what `crcbl-mtl` turns into Metal argument-table
3085/// indices by counting, so `the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage`
3086/// has to find this one layout among the recorder's.
3087const MESH_LAYOUT_LABEL: &str = "mesh frame";
3088
3089/// Imports a buffer a pass both reads and writes, carried from one frame on
3090/// its slot to the next: it arrives in the state the previous frame that used
3091/// the slot left it in, and that is the state it is declared to leave in.
3092///
3093/// A record of the cut or a statistics sink, which a pass writes and the next
3094/// frame on the same slot writes again — a barrier naming `Undefined` as its
3095/// source would carry no source scope and order this frame's write against
3096/// nothing.
3097fn import_read_write(graph: &mut RenderGraph<'_>, label: &str, buffer: BufferHandle) -> BufferId {
3098    graph.import_buffer(
3099        label,
3100        ImportedBuffer {
3101            buffer,
3102            initial: ResourceState::ShaderReadWrite,
3103            final_state: ResourceState::ShaderReadWrite,
3104        },
3105    )
3106}
3107
3108/// Declares the buffers a geometry pass reads to find its draws.
3109///
3110/// The other half of [`BucketDraws`]: what the *graph* has to be told, where that
3111/// struct is what the encoder is told. Three passes declare exactly this set, and
3112/// the seam calls the barrier it produces the single most important one in a
3113/// GPU-driven frame — its absence produces "sometimes nothing draws".
3114///
3115/// A caller with a cluster-selection buffer of its own appends it; that is the
3116/// one declaration that differs between the colour pass, a cascade and the depth
3117/// prepass.
3118fn read_draw_sources<'g, 'a>(
3119    pass: PassBuilder<'g, 'a>,
3120    draws: &GeneratedDraws,
3121    emit: EmitTail,
3122) -> PassBuilder<'g, 'a> {
3123    // The buffers the draws come out of. Declaring them is what makes the graph
3124    // transition them out of the compute pass's `ShaderReadWrite`.
3125    let pass = pass.read_buffer(draws.runs_id);
3126    if emit.is_mesh() {
3127        // **The same arguments, read as data rather than executed**, which is
3128        // what the stages use to bound the run of surviving instances they index.
3129        // The per-bucket draw *counts* are not read at all, because nothing here
3130        // is a draw whose count could come from memory.
3131        //
3132        // The dispatch *extents* are a real indirect read — one structure per
3133        // bucket, written by the same pass. They are in a **different buffer**
3134        // from the arguments above and that separation is load-bearing: a
3135        // resource is in exactly one state per pass and these two are in
3136        // different ones. They share a buffer with the counts instead, which
3137        // this path does not read at all — see [`GeneratedDraws::counts`].
3138        let pass = pass
3139            .read_buffer(draws.args_id)
3140            .use_buffer(draws.counts_id, ResourceState::IndirectArgument);
3141        // The amplification stage counts its survivors into the culling
3142        // statistics, which the draw-argument pass read a moment ago — so this
3143        // is a write-after-read the graph has to order, and declaring it is
3144        // the whole of how it learns to.
3145        //
3146        // Topic 25's hysteresis state is read here and written by
3147        // the draw-argument pass a moment ago. Declaring it is what orders the
3148        // two — and what puts it back into `ShaderReadWrite` at the end of the
3149        // graph, which is where the next frame's draw-argument pass expects to
3150        // find it.
3151        //
3152        // **Declared on the whole mesh path, not only where there is an
3153        // amplification stage**, because that is where the bind group now
3154        // names both — see the layout, which is where the Metal argument-table
3155        // arithmetic that forced it is argued. A buffer bound writable and
3156        // never transitioned is a descriptor in the wrong resource state, which
3157        // is what the graph exists to prevent.
3158        pass.use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite)
3159            .read_buffer(draws.group_state_id)
3160    } else {
3161        pass.use_buffer(draws.args_id, ResourceState::IndirectArgument)
3162            .use_buffer(draws.counts_id, ResourceState::IndirectArgument)
3163    }
3164}
3165
3166/// What one [`MeshDesc`](crate::scene::MeshDesc) became once it was resident.
3167///
3168/// One of these per description mesh, in description order — so a mesh's index
3169/// here is its index there, which is what lets the bucket table, the level
3170/// tables and the cluster pool all be filled in by walking one list.
3171struct ResidentMesh {
3172    /// This mesh's table ids, finest first: one entry for a flat mesh, one per
3173    /// level for a DAG. Never empty.
3174    ///
3175    /// Every level is its own vertex range and so its own table entry. Level 0's
3176    /// id is the one the *instance* carries and the one the cull pass reads a
3177    /// bounding box out of; the coarser ones are named by the bucket table on a
3178    /// path that takes a uniform cut, and by nothing at all on the mesh path,
3179    /// where a cluster reaches its own level through
3180    /// [`vertex_bases`](Self::vertex_bases) instead.
3181    levels: Vec<u32>,
3182    /// Per level, how far that level's vertices start past level 0's — so a flat
3183    /// mesh's single entry is zero.
3184    ///
3185    /// What [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`] holds,
3186    /// and the whole of what makes a DAG drawable from one instance: the mesh
3187    /// stage adds this to the instance's own `base_vertex`, so a cut spanning
3188    /// three levels reads three different vertex ranges out of one pool.
3189    vertex_bases: Vec<u32>,
3190    /// Level 0's pool handle, for a mesh that can be **skinned** — and [`None`]
3191    /// for a [`Geometry::Dag`].
3192    ///
3193    /// A DAG is refused because its coarser levels are separate vertex runs no
3194    /// skinning dispatch writes: an instance drawn out of a skinned region
3195    /// resolves every level through [`vertex_bases`](Self::vertex_bases) added
3196    /// to the region's base, which for anything but level 0 is memory the
3197    /// dispatch never touched.
3198    skinnable: Option<MeshHandle>,
3199}
3200
3201impl ResidentMesh {
3202    /// The table id an instance of this mesh carries: **level 0's**, whatever
3203    /// the geometry path, because it is the entry `cull.slang` reads a bounding
3204    /// box out of and the coarser levels approximate the same surface inside the
3205    /// same box.
3206    fn id(&self) -> u32 {
3207        self.levels[0]
3208    }
3209}
3210
3211/// One skinned object the renderer re-points every frame: the instance, and the
3212/// base vertex it draws out of under each parity.
3213///
3214/// The bases are copied out of the [`SkinnedMesh`] rather than borrowed from it,
3215/// so placing an object does not tie the renderer's lifetime to the caller's
3216/// reservation — the renderer never needs the region again, only the two
3217/// numbers.
3218#[derive(Clone, Copy, Debug)]
3219struct SkinnedInstance {
3220    handle: InstanceHandle,
3221    /// Indexed by parity, in [`crate::skinning::SkinnedRegion::base`]'s
3222    /// indexing — so the half a frame of parity `p` draws out of is
3223    /// `bases[p & 1]` and the half the frame before it filled is
3224    /// `bases[(p ^ 1) & 1]`, which is
3225    /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base)'s
3226    /// answer for the same `p`.
3227    bases: [u32; 2],
3228    /// Whether a frame has already pointed this entry at a half of the region
3229    /// it now names.
3230    ///
3231    /// **What makes the previous base meaningful.** The half a frame did not
3232    /// write holds whatever its reservation came with until a dispatch fills
3233    /// it, so an object's first frame out of a region has no previous
3234    /// deformation to point at — naming that half would give it a motion vector
3235    /// against undefined vertices. Such an entry is put at rest instead, which
3236    /// is the rule [`InstancePool::insert`](crate::instance_pool::InstancePool::insert)
3237    /// applies to `previous_transform` for the same reason: a spawn did not
3238    /// travel from anywhere.
3239    pointed: bool,
3240}
3241
3242/// The two base vertices an object drawn out of `mesh` alternates between, in
3243/// [`SkinnedInstance::bases`]' indexing.
3244fn skinned_bases(mesh: &SkinnedMesh) -> [u32; 2] {
3245    [mesh.region().base(0), mesh.region().base(1)]
3246}
3247
3248/// One shadow cull's per-frame buffers, read out of its [`DrawGen`] before that
3249/// generator is handed to the rollback.
3250struct TileBuffers {
3251    runs: Vec<BufferHandle>,
3252    args: Vec<BufferHandle>,
3253    cull_params: Vec<BufferHandle>,
3254    cull_stats: Vec<BufferHandle>,
3255    /// This cull's own hysteresis state, and not the camera's.
3256    ///
3257    /// A shadow view selects from the camera's eye at the camera's scale, like
3258    /// the colour pass, but under budgets [`SHADOW_LOD_BIAS`] times as large — so
3259    /// it reaches a different answer for the same group, and an answer carried
3260    /// between frames needs somewhere of its own to be carried. Sharing the
3261    /// camera's buffer would be two rules writing one history and each undoing
3262    /// the other's band every frame.
3263    ///
3264    /// One per cull rather than one for the shadow pass, even though every one of
3265    /// them selects identically: each cull is its own [`DrawGen`], and one buffer
3266    /// between them would be several dispatches writing one element with nothing
3267    /// ordering them.
3268    ///
3269    /// **This is what a cull costs that is not a dispatch.** It is
3270    /// [`Capacities::instances`](crate::scene::Capacities::instances) × the
3271    /// resident group count words of device-local
3272    /// memory, held for the renderer's whole life whether anything is drawn
3273    /// through it or not, and it is the reason [`shadow::LIGHT_SLOTS`] is a
3274    /// budget rather than "however many lights the scene has" — and the reason a
3275    /// point light's six faces share one of these rather than owning six.
3276    group_state: BufferHandle,
3277}
3278
3279impl ForwardRenderer {
3280    /// Builds both pipelines and makes [`scene::demo`] resident.
3281    ///
3282    /// [`ForwardRenderer::with_scene`] with the engine's own description, and
3283    /// nothing else — so the frame this draws is the one the golden suite has
3284    /// always compared, and every existing caller is untouched.
3285    ///
3286    /// `target_format` must be the format the tonemap pass will render into —
3287    /// dynamic rendering checks pipeline and attachment formats against each
3288    /// other at pass-begin time, not at creation.
3289    ///
3290    /// # Errors
3291    ///
3292    /// [`HalError`], on [`ForwardRenderer::with_scene`]'s terms.
3293    pub fn new(
3294        device: &dyn Device,
3295        queue: QueueHandle,
3296        target_format: Format,
3297    ) -> Result<Self, HalError> {
3298        Self::with_scene(device, queue, target_format, &scene::demo())
3299    }
3300
3301    /// Builds both pipelines and makes `scene` resident.
3302    ///
3303    /// Everything in the description is created here and never grows: the
3304    /// geometry pools, the cluster pool, the material table, the page, the
3305    /// instance array and the bucket table are all sized and filled once. See
3306    /// [`crate::scene`] for why that split is where the seam is, and for the
3307    /// four places a description's *order* decides what the frame looks like.
3308    ///
3309    /// `target_format` must be the format the tonemap pass will render into —
3310    /// dynamic rendering checks pipeline and attachment formats against each
3311    /// other at pass-begin time, not at creation.
3312    ///
3313    /// # No description is too small
3314    ///
3315    /// One mesh and one material row is a scene, and so is
3316    /// [`scene::demo`]'s four and three. Nothing on this type names a
3317    /// description entry by position any more — the five `set_*` demo wrappers
3318    /// that did are gone, and [`ForwardRenderer::add_instance`] takes the mesh
3319    /// and the row a caller wrote its **own** description in.
3320    ///
3321    /// # Errors
3322    ///
3323    /// [`HalError::InvalidDescriptor`] if the description cannot be made
3324    /// resident as written: a page layer that is not its kind's extent's worth of
3325    /// RGBA8, a page kind holding layers at no extent, a material row naming a
3326    /// layer that kind's page has not got, a DAG carrying a vertex array for anything but each of its
3327    /// levels, a cluster array with a read outside itself in it (see
3328    /// [`MeshClusters::check`]), or more vertices, indices, mesh table entries or
3329    /// material rows than [`SceneDesc::capacities`] reserves — that last naming the pool, the
3330    /// capacity and what the description needs, because the answer to it is to
3331    /// raise the number. Every one of those is settled **before the first device
3332    /// object exists**, so a refusal leaks nothing.
3333    ///
3334    /// [`HalError`] otherwise, from any seam call — including the geometry a
3335    /// pool refuses for itself, such as vertex bytes that are not a whole number
3336    /// of vertices. A backend that cannot build a pipeline says so here rather
3337    /// than drawing nothing later, and a failure part-way through releases
3338    /// everything already created, so a caller that retries or exits leaves
3339    /// nothing behind.
3340    pub fn with_scene(
3341        device: &dyn Device,
3342        queue: QueueHandle,
3343        target_format: Format,
3344        scene: &SceneDesc<'_>,
3345    ) -> Result<Self, HalError> {
3346        Self::with_scene_serviced(device, queue, target_format, scene, &mut || {})
3347    }
3348
3349    /// [`ForwardRenderer::with_scene`], calling `service` between the steps of
3350    /// the build so the thread running it can keep its window alive.
3351    ///
3352    /// # What it is for: a build on the thread that owns the window
3353    ///
3354    /// The build needs the device, so it runs on whichever thread holds it —
3355    /// for a game that is the loop thread, which also owns the window, and a
3356    /// desktop marks a window hung when its thread takes no message for a few
3357    /// seconds (see `crcbl_shell::Shell::keep_alive`). A game passes
3358    /// `&mut || shell.keep_alive()` here and the window keeps answering for the
3359    /// whole build.
3360    ///
3361    /// # Where it is called
3362    ///
3363    /// Where the time is, which was measured rather than guessed. With a cold
3364    /// driver shader cache — a player's first launch, or the first after a
3365    /// driver update — **pipeline creation is most of the build**. Measured in
3366    /// 2026-09 on an RX 7900 XTX, release, building one glTF scene: 2.2 to 2.4 s
3367    /// on Vulkan and 1.9 to 2.2 s on D3D12 cold against 0.25 s warm, while the
3368    /// mesh and page uploads took about 0.1 s either way. So `service` runs
3369    /// after every mesh upload (each level of a DAG), after every page layer's
3370    /// mip chain and each page's upload, after each of the camera's
3371    /// post-processing subsystems, before every mesh-pass and grass pipeline,
3372    /// and between the build's other phases.
3373    ///
3374    /// **The longest gap left is one pipeline**, and a pipeline cannot be
3375    /// split: on that scene, cold, it was the forward pass's colour pipeline
3376    /// at 0.31 s on Vulkan and 0.36 s on D3D12, where the build without calls
3377    /// had been one gap of 2 s. Warm, the longest was about 0.04 s. A machine
3378    /// eight times slower under contention still calls back inside the five
3379    /// seconds Windows allows.
3380    ///
3381    /// `service` sees nothing of the build and cannot touch the renderer or the
3382    /// scene. Whatever reaches the window meanwhile — input, a resize, a close
3383    /// request — is the caller's to keep for later, as
3384    /// `crcbl_shell::Shell::keep_alive` does.
3385    ///
3386    /// # Errors
3387    ///
3388    /// [`ForwardRenderer::with_scene`]'s, on its terms: a failure part-way
3389    /// through releases everything already created.
3390    pub fn with_scene_serviced(
3391        device: &dyn Device,
3392        queue: QueueHandle,
3393        target_format: Format,
3394        scene: &SceneDesc<'_>,
3395        service: &mut dyn FnMut(),
3396    ) -> Result<Self, HalError> {
3397        Self::build_on_path(
3398            device,
3399            queue,
3400            target_format,
3401            scene,
3402            device.preferred_geometry_path(),
3403            service,
3404        )
3405    }
3406
3407    /// Builds exactly the requested geometry tail, independently of the device's
3408    /// performance preference. Capabilities remain available to other callers.
3409    ///
3410    /// # Errors
3411    ///
3412    /// Returns [`HalError::UnsupportedFeatures`] before creating device objects
3413    /// when the requested tail lacks its required feature. Other failures follow
3414    /// [`Self::with_scene`]'s rollback contract.
3415    pub fn with_scene_on_path(
3416        device: &dyn Device,
3417        queue: QueueHandle,
3418        target_format: Format,
3419        scene: &SceneDesc<'_>,
3420        geometry_path: GeometryPath,
3421    ) -> Result<Self, HalError> {
3422        Self::build_on_path(
3423            device,
3424            queue,
3425            target_format,
3426            scene,
3427            geometry_path,
3428            &mut || {},
3429        )
3430    }
3431
3432    /// The body of [`Self::with_scene_on_path`] and
3433    /// [`Self::with_scene_serviced`], calling `service` where the latter
3434    /// documents.
3435    fn build_on_path(
3436        device: &dyn Device,
3437        queue: QueueHandle,
3438        target_format: Format,
3439        scene: &SceneDesc<'_>,
3440        geometry_path: GeometryPath,
3441        service: &mut dyn FnMut(),
3442    ) -> Result<Self, HalError> {
3443        let required = match geometry_path {
3444            GeometryPath::MeshShader => crcbl_hal::Features::MESH_SHADER,
3445            GeometryPath::IndirectCount => crcbl_hal::Features::DRAW_INDIRECT_COUNT,
3446            GeometryPath::IndirectPerBatch => crcbl_hal::Features::empty(),
3447        };
3448        let missing = required.difference(device.caps().features);
3449        if !missing.is_empty() {
3450            return Err(HalError::UnsupportedFeatures { missing });
3451        }
3452        let mut rollback = Rollback::default();
3453        match Self::build(
3454            device,
3455            queue,
3456            target_format,
3457            scene,
3458            geometry_path,
3459            &mut rollback,
3460            service,
3461        ) {
3462            Ok(renderer) => Ok(renderer),
3463            Err(error) => {
3464                rollback.run(device);
3465                Err(error)
3466            }
3467        }
3468    }
3469
3470    /// Everything `build` needs to be true of a description, checked **before
3471    /// the first device object exists**.
3472    ///
3473    /// That placement is the whole design of this function. `build` hands the
3474    /// geometry pool and the material table to the rollback and creates a dozen
3475    /// objects with `?` between them; a check that ran part way down that list
3476    /// would be a new early exit on the wrong side of a handover, and a rejected
3477    /// description would leak two device-local buffers. Run from the top of
3478    /// `build`, a refusal costs nothing to unwind because nothing was made.
3479    ///
3480    /// # Errors
3481    ///
3482    /// [`HalError::InvalidDescriptor`] naming the entry that is wrong and what
3483    /// is wrong with it.
3484    fn check_scene(scene: &SceneDesc<'_>) -> Result<(), HalError> {
3485        let refuse = |what: String| Err(HalError::InvalidDescriptor(what));
3486        // A renderer draws meshes, and every table below is sized from them:
3487        // with none, the mesh table's sizing has no level to take a maximum
3488        // of. A scene that draws only the sky is one with meshes and no
3489        // instances.
3490        if scene.meshes.is_empty() {
3491            return refuse(
3492                "a scene description needs at least one mesh; one with meshes and no \
3493                 instances draws only the sky"
3494                    .to_owned(),
3495            );
3496        }
3497        // Every layer's length against its own kind's extent, and layers at no
3498        // extent at all. Checked by the type that owns the page rather than
3499        // here, because that is where a page can be built wrong and where the
3500        // check can be made to fail; see `PageDesc::check`.
3501        scene.page.check()?;
3502        // The probe grid's counts against the rows it carries, which is what
3503        // bounds the shader's fetch. Checked by the type that owns the grid, on
3504        // `PageDesc::check`'s terms exactly — see `ProbeGrid::check`.
3505        scene.probes.check()?;
3506        // A row naming a layer the page does not have is an out-of-range sample,
3507        // which nothing below the seam reports.
3508        //
3509        // **A column carrying `NO_PAGE` is exempt**, and it is the only exempt
3510        // value: it is a sentinel rather than an index — `0xFFFF`, one past
3511        // `mesh::MAX_PAGE_LAYER`, so no page can grow to hold it — and the
3512        // fragment stage never reads a page for it. Exempting it here is what
3513        // lets a material name no texture without the page having to carry a
3514        // layer for it to point at — or, since row (d), having to exist at all.
3515        //
3516        // **Per kind**, because the kinds are separate images with separate
3517        // layer lists and separate extents: a row pointed at a base-colour layer
3518        // number would pass a check that only counted one of them and then
3519        // sample past the end of the other image.
3520        for (row, material) in scene.materials.iter().enumerate() {
3521            for kind in PageKind::ALL {
3522                let names = match kind {
3523                    PageKind::BaseColor => material.base_color_texture,
3524                    PageKind::Normal => material.normal_texture,
3525                    PageKind::MetallicRoughnessOcclusion => {
3526                        material.metallic_roughness_occlusion_texture
3527                    }
3528                    PageKind::Emissive => material.emissive_texture,
3529                };
3530                if names == mesh::GpuMaterial::NO_PAGE {
3531                    continue;
3532                }
3533                let have = scene.page.layers(kind).len();
3534                if names as usize >= have {
3535                    return refuse(format!(
3536                        "material row {row} samples {} page layer {names}, and that page \
3537                         has {have}",
3538                        kind.label()
3539                    ));
3540                }
3541            }
3542        }
3543
3544        for (index, desc) in scene.meshes.iter().enumerate() {
3545            let Geometry::Dag { levels, dag, .. } = &desc.geometry else {
3546                continue;
3547            };
3548            // Zipped together at upload and again at
3549            // `ClusterDag::selection_records`, so a short list would silently
3550            // leave a level's clusters reading the level below's vertices.
3551            if levels.len() != dag.levels.len() {
3552                return refuse(format!(
3553                    "mesh {index} ({}) carries {} vertex array(s) for a DAG of {} level(s)",
3554                    desc.label,
3555                    levels.len(),
3556                    dag.levels.len()
3557                ));
3558            }
3559            for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
3560                let want = level.positions.len() * mesh::VERTEX_STRIDE;
3561                if bytes.len() != want {
3562                    return refuse(format!(
3563                        "mesh {index} ({}) level {depth} carries {} vertex byte(s) for {} \
3564                         position(s), which is {want}",
3565                        desc.label,
3566                        bytes.len(),
3567                        level.positions.len()
3568                    ));
3569                }
3570            }
3571        }
3572
3573        // **Every read the mesh stage makes from a cluster array lands inside
3574        // it.** Checked by the type that owns the arrays, on `PageDesc::check`'s
3575        // terms exactly — see `MeshClusters::check`, which is where the reason
3576        // it cannot be checked below the seam is argued. Both variants carry
3577        // the same type beside a vertex count, so both are checked the same way.
3578        for (index, desc) in scene.meshes.iter().enumerate() {
3579            let levels: Vec<(usize, &MeshClusters)> = match &desc.geometry {
3580                Geometry::Flat {
3581                    vertices, clusters, ..
3582                } => vec![(vertices.len() / mesh::VERTEX_STRIDE, clusters)],
3583                Geometry::Dag { dag, .. } => dag
3584                    .levels
3585                    .iter()
3586                    .map(|level| (level.positions.len(), &level.clusters))
3587                    .collect(),
3588            };
3589            for (depth, (vertices, clusters)) in levels.into_iter().enumerate() {
3590                if let Err(fault) = clusters.check(vertices) {
3591                    return refuse(format!(
3592                        "mesh {index} ({}) level {depth} {fault}",
3593                        desc.label
3594                    ));
3595                }
3596            }
3597        }
3598
3599        // **Capacity, summed over the whole description**, which is the one
3600        // refusal no pool can make for itself. `MeshPool` and `MaterialTable`
3601        // do refuse their own overflow, but they refuse it part way through
3602        // filling something that already exists, and the pair of numbers
3603        // [`MeshPoolError::PoolExhausted`](crate::mesh_pool::MeshPoolError::PoolExhausted)
3604        // carries to tell fragmentation from a full pool says nothing *here*:
3605        // the pool was created empty a few lines below, nothing has been freed
3606        // in it, so its free list is one block and the largest block and the
3607        // total are the same number. At build the answer is always "raise this
3608        // capacity", so it is said by name and before anything is created.
3609        let mut vertices: u64 = 0;
3610        let mut indices: u64 = 0;
3611        for desc in &scene.meshes {
3612            match &desc.geometry {
3613                Geometry::Flat {
3614                    vertices: bytes,
3615                    indices: list,
3616                    ..
3617                } => {
3618                    // Bytes that are not a whole number of vertices are the
3619                    // pool's to refuse, and it refuses before it allocates.
3620                    vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3621                    indices += list.len() as u64;
3622                }
3623                Geometry::Dag { levels, dag, .. } => {
3624                    for bytes in levels {
3625                        vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3626                    }
3627                    for level in &dag.levels {
3628                        // The call the upload itself makes, so the two cannot
3629                        // disagree about what a level costs.
3630                        indices += level.indices().len() as u64;
3631                    }
3632                }
3633            }
3634        }
3635        let entries: u64 = scene
3636            .meshes
3637            .iter()
3638            .map(|desc| desc.geometry.levels() as u64)
3639            .sum();
3640        for (pool, needed, capacity) in [
3641            ("vertex pool", vertices, scene.capacities.vertices),
3642            ("index pool", indices, scene.capacities.indices),
3643            ("mesh table", entries, scene.capacities.meshes),
3644            (
3645                "material table",
3646                scene.materials.len() as u64,
3647                scene.capacities.materials,
3648            ),
3649            (
3650                "probe table",
3651                scene.probes.probes.len() as u64,
3652                scene.capacities.probes,
3653            ),
3654        ] {
3655            if needed > u64::from(capacity) {
3656                return refuse(format!(
3657                    "the {pool} holds {capacity} and the description needs {needed}"
3658                ));
3659            }
3660        }
3661        Ok(())
3662    }
3663
3664    /// The body of [`ForwardRenderer::with_scene`], recording what it has
3665    /// created into `rollback` as it goes and calling `service` where
3666    /// [`ForwardRenderer::with_scene_serviced`] documents.
3667    fn build(
3668        device: &dyn Device,
3669        queue: QueueHandle,
3670        target_format: Format,
3671        scene: &SceneDesc<'_>,
3672        geometry_path: GeometryPath,
3673        rollback: &mut Rollback,
3674        service: &mut dyn FnMut(),
3675    ) -> Result<Self, HalError> {
3676        // Before anything exists, so a refused description leaks nothing — see
3677        // `check_scene`, which is where that placement is argued.
3678        Self::check_scene(scene)?;
3679
3680        // Resolved before anything is created, because it decides the *shape*
3681        // of what is created — the bind group layout, which pipeline kind the
3682        // pass builds, and what a bucket's constant block says. A device on the
3683        // mesh path never builds the raster pipeline and a device on either
3684        // indirect tail never builds the mesh one, which is what makes "the
3685        // frame came out of the mesh stage" a fact about the object graph
3686        // rather than a claim about a branch.
3687        let emit = EmitTail::from_path(geometry_path);
3688        // And whether that tail draws a range of buckets per call, which only
3689        // changes what the passes record — the constant blocks carry the words
3690        // both shapes read — so it decides nothing about what is created.
3691        let range_limit = emit.range_limit(&device.caps());
3692        // **A second capability, asked separately.** `Features::TASK_SHADER` is
3693        // not implied by `MESH_SHADER`, so §3.5's per-cluster cull is an
3694        // amplification stage this renderer builds where the device has one and
3695        // leaves out where it does not — and a device without it keeps drawing
3696        // through `mesh_cluster.slang`'s un-amplified `meshMain`, which culls
3697        // nothing and emits every cluster. Same picture, more work.
3698        let culls_clusters = emit.is_mesh()
3699            && device
3700                .caps()
3701                .features
3702                .contains(crcbl_hal::Features::TASK_SHADER);
3703
3704        let (pool, residents) = Self::build_geometry(device, queue, scene, service)?;
3705        // What an `InstanceDesc::mesh` index resolves through: one id per
3706        // description mesh, in description order, and each of them that mesh's
3707        // **level 0** whatever the path — because it is the entry the cull pass
3708        // reads a bounding box out of, and a DAG's coarser levels approximate
3709        // the same surface inside the same box.
3710        let mesh_ids: Vec<u32> = residents.iter().map(ResidentMesh::id).collect();
3711        // The scene's own triangles, kept for the probe-visibility capture and
3712        // for nothing else — and kept at all only when the description reserves
3713        // a probe, so a scene without one pays no memory for this rung. Taken
3714        // here because `scene` is the caller's and is read once.
3715        let probe_occluders = crate::probe_visibility::Occluders::from_scene(scene, &mesh_ids);
3716        // The same list one level down: what a caller reserving a skinned region
3717        // names its mesh with. Read here beside the ids rather than from
3718        // `residents` later, because the descriptions this came from are the
3719        // caller's and are read once.
3720        let skinnable_meshes: Vec<Option<MeshHandle>> =
3721            residents.iter().map(|mesh| mesh.skinnable).collect();
3722        // The handles are `Copy`, so they can be read out before the pool
3723        // becomes the rollback's — which it must be before the first `?` below,
3724        // or a failed pipeline would leak two device-local buffers. The index
3725        // pool is not named here at all: it is bound at draw time rather than
3726        // descriptor-written, so only the vertex pool and the mesh table reach a
3727        // bind group.
3728        let vertices = pool.vertex_buffer();
3729        let mesh_table = pool.table_buffer();
3730        rollback.pool = Some(pool);
3731
3732        // §3.2's texture side, before the table that indexes it: a material row
3733        // is written with a layer number, so the layer has to exist to be named.
3734        //
3735        // **One loop over [`PageKind::ALL`]**, because the kinds differ only in
3736        // three answers the kind itself owns — its format, its mip filter and
3737        // its device label — and everything else about creating a page is the
3738        // same code. Two hand-written copies were what let the normal page be
3739        // created through the colour page's filter for as long as nobody
3740        // compared the two, and rung 3 adds two more kinds to get wrong.
3741        //
3742        // **`Rgba8UnormSrgb` on the base-colour page, `Rgba8Unorm` on the
3743        // normal page, and that is the colour-space decision.** A base-colour
3744        // description's texels are sRGB-encoded, which is what glTF defines a
3745        // base-colour texture to be, so the format is what makes the sampler
3746        // decode them — and `mesh.slang` then multiplies a linear texel by a
3747        // linear `base_color` and lights in linear, exactly as it did before
3748        // there was a texture. A normal texel is a *number* and nothing decodes
3749        // it. See `PageKind::format`, and topic 44's rung 2.
3750        //
3751        // Every layer's length against its kind's extent was settled by
3752        // `check_scene` above, before this device object existed.
3753        //
3754        // **Every layer goes up with its mip chain**, built here on the host by
3755        // [`crate::mip`] — topic 43's filtering rung.
3756        // The chain is what a trilinear sampler needs to stop shimmering on a
3757        // minified surface, and it is built at upload rather than by a compute
3758        // pass because the page's format is what decodes it and a host chain is
3759        // the same bytes on every backend.
3760        //
3761        // **A kind with no layers takes one texel.** `upload_texture_mip_layers`
3762        // refuses a zero-layer image and every bind group has to fill both page
3763        // bindings, so a page nothing names is created 1×1 in its own format
3764        // holding [`PAGE_PLACEHOLDER_TEXEL`] — which the shader never reads,
3765        // and which is magenta so that a frame says so if it ever does.
3766        //
3767        // The upload itself is [`upload_page`], shared with
3768        // [`ForwardRenderer::replace_page`] so a page reloaded under a running
3769        // renderer is built exactly as this one was. A layer's chain is host
3770        // work proportional to its texels, so a page of many large layers is
3771        // serviced one layer at a time.
3772        let mut pages: [Option<UploadedTexture>; PageKind::ALL.len()] = [None; PageKind::ALL.len()];
3773        let mut page_extents = [(1, 1); PageKind::ALL.len()];
3774        let mut page_layers = [0; PageKind::ALL.len()];
3775        for kind in PageKind::ALL {
3776            let layers = scene.page.layers(kind);
3777            let (page, extent) = upload_page(
3778                device,
3779                queue,
3780                kind,
3781                scene.page.extent(kind),
3782                layers,
3783                service,
3784            )?;
3785            rollback.textures.push(page);
3786            page_extents[kind.index()] = (extent, extent);
3787            page_layers[kind.index()] = layers.len();
3788            pages[kind.index()] = Some(page);
3789            service();
3790        }
3791        let [
3792            Some(base_color_page),
3793            Some(normal_page),
3794            Some(mro_page),
3795            Some(emissive_page),
3796        ] = pages
3797        else {
3798            unreachable!("the loop above fills a slot for every PageKind::ALL entry");
3799        };
3800
3801        // The page's sampler at the device's default — see `create_page_sampler`
3802        // for what it filters, and `set_anisotropy` for how a caller moves it.
3803        let anisotropy = Self::anisotropy_for(&device.caps());
3804        let base_color_sampler = Self::create_page_sampler(device, anisotropy)?;
3805        rollback.samplers.push(base_color_sampler);
3806        // What every slot's groups are built naming, and what each moves off
3807        // only at its own frame — see `ForwardRenderer::adopt_pages`.
3808        let page_bindings = PageBindings {
3809            sampler: base_color_sampler,
3810            views: [
3811                base_color_page.view,
3812                normal_page.view,
3813                mro_page.view,
3814                emissive_page.view,
3815            ],
3816        };
3817
3818        // The material table, before the instances: an instance is written with
3819        // the material id it carries, so the row has to exist to be named.
3820        let (materials, material_ids) = Self::build_materials(device, scene)?;
3821        let material_buffer = materials.buffer();
3822        rollback.materials = Some(materials);
3823
3824        // Topic 50's irradiance grid: the table is created here once, and
3825        // `crate::probe_gather`'s compute pass rewrites its rows every frame —
3826        // see [`crate::probe`]. **Created even for a description with no probes**, because
3827        // every group of this layout has to fill [`PROBE_TABLE_BINDING`] and the
3828        // honest filler for "no probes were authored" is the zeroed row the
3829        // shader's clamp lands on.
3830        let probe_table = ProbeTable::new(
3831            device,
3832            queue,
3833            &ProbeTableDesc {
3834                label: Some("forward"),
3835                capacity: scene.capacities.probes,
3836                frames: FRAMES_IN_FLIGHT,
3837            },
3838        )?;
3839        // Into the rollback before it is filled, so a copy that fails releases
3840        // the buffers rather than leaking them.
3841        rollback.probes = Some(probe_table);
3842        let probe_table = rollback.probes.as_ref().expect("just stored");
3843        probe_table.fill(device, queue, &scene.probes.probes)?;
3844        // Read out here, like the instance ring's below and for the same
3845        // reason: the handles are `Copy`, and the loop that builds the bind
3846        // groups mutates the rollback the table now lives in.
3847        let probe_buffers: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
3848            .map(|frame| probe_table.buffer(frame))
3849            .collect();
3850        // The irradiance probes' updater, built **only** for a
3851        // description that asked for it. A volume left at
3852        // [`ProbeUpdate::Authored`] gets no pipeline, no buffers and no pass, so
3853        // the default really is the frame every scene drew before this landed.
3854        let probe_gather = match scene.probes.update {
3855            ProbeUpdate::Authored => None,
3856            ProbeUpdate::EveryFrame => Some(ProbeGather::new(
3857                device,
3858                &ProbeGatherDesc {
3859                    label: Some("forward probes"),
3860                    volume: scene.probes.volume,
3861                    probes: &probe_buffers,
3862                },
3863            )?),
3864        };
3865        rollback.probe_gather = probe_gather;
3866        let probe_gather = rollback.probe_gather.take();
3867        service();
3868
3869        // **Empty.** Every object in the scene arrives through
3870        // [`ForwardRenderer::add_instance`], including the demo scene's cube: a
3871        // renderer that inserted one of its description's meshes here would put
3872        // an object in a caller's frame that the caller never asked for.
3873        let instances = InstancePool::new(
3874            device,
3875            &InstancePoolDesc {
3876                label: Some("forward instances"),
3877                capacity: scene.capacities.instances,
3878                frames_in_flight: FRAMES_IN_FLIGHT,
3879            },
3880        )?;
3881        // Same handle-then-hand-over dance as the geometry pool above: the
3882        // buffers are `Copy` and are read out before the pool becomes the
3883        // rollback's, which it must be before the first `?` below — after which
3884        // nothing needs the pool again until `begin_frame`.
3885        let instance_buffers: Vec<BufferHandle> = instances.buffers().to_vec();
3886        rollback.instances = Some(instances);
3887
3888        // The two compute passes, and the buffers the draws come out of. Built
3889        // here rather than beside the pipelines below because the mesh bind
3890        // group names one of its buffers, so it has to exist first.
3891        //
3892        // The bucket table, and the one place its order is decided.
3893        //
3894        // **Built by walking the description**, which is what makes a duplicate
3895        // structurally impossible rather than refused: every bucket's mesh id is
3896        // the id of the description mesh it came from, and two description
3897        // meshes are two uploads with two table entries however alike their
3898        // geometry is. That matters because `draw_gen.slang`'s scatter takes the
3899        // *first* bucket whose mesh id matches, so a second bucket naming one
3900        // mesh would never draw anything at all.
3901        //
3902        // One bucket per mesh, except for two things. A DAG is one bucket where
3903        // an amplification stage picks its cut per cluster and one per level
3904        // where the cull pass picks a uniform one — see [`buckets_for`]. And the
3905        // whole run is repeated once per **material mode** the scene holds, so
3906        // an instance's mode picks a bucket exactly as its mesh does; see
3907        // [`ForwardRenderer::bucket_modes`].
3908        //
3909        // **Mode-major: every mesh's run for one mode, then the next mode's.**
3910        // A mode picks the pipeline a pass binds, so this makes each pipeline's
3911        // partition — [`ForwardRenderer::depth_partitions`] and
3912        // [`ForwardRenderer::sided_partitions`] — one contiguous run of
3913        // buckets, which a device with a draw index records as one ranged call
3914        // rather than a call per bucket — and which the mesh tail behind a
3915        // task stage must have, because it draws each partition as one flat
3916        // call of its run. `DEPTH_MODES` order makes a sided partition one run
3917        // too: opaque sits beside masked, and double-sided beside both.
3918        //
3919        // **Once per mode the scene holds, not once per mode that exists.** A
3920        // scene whose materials are all opaque gets exactly the table it always
3921        // had — same length, same order, same bytes — so the twin costs nothing
3922        // where nothing is masked, which is every demo and every golden here. A
3923        // bucket is not free: every pass records one indirect call per bucket
3924        // per view, and every generator holds its run start.
3925        let scene_modes: Vec<u32> = {
3926            let held: Vec<u32> = DEPTH_MODES
3927                .into_iter()
3928                .filter(|mode| {
3929                    scene
3930                        .materials
3931                        .iter()
3932                        .any(|material| material.mode() == *mode)
3933                })
3934                .collect();
3935            // A description with no materials at all still needs a bucket per
3936            // mesh, or nothing it holds can be drawn.
3937            if held.is_empty() {
3938                vec![DEPTH_MODES[0]]
3939            } else {
3940                held
3941            }
3942        };
3943        // One mode's run: every description mesh's levels, in description
3944        // order. `bucket_bases` is where each mesh starts within it, so the
3945        // tables below can be filled in mesh by mesh rather than by re-deriving
3946        // the arithmetic; mode slot `s` of the mesh is `s` runs further on.
3947        let mut mode_run: Vec<u32> = Vec::new();
3948        let mut bucket_bases: Vec<usize> = Vec::with_capacity(residents.len());
3949        for resident in &residents {
3950            bucket_bases.push(mode_run.len());
3951            mode_run
3952                .extend_from_slice(&resident.levels[..buckets_for(resident.levels.len(), emit)]);
3953        }
3954        let mut bucket_meshes: Vec<u32> = Vec::with_capacity(mode_run.len() * scene_modes.len());
3955        // The mode each of those buckets draws, in step with it.
3956        let mut bucket_modes: Vec<u32> = Vec::with_capacity(bucket_meshes.capacity());
3957        for mode in &scene_modes {
3958            bucket_meshes.extend_from_slice(&mode_run);
3959            bucket_modes.extend(std::iter::repeat_n(*mode, mode_run.len()));
3960        }
3961        let bucket_count = u32::try_from(bucket_meshes.len())
3962            .unwrap_or_else(|_| unreachable!("a table of a few buckets"));
3963
3964        // Topic 25's selection tables, and the one thing that
3965        // decides whether `draw_gen.slang` takes a uniform cut at all.
3966        //
3967        // Every mesh id gets an entry, because the shader indexes this with
3968        // `GpuInstance::mesh` and an instance can name any of them; the default
3969        // is `MeshLevels::FLAT` pointing at a level run that is the mesh itself,
3970        // so a mesh with no hierarchy resolves back to itself with no branch.
3971        // **A DAG keeps that default on the mesh path**, which is how a device
3972        // already descending it per cluster avoids a second, coarser cut on top
3973        // of it — the suppression is data rather than a branch in the shader.
3974        //
3975        // **Sized by the mesh table's capacity, not by the meshes resident in
3976        // it**, because that is the invariant `draw_gen.slang`'s
3977        // `mesh_levels_of` states and indexes on: "every entry an instance can
3978        // name is filled". The read is unbounded and an instance's mesh id is a
3979        // bare table index, so a table sized to the description alone is an
3980        // out-of-range read of whatever the packer laid down next for any id the
3981        // description did not fill. What it finds there decides the frame: zeros
3982        // resolve to mesh 0 and draw another mesh's geometry, and a live
3983        // `group_count` sends `select_level`'s loop over a count no allocation
3984        // backs, which on radv is a hard GPU recovery rather than a wrong
3985        // picture. That is not a hypothetical: it is what a skinned instance
3986        // naming an alias entry did until 2026-08, before it learned to name its
3987        // source mesh instead.
3988        let table_len = usize::try_from(scene.capacities.meshes)
3989            .unwrap_or(usize::MAX)
3990            .max(
3991                usize::try_from(
3992                    residents
3993                        .iter()
3994                        .flat_map(|resident| resident.levels.iter().copied())
3995                        .max()
3996                        .unwrap_or_else(|| {
3997                            unreachable!("check_scene refused an empty description")
3998                        })
3999                        + 1,
4000                )
4001                .unwrap_or_else(|_| unreachable!("a table of a few meshes")),
4002            );
4003        let mut level_meshes: Vec<u32> = (0..table_len)
4004            .map(|id| u32::try_from(id).unwrap_or_else(|_| unreachable!("bounded by table_len")))
4005            .collect();
4006        let mut mesh_levels: Vec<level_select::MeshLevels> = level_meshes
4007            .iter()
4008            .map(|&id| level_select::MeshLevels {
4009                first_level: id,
4010                ..level_select::MeshLevels::FLAT
4011            })
4012            .collect();
4013        // Every DAG's groups end to end, in description order, and where each
4014        // one's run starts. `ClusterSelect` records name a group by its index in
4015        // *this* array — see `ClusterDag::selection_records`' `first_group` — so
4016        // several DAGs concatenate without `crcbl-shaders` knowing they did.
4017        let mut level_groups: Vec<level_select::LevelGroup> = Vec::new();
4018        let mut first_groups: Vec<u32> = Vec::with_capacity(residents.len());
4019        for (index, desc) in scene.meshes.iter().enumerate() {
4020            first_groups.push(
4021                u32::try_from(level_groups.len())
4022                    .unwrap_or_else(|_| unreachable!("a few dozen groups per DAG")),
4023            );
4024            let Geometry::Dag { dag, .. } = &desc.geometry else {
4025                continue;
4026            };
4027            let groups = dag.level_groups();
4028            let id = residents[index].id();
4029            mesh_levels[id as usize] = level_select::MeshLevels {
4030                first_group: first_groups[index],
4031                group_count: u32::try_from(groups.len())
4032                    .unwrap_or_else(|_| unreachable!("a DAG of a few dozen groups")),
4033                // **The mesh path suppresses the uniform cut with a top level of
4034                // zero, not with a group count of zero**, and the difference is
4035                // the hysteresis state: `draw_gen.slang` judges every group it is
4036                // given whatever level it answers, and the amplification stage
4037                // reads those answers. A record naming no groups would leave the
4038                // state untouched and every cluster of the patch collapsed. A
4039                // top level of zero makes the level loop's minimum unreachable,
4040                // so the instance routes to the mesh it already names — which is
4041                // level 0.
4042                first_level: if emit.is_mesh() {
4043                    id
4044                } else {
4045                    u32::try_from(level_meshes.len())
4046                        .unwrap_or_else(|_| unreachable!("a table of a few meshes"))
4047                },
4048                top_level: if emit.is_mesh() {
4049                    0
4050                } else {
4051                    u32::try_from(residents[index].levels.len() - 1)
4052                        .unwrap_or_else(|_| unreachable!("a DAG of a few levels"))
4053                },
4054            };
4055            level_groups.extend(groups);
4056            if !emit.is_mesh() {
4057                level_meshes.extend_from_slice(&residents[index].levels);
4058            }
4059        }
4060
4061        // §3.5's clusters, on the path that reads them and on no other. The
4062        // records are `crcbl-shaders`' — cooked, because the builder is
4063        // `crcbl-scene`'s and the renderer must not depend on that crate — and
4064        // they arrive in bucket-mesh order so a bucket's range is its own
4065        // index. See `crate::cluster_pool`.
4066        //
4067        // Before the draw generation below rather than after it, because the
4068        // per-bucket cluster counts are the x extent of each bucket's mesh
4069        // dispatch and that pass writes the argument structure carrying them.
4070        let mut bucket_clusters = vec![0u32; bucket_meshes.len()];
4071        let mut bucket_cluster_bases = vec![0u32; bucket_meshes.len()];
4072        let mut mesh_clusters: Vec<ClusterRange> = Vec::new();
4073        if emit.is_mesh() {
4074            // A flat mesh is one pool entry and its clusters carry
4075            // `ClusterSelect::ALWAYS`, so the descent draws them from every
4076            // camera; a DAG is **one entry per level**, laid end to end.
4077            let mut cooked: Vec<PooledMesh> = Vec::with_capacity(residents.len());
4078            // Where each description mesh's entries start, on `bucket_bases`'
4079            // terms — the two differ exactly where a DAG's levels are one bucket
4080            // and several entries.
4081            let mut entry_bases: Vec<usize> = Vec::with_capacity(residents.len());
4082            for (index, desc) in scene.meshes.iter().enumerate() {
4083                entry_bases.push(cooked.len());
4084                match &desc.geometry {
4085                    Geometry::Flat { clusters, .. } => {
4086                        cooked.push(PooledMesh::without_lod(clusters.clone()));
4087                    }
4088                    Geometry::Dag { dag, .. } => {
4089                        let selection = dag
4090                            .selection_records(&residents[index].vertex_bases, first_groups[index]);
4091                        for (level, records) in dag.levels.iter().zip(selection) {
4092                            cooked.push(PooledMesh {
4093                                clusters: level.clusters.clone(),
4094                                selection: records,
4095                            });
4096                        }
4097                    }
4098                }
4099            }
4100
4101            let clusters = ClusterPool::new(device, "forward", &cooked)?;
4102            let range = |entry: usize| {
4103                clusters
4104                    .range(entry)
4105                    .unwrap_or_else(|| unreachable!("one range per entry, in order"))
4106            };
4107            // **A DAG's levels are one run, not one per bucket.** `concatenate`
4108            // lays the entries down in the order it was given them, so the
4109            // levels are contiguous: the bucket starts where level 0 does and
4110            // reaches to the end of the last level. That is what lets one
4111            // dispatch cover a cut spanning several of them — and it is why a
4112            // flat mesh, whose one entry is the whole sum, needs no second case.
4113            mesh_clusters.reserve(residents.len());
4114            for (index, resident) in residents.iter().enumerate() {
4115                let entry = entry_bases[index];
4116                let base = range(entry).base;
4117                let count: u32 = (entry..entry + resident.levels.len())
4118                    .map(|entry| range(entry).count)
4119                    .sum();
4120                // **Every one of this mesh's buckets, not only the first.** A
4121                // mode twin draws the same geometry, so it dispatches over the
4122                // same clusters; a twin left at zero launches no workgroup and
4123                // its instances vanish from the frame. One bucket per mode here,
4124                // because the mesh path takes `buckets_for` of one, each a whole
4125                // mode's run past the one before.
4126                for slot in 0..scene_modes.len() {
4127                    let bucket = slot * mode_run.len() + bucket_bases[index];
4128                    bucket_cluster_bases[bucket] = base;
4129                    bucket_clusters[bucket] = count;
4130                }
4131                mesh_clusters.push(ClusterRange { base, count });
4132            }
4133
4134            rollback.clusters = Some(clusters);
4135            service();
4136        }
4137
4138        // One ring per shadow view, indexed `[view][frame]`: topic 25's
4139        // observable, one word per resident cluster holding the cut the descent
4140        // chose — see `ForwardRenderer::shadow_selection` for why a view cannot
4141        // share the camera's, which [`View::build`] allocates beside its cull.
4142        //
4143        // Allocated on the whole mesh path rather than only where there is an
4144        // amplification stage to write them, because the layout declares
4145        // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued.
4146        let mut tile_selection: Vec<Vec<BufferHandle>> = Vec::new();
4147        if emit.is_mesh() {
4148            let count = rollback
4149                .clusters
4150                .as_ref()
4151                .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
4152                .count();
4153            let mut ring = |label: &str| -> Result<Vec<BufferHandle>, HalError> {
4154                let mut buffers = Vec::with_capacity(instance_buffers.len());
4155                for frame in 0..instance_buffers.len() {
4156                    let buffer = device.create_buffer(&BufferDesc {
4157                        label: Some(&format!("{label} {frame}")),
4158                        size: u64::from(count) * 4,
4159                        usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
4160                        memory: MemoryLocation::DeviceLocal,
4161                    })?;
4162                    rollback.buffers.push(buffer);
4163                    buffers.push(buffer);
4164                }
4165                Ok(buffers)
4166            };
4167            for view in 0..SHADOW_VIEWS {
4168                tile_selection.push(ring(&format!("shadow selection {view}"))?);
4169            }
4170        }
4171
4172        // --- the mesh pass ---
4173        //
4174        // No `BindingFlags` anywhere: this layout is legal on **both** tiers,
4175        // because a lit mesh is not a Tier A feature. The bindless shape — a
4176        // trailing `VARIABLE_COUNT | PARTIALLY_BOUND | UPDATE_AFTER_BIND`
4177        // texture array — is topic 03's, at P3.
4178        // **Which stage pulls the geometry**, and the only thing the two shapes
4179        // of this layout disagree about for bindings 0 to 8. `ShaderStages::MESH`
4180        // is outside `GRAPHICS` and `ALL`, so it is named rather than implied,
4181        // and every backend refuses a layout carrying it on a device without
4182        // `Features::MESH_SHADER` — which is exactly the device that never
4183        // reaches this arm.
4184        //
4185        // **`TASK` joins it when there is an amplification stage**, and the
4186        // union is deliberately over every binding rather than the eight
4187        // `taskMain` actually reads. Slang's Metal backend materialises every
4188        // global in every entry point of a module — the argument bindings 6 to
4189        // 8 already carry — so a layout that named only the task stage's own
4190        // reads would be a layout `msl/mesh_cluster.metal` disagrees with, on a
4191        // runner this team cannot debug on.
4192        let geometry = match (emit.is_mesh(), culls_clusters) {
4193            (true, true) => ShaderStages::MESH.union(ShaderStages::TASK),
4194            (true, false) => ShaderStages::MESH,
4195            (false, _) => ShaderStages::VERTEX,
4196        };
4197        let mut mesh_entries = vec![
4198            BindGroupLayoutEntry {
4199                binding: 0,
4200                visibility: geometry.union(ShaderStages::FRAGMENT),
4201                kind: BindingKind::UniformBuffer { dynamic: false },
4202                count: 1,
4203                flags: BindingFlags::empty(),
4204            },
4205            BindGroupLayoutEntry {
4206                binding: 1,
4207                // **Both stages, and here it is the FRAGMENT half that needs
4208                // saying** — binding 6 and 7 are the mirror image, where the
4209                // fragment stage plainly reads the row and the vertex half is
4210                // the one Slang forces. Slang's Metal backend materialises
4211                // every module global into every entry point, so
4212                // `msl/mesh.metal`'s `fragmentMain` takes this buffer whether
4213                // its body dereferences it or not — and Metal's debug layer
4214                // answers a declared-but-unbound fragment argument with
4215                // `missing Buffer binding at index N`, once per draw. Vulkan,
4216                // D3D12 and WebGPU all accept a visibility wider than the
4217                // shader's reads, so naming FRAGMENT costs them nothing but the
4218                // entry itself.
4219                //
4220                // **It does not cost a redundant bind on Metal either**, and
4221                // that is what makes it safe rather than a trade: `crcbl-mtl`
4222                // consults `MTLPipelineOption::BindingInfo` reflection and
4223                // issues the fragment-stage bind only where `MTLBinding::isUsed`
4224                // says the compiled function kept the argument. This entry is
4225                // the permission; the reflection is the decision.
4226                visibility: geometry.union(ShaderStages::FRAGMENT),
4227                kind: BindingKind::StorageBuffer {
4228                    // The shader says `StructuredBuffer`, not
4229                    // `RWStructuredBuffer`, so this is the truth rather than a
4230                    // hint — and it is what lets the graph merge read-after-read.
4231                    read_only: true,
4232                    dynamic: false,
4233                    stride: size_of::<u32>() as u32,
4234                },
4235                count: 1,
4236                flags: BindingFlags::empty(),
4237            },
4238            BindGroupLayoutEntry {
4239                binding: 2,
4240                // Both stages, for binding 1's reason exactly.
4241                visibility: geometry.union(ShaderStages::FRAGMENT),
4242                kind: BindingKind::StorageBuffer {
4243                    // `StructuredBuffer` again: the vertex stage reads its
4244                    // instance and writes nothing. The *host* writes this one
4245                    // every frame, which is a mapped write rather than a shader
4246                    // one and does not make it read-write here.
4247                    read_only: true,
4248                    dynamic: false,
4249                    stride: crcbl_shaders::mesh::INSTANCE_STRIDE as u32,
4250                },
4251                count: 1,
4252                flags: BindingFlags::empty(),
4253            },
4254            BindGroupLayoutEntry {
4255                binding: 3,
4256                // Both stages, for binding 1's reason exactly.
4257                visibility: geometry.union(ShaderStages::FRAGMENT),
4258                // `dynamic: true`, and it is the whole mechanism: it is what
4259                // lets a draw say where its run of instances starts without
4260                // `draw_indexed`'s own base instance, which the module docs and
4261                // `mesh.slang`'s header explain the targets disagree about.
4262                // Same shape, for the same reason, as `crate::sprite_pass`'s.
4263                kind: BindingKind::UniformBuffer { dynamic: true },
4264                count: 1,
4265                flags: BindingFlags::empty(),
4266            },
4267            BindGroupLayoutEntry {
4268                binding: 4,
4269                // Both stages, for binding 1's reason exactly.
4270                visibility: geometry.union(ShaderStages::FRAGMENT),
4271                kind: BindingKind::StorageBuffer {
4272                    // The mesh table. `StructuredBuffer` again — the vertex
4273                    // stage looks its mesh up and writes nothing — and one
4274                    // buffer shared by every frame's group, because unlike the
4275                    // instance array nothing rewrites it between frames.
4276                    read_only: true,
4277                    dynamic: false,
4278                    stride: crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32,
4279                },
4280                count: 1,
4281                flags: BindingFlags::empty(),
4282            },
4283            BindGroupLayoutEntry {
4284                binding: 5,
4285                // Both stages, for binding 1's reason exactly.
4286                visibility: geometry.union(ShaderStages::FRAGMENT),
4287                kind: BindingKind::StorageBuffer {
4288                    // The per-bucket runs of surviving instances. Read-only
4289                    // here and written by the draw-argument pass, which is a
4290                    // different bind group and a different pass — the graph is
4291                    // what orders the two.
4292                    read_only: true,
4293                    dynamic: false,
4294                    stride: size_of::<u32>() as u32,
4295                },
4296                count: 1,
4297                flags: BindingFlags::empty(),
4298            },
4299            BindGroupLayoutEntry {
4300                binding: 6,
4301                // **Both stages, and the union is not belt-and-braces.** The
4302                // fragment stage is where `mesh.slang` now reads the table, so
4303                // it plainly needs it — a pipeline layout that leaves it out is
4304                // refused outright by wgpu and reported as
4305                // `VUID-VkGraphicsPipelineCreateInfo-layout-07988` by Vulkan.
4306                // The vertex half has to stay because Slang's Metal backend
4307                // materialises every global in every entry point: `vertexMain`
4308                // in `msl/mesh.metal` still takes `materials [[buffer(6)]]`
4309                // whether it reads it or not, so dropping VERTEX would break
4310                // Metal alone, on a runner this team cannot debug on.
4311                visibility: geometry.union(ShaderStages::FRAGMENT),
4312                kind: BindingKind::StorageBuffer {
4313                    // The material table. One buffer in every frame's group,
4314                    // like the mesh table above and unlike the instance ring:
4315                    // a material is written when it is created, not per frame.
4316                    read_only: true,
4317                    dynamic: false,
4318                    stride: crcbl_shaders::mesh::MATERIAL_STRIDE as u32,
4319                },
4320                count: 1,
4321                flags: BindingFlags::empty(),
4322            },
4323            BindGroupLayoutEntry {
4324                binding: BASE_COLOR_PAGE_BINDING,
4325                // Both stages, for binding 6's reason exactly: the fragment
4326                // stage samples it, and Slang's Metal backend materialises
4327                // every global in every entry point — `vertexMain` in
4328                // `msl/mesh.metal` takes the texture whether it reads it or
4329                // not, so a layout without VERTEX would break Metal alone.
4330                visibility: geometry.union(ShaderStages::FRAGMENT),
4331                // **`D2Array`, and the layout is where wgpu wants to hear it.**
4332                // The other three backends read the dimension off the bound
4333                // view and never consult this; WebGPU compares the two at
4334                // pipeline creation and refuses the pair, which is what a
4335                // layout claiming `D2` over an array view got — "expects
4336                // dimension = D2, but given a view with dimension = D2Array".
4337                kind: BindingKind::SampledImage {
4338                    view_type: ImageViewType::D2Array,
4339                    sample_type: SampleType::Float,
4340                },
4341                // **`count: 1`, and this is the binding-model decision.** One
4342                // `D2Array` image whose *layers* the material rows index is
4343                // `BindingModel::ArrayPages`; an array of `count` descriptors
4344                // indexed per fragment would be `Bindless` and would need
4345                // `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws.
4346                // So this layout is legal on every device, exactly as the six
4347                // buffers above are, and no `BindingFlags` appear anywhere in
4348                // this file yet.
4349                count: 1,
4350                flags: BindingFlags::empty(),
4351            },
4352            BindGroupLayoutEntry {
4353                binding: PAGE_SAMPLER_BINDING,
4354                visibility: geometry.union(ShaderStages::FRAGMENT),
4355                kind: BindingKind::Sampler { comparison: false },
4356                count: 1,
4357                flags: BindingFlags::empty(),
4358            },
4359        ];
4360        if emit.is_mesh() {
4361            // §3.5's four extra reads, and only on the path that has them.
4362            // Adding them unconditionally would make every device declare four
4363            // buffers `mesh.slang` does not name — and WebGPU, which checks a
4364            // bind group against its layout entry for entry, would then need
4365            // four buffers created for a path that never reads them.
4366            //
4367            // `read_only: true` on all four, which is the truth rather than a
4368            // hint: the mesh stage indexes them and writes nothing, and it is
4369            // what lets the graph merge read-after-read.
4370            //
4371            // Four different element types, so four strides, in binding order:
4372            // the clusters (`Meshlet`), the cluster vertex and corner pools
4373            // (`uint` each), and the per-cluster draw arguments
4374            // (`DrawIndexedArgs`, the indirect layout every API agrees on).
4375            let cluster_strides = [
4376                crcbl_shaders::meshlet::MESHLET_STRIDE as u32,
4377                size_of::<u32>() as u32,
4378                size_of::<u32>() as u32,
4379                crcbl_hal::indirect::DRAW_INDEXED_ARGS_BYTES as u32,
4380            ];
4381            mesh_entries.extend(
4382                (CLUSTERS_BINDING..=CLUSTER_DRAW_ARGS_BINDING)
4383                    .zip(cluster_strides)
4384                    .map(|(binding, stride)| {
4385                        BindGroupLayoutEntry {
4386                            binding,
4387                            // **Not the fragment stage.** These four are the geometry
4388                            // stage's alone, and `mesh_cluster.slang` has no fragment entry
4389                            // point of its own to materialise them into — its fragment
4390                            // stage is `mesh.slang`'s, which does not declare mesh-only
4391                            // buffers.
4392                            visibility: geometry,
4393                            kind: BindingKind::StorageBuffer {
4394                                read_only: true,
4395                                dynamic: false,
4396                                stride,
4397                            },
4398                            count: 1,
4399                            flags: BindingFlags::empty(),
4400                        }
4401                    }),
4402            );
4403        }
4404        // Both mesh entry points retain these declarations. Omitting unused
4405        // task buffers would shift later native buffer indices on the plain
4406        // mesh path, so the layout includes them on both paths.
4407        if emit.is_mesh() {
4408            mesh_entries.push(BindGroupLayoutEntry {
4409                binding: CLUSTER_CULL_BINDING,
4410                visibility: geometry,
4411                // **The same block the instance cull reads**, not a copy: one
4412                // camera, one frustum, and no way for the two rejections to
4413                // disagree about which. `dynamic: false` because there is one
4414                // block per frame rather than one per bucket.
4415                kind: BindingKind::UniformBuffer { dynamic: false },
4416                count: 1,
4417                flags: BindingFlags::empty(),
4418            });
4419            mesh_entries.push(BindGroupLayoutEntry {
4420                binding: CLUSTER_CULL_STATS_BINDING,
4421                visibility: geometry,
4422                kind: BindingKind::StorageBuffer {
4423                    // **The one writable binding this pass has.** The stage adds
4424                    // to a counter, so `read_only: false` is the truth rather
4425                    // than a hint, and it is what makes the graph order this
4426                    // write after the draw-argument pass's read of the same
4427                    // buffer.
4428                    read_only: false,
4429                    dynamic: false,
4430                    stride: size_of::<u32>() as u32,
4431                },
4432                count: 1,
4433                flags: BindingFlags::empty(),
4434            });
4435        }
4436        // Topic 18's cascades, read by the fragment stage and declared last —
4437        // above `mesh_cluster.slang`'s range rather than inside it, for the
4438        // reason `SHADOW_ATLAS_BINDING` gives.
4439        //
4440        // Both carry `geometry` in their visibility beside `FRAGMENT`, for
4441        // binding 7's reason exactly: Slang's Metal backend materialises every
4442        // global into every entry point, and `msl/mesh.metal`'s `vertexMain`
4443        // takes `shadow_atlas [[texture(1)]]` and `shadow_sampler
4444        // [[sampler(1)]]` whether it reads them or not.
4445        mesh_entries.push(BindGroupLayoutEntry {
4446            binding: SHADOW_ATLAS_BINDING,
4447            visibility: geometry.union(ShaderStages::FRAGMENT),
4448            kind: BindingKind::SampledImage {
4449                view_type: ImageViewType::D2,
4450                // **`Depth`, and this is the field the seam grew for this
4451                // pass.** WebGPU will only bind a `D32Float` view through a
4452                // depth sample type, and its shader side agrees — the WGSL
4453                // artifact declares `texture_depth_2d`. The other three
4454                // backends take the interpretation off the view's format and
4455                // never read this.
4456                sample_type: SampleType::Depth,
4457            },
4458            count: 1,
4459            flags: BindingFlags::empty(),
4460        });
4461        mesh_entries.push(BindGroupLayoutEntry {
4462            binding: SHADOW_SAMPLER_BINDING,
4463            visibility: geometry.union(ShaderStages::FRAGMENT),
4464            // The sampler-side twin of the line above: `sampler_comparison` in
4465            // the WGSL, `SamplerComparisonState` in the HLSL, and a
4466            // `compareEnable` on the Vulkan sampler object. The layout has to
4467            // say so on WebGPU and cannot on the other three.
4468            kind: BindingKind::Sampler { comparison: true },
4469            count: 1,
4470            flags: BindingFlags::empty(),
4471        });
4472        // DAG geometry and selection state, in the mesh-only binding range.
4473        if emit.is_mesh() {
4474            mesh_entries.push(BindGroupLayoutEntry {
4475                binding: CLUSTER_SELECT_BINDING,
4476                visibility: geometry,
4477                // Read-only and read by **both** mesh entry points, unlike the
4478                // pair below: a cluster's `vertex_base` is which level of a DAG
4479                // its geometry lives in, which an un-amplified stage needs just
4480                // as much as an amplified one.
4481                kind: BindingKind::StorageBuffer {
4482                    read_only: true,
4483                    dynamic: false,
4484                    stride: crcbl_shaders::cluster_select::CLUSTER_SELECT_STRIDE as u32,
4485                },
4486                count: 1,
4487                flags: BindingFlags::empty(),
4488            });
4489        }
4490        // Both on the whole mesh path, for the two above's reason exactly: the
4491        // amplification stage is the only writer and the only reader, and the
4492        // Metal argument table counts entries rather than reading binding
4493        // numbers.
4494        if emit.is_mesh() {
4495            mesh_entries.push(BindGroupLayoutEntry {
4496                binding: CLUSTER_SELECTION_BINDING,
4497                visibility: geometry,
4498                kind: BindingKind::StorageBuffer {
4499                    // The second writable binding: the amplification stage
4500                    // records the cut it chose, one word per resident cluster.
4501                    read_only: false,
4502                    dynamic: false,
4503                    stride: size_of::<u32>() as u32,
4504                },
4505                count: 1,
4506                flags: BindingFlags::empty(),
4507            });
4508            mesh_entries.push(BindGroupLayoutEntry {
4509                binding: CLUSTER_GROUP_STATE_BINDING,
4510                visibility: geometry,
4511                kind: BindingKind::StorageBuffer {
4512                    // Topic 25's hysteresis state, and read-only
4513                    // here: the draw-argument pass is its only writer, which is
4514                    // what lets a stage with one workgroup per cluster use a
4515                    // decision that has to survive a frame.
4516                    read_only: true,
4517                    dynamic: false,
4518                    stride: size_of::<u32>() as u32,
4519                },
4520                count: 1,
4521                flags: BindingFlags::empty(),
4522            });
4523        }
4524
4525        // The shared fragment light list and froxel grid are bound on every
4526        // path and in every group, unlike the four
4527        // conditional ranges above: `mesh.slang`'s fragment stage reads them
4528        // whatever geometry produced the primitive, so there is no configuration
4529        // in which the layout can omit them.
4530        //
4531        // `geometry` joins `FRAGMENT` in the visibility for binding 7's reason
4532        // exactly: Slang's Metal backend materialises every global into every
4533        // entry point, so the vertex and mesh stages take these buffers whether
4534        // they read them or not.
4535        mesh_entries.push(BindGroupLayoutEntry {
4536            binding: LIGHT_LIST_BINDING,
4537            visibility: geometry.union(ShaderStages::FRAGMENT),
4538            kind: BindingKind::StorageBuffer {
4539                read_only: true,
4540                dynamic: false,
4541                stride: crcbl_shaders::light::LIGHT_STRIDE as u32,
4542            },
4543            count: 1,
4544            flags: BindingFlags::empty(),
4545        });
4546        mesh_entries.push(BindGroupLayoutEntry {
4547            binding: LIGHT_GRID_BINDING,
4548            visibility: geometry.union(ShaderStages::FRAGMENT),
4549            kind: BindingKind::StorageBuffer {
4550                // **Read-only here**, and written by the clustering pass through
4551                // a layout of its own. The graph is what orders the two.
4552                read_only: true,
4553                dynamic: false,
4554                stride: size_of::<u32>() as u32,
4555            },
4556            count: 1,
4557            flags: BindingFlags::empty(),
4558        });
4559        // Topic 46's occlusion channel, last of the set
4560        // — see [`AMBIENT_OCCLUSION_BINDING`] on why last is structural rather
4561        // than tidy.
4562        //
4563        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4564        // `msl/mesh.metal` is the proof rather than the theory: its `vertexMain`
4565        // takes `ambient_occlusion [[texture(2)]]` whether it reads it or not.
4566        mesh_entries.push(BindGroupLayoutEntry {
4567            binding: AMBIENT_OCCLUSION_BINDING,
4568            visibility: geometry.union(ShaderStages::FRAGMENT),
4569            kind: BindingKind::SampledImage {
4570                view_type: ImageViewType::D2,
4571                // **`Float`, unlike the shadow atlas above.** This one is an
4572                // ordinary `R8Unorm` colour image and the WGSL artifact declares
4573                // `texture_2d<f32>` for it; `Depth` here would be a layout
4574                // claiming a depth format the view does not have.
4575                sample_type: SampleType::Float,
4576            },
4577            count: 1,
4578            flags: BindingFlags::empty(),
4579        });
4580        // The irradiance grid, past the occlusion channel — see
4581        // [`PROBE_TABLE_BINDING`] on why the list only ever grows at its top.
4582        //
4583        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4584        // `msl/mesh.metal` is again the proof rather than the theory: its
4585        // `vertexMain` takes `probes [[buffer(9)]]` whether it reads it or not.
4586        mesh_entries.push(BindGroupLayoutEntry {
4587            binding: PROBE_TABLE_BINDING,
4588            visibility: geometry.union(ShaderStages::FRAGMENT),
4589            kind: BindingKind::StorageBuffer {
4590                // **Read-only, and it stays read-only when the updater lands.**
4591                // The rows are device-local now — see [`crate::probe`], which is
4592                // where that is argued — so the seam no longer forces this;
4593                // what forces it is that the shading path does not write a
4594                // probe and this layout has no headroom to pretend otherwise.
4595                // The raster path is at the WebGPU per-stage storage-buffer
4596                // ceiling already, which the check at the end of the layout
4597                // holds it to, so `read_only: false` here would buy a write
4598                // nothing performs at the price of a binding budget there is
4599                // none of. The irradiance probes' gather is a
4600                // compute pass with a layout of its own, and that is where the
4601                // writable binding of these rows belongs.
4602                read_only: true,
4603                dynamic: false,
4604                stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
4605            },
4606            count: 1,
4607            flags: BindingFlags::empty(),
4608        });
4609        if emit.is_mesh() {
4610            // DAG group records follow the common buffer prefix; the
4611            // remaining mesh-only buffers are sorted after them below.
4612            //
4613            // **Conditional like the mesh-only bindings**, and not for tidiness:
4614            // the raster path's layout is at the WebGPU storage-buffer ceiling
4615            // already, so a row bound unconditionally would be a renderer that
4616            // cannot be built in a browser. The mesh path's own reads sit outside
4617            // that count because `ShaderStages::MESH` is not one of the three
4618            // stages it sums.
4619            mesh_entries.push(BindGroupLayoutEntry {
4620                binding: LEVEL_GROUP_TABLE_BINDING,
4621                // Only the geometry stage reads this table: the
4622                // heatmap's colour is chosen where the cluster is known, and
4623                // `mesh.slang`'s fragment stage — which is this pipeline's —
4624                // does not declare this buffer.
4625                visibility: geometry,
4626                kind: BindingKind::StorageBuffer {
4627                    // Read-only and read by **both** mesh entry points, like
4628                    // CLUSTER_SELECT_BINDING: an un-amplified stage draws through the same
4629                    // `emit_cluster`, so a row present for one and absent for the
4630                    // other is a descriptor read out of an empty slot.
4631                    read_only: true,
4632                    dynamic: false,
4633                    stride: size_of::<u32>() as u32,
4634                },
4635                count: 1,
4636                flags: BindingFlags::empty(),
4637            });
4638        }
4639
4640        // The `DFG` table, above everything — see [`SPECULAR_DFG_BINDING`].
4641        //
4642        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4643        // Metal backend materialises every global into every entry point, so
4644        // `msl/mesh.metal`'s `vertexMain` takes `specular_dfg [[texture(3)]]`
4645        // whether it reads it or not.
4646        mesh_entries.push(BindGroupLayoutEntry {
4647            binding: SPECULAR_DFG_BINDING,
4648            visibility: geometry.union(ShaderStages::FRAGMENT),
4649            kind: BindingKind::SampledImage {
4650                view_type: ImageViewType::D2,
4651                // `Float`, as the occlusion channel above: an `Rgba8Unorm`
4652                // colour image, declared `texture_2d<f32>` by the WGSL artifact.
4653                sample_type: SampleType::Float,
4654            },
4655            count: 1,
4656            flags: BindingFlags::empty(),
4657        });
4658
4659        // §2's normal page, above everything — see [`NORMAL_PAGE_BINDING`].
4660        //
4661        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4662        // Metal backend materialises every global into every entry point, so
4663        // `msl/mesh.metal`'s `vertexMain` takes the page whether it samples it
4664        // or not. **A sampled image and not a storage buffer**, which costs this
4665        // layout nothing at the WebGPU ceiling checked below — that limit counts
4666        // storage buffers, and this row is a texture.
4667        mesh_entries.push(BindGroupLayoutEntry {
4668            binding: NORMAL_PAGE_BINDING,
4669            visibility: geometry.union(ShaderStages::FRAGMENT),
4670            kind: BindingKind::SampledImage {
4671                view_type: ImageViewType::D2Array,
4672                // `Float`: an `Rgba8Unorm` image, declared
4673                // `texture_2d_array<f32>` by the WGSL artifact — the same
4674                // sample type the sRGB base-colour page reports, since both
4675                // decode to floats.
4676                sample_type: SampleType::Float,
4677            },
4678            count: 1,
4679            flags: BindingFlags::empty(),
4680        });
4681        // The area lights' table, above the page — see [`LTC_TABLE_BINDING`].
4682        //
4683        // `geometry` beside `FRAGMENT` for the two rows above it's reason.
4684        // `Float` because `Rgba16Float` is a filterable sampled format on every
4685        // target this engine opens, and the WGSL artifact declares it
4686        // `texture_2d<f32>` — the shader only ever `Load`s it, but the layout
4687        // has to say what the module declared.
4688        mesh_entries.push(BindGroupLayoutEntry {
4689            binding: LTC_TABLE_BINDING,
4690            visibility: geometry.union(ShaderStages::FRAGMENT),
4691            kind: BindingKind::SampledImage {
4692                view_type: ImageViewType::D2,
4693                sample_type: SampleType::Float,
4694            },
4695            count: 1,
4696            flags: BindingFlags::empty(),
4697        });
4698        // Topic 45's contact-shadow channel, last of the set —
4699        // see [`CONTACT_SHADOW_BINDING`] on why last is structural rather than
4700        // tidy.
4701        //
4702        // `geometry` beside `FRAGMENT` and `Float` for the occlusion channel's
4703        // reasons exactly: it is the same `R8Unorm` shape, and Slang's Metal
4704        // backend materialises every global into every entry point whether that
4705        // stage reads it or not.
4706        mesh_entries.push(BindGroupLayoutEntry {
4707            binding: CONTACT_SHADOW_BINDING,
4708            visibility: geometry.union(ShaderStages::FRAGMENT),
4709            kind: BindingKind::SampledImage {
4710                view_type: ImageViewType::D2,
4711                sample_type: SampleType::Float,
4712            },
4713            count: 1,
4714            flags: BindingFlags::empty(),
4715        });
4716        // The irradiance probes' per-probe visibility maps, last
4717        // of the set — see [`PROBE_VISIBILITY_BINDING`] on why last is
4718        // structural.
4719        //
4720        // `D2Array` has to be *declared*, not merely bound: WebGPU compares the
4721        // dimension a layout entry claims against the view handed to it at
4722        // pipeline creation, which is the normal page's own note.
4723        // `UnfilterableFloat` for the same reason and measured the same way: the
4724        // image is `Rg32Float`, which is unfilterable without WebGPU's
4725        // `float32-filterable`, and this slot declared `Float` made Chromium
4726        // refuse the whole mesh bind group — "None of the supported sample types
4727        // (UnfilterableFloat) ... match the expected sample types (Float)" —
4728        // which took every 3D demo's frame to black. Reading it only with `Load`
4729        // does not lift that: the check is on the layout against the view's
4730        // format, not on how the shader gets at it.
4731        mesh_entries.push(BindGroupLayoutEntry {
4732            binding: PROBE_VISIBILITY_BINDING,
4733            visibility: geometry.union(ShaderStages::FRAGMENT),
4734            kind: BindingKind::SampledImage {
4735                view_type: ImageViewType::D2Array,
4736                sample_type: SampleType::UnfilterableFloat,
4737            },
4738            count: 1,
4739            flags: BindingFlags::empty(),
4740        });
4741        // §2's other two pages, last of the set — see [`MRO_PAGE_BINDING`] and
4742        // [`EMISSIVE_PAGE_BINDING`] on why last is structural rather than tidy.
4743        //
4744        // `geometry` beside `FRAGMENT`, `D2Array` and `Float` are the normal
4745        // page's three answers exactly, and for its reasons: Slang's Metal
4746        // backend materialises every global into every entry point, WebGPU
4747        // compares the declared dimension against the bound view, and both
4748        // images are `Rgba8Unorm`-family formats that decode to filterable
4749        // floats.
4750        for binding in [MRO_PAGE_BINDING, EMISSIVE_PAGE_BINDING] {
4751            mesh_entries.push(BindGroupLayoutEntry {
4752                binding,
4753                visibility: geometry.union(ShaderStages::FRAGMENT),
4754                kind: BindingKind::SampledImage {
4755                    view_type: ImageViewType::D2Array,
4756                    sample_type: SampleType::Float,
4757                },
4758                count: 1,
4759                flags: BindingFlags::empty(),
4760            });
4761        }
4762        mesh_entries.sort_by_key(|entry| entry.binding);
4763        let mesh_desc = BindGroupLayoutDesc {
4764            label: Some(MESH_LAYOUT_LABEL),
4765            entries: &mesh_entries,
4766        };
4767        // **This layout is at the guaranteed limit with no headroom on the
4768        // raster path, in both raster stages**: the vertex stage takes every
4769        // storage buffer a WebGPU device promises, and since bindings 1 to 5
4770        // gained FRAGMENT visibility for Metal's debug layer the fragment stage
4771        // takes the same number. A ninth in either is a renderer that cannot be
4772        // built in a browser or on SwiftShader, so it fails here rather than at
4773        // somebody else's `createPipelineLayout` — see
4774        // [`crcbl_hal::check_portable_storage_buffers`], which also says why the
4775        // mesh path's extra reads are outside the count.
4776        // `Some("mesh")`, which is the *pipeline* layout's label, not
4777        // `mesh_desc.label` — the error text reads "pipeline layout {label}
4778        // binds …", so naming the bind group layout there sends the reader to
4779        // the wrong object.
4780        check_portable_storage_buffers(Some("mesh"), &[&mesh_desc])?;
4781        let mesh_layout = device.create_bind_group_layout(&mesh_desc)?;
4782        rollback.bind_group_layouts.push(mesh_layout);
4783
4784        // A dynamic offset must be a multiple of the device's alignment, and one
4785        // block has to fit inside one stride. Read from the device rather than
4786        // assumed, exactly as `crate::sprite_pass` does: 256 on WebGPU, 64 on a
4787        // typical desktop Vulkan driver.
4788        //
4789        // One stride for both blocks, sized for the larger — see
4790        // [`DRAW_CONSTANTS_BLOCK`]. Which of the two a bucket's block holds is
4791        // decided below.
4792        let alignment = device.caps().limits.min_uniform_buffer_offset_alignment;
4793        let draw_stride =
4794            u32::try_from(DRAW_CONSTANTS_BLOCK.next_multiple_of(alignment)).map_err(|_| {
4795                HalError::InvalidDescriptor(format!(
4796                    "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic \
4797                         offset can express"
4798                ))
4799            })?;
4800        let draw_constants = device.create_buffer(&BufferDesc {
4801            label: Some("mesh draw constants"),
4802            // A block per bucket per draw region: a region's draws name their
4803            // own run starts, and the mesh path's block names the region's
4804            // argument structure. See `crcbl_shaders::draw_gen::DRAW_REGIONS`.
4805            size: u64::from(draw_stride)
4806                * u64::from(bucket_count)
4807                * u64::from(crcbl_shaders::draw_gen::DRAW_REGIONS),
4808            usage: BufferUsage::UNIFORM,
4809            memory: MemoryLocation::HostUpload,
4810        })?;
4811        rollback.buffers.push(draw_constants);
4812        // --- the shadow map's own resources ---
4813        //
4814        // Before the bind groups, because every one of them names the atlas or
4815        // the placeholder standing in for it.
4816        let (atlas_width, atlas_height) = shadow::atlas_extent();
4817        let shadow_atlas = device.create_image(&ImageDesc {
4818            label: Some("shadow atlas"),
4819            image_type: ImageType::D2,
4820            format: Format::D32Float,
4821            extent: crcbl_hal::Extent3d::d2(atlas_width, atlas_height),
4822            mip_levels: 1,
4823            samples: 1,
4824            // `TRANSFER_SRC` so a test can copy the cascades back and check
4825            // that something was written into them. A shadow map that stayed at
4826            // its clear value produces a frame that looks entirely plausible —
4827            // everything is lit — so the readback is the only thing that can
4828            // tell a working pass from one that drew nothing.
4829            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
4830                .union(ImageUsage::SAMPLED)
4831                .union(ImageUsage::TRANSFER_SRC),
4832        })?;
4833        rollback.images.push(shadow_atlas);
4834        let shadow_atlas_view = device.create_image_view(&ImageViewDesc {
4835            label: Some("shadow atlas"),
4836            image: shadow_atlas,
4837            view_type: ImageViewType::D2,
4838            format: Format::D32Float,
4839            range: ImageSubresourceRange::all(Format::D32Float),
4840        })?;
4841        rollback.image_views.push(shadow_atlas_view);
4842
4843        let shadow_placeholder = device.create_image(&ImageDesc {
4844            label: Some("shadow placeholder"),
4845            image_type: ImageType::D2,
4846            format: Format::D32Float,
4847            extent: crcbl_hal::Extent3d::d2(1, 1),
4848            mip_levels: 1,
4849            samples: 1,
4850            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT.union(ImageUsage::SAMPLED),
4851        })?;
4852        rollback.images.push(shadow_placeholder);
4853        let shadow_placeholder_view = device.create_image_view(&ImageViewDesc {
4854            label: Some("shadow placeholder"),
4855            image: shadow_placeholder,
4856            view_type: ImageViewType::D2,
4857            format: Format::D32Float,
4858            range: ImageSubresourceRange::all(Format::D32Float),
4859        })?;
4860        rollback.image_views.push(shadow_placeholder_view);
4861
4862        // The occlusion placeholder, beside the shadow one and for the same
4863        // reason: every group of this layout has to fill
4864        // [`AMBIENT_OCCLUSION_BINDING`], and most of them are built before the
4865        // graph has an occlusion image to name.
4866        //
4867        // **Uploaded rather than cleared**, unlike the depth placeholder above,
4868        // and the four bytes are the whole point — see
4869        // [`AMBIENT_OCCLUSION_NONE`], which is where each of them is argued.
4870        // Left undefined this would be a random ambient scale *and* a random
4871        // direction to steer it along, on any frame that fell back to it.
4872        let ambient_occlusion_placeholder = upload_texture(
4873            device,
4874            queue,
4875            "ssao placeholder",
4876            Format::Rgba8Unorm,
4877            1,
4878            1,
4879            &AMBIENT_OCCLUSION_NONE,
4880        )?;
4881        rollback.textures.push(ambient_occlusion_placeholder);
4882
4883        // The contact-shadow placeholder, beside the occlusion one and on its
4884        // terms exactly: every group of this layout has to fill
4885        // [`CONTACT_SHADOW_BINDING`], and most of them are built before the graph
4886        // has a contact-shadow image to name. `0xFF` is `1.0` through `R8Unorm`,
4887        // so a fragment that reads this one is a fragment the sun reaches
4888        // unobstructed.
4889        let contact_shadow_placeholder = upload_texture(
4890            device,
4891            queue,
4892            "contact shadow placeholder",
4893            Format::R8Unorm,
4894            1,
4895            1,
4896            &[CONTACT_SHADOW_NONE],
4897        )?;
4898        rollback.textures.push(contact_shadow_placeholder);
4899
4900        // The probe-visibility placeholder, on the two above it's terms: every
4901        // group of this layout has to fill [`PROBE_VISIBILITY_BINDING`], and
4902        // nothing has been captured when they are built. One texel of
4903        // [`probe_visibility_none`], which no surface is further away than, so a
4904        // probe read through it keeps all of its weight.
4905        let probe_visibility_placeholder = upload_texture_layers(
4906            device,
4907            queue,
4908            "probe visibility placeholder",
4909            Format::Rg32Float,
4910            1,
4911            1,
4912            &[&probe_visibility_none()],
4913        )?;
4914        rollback.textures.push(probe_visibility_placeholder);
4915
4916        // The split-sum `DFG` table, uploaded once and read by every frame this
4917        // renderer will draw — `crcbl_shaders::dfg` is where it is integrated,
4918        // committed and encoded, and `SPECULAR_ALBEDO_BINDING` is where it lands.
4919        //
4920        // **Cooked bytes rather than a computed image**: the integrator
4921        // importance-samples a lobe, which is `sin`, `cos` and a `powf`, and this
4922        // engine's goldens are compared across four backends with no tolerance.
4923        // Baking here would be four slightly different tables.
4924        let specular_dfg = upload_texture(
4925            device,
4926            queue,
4927            "dfg table",
4928            // Two bytes of fixed point per channel, high byte first — see
4929            // `crcbl_shaders::dfg::PAIR_TEXEL_BYTES`, which argues why this is
4930            // not the `Rg16Float` the format's own doc anticipated.
4931            Format::Rgba8Unorm,
4932            DFG_SIZE_U32,
4933            DFG_SIZE_U32,
4934            &dfg::pair_texels(),
4935        )?;
4936        rollback.textures.push(specular_dfg);
4937
4938        // The area lights' fit, beside it and on its terms — cooked bytes for
4939        // the same reason, and `Rgba16Float` rather than fixed point because
4940        // these are matrix entries rather than shares of arriving light.
4941        // `crcbl_shaders::ltc::LTC_TEXEL_BYTES` argues the format.
4942        let ltc_table = upload_texture(
4943            device,
4944            queue,
4945            "ltc table",
4946            Format::Rgba16Float,
4947            LTC_SIZE_U32,
4948            LTC_SIZE_U32,
4949            &ltc::texels(),
4950        )?;
4951        rollback.textures.push(ltc_table);
4952        service();
4953
4954        // **A comparison sampler, and that is the PCF.** Each
4955        // `SampleCmpLevelZero` returns the filtered fraction of four texels that
4956        // passed the test, so the shader's 3×3 kernel is nine hardware-bilinear
4957        // comparisons rather than nine raw fetches it averages itself.
4958        //
4959        // `Greater` for the engine's reversed-Z, exactly as the depth *test*
4960        // is: the receiver survives when it is nearer the light than whatever
4961        // the map stored. `SamplerDesc::compare` carries the same warning.
4962        //
4963        // Clamped on every axis so a receiver just outside a cascade's box
4964        // reads the edge rather than wrapping into the opposite corner — the
4965        // shader's own bounds check is what actually handles that case, and this
4966        // is the second line of defence one texel wide.
4967        let shadow_sampler = device.create_sampler(&SamplerDesc {
4968            label: Some("shadow comparison"),
4969            mag_filter: FilterMode::Linear,
4970            min_filter: FilterMode::Linear,
4971            mip_filter: FilterMode::Nearest,
4972            address_mode: [SamplerAddressMode::ClampToEdge; 3],
4973            compare: Some(crcbl_hal::CompareOp::Greater),
4974            ..SamplerDesc::default()
4975        })?;
4976        rollback.samplers.push(shadow_sampler);
4977
4978        // --- the camera ---
4979        //
4980        // Everything the camera's picture needs of its own, built against the
4981        // scene resources above — see [`view`], which is where the line between
4982        // the two is drawn. Into the rollback whole as soon as it exists, so a
4983        // failure further down releases it with everything else.
4984        let slot_pages = vec![page_bindings; instance_buffers.len()];
4985        rollback.primary = Some(View::build(
4986            device,
4987            queue,
4988            &ViewInputs {
4989                id: ViewId::PRIMARY,
4990                effects: RenderEffects::all(),
4991                background: ViewBackground::Scene,
4992                lighting: ViewLighting::Scene,
4993                target_format,
4994                emit,
4995                instances: &instance_buffers,
4996                mesh_table,
4997                bucket_meshes: &bucket_meshes,
4998                bucket_modes: &bucket_modes,
4999                bucket_clusters: &bucket_clusters,
5000                bucket_cluster_bases: &bucket_cluster_bases,
5001                mesh_levels: &mesh_levels,
5002                level_groups: &level_groups,
5003                level_meshes: &level_meshes,
5004                instance_capacity: scene.capacities.instances,
5005                light_capacity: scene.capacities.lights,
5006                clusters: rollback.clusters.as_ref(),
5007                task_lanes: view::task_lanes(culls_clusters),
5008                mesh_layout,
5009                vertices,
5010                draw_constants,
5011                materials: material_buffer,
5012                pages: &slot_pages,
5013                probes: &probe_buffers,
5014                specular_dfg: specular_dfg.view,
5015                ltc_table: ltc_table.view,
5016                shadow_map: shadow_atlas_view,
5017                shadow_sampler,
5018                ambient_occlusion: ambient_occlusion_placeholder.view,
5019                contact_shadow: contact_shadow_placeholder.view,
5020                probe_visibility: probe_visibility_placeholder.view,
5021            },
5022            service,
5023        )?);
5024        let primary = rollback.primary.as_ref().expect("just stored");
5025
5026        // Written here and never again: **which word holds** a bucket's run
5027        // start is fixed by the bucket table and the capacity, and both are
5028        // fixed at build. What varies per frame is where the run starts and how
5029        // much of it is filled, and the GPU writes both — the start into that
5030        // word, the count into the bucket's indirect arguments. See
5031        // `mesh.slang`'s header for why the block names a word rather than
5032        // carrying the start.
5033        //
5034        // Taken from the camera's generator and bound for every generator's
5035        // draws: the shadow culls and every secondary view are built from the
5036        // same table and the same capacity, so `bucket_start_word` answers the
5037        // same for all of them.
5038        let draws = &primary.draws;
5039        let mut bucket_constants = vec![0u32; bucket_meshes.len()];
5040        // **Every draw region's copy**, region 0's at the offsets
5041        // `bucket_constants` records and each further region a bucket count of
5042        // strides behind the one before: a region's draw reads its own run
5043        // start and — on the mesh path — its own argument structure, and the
5044        // two are the only words a region changes. See
5045        // `crcbl_shaders::draw_gen::DRAW_REGIONS`.
5046        for (region, (bucket, index)) in
5047            (0..crcbl_shaders::draw_gen::DRAW_REGIONS).flat_map(|region| {
5048                (0..bucket_count).map(move |bucket| (region, (bucket, bucket as usize)))
5049            })
5050        {
5051            let offset = (region * bucket_count + bucket) * draw_stride;
5052            if region == 0 {
5053                bucket_constants[index] = offset;
5054            }
5055            let start_at = draws.region_start_word(region, bucket);
5056            // The mesh path's block says three more things — where this
5057            // bucket's mesh's clusters are, how many it has, and which element
5058            // of the indirect arguments holds its instance count — because a
5059            // dispatch carries none of them and a `draw_indexed_indirect` does
5060            // not need them. All three are fixed when the bucket table is,
5061            // exactly like `start_at`.
5062            let block = if emit.is_mesh() {
5063                crcbl_shaders::meshlet::ClusterDrawConstants {
5064                    start_at,
5065                    cluster_base: bucket_cluster_bases[index],
5066                    cluster_count: bucket_clusters[index],
5067                    // The region's argument structure, which is where this
5068                    // region's instance count is.
5069                    bucket: region * bucket_count + bucket,
5070                    // The same number the draw-argument pass indexes the state
5071                    // with, taken from the object that owns the buffer rather
5072                    // than recomputed from the group table — the two indexing it
5073                    // differently is a cluster reading another instance's
5074                    // decision.
5075                    group_stride: draws.group_stride(),
5076                    // Where the group records are in the table buffer, from the
5077                    // object that packed it — the screen-error heatmap's one
5078                    // input that is not already in the frame block. Taken from
5079                    // `DrawGen` rather than recomputed here for `group_stride`'s
5080                    // reason: two spellings of one offset is an overlay reading
5081                    // another region's words as a group.
5082                    level_groups_at: draws.table_offsets().level_groups_at,
5083                    // The same two numbers again as words of that buffer,
5084                    // which is where a draw that is not the first of a ranged
5085                    // call reads them — `mesh_cluster.slang`'s "One call for
5086                    // a range of buckets". This bucket's, not the region's
5087                    // argument structure's: the tables hold one word a bucket.
5088                    cluster_base_at: draws.table_offsets().bucket_cluster_bases_at + bucket,
5089                    cluster_count_at: draws.table_offsets().bucket_clusters_at + bucket,
5090                    // Where this bucket's task chunks start in this region,
5091                    // and where the region's end: what a flat call binding
5092                    // this block searches between — `mesh_cluster.slang`'s
5093                    // `taskMain`.
5094                    chunk_starts_at: draws.chunk_start_word(region, bucket),
5095                    chunk_starts_end: draws.chunk_start_word(region, bucket_count),
5096                }
5097                .to_bytes()
5098                .to_vec()
5099            } else {
5100                // **The bucket's mesh, which is not always the drawn instance's.**
5101                // A uniform cut selects one of a DAG's levels and each level is
5102                // a mesh table entry of its own, so this is what says which
5103                // geometry the draw's index range belongs to; the instance goes
5104                // on naming level 0. See `mesh::DrawConstants::mesh`.
5105                mesh::DrawConstants {
5106                    start_at,
5107                    mesh: bucket_meshes[index],
5108                    mesh_at: draws.bucket_mesh_word(bucket),
5109                }
5110                .to_bytes()
5111                .to_vec()
5112            };
5113            device.write_buffer(draw_constants, u64::from(offset), &block)?;
5114        }
5115
5116        let region_step = RegionStep {
5117            constants: bucket_count * draw_stride,
5118            args: draws.args_region_offset(1),
5119            counts: draws.counts_region_offset(1),
5120        };
5121
5122        // §3.3's cull, once per cascade and once per shadowed light. Each gets
5123        // its own `DrawGen` and therefore its own frustum, survivor list and
5124        // indirect arguments — which is what "one cull dispatch per cascade
5125        // against the same instance/geometry pools" means, and why the instance
5126        // ring and the mesh table below are the same handles the camera's cull
5127        // was given.
5128        //
5129        // **One per light rather than one per tile**, which is topic 18's fourth
5130        // decision and what `SHADOW_CULLS` is: a point light's six faces cull
5131        // against the light's sphere once and draw that one visible set through
5132        // six matrices.
5133        //
5134        // **Built for every slot, including the ones no light may ever hold.** A
5135        // generator's buffers are sized by the instance capacity rather than by
5136        // the scene, so building one on demand would mean allocating device
5137        // memory inside `begin_frame` — and a frame that cannot allocate is a
5138        // frame that cannot draw. The unused ones cost memory and no dispatch:
5139        // `add_shadow_pass` records passes for the occupied slots alone.
5140        for cull in 0..SHADOW_CULLS {
5141            // Into the rollback as each is built, on the same terms as the
5142            // camera's: a failure two culls in has to release the first one,
5143            // and the rollback is the only thing that knows about it.
5144            let label = if cull < shadow::CASCADES {
5145                format!("shadow cascade {cull}")
5146            } else {
5147                format!("shadow light {}", cull - shadow::CASCADES)
5148            };
5149            let draws = DrawGen::new(
5150                device,
5151                queue,
5152                &DrawGenDesc {
5153                    label: Some(&label),
5154                    instances: &instance_buffers,
5155                    mesh_table,
5156                    bucket_meshes: &bucket_meshes,
5157                    bucket_modes: &bucket_modes,
5158                    bucket_clusters: &bucket_clusters,
5159                    bucket_cluster_bases: &bucket_cluster_bases,
5160                    mesh_levels: &mesh_levels,
5161                    level_groups: &level_groups,
5162                    level_meshes: &level_meshes,
5163                    instance_capacity: scene.capacities.instances,
5164                    // No view's: a shadow map is drawn from everything resident
5165                    // that casts, so an instance a camera hides still casts its
5166                    // shadow and one `set_instance_casts_shadow` turned off does
5167                    // not — on every geometry path, since this is the cull they
5168                    // all draw from. The reflective shadow maps draw these same
5169                    // survivors, so such an instance bounces no light either.
5170                    hidden_view: mesh::GpuInstance::CASTS_NO_SHADOW,
5171                    // A light slot may hold a point light, whose six faces cull
5172                    // separately into six regions of the one generator; a
5173                    // cascade never does.
5174                    mode: if cull < shadow::CASCADES {
5175                        crcbl_shaders::draw_gen::DrawMode::Plain
5176                    } else {
5177                        crcbl_shaders::draw_gen::DrawMode::Faces
5178                    },
5179                    task_lanes: view::task_lanes(culls_clusters),
5180                },
5181            )?;
5182            rollback.shadow_draws.push(draws);
5183            service();
5184        }
5185        // The handles are `Copy` and are read out here for the same reason the
5186        // camera's are above: the pool they came from is the rollback's now.
5187        let tile_buffers: Vec<TileBuffers> = rollback
5188            .shadow_draws
5189            .iter()
5190            .map(|draws| TileBuffers {
5191                runs: (0..instance_buffers.len())
5192                    .map(|frame| draws.runs(frame))
5193                    .collect(),
5194                args: (0..instance_buffers.len())
5195                    .map(|frame| draws.args(frame))
5196                    .collect(),
5197                cull_params: (0..instance_buffers.len())
5198                    .map(|frame| draws.cull_params(frame))
5199                    .collect(),
5200                cull_stats: (0..instance_buffers.len())
5201                    .map(|frame| draws.visible_count(frame))
5202                    .collect(),
5203                group_state: draws.group_state(),
5204            })
5205            .collect();
5206
5207        let mut shadow_uniforms = Vec::with_capacity(FRAMES_IN_FLIGHT);
5208        let mut shadow_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
5209        let mut shadow_selection = Vec::with_capacity(FRAMES_IN_FLIGHT);
5210        let mut shadow_group_entries = Vec::with_capacity(FRAMES_IN_FLIGHT);
5211        for (frame, &slot_instances) in instance_buffers.iter().enumerate() {
5212            // Everything a group of this layout names that is the same in all of
5213            // this frame's — the camera's list and table buffers included, which
5214            // a shadow view binds because the layout declares them and reads
5215            // nothing of. The per-group half is what `MeshGroup` below varies,
5216            // and the two exist so the colour pass's group and the shadow pass's
5217            // are one description rather than two that agree today.
5218            let shared = SharedBindings {
5219                vertices,
5220                draw_constants,
5221                mesh_table,
5222                materials: material_buffer,
5223                pages: page_bindings,
5224                clusters: rollback.clusters.as_ref(),
5225                shadow_sampler,
5226                lights: primary.lights.lights(frame),
5227                light_grid: primary.lights.grid(frame),
5228                probes: probe_buffers[frame],
5229                tables: primary.draws.tables(),
5230                specular_dfg: specular_dfg.view,
5231                ltc_table: ltc_table.view,
5232            };
5233
5234            // The same layout again, once per shadow view, differing in exactly
5235            // the things a view is: which matrix, and which cull's survivors.
5236            //
5237            // **The view's own uniforms and the cull's shared buffers**, which
5238            // is the whole of what a point light's six faces are: one visible
5239            // set, six matrices. `shadow_cull` is the map from a view to the
5240            // generator behind it, and it is a compile-time one because a bind
5241            // group names its buffers when it is created — where a face's *tile*
5242            // is decided per frame and reaches the device as a viewport.
5243            let mut frame_shadow_uniforms = Vec::with_capacity(SHADOW_VIEWS);
5244            let mut frame_shadow_groups = Vec::with_capacity(SHADOW_VIEWS);
5245            let mut frame_shadow_selection = Vec::with_capacity(SHADOW_VIEWS);
5246            let mut frame_shadow_entries = Vec::with_capacity(SHADOW_VIEWS);
5247            for view in 0..SHADOW_VIEWS {
5248                let buffers = &tile_buffers[if view < shadow::CASCADES {
5249                    view
5250                } else {
5251                    shadow_cull((view - shadow::CASCADES) / shadow::POINT_FACES)
5252                }];
5253                let tile_uniforms = device.create_buffer(&BufferDesc {
5254                    label: Some("shadow view uniforms"),
5255                    size: mesh::FRAME_UNIFORMS_SIZE as u64,
5256                    usage: BufferUsage::UNIFORM,
5257                    memory: MemoryLocation::HostUpload,
5258                })?;
5259                rollback.buffers.push(tile_uniforms);
5260                let entries = MeshGroup {
5261                    uniforms: tile_uniforms,
5262                    instances: slot_instances,
5263                    runs: buffers.runs[frame],
5264                    args: buffers.args[frame],
5265                    // The amplification stage culls clusters against whatever
5266                    // frustum is in this block, and against
5267                    // `frame.camera_position` — which in a view's copy is the
5268                    // *light*. So the per-cluster cull rejects what faces away
5269                    // from the light, which is the right question for a shadow
5270                    // map and the wrong one to have asked with the camera's
5271                    // frustum.
5272                    cull_params: buffers.cull_params[frame],
5273                    cull_stats: buffers.cull_stats[frame],
5274                    // **This view's own**, and not the colour pass's: that pass
5275                    // is recorded last and would write over it. See
5276                    // `ForwardRenderer::shadow_selection`.
5277                    cluster_selection: tile_selection.get(view).map(|ring| ring[frame]),
5278                    // Its cull's — see `TileBuffers::group_state`, which is
5279                    // where that budget is argued.
5280                    group_state: emit.is_mesh().then_some(buffers.group_state),
5281                    shadow_map: shadow_placeholder_view,
5282                    // A cascade shades nothing — the pipeline has no fragment
5283                    // stage — so this slot exists only because Metal
5284                    // materialises every global into every entry point.
5285                    ambient_occlusion: ambient_occlusion_placeholder.view,
5286                    contact_shadow: contact_shadow_placeholder.view,
5287                    probe_visibility: probe_visibility_placeholder.view,
5288                }
5289                .entries(&shared);
5290                let group = device.create_bind_group(&BindGroupDesc {
5291                    label: Some("shadow view"),
5292                    layout: mesh_layout,
5293                    entries: &entries,
5294                    variable_count: None,
5295                })?;
5296                rollback.bind_groups.push(group);
5297                frame_shadow_uniforms.push(tile_uniforms);
5298                frame_shadow_groups.push(group);
5299                frame_shadow_entries.push(entries);
5300                frame_shadow_selection.extend(tile_selection.get(view).map(|ring| ring[frame]));
5301            }
5302            shadow_uniforms.push(frame_shadow_uniforms);
5303            shadow_groups.push(frame_shadow_groups);
5304            shadow_group_entries.push(frame_shadow_entries);
5305            shadow_selection.push(frame_shadow_selection);
5306            service();
5307        }
5308
5309        let mesh_set_layouts = [mesh_layout];
5310        let mesh_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5311            label: Some("mesh"),
5312            bind_group_layouts: &mesh_set_layouts,
5313            // The camera goes in the uniform buffer above rather than here:
5314            // `Features::PUSH_CONSTANTS` is absent on Tier B and the seam is
5315            // explicit that the substitute is a data-layout decision. So this
5316            // file needs no tier branch at all — it has been on Tier B's shape
5317            // since P1, and `crate::ui_pass` is where the split actually bites.
5318            push_constants: None,
5319        })?;
5320        rollback.pipeline_layouts.push(mesh_pipeline_layout);
5321
5322        // The colour pass's pipeline and its depth-only twin, out of one set of
5323        // modules — see [`MeshModules`], which is where the two shapes and the
5324        // reasons for them live. Both are created before either is unwrapped and
5325        // the modules are released between, so a failing creation leaks nothing.
5326        //
5327        // **Each shape is built twice, once per material side** — see
5328        // [`SidedPipelines`], which is where the cull modes and the reason for a
5329        // pipeline rather than a per-draw state live. The shadow tile clear is
5330        // the one exception: its triangle comes out of `SV_VertexID` and it
5331        // already culls nothing.
5332        //
5333        // **`service` before every one of them**: on a cold driver cache each is
5334        // a shader compilation, and this batch is the build's longest run of
5335        // them — see [`ForwardRenderer::with_scene_serviced`].
5336        let modules = MeshModules::new(device, emit, culls_clusters)?;
5337        let mesh_results = MeshModules::sided(|cull| {
5338            service();
5339            modules.color_pipeline(
5340                device,
5341                mesh_pipeline_layout,
5342                PolygonMode::Fill,
5343                cull,
5344                "forward",
5345            )
5346        });
5347        let shadow_results = MeshModules::sided(|cull| {
5348            service();
5349            modules.depth_pipeline(device, mesh_pipeline_layout, cull)
5350        });
5351        // And its cutout twin, which a frame whose material table masks alpha is
5352        // recorded with instead — see [`MeshModules::depth_masked_pipeline`].
5353        let depth_masked_results = MeshModules::sided(|cull| {
5354            service();
5355            modules.depth_masked_pipeline(device, mesh_pipeline_layout, cull)
5356        });
5357        // And the one that resets a tile, which the cadence rung needs and the
5358        // attachment's load operation cannot express — see
5359        // [`MeshModules::depth_clear_pipeline`].
5360        service();
5361        let shadow_clear_result = modules.depth_clear_pipeline(device, mesh_pipeline_layout);
5362        // And the irradiance probes' reflective shadow map, built
5363        // from the same modules and the same layout — see
5364        // [`MeshModules::rsm_pipeline`]. Built on every scene rather than only
5365        // on one whose probes ask to be updated: the modules are released a line
5366        // below and a pipeline built later would need them back, which is a
5367        // second shader compilation for a field a `ProbeGrid` decides.
5368        let rsm_results = MeshModules::sided(|cull| {
5369            service();
5370            modules.rsm_pipeline(device, mesh_pipeline_layout, cull)
5371        });
5372        modules.destroy(device);
5373        // Register every successful creation before propagating any error.
5374        // Results later in this batch may own pipelines even when the first
5375        // result failed; dropping an unvisited Result does not release a HAL
5376        // handle. The outer rollback owns all of them until build succeeds.
5377        for pipeline in mesh_results
5378            .iter()
5379            .chain(&shadow_results)
5380            .chain(&depth_masked_results)
5381            .chain(std::iter::once(&shadow_clear_result))
5382            .chain(&rsm_results)
5383            .flatten()
5384        {
5385            rollback.pipelines.push(*pipeline);
5386        }
5387        let into_sided = |results: [Result<GraphicsPipelineHandle, HalError>; 2]|
5388         -> Result<SidedPipelines, HalError> {
5389            let [single, double] = results;
5390            Ok(SidedPipelines { single: single?, double: double? })
5391        };
5392        let mesh_pipeline = into_sided(mesh_results)?;
5393        let shadow_pipeline = into_sided(shadow_results)?;
5394        let depth_masked_pipeline = into_sided(depth_masked_results)?;
5395        let shadow_clear_pipeline = shadow_clear_result?;
5396        let rsm_pipeline = into_sided(rsm_results)?;
5397
5398        // --- the tonemap pass ---
5399        let tonemap_entries = [
5400            BindGroupLayoutEntry {
5401                binding: 0,
5402                visibility: ShaderStages::FRAGMENT,
5403                kind: BindingKind::SampledImage {
5404                    view_type: ImageViewType::D2,
5405                    sample_type: SampleType::Float,
5406                },
5407                count: 1,
5408                flags: BindingFlags::empty(),
5409            },
5410            BindGroupLayoutEntry {
5411                binding: 1,
5412                visibility: ShaderStages::FRAGMENT,
5413                kind: BindingKind::Sampler { comparison: false },
5414                count: 1,
5415                flags: BindingFlags::empty(),
5416            },
5417            // The exposure — see [`set_exposure`](Self::set_exposure). A uniform
5418            // buffer rather than a push constant, which is [`crate::ui_pass`]'s
5419            // decision restated: WebGPU has no push constants at all, so a range
5420            // here would split this pass into a tier A and a tier B form —
5421            // two layouts, two buffers and, because one Slang entry point reads
5422            // either a `[[vk::push_constant]]` block or a `[[vk::binding]]`ed
5423            // one and never both, a second copy of `tonemap.slang`. Four bytes
5424            // once a frame do not buy that.
5425            //
5426            // `FRAGMENT` alone, and the artifact agrees: `spirv/tonemap.spv`
5427            // lists `%params` in the fragment `OpEntryPoint`'s interface and not
5428            // in the vertex one, because the vertex stage generates three
5429            // corners out of `SV_VertexID` and reads nothing.
5430            BindGroupLayoutEntry {
5431                binding: 2,
5432                visibility: ShaderStages::FRAGMENT,
5433                kind: BindingKind::UniformBuffer { dynamic: false },
5434                count: 1,
5435                flags: BindingFlags::empty(),
5436            },
5437            // The measured exposure — see [`crate::exposure`]. **Bound on every
5438            // frame, whether or not anything measured**, because a binding that
5439            // comes and goes is a second pipeline layout and a second group
5440            // cache keyed on which one is live, to save four bytes. The block
5441            // above carries the switch that decides whether the shader reads it.
5442            BindGroupLayoutEntry {
5443                binding: 3,
5444                visibility: ShaderStages::FRAGMENT,
5445                kind: BindingKind::StorageBuffer {
5446                    // Written by `exposure.slang`'s reduce and read here —
5447                    // `StructuredBuffer` in this shader, which is the truth
5448                    // rather than a hint.
5449                    read_only: true,
5450                    dynamic: false,
5451                    stride: size_of::<u32>() as u32,
5452                },
5453                count: 1,
5454                flags: BindingFlags::empty(),
5455            },
5456        ];
5457        let tonemap_desc = BindGroupLayoutDesc {
5458            label: Some("tonemap scene"),
5459            entries: &tonemap_entries,
5460        };
5461        check_portable_storage_buffers(Some("tonemap"), &[&tonemap_desc])?;
5462        let tonemap_layout = device.create_bind_group_layout(&tonemap_desc)?;
5463        rollback.bind_group_layouts.push(tonemap_layout);
5464        let tonemap_set_layouts = [tonemap_layout];
5465        let tonemap_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5466            label: Some("tonemap"),
5467            bind_group_layouts: &tonemap_set_layouts,
5468            push_constants: None,
5469        })?;
5470        rollback.pipeline_layouts.push(tonemap_pipeline_layout);
5471        let tonemap_vertex = entry(&TONEMAP, Stage::Vertex)?;
5472        let tonemap_fragment = entry(&TONEMAP, Stage::Fragment)?;
5473        let tonemap_module = device.create_shader_module(&ShaderModuleDesc {
5474            label: Some("tonemap.slang"),
5475            spirv: TONEMAP.spirv(),
5476            wgsl: TONEMAP.wgsl(),
5477            msl: TONEMAP.msl(),
5478            // A container per entry point, for the reason the mesh module above
5479            // gives.
5480            dxil: &TONEMAP.dxil_containers(),
5481        })?;
5482        let tonemap_targets = [ColorTargetState::opaque(target_format)];
5483        let tonemap_pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5484            label: Some("tonemap"),
5485            layout: tonemap_pipeline_layout,
5486            vertex: ShaderEntry {
5487                module: tonemap_module,
5488                entry_point: tonemap_vertex,
5489            },
5490            fragment: Some(ShaderEntry {
5491                module: tonemap_module,
5492                entry_point: tonemap_fragment,
5493            }),
5494            // The full-screen triangle is deliberately oversized, so two of its
5495            // vertices are outside the viewport and its winding is not worth
5496            // reasoning about. `CullMode::None` is the honest setting.
5497            primitive: PrimitiveState::default(),
5498            depth_stencil: None,
5499            multisample: MultisampleState::default(),
5500            color_targets: &tonemap_targets,
5501        });
5502        device.destroy_shader_module(tonemap_module);
5503        let tonemap_pipeline = tonemap_pipeline?;
5504        rollback.pipelines.push(tonemap_pipeline);
5505        service();
5506
5507        // Nearest, not linear: see `tonemap.slang` on why a 1:1 blit must not
5508        // leave a golden image depending on two rasterisers agreeing about
5509        // texel-centre arithmetic.
5510        let sampler = device.create_sampler(&SamplerDesc {
5511            label: Some("tonemap scene"),
5512            mag_filter: FilterMode::Nearest,
5513            min_filter: FilterMode::Nearest,
5514            mip_filter: FilterMode::Nearest,
5515            address_mode: [SamplerAddressMode::ClampToEdge; 3],
5516            ..SamplerDesc::default()
5517        })?;
5518        rollback.samplers.push(sampler);
5519
5520        // --- the shadow atlas viewer ---
5521        //
5522        // Built last, so `Rollback::run` releases it first. It writes the
5523        // caller's target rather than a transient — it replaces the picture the
5524        // tonemap put there, which is [`crate::atlas_view`]'s argument — and it
5525        // records on no frame but the one that resolved
5526        // [`DebugView::ShadowAtlas`].
5527        rollback.atlas_viewer = Some(AtlasView::new(
5528            device,
5529            instance_buffers.len(),
5530            target_format,
5531            Self::build_fullscreen,
5532        )?);
5533        service();
5534
5535        Ok(Self {
5536            pool: rollback
5537                .pool
5538                .take()
5539                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5540            bucket_constants,
5541            region_step,
5542            bucket_modes,
5543            instances: rollback
5544                .instances
5545                .take()
5546                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5547            mesh_ids,
5548            skinnable_meshes,
5549            skinned_instances: Vec::new(),
5550            materials: rollback
5551                .materials
5552                .take()
5553                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5554            material_ids,
5555            probes: rollback
5556                .probes
5557                .take()
5558                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5559            probe_volume: scene.probes.volume,
5560            base_color_page,
5561            normal_page,
5562            mro_page,
5563            emissive_page,
5564            page_extents,
5565            page_layers,
5566            base_color_sampler,
5567            anisotropy,
5568            // Every slot's groups were just built naming these.
5569            slot_pages: vec![page_bindings; FRAMES_IN_FLIGHT],
5570            retired_pages: Vec::new(),
5571            // No frame has been recorded yet, and the counters say so rather
5572            // than reporting the count a frame *would* have.
5573            recorded_draws: 0,
5574            emit,
5575            range_limit,
5576            clusters: rollback.clusters.take(),
5577            culls_clusters,
5578            draw_constants,
5579            mesh_clusters,
5580            // One entry per description mesh, each holding one bucket per level,
5581            // where the cull pass takes a uniform cut — and nothing at all where
5582            // the amplification stage takes a per-cluster one. Read off the
5583            // bucket table that was actually built rather than re-derived from
5584            // the path.
5585            mesh_level_buckets: if emit.is_mesh() {
5586                Vec::new()
5587            } else {
5588                residents
5589                    .iter()
5590                    .enumerate()
5591                    .map(|(index, resident)| {
5592                        let base = bucket_bases[index];
5593                        (base..base + resident.levels.len())
5594                            .map(|bucket| {
5595                                u32::try_from(bucket)
5596                                    .unwrap_or_else(|_| unreachable!("a table of a few buckets"))
5597                            })
5598                            .collect()
5599                    })
5600                    .collect()
5601            },
5602            lod_error_budget: LOD_ERROR_BUDGET,
5603            lod_hold_ratio: LOD_HOLD_RATIO,
5604            // Overwritten by the first `begin_frame`, which is the only thing
5605            // that can know the viewport.
5606            shadow_lod_params: [0.0, 0.0, 0.0],
5607            extra_lights: Vec::new(),
5608            primary: rollback
5609                .primary
5610                .take()
5611                .unwrap_or_else(|| unreachable!("the camera was placed in the rollback above")),
5612            views: Vec::new(),
5613            draw_tables: DrawTables {
5614                bucket_meshes,
5615                bucket_clusters,
5616                bucket_cluster_bases,
5617                mesh_levels,
5618                level_groups,
5619                level_meshes,
5620                instance_capacity: scene.capacities.instances,
5621                light_capacity: scene.capacities.lights,
5622            },
5623            frame_serial: 0,
5624            frame_scene: None,
5625            frame: 0,
5626            mesh_layout,
5627            mesh_pipeline_layout,
5628            mesh_pipeline,
5629            // Off, and unbuilt, on the ground grid's terms below: the wireframe
5630            // view is opt-in, so a caller that never asks for one draws the
5631            // frame it drew before `set_wireframe` existed.
5632            wireframe_pipeline: None,
5633            wireframe_on: false,
5634            occlusion_culling: OcclusionCulling::OFF,
5635            point_face_culls: true,
5636            shadow_view_tamper: None,
5637            // Off, on the line above's terms: the normals view is opt-in, so a
5638            // caller that never asks for one draws the frame it drew before
5639            // `set_normals_view` existed. It builds nothing, so there is no
5640            // second field here.
5641            normals_view: false,
5642            // Off on the same terms, and "off" here is a density of zero: the
5643            // shader's composite is exactly the identity there, so a caller who
5644            // never calls `set_fog` gets the frame byte for byte.
5645            fog: Fog::NONE,
5646            sky: Sky::NONE,
5647            atmosphere: None,
5648            sky_view: None,
5649            sky_view_build: None,
5650            lod_view: false,
5651            heatmap: false,
5652            occlusion_view: false,
5653            motion_view: false,
5654            bent_normal_view: false,
5655            cascade_view: false,
5656            atlas_view: false,
5657            // Following the camera, on the line above's terms: the selection eye
5658            // is the camera's until a caller pins it, so a renderer nobody calls
5659            // `set_frozen_selection_eye` on hands `begin_frame` exactly what it
5660            // handed before this field existed.
5661            frozen_selection_eye: None,
5662            shadow_atlas,
5663            shadow_atlas_view,
5664            shadow_placeholder,
5665            shadow_placeholder_view,
5666            shadow_sampler,
5667            shadow_pipeline,
5668            depth_masked_pipeline,
5669            shadow_clear_pipeline,
5670            rsm_pipeline,
5671            probe_gather,
5672            probe_update: scene.probes.update,
5673            // Overwritten by the first `begin_frame`, which is the only reader's
5674            // only source. Zero is the honest placeholder: no cascade has been
5675            // fitted yet, and a gather recorded against it would scale by zero
5676            // rather than by a number nobody chose.
5677            cascade_reach: 0.0,
5678            // Nothing has been fitted before the first `begin_frame`.
5679            rsm_cull_ready: false,
5680            sun_color: Vec3::ZERO,
5681            shadow_draws: std::mem::take(&mut rollback.shadow_draws),
5682            shadow_uniforms,
5683            shadow_prepare_views: Vec::new(),
5684            shadow_prepare_culls: Vec::new(),
5685            shadow_groups,
5686            shadow_selection,
5687            shadow_lights: shadow::Selection::default(),
5688            // Nothing has drawn the atlas, so the first frame draws every group
5689            // whatever it is asked for — which is also what gives the image a
5690            // defined content before anything samples it. A record is never
5691            // empty, so the first frame's is a change and takes every id past
5692            // the zero below it.
5693            shadow_group_inputs: vec![Vec::new(); SHADOW_CULLS],
5694            shadow_group_id: vec![0; SHADOW_CULLS],
5695            shadow_group_writes: vec![0; SHADOW_CULLS],
5696            shadow_footprints: Vec::new(),
5697            shadow_dag_elements: std::collections::BTreeSet::new(),
5698            shadow_written: Vec::new(),
5699            shadow_moved: Vec::new(),
5700            shadow_pass_id: 0,
5701            shadow_pass_ran: Arc::new(AtomicU64::new(0)),
5702            shadow_pending: None,
5703            // A reach of zero, so every centre on the first frame is further
5704            // from what the image holds than the nothing it holds reaches —
5705            // which is the reset that frame should be.
5706            shadow_group_held: vec![(0, Vec3::ZERO, 0.0); SHADOW_CULLS],
5707            shadow_group_redrawn: vec![false; SHADOW_CULLS],
5708            shadow_atlas_layout: None,
5709            shadow_atlas_cached: false,
5710            shadow_cadence_reset: false,
5711            shadow_faces_redrawn: 0,
5712            shadow_cadence_request: None,
5713            shadow_atlas_clears: true,
5714            shadow_frame: 0,
5715            frame_skins: false,
5716            // [`FRAMES_IN_FLIGHT`], the number every other ring here is sized
5717            // by, so a slot has been through the whole loop before it is read.
5718            // `culls_clusters` rather than the device's feature bits: what
5719            // decides whether the cluster word is a count is whether *this
5720            // renderer* built an amplification stage.
5721            cull_stats: CullStatsRing::new(device, FRAMES_IN_FLIGHT, culls_clusters),
5722            tonemap_layout,
5723            tonemap_pipeline_layout,
5724            tonemap_pipeline,
5725            sampler,
5726            // The value `tonemap.slang`'s `EXPOSURE` constant held, so a
5727            // renderer nobody has called `set_exposure` on writes the frame it
5728            // wrote before the block existed.
5729            exposure: tonemap::DEFAULT_EXPOSURE,
5730            exposure_adaptation: None,
5731            // And the filmic roll-off over it: this renderer shades in linear
5732            // HDR, so a view that has asked for nothing gets the operator that
5733            // range was shaded for.
5734            tonemap_curve: tonemap::TonemapCurve::Aces,
5735            target_format,
5736            ambient_occlusion_placeholder,
5737            contact_shadow_placeholder,
5738            probe_visibility_placeholder,
5739            // Nothing has been captured, so every frame drawn before
5740            // `capture_probe_visibility` reads the placeholder and weighs every
5741            // probe at one — which is the frame this renderer drew before the
5742            // maps existed.
5743            probe_visibility: None,
5744            probe_occluders,
5745            specular_dfg,
5746            ltc_table,
5747            shadow_group_entries,
5748            // Off, and unbuilt: the grid is opt-in, so a caller that never asks
5749            // for one draws the frame it drew before this module existed.
5750            ground_grid: None,
5751            ground_grid_on: false,
5752            // Empty, and unbuilt: nothing has appended a segment, so this
5753            // renderer records the frame it recorded before the layer existed.
5754            debug_draw: DebugDraw::default(),
5755            atlas_viewer: rollback
5756                .atlas_viewer
5757                .take()
5758                .unwrap_or_else(|| unreachable!("the viewer was placed in the rollback above")),
5759            // Full resolution, which is the frame every caller of this type drew
5760            // before there was a knob — see [`Self::set_render_scale`].
5761            render_scale: 1.0,
5762            // The default stack the view wants, no quality clamp and no
5763            // override, which resolves to every effect this device permits but
5764            // the lens one — the frame every caller of this type drew before
5765            // there were toggles. See [`RenderEffects::DEFAULT_STACK`].
5766            effect_request: EffectRequest::default(),
5767            device_effects: RenderEffects::all(),
5768            frame_effects: RenderEffects::DEFAULT_STACK,
5769            // What the switch says today, so a renderer built and never opened
5770            // still describes the frame it would draw. `begin_frame` reads it
5771            // again for the frame it opens.
5772            frame_ssao_blurs: crate::ssao::blur_passes(),
5773            // No frame has been recorded yet, on `recorded_draws`' terms.
5774            recorded_fullscreen: 0,
5775            // No frame has been recorded yet, on `recorded_fullscreen`'s terms.
5776            recorded_debug_draw: 0,
5777            recorded_tile_clears: 0,
5778            // No bodies, so no pass: the frame every caller of this type drew
5779            // before water existed. Nothing is allocated until a body is set.
5780            water: WaterBodies::new(FRAMES_IN_FLIGHT),
5781            recorded_water_draws: 0,
5782            // No field, so no pass: the frame every caller of this type drew
5783            // before grass existed. The two calm wind layers are one texel
5784            // each and are what makes a field with no weather set still.
5785            grass: GrassScene::new(device, queue, FRAMES_IN_FLIGHT)?,
5786            wind: crcbl_shaders::wind::WindParams::default(),
5787            recorded_grass_draws: 0,
5788        })
5789    }
5790
5791    /// Builds a full-screen-triangle pipeline out of `shader`'s vertex and
5792    /// fragment entry points.
5793    ///
5794    /// One helper because every post pass in this crate wants the same
5795    /// pipeline — the tonemap's, `ssao`'s, `ssao-blur`'s, `ssr`'s and the rest —
5796    /// differing in the module, the layout and the target format alone. The
5797    /// tonemap's stays written out where it is: it is the one that carries the
5798    /// *why* of the shape, and this is the shape repeated.
5799    ///
5800    /// The module is destroyed before the pipeline result is unwrapped, so a
5801    /// failing creation leaks nothing.
5802    ///
5803    /// # Errors
5804    ///
5805    /// [`HalError`] from the manifest lookup, the module or the pipeline.
5806    fn build_fullscreen(
5807        device: &dyn Device,
5808        label: &str,
5809        shader: &crcbl_shaders::Shader,
5810        layout: PipelineLayoutHandle,
5811        color_targets: &[ColorTargetState],
5812    ) -> Result<GraphicsPipelineHandle, HalError> {
5813        Self::build_fullscreen_with(device, label, shader, layout, color_targets, None)
5814    }
5815
5816    /// [`Self::build_fullscreen`] for a pass that **depth-tests** what it draws
5817    /// against an attachment it does not write.
5818    ///
5819    /// The state is [`DepthStencilState::equal_depth_read_only`], whose
5820    /// [`CompareOp::GreaterOrEqual`] is the reversed-Z pair for "the fragment's
5821    /// depth must equal what is already there". One caller, [`crate::sky_pass`],
5822    /// which emits its triangle at the far plane so that the test selects
5823    /// exactly the pixels no geometry covered — see that module.
5824    ///
5825    /// # Errors
5826    ///
5827    /// [`HalError`] from the manifest lookup, the module or the pipeline.
5828    fn build_tested_fullscreen(
5829        device: &dyn Device,
5830        label: &str,
5831        shader: &crcbl_shaders::Shader,
5832        layout: PipelineLayoutHandle,
5833        color_targets: &[ColorTargetState],
5834        depth_format: Format,
5835    ) -> Result<GraphicsPipelineHandle, HalError> {
5836        Self::build_fullscreen_with(
5837            device,
5838            label,
5839            shader,
5840            layout,
5841            color_targets,
5842            Some(DepthStencilState::equal_depth_read_only(depth_format)),
5843        )
5844    }
5845
5846    /// The body of the two above, which differ in their depth state and in
5847    /// nothing else.
5848    ///
5849    /// # Errors
5850    ///
5851    /// [`HalError`] from the manifest lookup, the module or the pipeline.
5852    fn build_fullscreen_with(
5853        device: &dyn Device,
5854        label: &str,
5855        shader: &crcbl_shaders::Shader,
5856        layout: PipelineLayoutHandle,
5857        color_targets: &[ColorTargetState],
5858        depth_stencil: Option<DepthStencilState>,
5859    ) -> Result<GraphicsPipelineHandle, HalError> {
5860        let vertex = entry(shader, Stage::Vertex)?;
5861        let fragment = entry(shader, Stage::Fragment)?;
5862        let module = device.create_shader_module(&ShaderModuleDesc {
5863            label: Some(shader.source()),
5864            spirv: shader.spirv(),
5865            wgsl: shader.wgsl(),
5866            msl: shader.msl(),
5867            // A container per entry point, for the reason the mesh module gives.
5868            dxil: &shader.dxil_containers(),
5869        })?;
5870        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5871            label: Some(label),
5872            layout,
5873            vertex: ShaderEntry {
5874                module,
5875                entry_point: vertex,
5876            },
5877            fragment: Some(ShaderEntry {
5878                module,
5879                entry_point: fragment,
5880            }),
5881            // The triangle is deliberately oversized, so two of its vertices are
5882            // outside the viewport and its winding is not worth reasoning about.
5883            primitive: PrimitiveState::default(),
5884            depth_stencil,
5885            multisample: MultisampleState::default(),
5886            color_targets,
5887        });
5888        device.destroy_shader_module(module);
5889        pipeline
5890    }
5891
5892    /// Builds a full-screen-triangle pipeline that writes a **depth**
5893    /// attachment and no colour one.
5894    ///
5895    /// [`Self::build_fullscreen`]'s shape with the two halves of that swapped:
5896    /// no colour target at all, and a depth state whose comparison always
5897    /// passes so every texel of the destination takes the value the fragment
5898    /// computed. The reversed-Z [`CompareOp::Greater`] every geometry pipeline
5899    /// in this file uses would be wrong here — this pass is not depth-testing
5900    /// anything, it is writing a reduction, and a test against the target's
5901    /// undefined contents would drop texels at random.
5902    ///
5903    /// Two callers, [`crate::hiz`] and [`crate::occlusion_cull`], and it stays
5904    /// a method rather than moving there because the module and the
5905    /// destroy-before-unwrap above are this file's, and both take it in exactly
5906    /// as `crate::ssao` takes the sibling.
5907    ///
5908    /// **The entry points are named**, unlike the sibling's: `hiz.slang` has a
5909    /// fragment stage per pyramid, and a stage looked up by kind would be
5910    /// ambiguous.
5911    ///
5912    /// # Errors
5913    ///
5914    /// [`HalError`] from the module or the pipeline.
5915    fn build_depth_fullscreen(
5916        device: &dyn Device,
5917        label: &str,
5918        shader: &crcbl_shaders::Shader,
5919        vertex: &str,
5920        fragment: &str,
5921        layout: PipelineLayoutHandle,
5922        format: Format,
5923    ) -> Result<GraphicsPipelineHandle, HalError> {
5924        let module = device.create_shader_module(&ShaderModuleDesc {
5925            label: Some(shader.source()),
5926            spirv: shader.spirv(),
5927            wgsl: shader.wgsl(),
5928            msl: shader.msl(),
5929            dxil: &shader.dxil_containers(),
5930        })?;
5931        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5932            label: Some(label),
5933            layout,
5934            vertex: ShaderEntry {
5935                module,
5936                entry_point: vertex,
5937            },
5938            fragment: Some(ShaderEntry {
5939                module,
5940                entry_point: fragment,
5941            }),
5942            primitive: PrimitiveState::default(),
5943            depth_stencil: Some(DepthStencilState {
5944                format,
5945                depth_write: true,
5946                depth_compare: CompareOp::Always,
5947                stencil: None,
5948                bias: DepthBias::default(),
5949            }),
5950            multisample: MultisampleState::default(),
5951            color_targets: &[],
5952        });
5953        device.destroy_shader_module(module);
5954        pipeline
5955    }
5956
5957    /// Creates the geometry pool and makes every mesh of `scene` resident in it.
5958    ///
5959    /// Separate from [`ForwardRenderer::build`] because it is **self-cleaning**:
5960    /// the pool is not the rollback's until this has returned, so a failure
5961    /// between creating it and flushing the last upload releases it here.
5962    fn build_geometry(
5963        device: &dyn Device,
5964        queue: QueueHandle,
5965        scene: &SceneDesc<'_>,
5966        service: &mut dyn FnMut(),
5967    ) -> Result<(MeshPool, Vec<ResidentMesh>), HalError> {
5968        let mut pool = MeshPool::new(
5969            device,
5970            &MeshPoolDesc {
5971                label: Some("forward geometry"),
5972                vertex_capacity: scene.capacities.vertices,
5973                index_capacity: scene.capacities.indices,
5974                mesh_capacity: scene.capacities.meshes,
5975            },
5976        )?;
5977        match Self::residents(device, queue, &mut pool, scene, service) {
5978            Ok(residents) => Ok((pool, residents)),
5979            Err(error) => {
5980                pool.destroy(device);
5981                Err(error)
5982            }
5983        }
5984    }
5985
5986    /// Creates the material table and fills it with `scene`'s rows, returning it
5987    /// and the id of each.
5988    ///
5989    /// Self-cleaning for the same reason [`ForwardRenderer::build_geometry`] is:
5990    /// the table is not the rollback's until this has returned.
5991    fn build_materials(
5992        device: &dyn Device,
5993        scene: &SceneDesc<'_>,
5994    ) -> Result<(MaterialTable, Vec<u32>), HalError> {
5995        let mut materials = MaterialTable::new(
5996            device,
5997            &MaterialTableDesc {
5998                label: Some("forward"),
5999                capacity: scene.capacities.materials,
6000            },
6001        )?;
6002        match Self::material_rows(device, &mut materials, &scene.materials) {
6003            Ok(ids) => Ok((materials, ids)),
6004            Err(error) => {
6005                materials.destroy(device);
6006                Err(error)
6007            }
6008        }
6009    }
6010
6011    /// Inserts `rows` **in order** and returns the id of each.
6012    ///
6013    /// Split out of [`ForwardRenderer::build_materials`] only so the table can
6014    /// be released on a failure without the borrow that filling it takes, which
6015    /// is the same shape [`ForwardRenderer::residents`] has.
6016    ///
6017    /// **In order, because row 0 is not this function's to choose**: it is what
6018    /// [`mesh::GpuInstance::default`] names, so it is what an instance written
6019    /// without a material id shades with. Inserting a description's rows in any
6020    /// other order would move that row under every caller — see
6021    /// [`SceneDesc::materials`], which is where it is a caller's decision.
6022    fn material_rows(
6023        device: &dyn Device,
6024        materials: &mut MaterialTable,
6025        rows: &[mesh::GpuMaterial],
6026    ) -> Result<Vec<u32>, HalError> {
6027        let mut ids = Vec::with_capacity(rows.len());
6028        for row in rows {
6029            let handle = materials.insert(device, row)?;
6030            // The id is asked for rather than assumed, because the number an
6031            // instance carries is this one and nothing else knows it.
6032            ids.push(materials.index(handle).ok_or_else(|| {
6033                HalError::Backend(
6034                    "a material inserted into an empty table did not resolve".to_string(),
6035                )
6036            })?);
6037        }
6038        Ok(ids)
6039    }
6040
6041    /// Uploads every mesh of `scene` and returns their mesh ids — **only** once
6042    /// the transfers have completed.
6043    ///
6044    /// The calls are §3.1's upload path in order: the copies are recorded and
6045    /// submitted against timeline values, [`MeshPool::flush`] is what makes those
6046    /// values pass, and [`MeshPool::mesh`] is what refuses to hand out a range
6047    /// before they have.
6048    ///
6049    /// **In description order**, which is what makes a mesh's table id a
6050    /// property of the description rather than of this loop — the second mesh
6051    /// uploaded is the pool's first resident at a non-zero base vertex, which is
6052    /// what the module docs call the one thing that can tell a working base
6053    /// vertex from a cancelled one.
6054    ///
6055    /// A DAG is **one upload per level**. Every level was decimated separately,
6056    /// so a coarser level's vertices are wherever the collapses put them and
6057    /// belong to no vertex of the level below — a DAG is several vertex ranges,
6058    /// and the pool suballocates in vertices, so several ranges means several
6059    /// uploads. Level 0 goes first, so every other level starts past it and the
6060    /// offsets a cluster carries are non-negative; that is checked rather than
6061    /// assumed, because the pool's free list makes no promise about where a mesh
6062    /// lands.
6063    fn residents(
6064        device: &dyn Device,
6065        queue: QueueHandle,
6066        pool: &mut MeshPool,
6067        scene: &SceneDesc<'_>,
6068        service: &mut dyn FnMut(),
6069    ) -> Result<Vec<ResidentMesh>, HalError> {
6070        let mut uploaded: Vec<Vec<crate::mesh_pool::MeshHandle>> =
6071            Vec::with_capacity(scene.meshes.len());
6072        for desc in &scene.meshes {
6073            match &desc.geometry {
6074                Geometry::Flat {
6075                    vertices,
6076                    indices,
6077                    uv_range,
6078                    flags,
6079                    ..
6080                } => {
6081                    uploaded.push(vec![pool.upload(
6082                        device,
6083                        queue,
6084                        &MeshUpload {
6085                            label: &desc.label,
6086                            vertices,
6087                            indices,
6088                            uv_range: *uv_range,
6089                            flags: *flags,
6090                        },
6091                    )?]);
6092                    service();
6093                }
6094                Geometry::Dag {
6095                    levels,
6096                    dag,
6097                    uv_range,
6098                    flags,
6099                } => {
6100                    let mut handles = Vec::with_capacity(levels.len());
6101                    for (depth, (vertices, level)) in levels.iter().zip(&dag.levels).enumerate() {
6102                        handles.push(pool.upload(
6103                            device,
6104                            queue,
6105                            &MeshUpload {
6106                                label: &format!("{} level {depth}", desc.label),
6107                                vertices,
6108                                indices: &level.indices(),
6109                                // Level 0's range for every level, which is the
6110                                // one the mesh path reads whichever level it
6111                                // draws — see `Geometry::Dag::uv_range`.
6112                                uv_range: *uv_range,
6113                                // And the description's flags for every level,
6114                                // for the same reason: the levels are one
6115                                // surface, so a tangent frame either describes
6116                                // all of them or none.
6117                                flags: *flags,
6118                            },
6119                        )?);
6120                        service();
6121                    }
6122                    uploaded.push(handles);
6123                }
6124            }
6125        }
6126
6127        pool.flush(device)?;
6128        service();
6129        // The table index is the only number that leaves here — where the
6130        // geometry actually is reaches the GPU through the mesh table, and the
6131        // draw arguments are built from that table by a shader. `MeshPool::mesh`
6132        // is still asked, because it is the call that refuses a mesh whose
6133        // upload has not completed, and an id for a mesh that is not there yet
6134        // would be a draw of nothing.
6135        let resolve = |handle| match (pool.mesh(handle), pool.table_index(handle)) {
6136            (Some(_), Some(id)) => Ok(id),
6137            _ => Err(MeshPoolError::NotResident { handle }),
6138        };
6139        let base_vertex = |handle| match pool.mesh(handle) {
6140            Some(range) => Ok(range.base_vertex),
6141            None => Err(MeshPoolError::NotResident { handle }),
6142        };
6143
6144        let mut residents = Vec::with_capacity(uploaded.len());
6145        for (desc, handles) in scene.meshes.iter().zip(&uploaded) {
6146            // **Relative to level 0's base**, because that is the base the
6147            // instance resolves through its mesh id and the one the stage adds
6148            // this on top of. A level that landed *below* level 0 would make the
6149            // sum wrap, so it is refused here rather than drawn as another
6150            // mesh's vertices. A flat mesh is one level and reads zero.
6151            let level_zero = base_vertex(handles[0])?;
6152            let mut vertex_bases = Vec::with_capacity(handles.len());
6153            for (depth, &handle) in handles.iter().enumerate() {
6154                let base = base_vertex(handle)?;
6155                vertex_bases.push(base.checked_sub(level_zero).ok_or_else(|| {
6156                    HalError::InvalidDescriptor(format!(
6157                        "{} level {depth} landed at vertex {base}, below level 0's \
6158                         {level_zero}, so its clusters cannot name their own geometry",
6159                        desc.label
6160                    ))
6161                })?);
6162            }
6163            residents.push(ResidentMesh {
6164                levels: handles
6165                    .iter()
6166                    .map(|&handle| resolve(handle))
6167                    .collect::<Result<_, _>>()?,
6168                vertex_bases,
6169                // Matched on the description rather than counted off `handles`,
6170                // so a DAG decimated to a single level is still refused: what
6171                // makes a mesh skinnable is that every draw of it reads one
6172                // vertex run, and that is a property of the geometry rather than
6173                // of how many levels it happened to arrive with.
6174                skinnable: matches!(desc.geometry, Geometry::Flat { .. }).then(|| handles[0]),
6175            });
6176        }
6177        Ok(residents)
6178    }
6179
6180    /// Rotates to the next frame's uniform buffer and instance buffer, writes
6181    /// this frame's camera and light into the first, and uploads whatever
6182    /// changed into the second.
6183    ///
6184    /// Must be called once per frame, before [`ForwardRenderer::add_passes`].
6185    /// Separate from `add_passes` because the write happens on the CPU and the
6186    /// passes are recorded on the GPU timeline: fusing them would hide the ring
6187    /// rotation inside a function whose name says nothing about it.
6188    ///
6189    /// **It moves nothing.** Every object's transform is the caller's, written
6190    /// through [`ForwardRenderer::set_instance`] whenever it changes, so the
6191    /// transfer this records is [`InstancePool::begin_frame`]'s delta and a
6192    /// frame in which nothing moved uploads no instance bytes at all. The
6193    /// sandbox's spinning cube is one 80-byte write a frame because the sandbox
6194    /// spins it; a still scene is free.
6195    ///
6196    /// It also writes this frame's **cull parameters** — the camera's frustum,
6197    /// extracted from the very same view-projection the uniform block carries,
6198    /// so the pass that decides what is on screen and the pass that draws it
6199    /// cannot be looking at two different cameras — and zeroes the counters the
6200    /// two compute passes only ever add to. See [`crate::draw_gen`] on why those
6201    /// zeroes come from the host.
6202    ///
6203    /// # Errors
6204    ///
6205    /// [`HalError`] if the uniform buffer, the instance buffer or any of the
6206    /// draw-generation buffers could not be written.
6207    pub fn begin_frame(
6208        &mut self,
6209        device: &dyn Device,
6210        camera: &Camera,
6211        light: &DirectionalLight,
6212        extent: (u32, u32),
6213    ) -> Result<(), HalError> {
6214        // The instance pool owns the ring, so its slot is the frame index the
6215        // uniform buffer and the bind group below are picked with.
6216        self.frame = self.instances.rotate();
6217        self.frame_skins = false;
6218        self.instances.flush(device)?;
6219        self.begin_frame_body(device, camera, light, extent)
6220    }
6221
6222    /// [`begin_frame`](Self::begin_frame) for a frame that **skins**: the same
6223    /// call with the skinning plan folded into it.
6224    ///
6225    /// It does four things in the one order that is correct, which is why it is
6226    /// a call and not a note in someone's docs:
6227    ///
6228    /// 1. rotates the instance ring, so the frame slot exists;
6229    /// 2. hands that slot and `ranges` to `skinning`, which validates them,
6230    ///    uploads the palettes and **moves the ping-pong** — the only place the
6231    ///    parity ever moves;
6232    /// 3. points every object placed by
6233    ///    [`add_skinned_instance`](Self::add_skinned_instance) at the half of its
6234    ///    region the parity now names;
6235    /// 4. uploads the instance delta, so those bases are the ones this frame
6236    ///    draws.
6237    ///
6238    /// Do those three and four in the other order and the objects carry the
6239    /// previous frame's half — a character posed one frame late, every frame,
6240    /// with nothing to report it. A caller never sees a parity or a table id, and
6241    /// so cannot get that wrong.
6242    ///
6243    /// Build `ranges` with [`SkinnedMesh::skin_range`], one per reserved region
6244    /// this frame animates. A frame with **no** skinned object still calls this
6245    /// with an empty slice — see [`Skinning::begin_frame`], whose slot would
6246    /// otherwise re-dispatch whichever frame last used it.
6247    ///
6248    /// [`add_skinned_passes`](Self::add_skinned_passes) is the other half, and
6249    /// the one that orders the dispatch before the draws.
6250    ///
6251    /// # Errors
6252    ///
6253    /// Whatever [`Skinning::begin_frame`] refuses — a joint index past its
6254    /// palette, a binding count that is not the region's vertex count, more than
6255    /// the pass was built for — and [`SkinningError::Hal`] for anything the seam
6256    /// refused, this renderer's own uniform and instance writes included.
6257    ///
6258    /// # Panics
6259    ///
6260    /// If `skinning` was not built with at least [`FRAMES_IN_FLIGHT`] frames:
6261    /// its rings are indexed by this renderer's frame slot, and
6262    /// [`Skinning::begin_frame`] refuses a slot it has no buffers for.
6263    pub fn begin_skinned_frame(
6264        &mut self,
6265        device: &dyn Device,
6266        skinning: &mut Skinning,
6267        ranges: &[SkinRange<'_>],
6268        camera: &Camera,
6269        light: &DirectionalLight,
6270        extent: (u32, u32),
6271    ) -> Result<(), SkinningError> {
6272        self.frame = self.instances.rotate();
6273        // An empty plan dispatches nothing — see [`Skinning::begin_frame`] — so
6274        // it leaves the vertex pool where it was, and the shadow atlas with it.
6275        self.frame_skins = !ranges.is_empty();
6276        skinning.begin_frame(device, self.frame, ranges)?;
6277        self.point_skinned_instances(skinning.parity());
6278        self.instances.flush(device)?;
6279        self.begin_frame_body(device, camera, light, extent)?;
6280        Ok(())
6281    }
6282
6283    /// Whether this frame records the irradiance probes' two
6284    /// updater passes.
6285    ///
6286    /// The scene's own answer and the console's together: the volume decides
6287    /// whether the feature applies at all — see [`ProbeUpdate`], which is where
6288    /// the reason it is not an effect bit lives — and `r_probe_bounce` is the
6289    /// on/off pair a pricing run reads the two passes' cost off with everything
6290    /// else held still.
6291    ///
6292    /// **It is not the whole condition.** The map is cascade 0's own draws, so
6293    /// the pass is recorded only where that cascade is being drawn too — see
6294    /// `add_shadow_pass`, which is where the rest of it is.
6295    fn probe_update_runs(&self) -> bool {
6296        self.probe_update == ProbeUpdate::EveryFrame && rsm::enabled()
6297    }
6298
6299    /// The six side-plane sets a point light's face culls test, or `None` for
6300    /// a light that is not a point — or with the face culls switched off, which
6301    /// is one cull against the light's box drawn into all six faces.
6302    ///
6303    /// `faces` are the light's face matrices in face order, the ones its tiles
6304    /// render through.
6305    fn point_face_planes(&self, light: &Light, faces: &[Mat4]) -> Option<crate::cull::FacePlanes> {
6306        if !self.point_face_culls || !matches!(light, Light::Point(_)) {
6307            return None;
6308        }
6309        let matrices: [Mat4; shadow::POINT_FACES] = faces.try_into().ok()?;
6310        Some(crate::cull::face_planes(&matrices))
6311    }
6312
6313    /// Every punctual shadow face this frame draws into the punctual reflective
6314    /// shadow map, in the order the pass draws them and the producer table lists
6315    /// them.
6316    ///
6317    /// **One list for both halves of the updater**, and that is the point:
6318    /// `add_shadow_pass` sets a viewport from a face's
6319    /// [`tile`](PunctualFace::tile) and the gather reads that same rectangle out
6320    /// of the matching producer row, so a face the pass drew and a row the
6321    /// gather walked have to be the same face. Building the two from separate
6322    /// filters is two things that can drift, and the drift would be a light
6323    /// bouncing another light's map.
6324    ///
6325    /// **The occupied slots this frame redraws**, which is the same set
6326    /// `add_shadow_pass` gives the atlas: a face's transform is a shadow view's
6327    /// block and its draws are a shadow cull's, and
6328    /// [`Self::begin_frame_body`](Self::begin_frame) writes neither for a slot
6329    /// it is holding.
6330    ///
6331    /// # Every occupied tile, and no budget of its own
6332    ///
6333    /// The producers are exactly the atlas's occupied faces — up to
6334    /// [`shadow::LIGHT_SLOTS`] lights and [`shadow::LIGHT_TILES`] tiles between
6335    /// them — rather than the highest-ranked light or some smaller count.
6336    ///
6337    /// **Because the budget already exists and is spent.**
6338    /// [`shadow::Selection`] has ranked these lights by projected screen
6339    /// influence and handed out every tile there is; a second budget on top
6340    /// would rank the same lights again, differently, and produce a light that
6341    /// casts a shadow and lends no bounce. That is a difference no picture shows
6342    /// — the same argument [`Self::shadow_lights`] makes about a map's size —
6343    /// and it is the kind of quiet inconsistency the two halves of one light are
6344    /// worst placed to have.
6345    ///
6346    /// It is affordable at the extent that was chosen for it:
6347    /// `apps/lantern` lights seven faces, and
6348    /// [`PUNCTUAL_RSM_SIDE`](crcbl_shaders::probe_gather::PUNCTUAL_RSM_SIDE)
6349    /// carries the sweep that priced them.
6350    ///
6351    /// **Empty where shadows are off**, for that same reason — a punctual face
6352    /// *is* a shadow view. The sun's half is not, which is what
6353    /// `updater_drives_cascade_zero` exists for: switching shadows off keeps the
6354    /// sun's bounce and loses every punctual one, rather than switching the
6355    /// whole updater off with them.
6356    fn punctual_faces(&self) -> Vec<PunctualFace> {
6357        if !self.probe_update_runs() {
6358            return Vec::new();
6359        }
6360        // A frame with the shadows switched off draws no atlas, so no group of
6361        // it is *redrawn* — and `begin_frame_body`'s `updater_drives_cascade_zero`
6362        // branch has still written every one of these views and dispatched every
6363        // one of these culls, for this pass to draw through.
6364        let updater_drives = !self.frame_effects.contains(RenderEffects::SHADOWS);
6365        let mut faces = Vec::new();
6366        for (slot, held) in self.shadow_lights.slots().iter().enumerate() {
6367            let Some(held) = *held else {
6368                continue;
6369            };
6370            if !updater_drives && !self.shadow_group_redrawn[shadow_cull(slot)] {
6371                continue;
6372            }
6373            let Some(light) = self.extra_lights.get(held.light) else {
6374                continue;
6375            };
6376            // A spot draws face 0 alone and a point light all six, each through
6377            // its own matrix into its own tile — `shadow::tile_span` is the same
6378            // function `Selection` allocated the run with, so a face here and a
6379            // tile there cannot disagree about how many there are.
6380            for face in 0..shadow::tile_span(light) {
6381                let tile = rsm::punctual_tile(held.base + face);
6382                faces.push(PunctualFace {
6383                    view: shadow_view(slot, face),
6384                    cull: shadow_cull(slot),
6385                    face,
6386                    tile,
6387                    producer: producer_row(light, tile),
6388                });
6389            }
6390        }
6391        faces
6392    }
6393
6394    /// Puts an object in the scene and returns the handle that names it.
6395    ///
6396    /// An instance in the pool **is** an object in the scene: the frame records
6397    /// a fixed number of draws and the cull pass decides which instances they
6398    /// walk, so adding one costs a slot in an array and not a command. It is
6399    /// drawn from the next [`ForwardRenderer::begin_frame`], which is what
6400    /// uploads it.
6401    ///
6402    /// # The index it lands at is not decoration
6403    ///
6404    /// `draw_gen.slang` keys topic 25's hysteresis state by the
6405    /// instance's **array index**, at `instance_index * group_stride`, and
6406    /// `mesh_cluster.slang`'s amplification stage reads the same address. So the
6407    /// record of which of a DAG's groups an object had expanded belongs to the
6408    /// *slot*, not to the object — and a slot that [`remove_instance`] freed is
6409    /// handed to the next `add_instance`, which inherits it. What that costs is
6410    /// one frame selected against a history that is not this object's, and the
6411    /// next frame's own judgement replaces it; it is never a wrong picture,
6412    /// because every group is judged afresh whatever the state said.
6413    ///
6414    /// That inheritance is inert while the scene holds **one** instance of a DAG
6415    /// mesh, which is every frame the engine has drawn so far — one instance's
6416    /// run has no previous occupant, and a flat mesh's
6417    /// [`MeshLevels`](level_select::MeshLevels) record names no groups at all, so
6418    /// nothing indexes the state for it. It stops being inert the moment an
6419    /// application places a second.
6420    ///
6421    /// [`remove_instance`]: ForwardRenderer::remove_instance
6422    ///
6423    /// # A DAG mesh needs a device that can choose a level
6424    ///
6425    /// One device shape cannot draw a [`Geometry::Dag`] mesh: a mesh stage with
6426    /// **no** amplification stage in front of it emits every cluster of the
6427    /// bucket, which for a DAG is every level at once — several overlapping
6428    /// copies of one surface. This does not refuse it, because it has no
6429    /// vocabulary for that refusal; a caller placing a DAG asks
6430    /// [`ForwardRenderer::selects_levels`] first, and places it only where that
6431    /// says yes. A flat mesh is unaffected on every path.
6432    ///
6433    /// # Errors
6434    ///
6435    /// [`InstancePoolError::PoolFull`] when the instance pool is full. It never
6436    /// grows — [`Capacities::instances`](crate::scene::Capacities::instances) is
6437    /// what a caller sizes it with.
6438    ///
6439    /// # Panics
6440    ///
6441    /// If [`InstanceDesc::mesh`] or [`InstanceDesc::material`] is past the end of
6442    /// the description this renderer was built from. Both are indices a caller
6443    /// wrote against a description it holds, so an out-of-range one is a mistake
6444    /// in the calling code rather than a condition the frame can be in — and the
6445    /// alternative is an object silently drawn as some other mesh, in some other
6446    /// colour.
6447    pub fn add_instance(
6448        &mut self,
6449        desc: &InstanceDesc,
6450    ) -> Result<InstanceHandle, InstancePoolError> {
6451        let instance = self.gpu_instance(desc);
6452        self.instances.insert(&instance)
6453    }
6454
6455    /// Rewrites the object `handle` names — its mesh, its material and its
6456    /// transform, all three.
6457    ///
6458    /// A stale handle — one [`ForwardRenderer::remove_instance`] retired — writes
6459    /// nothing, rather than overwriting whatever took its slot.
6460    ///
6461    /// Takes effect at the next [`ForwardRenderer::begin_frame`], which uploads
6462    /// the element and nothing else: an object that did not move costs no
6463    /// transfer at all.
6464    ///
6465    /// # Panics
6466    ///
6467    /// On [`ForwardRenderer::add_instance`]'s terms, for the same reason.
6468    pub fn set_instance(&mut self, handle: InstanceHandle, desc: &InstanceDesc) {
6469        let mut instance = self.gpu_instance(desc);
6470        instance.flags |= self.kept_flags(handle);
6471        self.instances.set(handle, &instance);
6472    }
6473
6474    /// The bits of `handle`'s record a rewrite of it keeps: its hidden views
6475    /// and whether it casts — see [`ForwardRenderer::set_instance_views`] and
6476    /// [`ForwardRenderer::set_instance_casts_shadow`]. Zero for a stale
6477    /// handle, whose rewrite writes nothing anyway.
6478    fn kept_flags(&self, handle: InstanceHandle) -> u32 {
6479        self.instances.get(handle).map_or(0, |record| {
6480            record.flags
6481                & (mesh::GpuInstance::HIDDEN_VIEWS_MASK | mesh::GpuInstance::CASTS_NO_SHADOW)
6482        })
6483    }
6484
6485    /// Sets whether `handle` casts a shadow. Every instance starts casting.
6486    ///
6487    /// **Every shadow map and nothing else**: an instance that casts none is
6488    /// rejected by the cull of the sun's cascades and of every shadowed light,
6489    /// on every geometry path, so it lands in no tile of the atlas — and in no
6490    /// reflective shadow map, which draws those same culls' survivors, so it
6491    /// bounces no light into the probes either. Every camera still draws it,
6492    /// and it still receives the shadows the rest of the scene casts.
6493    ///
6494    /// What a model drawn for an icon wants, placed where the scene's sun can
6495    /// see it: see [`ViewBackground::Transparent`] and
6496    /// [`set_instance_views`](Self::set_instance_views).
6497    ///
6498    /// A change redraws every shadow map whose cull the instance could be kept
6499    /// by, because it is a write [`InstancePool::take_written`] names. Not a
6500    /// move, on
6501    /// [`set_instance_views`](Self::set_instance_views)' terms, and a stale
6502    /// handle is ignored.
6503    pub fn set_instance_casts_shadow(&mut self, handle: InstanceHandle, casts: bool) {
6504        if let Some(record) = self.instances.get(handle) {
6505            let flags = if casts {
6506                record.flags & !mesh::GpuInstance::CASTS_NO_SHADOW
6507            } else {
6508                record.flags | mesh::GpuInstance::CASTS_NO_SHADOW
6509            };
6510            self.instances.set_flags(handle, flags);
6511        }
6512    }
6513
6514    /// Whether `handle` casts a shadow, or `None` for a stale handle.
6515    #[must_use]
6516    pub fn instance_casts_shadow(&self, handle: InstanceHandle) -> Option<bool> {
6517        self.instances
6518            .get(handle)
6519            .map(|record| record.flags & mesh::GpuInstance::CASTS_NO_SHADOW == 0)
6520    }
6521
6522    /// Takes the object `handle` names back out of the scene, freeing its slot.
6523    ///
6524    /// **A removal is a cleared live bit, not a skipped draw**, because the frame
6525    /// no longer records a draw per object: `cull.slang` asks whether an instance
6526    /// is live before it reads anything else, so removing an object and culling
6527    /// it off screen take the same path out of the frame. An instance left in the
6528    /// pool would be drawn wherever its transform put it.
6529    ///
6530    /// A stale handle removes nothing. Takes effect at the next
6531    /// [`ForwardRenderer::begin_frame`], on
6532    /// [`ForwardRenderer::set_instance`]'s terms.
6533    pub fn remove_instance(&mut self, handle: InstanceHandle) {
6534        self.instances.remove(handle);
6535    }
6536
6537    /// Captures a visibility map for every probe, from the static geometry
6538    /// standing in the scene right now.
6539    ///
6540    /// The probe visibility rung: each probe records how far
6541    /// away the nearest surface is in every direction, and `mesh.slang`'s
6542    /// `probe_irradiance` then weighs each of a fragment's eight probes by
6543    /// whether it can *see* that fragment — so a probe on the far side of a wall
6544    /// contributes nothing and a room stops lighting the room next door.
6545    /// This crate's own `probe_capture` module is the pass, `probe_visibility`
6546    /// is the geometry it draws, and [`crcbl_shaders::probe_visibility`] is the
6547    /// format.
6548    ///
6549    /// # Call it once, after the scene's walls are placed
6550    ///
6551    /// **A description carries no instances** — [`SceneDesc`] is meshes,
6552    /// materials, a page and the probe rows, and the objects arrive afterwards
6553    /// through [`ForwardRenderer::add_instance`] — so there is nothing for a
6554    /// capture inside [`ForwardRenderer::with_scene`] to be about. This is the
6555    /// call that has the room in it, and an application makes it once its static
6556    /// geometry is placed.
6557    ///
6558    /// A caller that never makes it draws exactly the frame this renderer drew
6559    /// before the maps existed: every group names the one-texel placeholder,
6560    /// which no surface is further away than, and every probe keeps all of its
6561    /// weight.
6562    ///
6563    /// **It is a capture of geometry and not a bake of light.** Nothing about
6564    /// the lights is recorded, every one of them still moves, and the rows the
6565    /// probes carry are untouched.
6566    ///
6567    /// # What it sees, and what it does not
6568    ///
6569    /// Every instance live in the pool when it is called, at the transform it
6570    /// then has, rasterised from its mesh's level-0 triangles into six 90°
6571    /// faces per probe. Objects that move
6572    /// afterwards keep the occlusion they had here, which is the accepted limit
6573    /// this technique has everywhere it is used — a probe volume is about the
6574    /// walls. Recapturing after a wall moves is this call again.
6575    ///
6576    /// **The device must be idle.** The previous capture's image is released
6577    /// here, and a frame in flight may still be reading it.
6578    ///
6579    /// # Errors
6580    ///
6581    /// [`HalError`] from the capture. The previous maps are kept on the failing
6582    /// path, so a renderer that has captured once and then failed goes on
6583    /// drawing with what it had.
6584    pub fn capture_probe_visibility(
6585        &mut self,
6586        device: &dyn Device,
6587        queue: QueueHandle,
6588    ) -> Result<(), HalError> {
6589        let placed: Vec<crate::probe_visibility::Occluder> = self
6590            .instances
6591            .live()
6592            .into_iter()
6593            .map(|record| crate::probe_visibility::Occluder {
6594                mesh: record.mesh,
6595                transform: Mat4::from_cols_array(&record.transform),
6596            })
6597            .collect();
6598        let Some(uploaded) = crate::probe_capture::capture(
6599            device,
6600            queue,
6601            &self.probe_volume,
6602            &self.probe_occluders,
6603            &placed,
6604        )?
6605        else {
6606            // No probes, or nothing placed for a map to be about. Leaving the
6607            // placeholder bound is the honest answer, and it is what a scene
6608            // with no probes has always read.
6609            return Ok(());
6610        };
6611        // The cached groups name the view this replaces, so they go before it
6612        // does — a bind group outliving the image it names is a validation
6613        // error on every backend that checks, and a use-after-free on the ones
6614        // that do not.
6615        for slot in &mut self.primary.screen_channel_groups {
6616            if let Some((_, stale)) = slot.take() {
6617                device.destroy_bind_group(stale);
6618            }
6619        }
6620        if let Some(previous) = self.probe_visibility.replace(uploaded) {
6621            previous.destroy(device);
6622        }
6623        Ok(())
6624    }
6625
6626    /// Re-centres the irradiance clipmap on `point` by whole probe steps, and
6627    /// captures the probes the step exposed.
6628    ///
6629    /// The irradiance probes' scrolling: each level moves a whole
6630    /// number of its own probe spacings towards `point`, so the probes that stay
6631    /// inside it stand exactly where they stood and go on being addressed at the
6632    /// rows they already had — and only the slabs the step brought in are
6633    /// captured. Answers how many rows that was, which is **zero for the
6634    /// ordinary frame**: the point has to travel half a probe spacing before the
6635    /// nearest whole step changes at all.
6636    ///
6637    /// [`ProbeVolume::follow`](crcbl_shaders::probe::ProbeVolume::follow) is the
6638    /// rule and `exposed` beside it is the invalidation; this is the two of them
6639    /// plus the device work they imply — the visibility maps of the exposed
6640    /// rows, and the position table the reflective-shadow-map gather reads.
6641    ///
6642    /// # A volume authored to cover its whole world does not move
6643    ///
6644    /// The steps are the ones that centre a level on `point`, and a caller whose
6645    /// volume is already the world it is in wants none of them — so a caller
6646    /// passes the point it wants the *centre* at rather than the camera outright
6647    /// when the two differ. `apps/lantern` and `apps/shard` are that case and
6648    /// their own modules say so.
6649    ///
6650    /// # A step stalls, and a frame that does not step costs a comparison
6651    ///
6652    /// The recapture is [`ForwardRenderer::capture_probe_visibility`]'s pass
6653    /// over fewer rows, and it waits on [`Device::wait_idle`] exactly as that
6654    /// one does — so a step drains the device before it rewrites anything and
6655    /// leaves it drained. That is a stall, and it is why the probe records price a step
6656    /// separately from a frame. A call that steps nothing returns before the
6657    /// wait, so the ordinary frame pays a rounding per level and per axis and
6658    /// nothing else.
6659    ///
6660    /// It may therefore be called from a frame loop, but **not after**
6661    /// [`ForwardRenderer::begin_frame`] has been called for the frame being
6662    /// recorded: the header it moves is the one that frame's uniform block has
6663    /// already been written from.
6664    ///
6665    /// A renderer that has never captured re-centres the header and captures
6666    /// nothing: there is no image to write slabs into, every group still names
6667    /// the placeholder, and the first
6668    /// [`ForwardRenderer::capture_probe_visibility`] covers the scrolled volume
6669    /// whole.
6670    ///
6671    /// # It moves the geometry and not the light
6672    ///
6673    /// What a step re-captures is the *visibility* of the probes it exposed,
6674    /// which is what the maps are about. The **rows** are not touched, so under
6675    /// [`ProbeUpdate::Authored`] a probe
6676    /// that a step brought in keeps the irradiance the probe that left had —
6677    /// authored for somewhere else. A volume that scrolls therefore wants
6678    /// [`ProbeUpdate::EveryFrame`], whose
6679    /// gather refills every row from the scene each frame and has no such gap;
6680    /// `docs/backlog.md` carries what an authored one would need instead.
6681    ///
6682    /// # Errors
6683    ///
6684    /// [`HalError`] from the recapture or from the position rewrite. The volume
6685    /// keeps the steps it had on either failing path, so a renderer that could
6686    /// not capture a slab does not go on drawing with rows about somewhere else.
6687    pub fn follow_probe_volume(
6688        &mut self,
6689        device: &dyn Device,
6690        queue: QueueHandle,
6691        point: [f32; 3],
6692    ) -> Result<u32, HalError> {
6693        let mut moved = self.probe_volume;
6694        let rows = moved.follow(point);
6695        if rows.is_empty() && moved.steps == self.probe_volume.steps {
6696            return Ok(0);
6697        }
6698        // **Before anything is written**, so a caller may make this call from
6699        // its frame loop: the layers the recapture rewrites and the position
6700        // table beside them are read by whatever frames are still in flight, and
6701        // neither is a ring. A frame that does not step never reaches this line,
6702        // which is what keeps the ordinary frame free of it.
6703        device.wait_idle()?;
6704        if let Some(captured) = &self.probe_visibility {
6705            let placed: Vec<crate::probe_visibility::Occluder> = self
6706                .instances
6707                .live()
6708                .into_iter()
6709                .map(|record| crate::probe_visibility::Occluder {
6710                    mesh: record.mesh,
6711                    transform: Mat4::from_cols_array(&record.transform),
6712                })
6713                .collect();
6714            crate::probe_capture::recapture(
6715                device,
6716                queue,
6717                &moved,
6718                &self.probe_occluders,
6719                &placed,
6720                &rows,
6721                captured.image,
6722            )?;
6723        }
6724        // After the capture, so a volume whose slabs could not be drawn keeps
6725        // the header its maps are about.
6726        if let Some(gather) = &self.probe_gather {
6727            gather.rewrite_positions(device, &moved)?;
6728        }
6729        self.probe_volume = moved;
6730        Ok(u32::try_from(rows.len()).unwrap_or(u32::MAX))
6731    }
6732
6733    /// Where the irradiance clipmap stands right now — the header the frame
6734    /// block carries, [`ForwardRenderer::follow_probe_volume`]'s scroll
6735    /// included.
6736    #[must_use]
6737    pub const fn probe_volume(&self) -> crcbl_shaders::probe::ProbeVolume {
6738        self.probe_volume
6739    }
6740
6741    /// `draws` split by the **whole** material mode, each partition under the
6742    /// depth-only pipeline that honours it — what the depth prepass and every
6743    /// shadow view record instead of one call list under one pipeline.
6744    ///
6745    /// Four pipelines for [`DEPTH_MODES`]' four values, which is what makes the
6746    /// split total: the opaque buckets are drawn with
6747    /// [`shadow_pipeline`](Self::shadow_pipeline) — `depthVertexMain` and no
6748    /// fragment stage — the masked ones with
6749    /// [`depth_masked_pipeline`](Self::depth_masked_pipeline), which can
6750    /// `discard`, and each of those has a [`CullMode::None`] twin for the
6751    /// buckets whose material is double-sided. A scene with one cutout in it
6752    /// pays a fragment stage for that mesh's draws and for no others; before
6753    /// this it paid for the whole frame, which on lavapipe roughly doubled the
6754    /// prepass and added two thirds to the shadow pass.
6755    ///
6756    /// **Both depth passes and not just the atlas.** A double-sided plate whose
6757    /// back face the prepass culled writes no depth there, so the colour pass's
6758    /// `GreaterOrEqual` test against it rejects the fragment and the surface is
6759    /// missing from the frame; and a cascade that culled it casts no shadow.
6760    fn depth_partitions(&self, draws: &BucketDraws) -> Vec<BucketDraws> {
6761        self.partitions(
6762            draws,
6763            mesh::GpuMaterial::MODE_MASK,
6764            &[
6765                (DEPTH_MODES[0], self.shadow_pipeline.single),
6766                (DEPTH_MODES[1], self.depth_masked_pipeline.single),
6767                (DEPTH_MODES[2], self.shadow_pipeline.double),
6768                (DEPTH_MODES[3], self.depth_masked_pipeline.double),
6769            ],
6770        )
6771    }
6772
6773    /// `draws` split by the material's **side** alone, each partition under the
6774    /// matching half of `pipelines` — what the colour pass and the two
6775    /// reflective shadow maps record.
6776    ///
6777    /// Two partitions where [`depth_partitions`](Self::depth_partitions) has
6778    /// four, and the difference is the whole of what these passes do not care
6779    /// about: their pipelines carry a fragment stage either way and cut the
6780    /// alpha mask inside it, so a masked bucket and an opaque one are the same
6781    /// draw here. What they cannot express inside the stage is the cull mode.
6782    fn sided_partitions(&self, draws: &BucketDraws, pipelines: SidedPipelines) -> Vec<BucketDraws> {
6783        self.partitions(
6784            draws,
6785            mesh::GpuMaterial::DOUBLE_SIDED,
6786            &[
6787                (0, pipelines.single),
6788                (mesh::GpuMaterial::DOUBLE_SIDED, pipelines.double),
6789            ],
6790        )
6791    }
6792
6793    /// Resolves a description's mesh and material indices into the table ids the
6794    /// GPU reads.
6795    ///
6796    /// The whole record every time, because [`InstancePool::set`] writes the
6797    /// whole record: an instance that lost either id would name entry 0 of that
6798    /// table, which is a mesh and a material rather than an absence.
6799    fn gpu_instance(&self, desc: &InstanceDesc) -> mesh::GpuInstance {
6800        mesh::GpuInstance {
6801            transform: desc.transform.to_cols_array(),
6802            mesh: self.mesh_ids[desc.mesh],
6803            material: self.material_ids[desc.material],
6804            flags: self.material_mode_bits(desc.material),
6805            ..mesh::GpuInstance::default()
6806        }
6807    }
6808
6809    /// The material mode of description material `material`, in the bits an
6810    /// instance record carries it in.
6811    ///
6812    /// **Read out of the table rather than out of the description**, because the
6813    /// table is what a `set` would move and the row is what the shader shades
6814    /// through. It is the other half of the record's routing key: `draw_gen`
6815    /// buckets an instance by [`mesh`](mesh::GpuInstance::mesh) and by this,
6816    /// which is how a masked material costs a fragment stage in the depth passes
6817    /// for its own mesh alone.
6818    ///
6819    /// The mode is captured **here**, when the record is written — see
6820    /// [`GpuInstance::MATERIAL_MODE_SHIFT`](mesh::GpuInstance::MATERIAL_MODE_SHIFT)
6821    /// for what that means for a material rewritten afterwards.
6822    fn material_mode_bits(&self, material: usize) -> u32 {
6823        self.materials.mode(self.material_ids[material]) << mesh::GpuInstance::MATERIAL_MODE_SHIFT
6824    }
6825
6826    // --- skinning: reserving the region, placing the object, ordering the
6827    // dispatch ---
6828
6829    /// The vertex pool every mesh here is resident in — what
6830    /// [`SkinningDesc::vertices`](crate::skinning::SkinningDesc::vertices)
6831    /// takes.
6832    ///
6833    /// The skinning pass reads a bind pose out of this buffer and writes the
6834    /// deformed vertices back into another run of it, which is what makes a
6835    /// skinned draw an ordinary draw. It must be *this* pool's buffer: a
6836    /// [`Skinning`] built against any other writes vertices no draw here can
6837    /// reach.
6838    #[must_use]
6839    pub const fn vertex_buffer(&self) -> BufferHandle {
6840        self.pool.vertex_buffer()
6841    }
6842
6843    /// Where that pool's **attribute** region begins, in words — what
6844    /// [`SkinningDesc::attribute_base`](crate::skinning::SkinningDesc::attribute_base)
6845    /// takes.
6846    ///
6847    /// The buffer holds two streams, so a pass that writes it needs the
6848    /// boundary as well as the handle; a [`Skinning`] built with the wrong one
6849    /// writes a mesh's attributes over another mesh's positions. See
6850    /// [`MeshPool::attribute_base`](crate::MeshPool::attribute_base).
6851    #[must_use]
6852    pub const fn attribute_base(&self) -> u32 {
6853        self.pool.attribute_base()
6854    }
6855
6856    /// Reserves a skinned region for description mesh `mesh`.
6857    ///
6858    /// The whole of what a caller needs to skin something, in one value: hand
6859    /// [`SkinnedMesh::skin_range`] a palette and a set of bindings to get the
6860    /// frame's [`SkinRange`], hand the result to
6861    /// [`begin_skinned_frame`](Self::begin_skinned_frame), and place it with
6862    /// [`add_skinned_instance`](Self::add_skinned_instance). The bases and the
6863    /// parity never have to be spelled by the caller at all — see
6864    /// [`crate::skinning::SkinnedMesh`], where the ping-pong lives.
6865    ///
6866    /// **The mesh keeps its own entry and the region takes none**, so the same
6867    /// description mesh can be drawn skinned through this and in its bind pose
6868    /// through [`add_instance`](Self::add_instance) in the same frame, both
6869    /// resolving through the one table entry it already had.
6870    ///
6871    /// Give it back with [`release_skinned`](Self::release_skinned).
6872    ///
6873    /// # Errors
6874    ///
6875    /// Whatever [`SkinnedMesh::reserve`] refuses: a vertex pool with no room for
6876    /// both halves. **Two vertex runs per skinned primitive** is what a scene's
6877    /// [`Capacities`](crate::scene::Capacities) has to have been sized for.
6878    ///
6879    /// # Panics
6880    ///
6881    /// If `mesh` is past the end of the description this renderer was built
6882    /// from, on [`add_instance`](Self::add_instance)'s terms — and if it names a
6883    /// [`Geometry::Dag`], which cannot be drawn out of a skinned region at all.
6884    /// A DAG is refused rather than skinned wrongly: its coarser levels are
6885    /// separate vertex runs no dispatch writes, so a cut that descended past
6886    /// level 0 would draw whatever the pool happened to be holding there.
6887    pub fn reserve_skinned(&mut self, mesh: usize) -> Result<SkinnedMesh, MeshPoolError> {
6888        let source = self.skinnable_meshes[mesh].unwrap_or_else(|| {
6889            panic!(
6890                "description mesh {mesh} is a Geometry::Dag, whose coarser levels are vertex \
6891                 runs no skinning dispatch writes; only a flat mesh can be skinned"
6892            )
6893        });
6894        SkinnedMesh::reserve(&mut self.pool, source)
6895    }
6896
6897    /// Gives `skinned`'s region back to the vertex pool.
6898    ///
6899    /// The device must not still be drawing it: this records no barrier, on
6900    /// [`SkinnedMesh::release`]'s terms. Objects placed through it are **not**
6901    /// removed — [`remove_instance`](Self::remove_instance) is what does that,
6902    /// and an instance left behind goes on drawing its source mesh's geometry
6903    /// out of vertices the pool has handed back. Remove the objects first.
6904    pub fn release_skinned(&mut self, skinned: SkinnedMesh) {
6905        skinned.release(&mut self.pool);
6906    }
6907
6908    /// Places a skinned object in the scene.
6909    ///
6910    /// [`add_instance`](Self::add_instance) with a reserved region in place of a
6911    /// description mesh. The renderer keeps the object in a list of its own and
6912    /// **re-points it every [`begin_skinned_frame`](Self::begin_skinned_frame)**
6913    /// at the half of the region that frame's dispatch fills, so the parity is
6914    /// never something a caller writes.
6915    ///
6916    /// A skinned object driven by plain [`begin_frame`](Self::begin_frame) is
6917    /// therefore left pointing wherever it last was, which after the first frame
6918    /// is the pose of the frame before — the reason the two entry points are
6919    /// separate calls rather than a flag.
6920    ///
6921    /// # Errors
6922    ///
6923    /// [`InstancePoolError::PoolFull`], on
6924    /// [`add_instance`](Self::add_instance)'s terms.
6925    ///
6926    /// # Panics
6927    ///
6928    /// If [`SkinnedInstanceDesc::material`] is past the end of the description
6929    /// this renderer was built from, on
6930    /// [`add_instance`](Self::add_instance)'s terms.
6931    pub fn add_skinned_instance(
6932        &mut self,
6933        desc: &SkinnedInstanceDesc<'_>,
6934    ) -> Result<InstanceHandle, InstancePoolError> {
6935        // Parity zero, and it never reaches the GPU as such: the instance pool
6936        // uploads by delta at `begin_skinned_frame`, which re-points every entry
6937        // of the list below before it flushes. What this writes is the rest of
6938        // the record.
6939        let instance = self.skinned_gpu_instance(desc, 0);
6940        let handle = self.instances.insert(&instance)?;
6941        self.skinned_instances.push(SkinnedInstance {
6942            handle,
6943            bases: skinned_bases(desc.mesh),
6944            pointed: false,
6945        });
6946        Ok(handle)
6947    }
6948
6949    /// Rewrites the skinned object `handle` names — its region, its material and
6950    /// its transform.
6951    ///
6952    /// [`set_instance`](Self::set_instance) for an object placed by
6953    /// [`add_skinned_instance`](Self::add_skinned_instance), and the call a
6954    /// character's transform changes through. A stale handle writes nothing.
6955    ///
6956    /// Passing a handle this renderer has never seen skinned adopts it: the
6957    /// object joins the re-pointed list from here on. That is what lets a caller
6958    /// swap a bind-pose instance over to a region without removing and replacing
6959    /// it.
6960    ///
6961    /// # Panics
6962    ///
6963    /// On [`add_skinned_instance`](Self::add_skinned_instance)'s terms.
6964    pub fn set_skinned_instance(&mut self, handle: InstanceHandle, desc: &SkinnedInstanceDesc<'_>) {
6965        let mut instance = self.skinned_gpu_instance(desc, 0);
6966        instance.flags |= self.kept_flags(handle);
6967        if !self.instances.set(handle, &instance) {
6968            return;
6969        }
6970        let bases = skinned_bases(desc.mesh);
6971        match self
6972            .skinned_instances
6973            .iter_mut()
6974            .find(|entry| entry.handle == handle)
6975        {
6976            // **A different region is a fresh entry.** The half this object has
6977            // never been drawn out of holds whatever its reservation came with,
6978            // so the next pointing owes it rest rather than a previous
6979            // deformation — see [`SkinnedInstance::pointed`]. The pair of bases
6980            // is what "different" means here: two calls naming one region give
6981            // the same two runs, so rewriting an object's material or transform
6982            // is not a change of region.
6983            Some(entry) => {
6984                entry.pointed &= entry.bases == bases;
6985                entry.bases = bases;
6986            }
6987            None => self.skinned_instances.push(SkinnedInstance {
6988                handle,
6989                bases,
6990                pointed: false,
6991            }),
6992        }
6993    }
6994
6995    /// A skinned object's record, at one parity — [`gpu_instance`](Self::gpu_instance)
6996    /// with the region's base vertex carried in the record and the bit that says
6997    /// to read it.
6998    ///
6999    /// The mesh id is the **source** mesh's, not a second entry's, so the bucket
7000    /// this instance is scattered into, the levels it selects through and the
7001    /// box it is culled against are the ones the undeformed mesh already had.
7002    fn skinned_gpu_instance(
7003        &self,
7004        desc: &SkinnedInstanceDesc<'_>,
7005        parity: u32,
7006    ) -> mesh::GpuInstance {
7007        let base_vertex = desc.mesh.region().base(parity);
7008        mesh::GpuInstance {
7009            transform: desc.transform.to_cols_array(),
7010            mesh: desc.mesh.mesh_id(),
7011            material: self.material_ids[desc.material],
7012            // The override bit **and** the material mode: a skinned instance is
7013            // routed by the same key as a rigid one, so a skinned cutout lands
7014            // in its mesh's masked bucket rather than in the opaque twin.
7015            flags: mesh::GpuInstance::BASE_VERTEX_OVERRIDE | self.material_mode_bits(desc.material),
7016            base_vertex,
7017            // At rest, which is what a record this call writes has to be: the
7018            // object has not been drawn out of this region yet, so the other
7019            // half holds whatever its reservation came with. A frame that runs
7020            // [`point_skinned_instances`](Self::point_skinned_instances) is
7021            // what starts pointing this at the half before.
7022            previous_base_vertex: base_vertex,
7023            ..mesh::GpuInstance::default()
7024        }
7025    }
7026
7027    /// Points every skinned object at the half of its region a frame of this
7028    /// parity fills **and at the half the frame before it filled**, and forgets
7029    /// the ones whose instance has gone.
7030    ///
7031    /// Called between the instance ring's rotation and its upload, which is the
7032    /// whole reason those two are separate calls — see
7033    /// [`InstancePool::rotate`](crate::instance_pool::InstancePool::rotate).
7034    ///
7035    /// The second base is what a skinned fragment's motion vector is subtracted
7036    /// against — see
7037    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
7038    /// **A region this frame's `ranges` left out was not skinned this frame**,
7039    /// so the half this points at as the current one already holds an earlier
7040    /// frame's pose. That is pre-existing — it is what a caller driving a
7041    /// skinned object through plain [`begin_frame`](Self::begin_frame) gets, and
7042    /// it predates this second base — and the previous half is then no worse off
7043    /// than the current one.
7044    fn point_skinned_instances(&mut self, parity: u32) {
7045        let Self {
7046            instances,
7047            skinned_instances,
7048            ..
7049        } = self;
7050        skinned_instances.retain_mut(|entry| {
7051            // `SkinnedRegion::base`'s indexing and `SkinnedRegion::previous_base`'s,
7052            // applied to the entry's own copy of the pair — see
7053            // [`SkinnedInstance::bases`].
7054            let base_vertex = entry.bases[(parity & 1) as usize];
7055            let previous_base_vertex = if entry.pointed {
7056                entry.bases[((parity ^ 1) & 1) as usize]
7057            } else {
7058                // Nothing has been written into the other half for this object,
7059                // so it is put at rest — see [`SkinnedInstance::pointed`].
7060                base_vertex
7061            };
7062            entry.pointed = true;
7063            // The two bases and nothing else: the transform, the material and
7064            // the mesh the caller last set survive, and so does the transform
7065            // the record moved *from* — which
7066            // [`InstancePool::set`](crate::instance_pool::InstancePool::set)
7067            // would overwrite with this frame's, leaving a skinned object's own
7068            // travel out of the motion target. See
7069            // [`InstancePool::set_bases`](crate::instance_pool::InstancePool::set_bases).
7070            // Its answer is also what says the instance is still there, so an
7071            // object a caller removed drops out of the list here.
7072            instances.set_bases(entry.handle, base_vertex, previous_base_vertex)
7073        });
7074    }
7075
7076    /// The lights in the frame **beside the sun**, which
7077    /// [`begin_frame`](Self::begin_frame) still takes on its own.
7078    ///
7079    /// Topic 44's light list, minus its first row: the
7080    /// sun is row 0 of every frame's list and the ones set here follow it, in
7081    /// the order given. That order is the one a froxel keeps a prefix of when it
7082    /// runs out of budget — see [`ForwardRenderer::light_capacity`] and the
7083    /// overflow counter beside it — so it is a caller's lever and not an
7084    /// accident.
7085    ///
7086    /// The sun keeps a parameter of its own because it is the light that owns
7087    /// the ambient term and the shadow cascades, neither of which a [`Light`]
7088    /// has. What it stopped being is a special case in the *shader*, which is
7089    /// what the list bought.
7090    ///
7091    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7092    /// what uploads the rows.
7093    ///
7094    /// # Panics
7095    ///
7096    /// If there are more lights than [`ForwardRenderer::light_capacity`] leaves
7097    /// room for once the sun has its row. Refused rather than truncated: a light
7098    /// missing from the list is missing from every froxel, and **no counter in
7099    /// the frame would report it** — the overflow counter counts what a froxel's
7100    /// budget refused, which is a different number.
7101    pub fn set_lights(&mut self, lights: &[Light]) {
7102        assert!(
7103            lights.len() < self.primary.lights.capacity() as usize,
7104            "{} lights beside the sun, in a list of {}",
7105            lights.len(),
7106            self.primary.lights.capacity()
7107        );
7108        self.extra_lights.clear();
7109        self.extra_lights.extend_from_slice(lights);
7110    }
7111
7112    /// Rows the light list holds, the sun's included.
7113    #[must_use]
7114    pub const fn light_capacity(&self) -> u32 {
7115        self.primary.lights.capacity()
7116    }
7117
7118    /// This frame's froxel grid, as [`begin_frame`](Self::begin_frame) sized it
7119    /// from the viewport and the camera.
7120    ///
7121    /// Exposed for the reason [`lod_params`](Self::lod_params) is: a test that
7122    /// wants to know which froxel a point was shaded out of has to use the grid
7123    /// the frame really used, and re-deriving it would be a second copy of the
7124    /// arithmetic rather than a reading of the first.
7125    #[must_use]
7126    pub const fn grid(&self) -> Grid {
7127        self.primary.grid
7128    }
7129
7130    /// `frame`'s froxel grid buffer, for a test copying out what the clustering
7131    /// pass decided.
7132    ///
7133    /// # Panics
7134    ///
7135    /// If `frame` is not a slot this was built with.
7136    #[must_use]
7137    pub fn light_grid_buffer(&self, frame: usize) -> BufferHandle {
7138        self.primary.lights.grid(frame)
7139    }
7140
7141    /// The pixel budget the descent compares a group's projected error against.
7142    ///
7143    /// One pixel until this is called — see the constant this crate keeps it
7144    /// in. Larger is coarser: a group
7145    /// projecting *over* the budget is expanded and its children are drawn, so
7146    /// raising it stops the descent higher up the DAG.
7147    ///
7148    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7149    /// what writes it into the frame block.
7150    pub const fn set_lod_error_budget(&mut self, budget: f32) {
7151        self.lod_error_budget = budget;
7152    }
7153
7154    /// The budget this renderer selects under unless
7155    /// [`set_lod_error_budget`](Self::set_lod_error_budget) says otherwise, and
7156    /// the ratio the hold budget sits at below whichever one is in force.
7157    ///
7158    /// Public because a test that drives a camera across a level boundary has to
7159    /// know where the boundary is, and where it is depends on both numbers —
7160    /// re-deriving either in the test would be a second copy to drift.
7161    pub const LOD_ERROR_BUDGET: f32 = LOD_ERROR_BUDGET;
7162    /// See [`LOD_ERROR_BUDGET`](Self::LOD_ERROR_BUDGET).
7163    pub const LOD_HOLD_RATIO: f32 = LOD_HOLD_RATIO;
7164
7165    /// How far below the budget an already-expanded group is held before it
7166    /// collapses again — topic 25's hysteresis, as a fraction of
7167    /// the budget.
7168    ///
7169    /// [`LOD_HOLD_RATIO`](Self::LOD_HOLD_RATIO) until this is called. **A ratio
7170    /// of one removes the band**, which makes the two budgets equal and the
7171    /// previous frame's answer stop mattering — the setting a test uses to show
7172    /// that the band is what stops a drifting camera flickering, on the same
7173    /// code path and one number apart.
7174    ///
7175    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7176    /// what writes it into the two params blocks.
7177    pub const fn set_lod_hold_ratio(&mut self, ratio: f32) {
7178        self.lod_hold_ratio = ratio;
7179    }
7180
7181    /// What the last [`begin_frame`](Self::begin_frame) handed the descent:
7182    /// pixels per unit at one unit from the eye, and the pixel budget.
7183    ///
7184    /// Pixels per unit at one unit from the eye, the budget an unexpanded group
7185    /// starts expanding over, and the budget an expanded one is held down to.
7186    ///
7187    /// What `ClusterDag::expand` takes, so a caller reading
7188    /// [`cluster_selection`](Self::cluster_selection) back can run the same
7189    /// frames host-side rather than re-deriving the numbers from the camera and
7190    /// hoping they agree. `[0.0, 0.0, 0.0]` before the first frame.
7191    #[must_use]
7192    pub const fn lod_params(&self) -> [f32; 3] {
7193        self.primary.lod_params
7194    }
7195
7196    /// The same three numbers the **shadow cascades** selected under, which is
7197    /// [`lod_params`](Self::lod_params) with both budgets multiplied by
7198    /// [`SHADOW_LOD_BIAS`] — topic 25's shadow LOD bias, as the
7199    /// parameters it actually reaches the GPU as.
7200    ///
7201    /// The pixels-per-unit is the camera's, unchanged, because the cascades
7202    /// select from the camera's eye at the camera's scale; see
7203    /// [`begin_frame`](Self::begin_frame). `[0.0, 0.0, 0.0]` before the first
7204    /// frame.
7205    #[must_use]
7206    pub const fn shadow_lod_params(&self) -> [f32; 3] {
7207        self.shadow_lod_params
7208    }
7209
7210    /// Where description mesh `mesh`'s clusters are in the cluster pool — every
7211    /// level of it, as one run — or `None` off the mesh path, where there is no
7212    /// cluster pool at all.
7213    ///
7214    /// The base a reader adds a `(level, cluster)` to in order to index
7215    /// [`cluster_selection`](Self::cluster_selection): the levels are laid down
7216    /// finest first and contiguously, so level `d` cluster `c` is at
7217    /// `base + (clusters of levels below d) + c`. A flat mesh is one level, so
7218    /// its run is its clusters and `c` indexes it directly.
7219    ///
7220    /// # Panics
7221    ///
7222    /// If `mesh` is past the end of the description this renderer was built
7223    /// from, on [`add_instance`](Self::add_instance)'s terms.
7224    #[must_use]
7225    pub fn cluster_range(&self, mesh: usize) -> Option<ClusterRange> {
7226        (!self.mesh_clusters.is_empty()).then(|| self.mesh_clusters[mesh])
7227    }
7228
7229    /// The buffer `frame`'s amplification stage recorded its chosen cut into:
7230    /// one `u32` per resident cluster, `1` where the cluster was drawn.
7231    ///
7232    /// `None` where there is no amplification stage, which is every device that
7233    /// reports no [`Features::TASK_SHADER`] and every non-mesh geometry path.
7234    ///
7235    /// **This is topic 25's observable and nothing in the frame
7236    /// reads it.** A frame whose every cluster came from one level is a
7237    /// plausible picture and matches any golden blessed from it, so a golden
7238    /// cannot show per-cluster selection happening at all; this can. It is
7239    /// `TRANSFER_SRC`, and copying it out is the caller's to record.
7240    ///
7241    /// [`Features::TASK_SHADER`]: crcbl_hal::Features::TASK_SHADER
7242    #[must_use]
7243    pub fn cluster_selection(&self, frame: usize) -> Option<BufferHandle> {
7244        self.primary.cluster_selection.get(frame).copied()
7245    }
7246
7247    /// The same, for `cascade`'s shadow pass: the cut that cascade's
7248    /// amplification stage chose this frame.
7249    ///
7250    /// **The shadow LOD bias' observable.** A budget the cascades merely *were
7251    /// passed* is a parameter; the cut they reached under it is the behaviour,
7252    /// and this is the only thing that carries it out of a frame — the colour
7253    /// pass overwrites [`cluster_selection`](Self::cluster_selection) after the
7254    /// cascades have run. Indexed and read exactly as that buffer is, through
7255    /// [`cluster_range`](Self::cluster_range).
7256    ///
7257    /// `None` where there is no amplification stage, and where `cascade` is not
7258    /// one of [`shadow::CASCADES`].
7259    #[must_use]
7260    pub fn shadow_selection(&self, frame: usize, cascade: usize) -> Option<BufferHandle> {
7261        self.shadow_selection
7262            .get(frame)
7263            .and_then(|cascades| cascades.get(cascade))
7264            .copied()
7265    }
7266
7267    /// The buckets description mesh `mesh`'s levels draw through, finest first —
7268    /// element `d` is level `d`'s bucket, and it is empty on the mesh path.
7269    ///
7270    /// **This is the uniform cut's observable**, and it is the indirect
7271    /// arguments rather than a buffer of its own: `draw_gen.slang` scatters an
7272    /// instance into the bucket for the level it selected, so exactly one of
7273    /// these buckets comes out of a frame with a non-zero instance count and
7274    /// which one it is *is* the chosen level. A reader takes
7275    /// [`DrawGen::args_offset`](crate::draw_gen::DrawGen::args_offset) of each
7276    /// and looks at
7277    /// [`DrawIndexedArgs::instance_count`](crcbl_shaders::draw_gen::DrawIndexedArgs::instance_count).
7278    ///
7279    /// Empty on [`GeometryPath::MeshShader`], where a mesh is one bucket and the
7280    /// level is chosen per cluster instead — see
7281    /// [`cluster_selection`](Self::cluster_selection), which is that path's
7282    /// observable.
7283    ///
7284    /// **These are the buckets of the scene's first material mode** — `OPAQUE`
7285    /// in any scene that has an opaque material, since the table is every
7286    /// mesh's levels once per mode the scene holds, mode by mode in
7287    /// `DEPTH_MODES` order. An instance of another mode selects the same level
7288    /// and lands in that level's bucket in its own mode's run, which this does
7289    /// not name; every scene in this tree that reads this accessor is all
7290    /// opaque, so "exactly one of these has a non-zero instance count" holds for
7291    /// them as it always did.
7292    ///
7293    /// # Panics
7294    ///
7295    /// If `mesh` is past the end of the description this renderer was built
7296    /// from, on [`add_instance`](Self::add_instance)'s terms.
7297    #[must_use]
7298    pub fn level_buckets(&self, mesh: usize) -> &[u32] {
7299        if self.mesh_level_buckets.is_empty() {
7300            return &[];
7301        }
7302        &self.mesh_level_buckets[mesh]
7303    }
7304
7305    /// `frame`'s indirect draw arguments, [`crcbl_shaders::draw_gen::DRAW_ARGS_SIZE`]
7306    /// bytes per bucket — what a reader of
7307    /// [`level_buckets`](Self::level_buckets) copies out.
7308    ///
7309    /// # Panics
7310    ///
7311    /// If `frame` is not a slot this renderer was built with.
7312    #[must_use]
7313    pub fn draw_args(&self, frame: usize) -> BufferHandle {
7314        self.primary.draws.args(frame)
7315    }
7316
7317    /// `frame`'s survivor list for the primary camera and the culling
7318    /// statistics beside it — `cull.slang`'s entries, tags and all, in the first
7319    /// [`DrawGen::visible_capacity`](crate::DrawGen::visible_capacity) words of
7320    /// the first buffer, and their count in word
7321    /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
7322    /// of the second — for a test holding the GPU's occlusion verdicts against
7323    /// [`crate::cull`]'s oracle. The first buffer holds the routes and runs
7324    /// behind the list; see [`crate::draw_gen`].
7325    ///
7326    /// # Panics
7327    ///
7328    /// If `frame` is not a slot this renderer was built with.
7329    #[must_use]
7330    pub fn camera_cull_buffers(&self, frame: usize) -> (BufferHandle, BufferHandle) {
7331        (
7332            self.primary.draws.visible(frame),
7333            self.primary.draws.visible_count(frame),
7334        )
7335    }
7336
7337    /// What the primary camera's cull reads, as the oracle in [`crate::cull`]
7338    /// takes it: every instance slot the pool has handed out, and the whole mesh
7339    /// table — both decoded from the host's own copies of what was uploaded.
7340    #[must_use]
7341    pub fn cull_records(&self) -> (Vec<mesh::GpuInstance>, Vec<mesh::GpuMesh>) {
7342        (self.instances.records(), self.pool.table_entries())
7343    }
7344
7345    /// The generator behind shadow cull `cull` — a cascade's below
7346    /// [`shadow::CASCADES`], a light slot's after —
7347    /// for a test reading back what a point light's face culls kept.
7348    ///
7349    /// # Panics
7350    ///
7351    /// If `cull` is not one of the renderer's shadow culls.
7352    #[must_use]
7353    pub fn shadow_generator(&self, cull: usize) -> &DrawGen {
7354        &self.shadow_draws[cull]
7355    }
7356
7357    /// The primary camera's farthest-depth pyramid — every level's image, view
7358    /// and extent, level 1 first — or empty before a frame culled by occlusion.
7359    ///
7360    /// For a test reading a level back: the images carry `TRANSFER_SRC` for
7361    /// exactly that, and they hold the last frame's early depth once that frame
7362    /// has finished.
7363    #[must_use]
7364    pub fn occlusion_pyramid(&self) -> Vec<(crcbl_hal::ImageHandle, ImageViewHandle, (u32, u32))> {
7365        self.primary.occlusion_pyramid.level_images()
7366    }
7367
7368    /// The most passes [`add_passes`](Self::add_passes) adds to one frame.
7369    ///
7370    /// [`DrawGen::MAX_PASSES`] per cull — the camera's, and one per shadow cull
7371    /// beside it — plus [`LightGrid::MAX_PASSES`] for the froxel grid and the
7372    /// passes that draw. **A ceiling, not a count**: a frame whose shadow slots
7373    /// are not all filled runs fewer culls, which is what makes a free tile
7374    /// free.
7375    ///
7376    /// Derived rather than written down, because a number written down is one
7377    /// that stops matching the frame the day a pass is added — which is exactly
7378    /// how the samples' hand-picked `8` came to time the first eight passes of a
7379    /// fourteen-pass frame. A caller sizing
7380    /// [`PassTimers`](crate::timing::PassTimers) wants
7381    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES), which adds this to
7382    /// what the overlay renderers record.
7383    pub const MAX_PASSES: u32 = DrawGen::MAX_PASSES * (1 + SHADOW_CULLS as u32)
7384        + DrawGen::LATE_PASSES
7385        + LightGrid::MAX_PASSES
7386        + RENDER_PASSES;
7387
7388    /// Adds the forward and tonemap passes to `graph`, rendering into `target`,
7389    /// and returns the HDR scene target they went through.
7390    ///
7391    /// `target` is normally the imported swapchain image. Everything else — the
7392    /// HDR scene colour, the depth buffer, and every barrier between them — is
7393    /// the graph's.
7394    ///
7395    /// The returned [`ImageId`] is the `Rgba16Float` frame the tonemap read:
7396    /// the scene colour **with the screen-space reflections already added**, not
7397    /// the target the forward pass wrote. A caller that wants to add a pass of
7398    /// its own after the tonemap — a debug overlay, or a readback proving the
7399    /// HDR range is real — declares a read of it and the graph works out the
7400    /// transition, exactly as it does for the tonemap.
7401    ///
7402    /// The two are the same description and different images, which is the
7403    /// design's off-switch as data rather than as a branch: a frame with
7404    /// [`RenderEffects::REFLECTIONS`] off adds neither pass, returns the forward
7405    /// pass's own id, and is bit-identical.
7406    ///
7407    /// # Which passes this adds is [`effects`](Self::effects)
7408    ///
7409    /// Resolved by the [`begin_frame`](Self::begin_frame) that opened this frame
7410    /// and read here — see [`crate::effects`] for the four layers and for what
7411    /// each toggle removes. Every effect is on by default, which is the frame
7412    /// every caller drew before the toggles existed.
7413    ///
7414    /// A switched-off effect is **fewer passes and one different bound
7415    /// descriptor**, never a shader permutation: the shadow atlas keeps its
7416    /// reversed-Z clear and reads as fully lit, the occlusion binding falls back
7417    /// to the renderer's white 1×1, and the reflection pair simply is not there.
7418    ///
7419    /// # The ground grid comes last, and after the tonemap
7420    ///
7421    /// [`set_ground_grid`](Self::set_ground_grid) is what puts it in the frame,
7422    /// and it is off by default. When it is on, its pass is added **after** the
7423    /// tonemap and writes `target` rather than the HDR scene colour, depth-tested
7424    /// against the scene depth: the grid is reference chrome, and a grid drawn
7425    /// before the tonemap would be exposed and tonemapped like geometry, so its
7426    /// colour would move with how bright the scene is. See [`crate::grid`].
7427    ///
7428    /// # `pool` is where the shadow atlas's incoming state comes from
7429    ///
7430    /// It must be the same pool the caller is about to
7431    /// [`compile`](RenderGraph::compile) and
7432    /// [`execute`](crate::CompiledGraph::execute) against, because the atlas and
7433    /// its placeholder are imports this renderer owns across frames and the
7434    /// pool's ledger is the record of what the last executed graph left them in
7435    /// — [`TransientPool::imported_image_use`], with [`None`] read as
7436    /// [`ResourceState::Undefined`]. Reading it here rather than carrying a
7437    /// field of our own is what keeps the declaration and the audit
7438    /// ([`InitialClaim::Tracked`]) one answer instead of two that drift: a frame
7439    /// whose `compile` fails is a frame that never ran, and a field advanced at
7440    /// build time would already have moved on without it.
7441    pub fn add_passes<'a>(
7442        &'a mut self,
7443        graph: &mut RenderGraph<'a>,
7444        pool: &TransientPool,
7445        target: ImageId,
7446        extent: (u32, u32),
7447    ) -> ImageId {
7448        self.add_frame_passes(
7449            graph,
7450            pool,
7451            FrameTargets::primary(target, extent, None),
7452            |_, _| {},
7453        )
7454    }
7455
7456    /// [`add_passes`](Self::add_passes) for a frame that **skins**: the same
7457    /// frame with `skinning`'s dispatch in front of every pass that draws.
7458    ///
7459    /// # This takes the pass rather than its [`BufferId`], and that is the point
7460    ///
7461    /// [`Skinning::add_pass`] hands back the id of the vertex pool so that a
7462    /// mesh pass can declare a read of it and be ordered after the dispatch. The
7463    /// obvious seam is therefore an id parameter here — and it is the wrong one,
7464    /// because every way of getting it wrong is silent. A caller can pass the id
7465    /// of a *different* import, add the skinning pass after this one, or not add
7466    /// it at all, and in each case the graph orders nothing, the draws read the
7467    /// region before the compute write has been made visible, and what comes out
7468    /// is a mesh that flickers between two poses on hardware and looks perfect
7469    /// under a validation layer.
7470    ///
7471    /// So this takes the [`Skinning`] and **adds the pass itself**, first, with
7472    /// this renderer's own frame slot, and declares the read on the three passes
7473    /// that pull vertices out of the pool — the shadow atlas, the depth prepass
7474    /// and the forward pass. There is no order for a caller to get right,
7475    /// because there is only one call.
7476    ///
7477    /// A frame whose [`begin_skinned_frame`](Self::begin_skinned_frame) was
7478    /// handed no ranges adds no dispatch and no declarations, and is the frame
7479    /// [`add_passes`](Self::add_passes) would have built.
7480    ///
7481    /// # It records one pass more than [`MAX_PASSES`](Self::MAX_PASSES)
7482    ///
7483    /// That constant is the bound on [`add_passes`](Self::add_passes) and stays
7484    /// so; the skinning dispatch is [`Skinning::MAX_PASSES`], and
7485    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES) — what a caller
7486    /// sizes [`PassTimers`](crate::PassTimers) with — already sums the two.
7487    pub fn add_skinned_passes<'a>(
7488        &'a mut self,
7489        graph: &mut RenderGraph<'a>,
7490        pool: &TransientPool,
7491        target: ImageId,
7492        extent: (u32, u32),
7493        skinning: &Skinning,
7494    ) -> ImageId {
7495        self.add_frame_passes(
7496            graph,
7497            pool,
7498            FrameTargets::primary(target, extent, Some(skinning)),
7499            |_, _| {},
7500        )
7501    }
7502
7503    /// [`add_skinned_passes`](Self::add_skinned_passes) with one game-owned
7504    /// overlay inserted after the display-space frame is complete and before
7505    /// antialiasing or render-scale reconstruction.
7506    ///
7507    /// The callback receives the display target and its matching scene depth
7508    /// attachment at the internal render extent. It may add graph passes that
7509    /// sample `display` and attach `depth` read-only; it must leave both images
7510    /// in states its declarations name. The forward renderer continues with its
7511    /// existing resolve and upscale passes after the callback returns.
7512    pub fn add_skinned_passes_with_overlay<'a, F>(
7513        &'a mut self,
7514        graph: &mut RenderGraph<'a>,
7515        pool: &TransientPool,
7516        target: ImageId,
7517        extent: (u32, u32),
7518        skinning: &Skinning,
7519        overlay: F,
7520    ) -> ImageId
7521    where
7522        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7523    {
7524        self.add_frame_passes(
7525            graph,
7526            pool,
7527            FrameTargets::primary(target, extent, Some(skinning)),
7528            overlay,
7529        )
7530    }
7531
7532    /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
7533    /// for a frame that also draws secondary views — see
7534    /// [`create_view`](Self::create_view).
7535    ///
7536    /// **The scene's passes are recorded once**: one skinning dispatch (where
7537    /// `skinning` is `Some`), one shadow atlas, one probe gather. Then each view
7538    /// in `views` records its own cull, clustering and frame into its own
7539    /// target, and the primary camera's frame into `target` comes last — so
7540    /// `overlay` may read a view's target, which is already drawn by then.
7541    ///
7542    /// Every view named must have been begun this frame by
7543    /// [`begin_view`](Self::begin_view).
7544    ///
7545    /// # Panics
7546    ///
7547    /// If a [`ViewTarget`] in [`FrameTargets::views`] names [`ViewId::PRIMARY`],
7548    /// a view this renderer did not build, a view not begun this frame, or a
7549    /// view twice.
7550    pub fn add_passes_with_views<'a, F>(
7551        &'a mut self,
7552        graph: &mut RenderGraph<'a>,
7553        pool: &TransientPool,
7554        frame: FrameTargets<'_>,
7555        overlay: F,
7556    ) -> ImageId
7557    where
7558        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7559    {
7560        self.add_frame_passes(graph, pool, frame, overlay)
7561    }
7562
7563    /// The body of every `add_*passes` entry point, which differ in their
7564    /// arguments and in nothing else.
7565    fn add_frame_passes<'a, F>(
7566        &'a mut self,
7567        graph: &mut RenderGraph<'a>,
7568        pool: &TransientPool,
7569        frame: FrameTargets<'_>,
7570        overlay: F,
7571    ) -> ImageId
7572    where
7573        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7574    {
7575        let FrameTargets {
7576            target,
7577            extent,
7578            skinning,
7579            views,
7580        } = frame;
7581        // **From here down `extent` is the extent the frame is *drawn* at**,
7582        // which is the caller's at a render scale of `1.0` and smaller below it.
7583        // Every use of it in this function sizes a transient, and every one of
7584        // those transients belongs to the internal frame; `target` is the only
7585        // thing here at the caller's extent, and it is an id whose image already
7586        // knows how big it is. `begin_frame_body` shadows it the same way and
7587        // for the same reason, so the two halves of a frame cannot disagree.
7588        //
7589        // `upscaling` is derived from the two extents rather than from the scale
7590        // itself, which is what makes it exact: a target small enough that the
7591        // scaled extent rounds back onto it adds no pass, because there would be
7592        // nothing for the pass to do.
7593        let target_extent = extent;
7594        let extent = self.internal_extent(target_extent);
7595        let upscaling = extent != target_extent;
7596        let frame = self.frame;
7597        let instance_count = self.instances.slot_count();
7598        let emit = self.emit;
7599
7600        // Every secondary view the caller asked for, checked before anything of
7601        // theirs is recorded: a view that does not exist, or one nothing began
7602        // this frame, would draw out of blocks written for some other frame.
7603        let secondary: Vec<(ViewTarget, (u32, u32))> = views
7604            .iter()
7605            .map(|view| {
7606                assert!(
7607                    view.view != ViewId::PRIMARY,
7608                    "the primary camera draws into the target `add_passes_with_views` takes, \
7609                     not into a `ViewTarget`"
7610                );
7611                let built = self
7612                    .views
7613                    .get(view.view.index() - 1)
7614                    .and_then(Option::as_ref)
7615                    .unwrap_or_else(|| panic!("{:?} is not a view this renderer built", view.view));
7616                assert_eq!(
7617                    built.begun, self.frame_serial,
7618                    "{:?} was not begun this frame; call `begin_view` after `begin_frame`",
7619                    view.view
7620                );
7621                assert!(
7622                    views.iter().filter(|other| other.view == view.view).count() == 1,
7623                    "{:?} was named twice in one frame",
7624                    view.view
7625                );
7626                (*view, self.view_extent(built.background, view.extent))
7627            })
7628            .collect();
7629
7630        // **The skinning dispatch, before anything else is added.** It imports
7631        // the vertex pool and hands back that node's id; every pass below that
7632        // pulls vertices declares a read of it, and the graph is what turns the
7633        // two declarations into the barrier between the compute write and the
7634        // draws. `None` is a frame with nothing to skin, which adds no pass and
7635        // declares nothing — see `Skinning::add_pass`.
7636        let skinned = skinning.and_then(|skinning| skinning.add_pass(graph, frame));
7637
7638        // The camera's cull dispatch and the draw-argument dispatch, and the
7639        // light clustering after them — before anything draws, and before the
7640        // shadow atlas, which is where they always ran. See [`View::add_cull`].
7641        let cull = self.primary.add_cull(graph, pool, frame, instance_count);
7642
7643        // Topic 25's record of each cascade's cut. Each is written by
7644        // exactly one mesh pass, so what the graph orders here is this frame's
7645        // write against the next frame's use of the same slot. Each arrives in
7646        // the state the previous frame left it in, which is the one declared as
7647        // final.
7648        let tile_selection: Vec<BufferId> = self
7649            .shadow_selection
7650            .get(self.frame)
7651            .into_iter()
7652            .flatten()
7653            .enumerate()
7654            .map(|(tile, &buffer)| {
7655                import_read_write(graph, &format!("shadow-selection-{tile}"), buffer)
7656            })
7657            .collect();
7658
7659        // **This frame's slot of the probe ring**, which is the buffer every
7660        // one of this frame's bind groups names — see [`crate::probe`] for why
7661        // there is more than one. Imported in `ShaderRead` and handed back in
7662        // it: the build's staging copy left it there and no pass in the frame
7663        // writes it yet.
7664        let probe_buffer = self.probes.buffer(frame);
7665        let probe_table = graph.import_buffer(
7666            "probes",
7667            ImportedBuffer {
7668                buffer: probe_buffer,
7669                initial: ResourceState::ShaderRead,
7670                final_state: ResourceState::ShaderRead,
7671            },
7672        );
7673
7674        // The occlusion placeholder, imported once and read by every pass whose
7675        // bind group names it: the shadow pass's views, the depth prepass's copy
7676        // of the camera's group, and — on a frame drawing without
7677        // `RenderEffects::AMBIENT_OCCLUSION` — the forward pass itself. It was
7678        // uploaded at build, so it is already in `ShaderRead` and the graph has
7679        // nothing to transition; declaring it is what keeps that true if a later
7680        // pass wants it in some other state.
7681        let occlusion_placeholder = graph.import_image(
7682            "ssao-placeholder",
7683            ImportedImage {
7684                image: self.ambient_occlusion_placeholder.image,
7685                view: self.ambient_occlusion_placeholder.view,
7686                format: Format::R8Unorm,
7687                extent: (1, 1),
7688                initial: ResourceState::ShaderRead,
7689                claim: InitialClaim::Tracked,
7690                final_state: ResourceState::ShaderRead,
7691            },
7692        );
7693
7694        // The contact-shadow placeholder, imported beside the occlusion one and
7695        // on its terms exactly: every group of the mesh layout names this
7696        // binding, and on a frame drawing without `RenderEffects::CONTACT_SHADOWS`
7697        // it is what the forward pass binds.
7698        let contact_placeholder = graph.import_image(
7699            "contact-shadows-placeholder",
7700            ImportedImage {
7701                image: self.contact_shadow_placeholder.image,
7702                view: self.contact_shadow_placeholder.view,
7703                format: Format::R8Unorm,
7704                extent: (1, 1),
7705                initial: ResourceState::ShaderRead,
7706                claim: InitialClaim::Tracked,
7707                final_state: ResourceState::ShaderRead,
7708            },
7709        );
7710
7711        // §3.2's base-colour page, in every bind group of `mesh_layout` and so
7712        // read by all three of the passes that draw geometry. Like the
7713        // placeholder above it is already in `ShaderRead` and the graph has
7714        // nothing to transition on a frame nothing writes it — **the
7715        // declaration is for the frames something does**. A caller that copies a
7716        // render-to-texture view into one of its layers imports the same handle,
7717        // gets this same id back (`RenderGraph::import_image`), and the graph
7718        // then has an edge to order its write against these reads. Without the
7719        // declaration there is no such edge: the page is bound out of a
7720        // descriptor the graph never hears about, and a copy scheduled anywhere
7721        // but the tail of the frame leaves it in `TransferDst` for the passes
7722        // that sample it.
7723        let base_color_page =
7724            graph.import_image(Self::BASE_COLOR_PAGE_LABEL, self.base_color_page_import());
7725        // §2's normal page beside it, declared for exactly the reason above: it
7726        // is in every group of `mesh_layout` too, so a caller copying into one
7727        // of its layers needs the same edge against these draws.
7728        let normal_page = graph.import_image(Self::NORMAL_PAGE_LABEL, self.normal_page_import());
7729        // §2's other two pages beside them, declared for exactly the same
7730        // reason: both are in every group of `mesh_layout`, so a caller copying
7731        // into one of their layers needs the same edge against these draws.
7732        let mro_page = graph.import_image(Self::MRO_PAGE_LABEL, self.mro_page_import());
7733        let emissive_page =
7734            graph.import_image(Self::EMISSIVE_PAGE_LABEL, self.emissive_page_import());
7735
7736        // What this frame draws, resolved by the `begin_frame` that opened it —
7737        // see [`crate::effects`]. Read once here so every conditional below is
7738        // about one value rather than about four reads of a field.
7739        let effects = self.frame_effects;
7740        // Read here for `effects`' reason and for one more: the passes below
7741        // borrow `self` field by field, and a `&self` method called between
7742        // them would borrow the whole of it.
7743        let draws_sky = self.draws_sky();
7744        // What the frame's water draws, or `None` for a frame with none — read
7745        // here for `draws_sky`'s reason, and the same value every view records
7746        // from.
7747        let water = self.water.frame(self.frame);
7748        // The same, for the grass field: read here for `draws_sky`'s reason,
7749        // and the same value every view records from.
7750        let grass = self.grass.frame();
7751        // Whether this frame ends by drawing the shadow atlas over itself — the
7752        // resolved view rather than the switch, so a caller who left the atlas
7753        // up and then asked for normals gets normals. Read here for
7754        // `draws_sky`'s reason exactly: `debug_view` takes `&self`.
7755        let draws_atlas_view = self.debug_view() == DebugView::ShadowAtlas;
7756
7757        let pages = MaterialPages {
7758            base_color: base_color_page,
7759            normal: normal_page,
7760            mro: mro_page,
7761            emissive: emissive_page,
7762        };
7763        let (shadow_atlas, shadow_draws, shadow_tile_clears, rsm_images) = self.add_shadow_pass(
7764            graph,
7765            pool,
7766            &tile_selection,
7767            ShadowReads {
7768                occlusion_placeholder,
7769                pages,
7770                skinned,
7771                probes: probe_table,
7772            },
7773        );
7774
7775        // The wireframe twin where a caller switched the view on, and `None`
7776        // everywhere else — see `set_wireframe`. Written on `ground_grid`'s
7777        // terms, and the `filter` is what keeps "switched on" from outrunning
7778        // "built": the field is only `Some` after a build that succeeded.
7779        //
7780        // The depth prepass below takes the depth-only pipeline and is untouched
7781        // by this, which is the half that makes a wireframe frame legible: the
7782        // occlusion pair still reads solid depth. **It is also what makes this
7783        // one variable rather than two**: the colour pass's depth attachment
7784        // branches on it as well, because a wireframe is not the geometry the
7785        // prepass drew — see `MeshModules::color_depth_stencil`.
7786        let wireframe = self.wireframe_pipeline.filter(|_| self.wireframe_on);
7787        let bucket_draws = BucketDraws {
7788            // Replaced per partition below, in both passes that draw this list —
7789            // see [`ForwardRenderer::sided_partitions`] and
7790            // [`ForwardRenderer::depth_partitions`]. The field is what the
7791            // partitions inherit everything else from.
7792            pipeline: self.mesh_pipeline.single,
7793            layout: self.mesh_pipeline_layout,
7794            indices: self.pool.index_buffer(),
7795            emit,
7796            calls: self
7797                .bucket_constants
7798                .iter()
7799                .enumerate()
7800                .map(|(bucket, constant_offset)| {
7801                    let bucket = u32::try_from(bucket)
7802                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
7803                    (
7804                        *constant_offset,
7805                        self.primary.draws.args_offset(bucket),
7806                        self.primary.draws.count_offset(bucket),
7807                        self.primary.draws.mesh_args_offset(bucket),
7808                    )
7809                })
7810                .collect(),
7811            region_step: self.region_step,
7812            // Packed per partition, where the partition's buckets are known.
7813            ranges: None,
7814            flat: None,
7815        };
7816
7817        // Every draw this frame records: the shadow pass's, one per bucket — or
7818        // per range of buckets, or per partition behind a task stage — in
7819        // **each** of the depth prepass and the forward pass, and one full-screen
7820        // triangle per full-screen pass. Assigned before the passes below borrow
7821        // the fields they need, so it is the count for the frame being built
7822        // rather than the one before it — and off this frame's resolved effects
7823        // rather than off a constant, so a switched-off effect's triangle is not
7824        // counted as submitted.
7825        //
7826        // The ground grid is added on top rather than folded into
7827        // `fullscreen_passes`: it is not a [`RenderEffects`] bit and is not
7828        // resolved by the toggle order — it is a caller's opt-in, off by
7829        // default — so what decides it is the field and not this frame's
7830        // effects.
7831        self.recorded_fullscreen = fullscreen_passes(effects, extent, upscaling, self.frame_ssao_blurs)
7832                + u64::from(self.ground_grid().is_some() && !draws_atlas_view)
7833                + if draws_sky { SkyPass::PASSES } else { 0 }
7834                // The composite on an atmosphere frame whose fog effect is off,
7835                // on the sky's terms: it is there for the air in front of the
7836                // scene, which the atmosphere decides and no effect bit does.
7837                // With the effect on, `fullscreen_passes` already counted it.
7838                + if self.primary.frame_aerial
7839                    && !effects.contains(RenderEffects::VOLUMETRIC_FOG)
7840                {
7841                    u64::from(Volumetric::COMPOSITE_PASSES)
7842                } else {
7843                    0
7844                }
7845                // The water copy's triangle, on the sky's terms: content rather
7846                // than an effect bit, so the bodies decide it.
7847                + if water.is_some() { Water::FULLSCREEN_PASSES } else { 0 }
7848                // The atlas viewer, on the ground grid's terms: not an effect
7849                // bit and not resolved by the toggle order, so what decides it
7850                // is the debug view and not this frame's effects. It *replaces*
7851                // the tonemap `fullscreen_passes` counted and the grid above —
7852                // see `View::add_passes` — so its passes stand in for the one.
7853                + if draws_atlas_view {
7854                    u64::from(AtlasView::PASSES) - 1
7855                } else {
7856                    0
7857                };
7858        // The debug draw layer's own call, on the ground grid's terms: not an
7859        // effect bit, and decided by whether this frame's slot has a segment in
7860        // it. One direct draw of one instance covering every segment appended,
7861        // which is why it joins the full-screen triangles rather than the
7862        // indirect draws — `counters` counts both as submitted *and* drawn,
7863        // because the CPU knows what they cover.
7864        self.recorded_debug_draw = u64::from(self.debug_draw.records_pass(self.frame));
7865        // The shadow pass's tile resets, on the same terms: one over-sized
7866        // triangle of one instance per tile it redrew, and none at all on a
7867        // frame that cleared the whole attachment — see
7868        // [`MeshModules::depth_clear_pipeline`].
7869        self.recorded_tile_clears = shadow_tile_clears;
7870        // One indexed draw per body the frame's water holds.
7871        self.recorded_water_draws = water
7872            .as_ref()
7873            .map_or(0, |water: &WaterFrame| water.draws.len() as u64);
7874        // One indirect draw per tile slot the frame's field holds, per look it
7875        // draws.
7876        self.recorded_grass_draws = grass.as_ref().map_or(0, |grass: &GrassFrame| {
7877            u64::from(grass.slots) * u64::from(grass.draws_per_slot())
7878        });
7879        // The late depth prepass is a third list of calls, on a frame whose
7880        // camera culls in two phases.
7881        let camera_passes: u64 = if self.primary.draws.frame_mode(frame)
7882            == crcbl_shaders::draw_gen::DrawMode::Occlusion
7883        {
7884            3
7885        } else {
7886            2
7887        };
7888        let prepass_partitions = self.depth_partitions(&bucket_draws);
7889        // And the colour pass's own split, which is by **side** alone: its
7890        // pipeline has a fragment stage either way, so an alpha mask is nothing
7891        // it has to route around and a cull mode is. The wireframe twin pair
7892        // substitutes for the shaded one here exactly as the single pipeline
7893        // used to.
7894        let color_partitions =
7895            self.sided_partitions(&bucket_draws, wireframe.unwrap_or(self.mesh_pipeline));
7896        // Off the partitions the passes below record, because where a call
7897        // draws a range of buckets the two splits pack into different numbers
7898        // of ranges — see [`BucketDraws::call_count`].
7899        let calls = |partitions: &[BucketDraws]| -> u64 {
7900            partitions.iter().map(BucketDraws::call_count).sum()
7901        };
7902        self.recorded_draws = shadow_draws
7903            + (camera_passes - 1) * calls(&prepass_partitions)
7904            + calls(&color_partitions)
7905            + self.recorded_grass_draws
7906            + self.direct_draws();
7907
7908        // --- the probe gather ---
7909        //
7910        // The irradiance probes' updater, second half: the map
7911        // the pass above drew, read into every row of the table. **Here rather
7912        // than beside that pass** because the write is `&mut` — the group naming
7913        // the map's transient views is cached across frames, and a group naming a
7914        // transient cannot be built where the others are; see
7915        // [`crate::ssao::cached_group`].
7916        //
7917        // It is before the depth prepass and the forward pass, which is the
7918        // ordering that matters: both declare a read of these rows, so the graph
7919        // barriers this write against them.
7920        //
7921        // Which map layer a row is weighed against is the row's own index, so
7922        // the view is resolved exactly as the drawing passes resolve it — the
7923        // placeholder until `capture_probe_visibility` has run, and off entirely
7924        // where `r_probe_visibility` is off. A gather against the placeholder
7925        // occludes nothing, which is the honest answer for a scene that never
7926        // captured.
7927        let probe_visibility_view = match &self.probe_visibility {
7928            Some(captured) if crate::probe_visibility::enabled() => captured.view,
7929            _ => self.probe_visibility_placeholder.view,
7930        };
7931        let frame = self.frame;
7932        if let Some((gather, images)) = self.probe_gather.as_mut().zip(rsm_images) {
7933            gather.add_pass(graph, frame, images, probe_visibility_view, probe_table);
7934        }
7935
7936        let passes = FramePasses {
7937            slot: frame,
7938            emit,
7939            target_format: self.target_format,
7940            ssao_blurs: self.frame_ssao_blurs,
7941            draws_sky,
7942            water,
7943            grass,
7944            skinned,
7945            probe_buffer,
7946            probe_table,
7947            occlusion_placeholder,
7948            contact_placeholder,
7949            pages,
7950            shadow_atlas,
7951            probe_visibility: probe_visibility_view,
7952            mesh_layout: self.mesh_layout,
7953            wireframe,
7954            prepass_partitions,
7955            color_partitions,
7956            tonemap: TonemapPipeline {
7957                sampler: self.sampler,
7958                layout: self.tonemap_layout,
7959                pipeline_layout: self.tonemap_pipeline_layout,
7960                pipeline: self.tonemap_pipeline,
7961            },
7962        };
7963        // From here the frame is borrowed field by field, because every view's
7964        // passes hold its own caches for the life of the graph.
7965        let Self {
7966            primary,
7967            views: built,
7968            debug_draw,
7969            ground_grid,
7970            ground_grid_on,
7971            atlas_viewer,
7972            cull_stats,
7973            ..
7974        } = self;
7975
7976        // **Every secondary view before the primary camera's frame**, so a pass
7977        // the primary records — an overlay compositing a scope's picture onto
7978        // the lens it is seen through — reads a view that is already drawn. Each
7979        // records its whole frame straight through: its own cull, its own
7980        // clustering, and every pass the primary records after them, against the
7981        // atlas and the probe rows the scene passes above left behind.
7982        for (index, slot) in built.iter_mut().enumerate() {
7983            let Some((view_target, view_extent)) = secondary
7984                .iter()
7985                .find(|(view, _)| view.view.index() == index + 1)
7986            else {
7987                continue;
7988            };
7989            let view = slot
7990                .as_mut()
7991                .unwrap_or_else(|| unreachable!("checked against the built views above"));
7992            let view_cull = view.add_cull(graph, pool, frame, instance_count);
7993            view.add_passes(
7994                graph,
7995                &passes,
7996                view_cull,
7997                ViewOutput {
7998                    target: view_target.target,
7999                    target_extent: view_target.extent,
8000                    extent: *view_extent,
8001                },
8002                Overlays::default(),
8003                |_, _| {},
8004            );
8005        }
8006
8007        // The statistics buffer's id, read before the cull moves into the pass
8008        // recording below: the copy that reads it is the frame's last pass.
8009        let stats_id = cull.generated.visible_count_id;
8010        let tonemapped = primary.add_passes(
8011            graph,
8012            &passes,
8013            cull,
8014            ViewOutput {
8015                target,
8016                target_extent,
8017                extent,
8018            },
8019            Overlays {
8020                debug_draw: Some(debug_draw),
8021                ground_grid: ground_grid.as_ref().filter(|_| *ground_grid_on),
8022                atlas_viewer: draws_atlas_view.then_some(atlas_viewer),
8023            },
8024            overlay,
8025        );
8026
8027        // **Last, and that is the point.** Three passes add to the statistics
8028        // buffer — the cull dispatch, the light grid's overflow counter and the
8029        // amplification stage inside the forward pass — so a copy scheduled any
8030        // earlier would take a total the frame had not finished writing. The
8031        // graph puts it in `TransferSrc` for this and back into the state the
8032        // next frame on this slot imports it in; there is not a barrier written
8033        // here.
8034        if let Some(stats) = cull_stats.as_mut() {
8035            stats.add_copy_pass(graph, stats_id);
8036        }
8037
8038        tonemapped
8039    }
8040
8041    /// Adds the cull dispatches and the depth-only pass that fill the shadow
8042    /// atlas, and returns the atlas as the graph knows it.
8043    ///
8044    /// Every tile is one viewport of one render pass. A pass per tile would be
8045    /// one clear of the same image and one more barrier per tile, and the graph
8046    /// would have to be told each of them only touches part of it — where one
8047    /// pass with a viewport per tile is what a shadow *atlas* is for in the first
8048    /// place.
8049    ///
8050    /// **Only the occupied tiles get a cull and a viewport.** The cascades
8051    /// always are; a light tile is occupied when
8052    /// [`shadow::Selection`] gave it to a light. A free one keeps the
8053    /// reversed-Z clear the pass wrote, which is `0.0` — "nothing stored, as far
8054    /// away as depth goes" — so anything that did sample it would come back
8055    /// fully lit rather than fully shadowed.
8056    ///
8057    /// # With [`RenderEffects::SHADOWS`] off, every tile is a free one
8058    ///
8059    /// That is the whole switch, and it is the same mechanism a free tile
8060    /// already had rather than a second one: no cull is dispatched and no
8061    /// viewport is drawn, the pass records its clear and nothing else, and every
8062    /// comparison against the atlas comes back fully lit. The pass itself stays
8063    /// on the frame that switches it off — it is what *writes* that clear, and a
8064    /// frame that skipped it would leave the atlas holding the last frame that
8065    /// did draw into it, or undefined memory on the first frame of all.
8066    ///
8067    /// # A cached atlas records nothing at all
8068    ///
8069    /// Topic 45's static-caching rung. When
8070    /// [`ForwardRenderer::shadow_atlas_cached`] says the image already holds
8071    /// what this frame would draw, this adds **no cull and no pass**: the atlas
8072    /// is imported so the passes that sample it have an edge to the resource,
8073    /// and it keeps the contents an earlier frame left in it. That is why the
8074    /// image is a persistent one with a tracked ledger entry rather than a
8075    /// transient — nothing else in the frame can alias it, so what it holds is
8076    /// what the last pass to write it wrote.
8077    ///
8078    /// # Per group, and what pays for the tiles it keeps
8079    ///
8080    /// Topic 45's cadence rung. A **group** — a cascade, or a
8081    /// light slot's whole run of tiles — is redrawn or held on its own, and
8082    /// [`ForwardRenderer::shadow_group_redrawn`] is what says which. A frame
8083    /// that holds nothing clears the whole attachment, which is the recording
8084    /// that shipped before the rung; a frame that holds something **loads** the
8085    /// attachment instead and resets each tile it redraws with
8086    /// [`MeshModules::depth_clear_pipeline`], which is the portable statement of
8087    /// a clear bounded to one tile.
8088    ///
8089    /// The attachment's own [`LoadOp::Clear`] cannot serve there: it covers
8090    /// every tile including the ones being kept, and the region-bounded
8091    /// alternatives are not portable — Metal's load action and WebGPU's
8092    /// `loadOp` have no render area to bound them, so a clear that covered part
8093    /// of the image on Vulkan and all of it on Metal would be a held tile that
8094    /// survives on one backend and is erased on another.
8095    fn add_shadow_pass(
8096        &self,
8097        graph: &mut RenderGraph<'_>,
8098        pool: &TransientPool,
8099        selection: &[BufferId],
8100        reads: ShadowReads,
8101    ) -> (ImageId, u64, u64, Option<RsmImages>) {
8102        let shadows = self.frame_effects.contains(RenderEffects::SHADOWS);
8103        let (atlas_width, atlas_height) = shadow::atlas_extent();
8104        let atlas = graph.import_image(
8105            "shadow-atlas",
8106            ImportedImage {
8107                image: self.shadow_atlas,
8108                view: self.shadow_atlas_view,
8109                format: Format::D32Float,
8110                extent: (atlas_width, atlas_height),
8111                // What the previous executed frame left it in — `Undefined` on
8112                // the first, which is what makes the graph give it a layout at
8113                // all.
8114                initial: imported_state(pool, self.shadow_atlas),
8115                // The renderer keeps this image across frames, so the pool's
8116                // ledger is the record of what happened to it and the line above
8117                // is that record read back rather than a second copy of it.
8118                claim: InitialClaim::Tracked,
8119                final_state: ResourceState::ShaderRead,
8120            },
8121        );
8122        // The cached frame's whole answer: the image above and nothing that
8123        // touches it. It is already in `ShaderRead` — the frame that drew it
8124        // handed it back that way — so the graph has no transition to make, and
8125        // the passes that sample it read the maps an earlier frame left there.
8126        if self.shadow_atlas_cached {
8127            // **And no reflective shadow map either**, which cannot happen while
8128            // the updater is on: `begin_frame` keeps cascade 0 off the hold in
8129            // exactly that case, so a frame reaching here has nothing to draw
8130            // the map from. See `probe_update_runs`.
8131            return (atlas, 0, 0, None);
8132        }
8133        let placeholder = graph.import_image(
8134            "shadow-placeholder",
8135            ImportedImage {
8136                image: self.shadow_placeholder,
8137                view: self.shadow_placeholder_view,
8138                format: Format::D32Float,
8139                extent: (1, 1),
8140                // **Its own ledger entry, not the atlas's.** The two move
8141                // together today — both are imported by this function on every
8142                // frame and both are handed back in `ShaderRead` — so one lookup
8143                // would answer both, and that is exactly the coincidence a
8144                // second declared state here stops depending on.
8145                initial: imported_state(pool, self.shadow_placeholder),
8146                claim: InitialClaim::Tracked,
8147                final_state: ResourceState::ShaderRead,
8148            },
8149        );
8150
8151        // Which light slots have a light this frame, resolved once: a slot's
8152        // cull is dispatched and its faces are drawn together or not at all, and
8153        // `begin_frame` filled that generator's parameters under exactly this
8154        // condition.
8155        //
8156        // **And only the ones this frame redraws**, since the cadence rung: a
8157        // held slot keeps the texels it has, so recording its cull and its
8158        // draws would be the same picture at the full price.
8159        let occupied: Vec<(usize, shadow::Assignment, &Light)> = self
8160            .shadow_lights
8161            .slots()
8162            .iter()
8163            .enumerate()
8164            .filter(|_| shadows)
8165            .filter(|(slot, _)| self.shadow_group_redrawn[shadow_cull(*slot)])
8166            .filter_map(|(slot, held)| {
8167                let held = (*held)?;
8168                Some((slot, held, self.extra_lights.get(held.light)?))
8169            })
8170            .collect();
8171
8172        // One cull dispatch per cascade and per occupied slot, before the pass
8173        // that draws from them — **not one per tile**, which is topic 18's
8174        // fourth decision: a point light's six faces draw one visible set.
8175        let cascades: Vec<usize> = if shadows {
8176            (0..shadow::CASCADES)
8177                .filter(|cascade| self.shadow_group_redrawn[*cascade])
8178                .collect()
8179        } else {
8180            Vec::new()
8181        };
8182        // **Cascade 0's cull, on a frame that is not drawing it into the
8183        // atlas.** `begin_frame` fits it whenever the updater is on, shadows or
8184        // no shadows — see `rsm_cull_ready` — so this is the case where the map
8185        // is drawn and the atlas keeps its clear. Chained **last**, because the
8186        // occupied slots' entries are indexed by `cascades.len() + index` a few
8187        // lines below and an insertion before them would hand a light's draws to
8188        // the wrong viewport.
8189        let rsm_only_cull = self.rsm_cull_ready && !cascades.contains(&0);
8190        // The punctual producer's faces, which are also the light slots'
8191        // atlas views — see `punctual_faces`, the one list both halves of the
8192        // updater walk.
8193        let punctual = self.punctual_faces();
8194        // And their culls on a frame that is not drawing the atlas, which
8195        // `occupied` is empty on for the same reason `cascades` is. Deduplicated
8196        // because a point light's six faces draw one visible set, and chained
8197        // **after** the entries `views` indexes positionally below.
8198        let punctual_only_culls: Vec<usize> = if shadows {
8199            Vec::new()
8200        } else {
8201            punctual
8202                .iter()
8203                .map(|face| face.cull)
8204                .collect::<std::collections::BTreeSet<_>>()
8205                .into_iter()
8206                .collect()
8207        };
8208        let generated: Vec<(usize, GeneratedDraws)> = cascades
8209            .iter()
8210            .copied()
8211            .chain(occupied.iter().map(|(slot, _, _)| shadow_cull(*slot)))
8212            .chain(rsm_only_cull.then_some(0))
8213            .chain(punctual_only_culls)
8214            .map(|cull| {
8215                (
8216                    cull,
8217                    self.shadow_draws[cull].add_passes(
8218                        graph,
8219                        self.frame,
8220                        self.instances.slot_count(),
8221                    ),
8222                )
8223            })
8224            .collect();
8225
8226        // What the pass body records, in order: which view's bind group, which
8227        // rectangle of the atlas its viewport covers, and which of the culls
8228        // above it draws from. Paired rather than positional, because the free
8229        // slots are missing from every one of these lists and a bare index into
8230        // one would hand a light's draws to the wrong viewport the moment one
8231        // slot is free and a later one is not.
8232        //
8233        // **The rectangle rather than the slot**, resolved here: the body runs
8234        // in a closure that outlives this borrow, and asking the selection for
8235        // it there would be a second reading of an allocation that has to be the
8236        // one the frame block was written from.
8237        //
8238        // **And which draw region of that cull**: region 0, every survivor, for
8239        // a cascade and a spot; and for a point light whose cull tagged its
8240        // casters by face, the region of the face being drawn — see
8241        // `set_point_face_culls`.
8242        let mut views: Vec<(usize, shadow::TileRect, usize, u32)> = cascades
8243            .iter()
8244            .enumerate()
8245            .map(|(position, cascade)| {
8246                (
8247                    *cascade,
8248                    self.shadow_lights.atlas_rect(*cascade),
8249                    position,
8250                    0,
8251                )
8252            })
8253            .collect();
8254        for (index, (slot, held, light)) in occupied.iter().enumerate() {
8255            // A spot draws face 0 alone; a point light draws all six, each
8256            // through its own matrix into its own tile. `shadow::tile_span` is
8257            // the same function `Selection` allocated the run with, so a face
8258            // here and a tile there cannot disagree about how many there are.
8259            let by_face = self.shadow_draws[shadow_cull(*slot)].frame_mode(self.frame)
8260                == crcbl_shaders::draw_gen::DrawMode::Faces;
8261            for face in 0..shadow::tile_span(light) {
8262                views.push((
8263                    shadow_view(*slot, face),
8264                    self.shadow_lights
8265                        .atlas_rect(shadow::light_tile(held.base + face)),
8266                    cascades.len() + index,
8267                    face_region(by_face, face),
8268                ));
8269            }
8270        }
8271
8272        let mut pass = graph
8273            .add_render_pass("shadow")
8274            // **Stored, unlike the scene's depth.** This is the one depth buffer
8275            // in the engine that something downstream reads, which is what
8276            // `PassBuilder::clear_depth`'s docs said would need a `StoreOp` the
8277            // day a prepass existed.
8278            .depth(
8279                atlas,
8280                // **Loaded on a frame that is keeping a tile**, which is the
8281                // cadence rung's whole seam: a clear here covers the image, so
8282                // the tiles this frame *does* redraw are reset one at a time by
8283                // the pipeline below instead. A frame keeping nothing clears,
8284                // which is what shipped.
8285                if self.shadow_atlas_clears {
8286                    LoadOp::Clear
8287                } else {
8288                    LoadOp::Load
8289                },
8290                StoreOp::Store,
8291                crcbl_hal::ClearValue {
8292                    depth: crcbl_hal::depth::CLEAR,
8293                    ..crcbl_hal::ClearValue::default()
8294                },
8295            )
8296            // Declared so the graph gives it a shader-read layout: it is in
8297            // every cascade's bind group, standing in for the atlas this pass is
8298            // writing. See `ForwardRenderer::shadow_placeholder`.
8299            .read_image(placeholder)
8300            // Likewise, and it is in every one of those groups too — see
8301            // `ForwardRenderer::ambient_occlusion_placeholder`. Nothing samples
8302            // it here either: the depth-only pipeline has no fragment stage.
8303            .read_image(reads.occlusion_placeholder)
8304            // And §3.2's page, which `mesh_layout` names in every group — a
8305            // cascade's included. See `ForwardRenderer::base_color_page_import`
8306            // for what the declaration buys a caller that writes the page.
8307            .read_image(reads.pages.base_color)
8308            // And §2's other three pages beside it, in those same groups and
8309            // sampled by no cascade — see
8310            // `ForwardRenderer::normal_page_import`.
8311            .read_image(reads.pages.normal)
8312            .read_image(reads.pages.mro)
8313            .read_image(reads.pages.emissive)
8314            // And the probe rows, which are in those groups too and which no
8315            // cascade reads — declared on the placeholder's and the pages'
8316            // terms, plus one of their own: the rows are device-local and a copy
8317            // destination so the irradiance probes' gather can
8318            // write them, and a pass that binds a buffer it has not declared is
8319            // one the graph cannot order that write against.
8320            .read_buffer(reads.probes);
8321        // Each tile's mesh pass records the cut it descended to, into a buffer
8322        // of its own — see `ForwardRenderer::shadow_selection`. Empty where
8323        // there is no amplification stage to descend anything.
8324        //
8325        // Declared for every tile rather than for the occupied ones: the state
8326        // is what the buffer is *in*, which does not depend on whether this
8327        // frame happened to write it, and a free tile's buffer still has to
8328        // arrive in the state the next frame's import claims.
8329        for &buffer in selection {
8330            pass = pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8331        }
8332        // The skinned vertices this pass may pull, and the reason it is declared
8333        // here as well as on the colour passes: a cascade draws the same
8334        // geometry out of the same pool, so a shadow that fell before the
8335        // dispatch was visible would be cast by the previous pose — a shadow
8336        // that does not match its caster, on a frame whose picture is otherwise
8337        // right.
8338        if let Some(vertices) = reads.skinned {
8339            pass = pass.read_buffer(vertices);
8340        }
8341        for (_, draws) in &generated {
8342            pass = read_draw_sources(pass, draws, self.emit);
8343        }
8344
8345        let groups = self.shadow_groups[self.frame].clone();
8346        // **What the reflective shadow map is drawn from**, read out here rather
8347        // than reconstructed by the caller: cascade 0's bind group — whose
8348        // uniform block already holds that cascade's `view_proj`, which is what
8349        // "reusing cascade 0's matrix" means — and the `GeneratedDraws` its cull
8350        // produced a moment ago. Both are `Copy`, so recording a second pass
8351        // from them costs no second cull and no second matrix.
8352        //
8353        // [`None`] on a frame that is not drawing cascade 0 at all: shadows off,
8354        // or a `r_shadow_cadence` past one that held the group anyway. The rows
8355        // then keep what the last gather wrote — see [`ProbeUpdate::EveryFrame`],
8356        // which says so.
8357        let cascade_zero: Option<(BindGroupHandle, GeneratedDraws)> = self
8358            .rsm_cull_ready
8359            .then(|| {
8360                generated
8361                    .iter()
8362                    .find(|(cull, _)| *cull == 0)
8363                    .map(|(_, draws)| (groups[CASCADE_ZERO_VIEW], *draws))
8364            })
8365            .flatten();
8366        // **What the punctual reflective shadow map is drawn from**, resolved
8367        // here for `cascade_zero`'s reason and on its terms: each face's own
8368        // bind group — whose uniform block already holds that face's
8369        // `view_proj` — and the `GeneratedDraws` its slot's cull produced a
8370        // moment ago. Both are `Copy`, so the second pass costs no second cull
8371        // and no second matrix.
8372        //
8373        // Found by cull id rather than by position, so this list and the atlas's
8374        // cannot be knocked out of step by a slot the other one skipped.
8375        //
8376        // And the face's draw region, on the atlas's terms: a point light whose
8377        // cull tagged its casters draws each face from that face's region.
8378        let punctual_views: Vec<(BindGroupHandle, shadow::TileRect, GeneratedDraws, u32)> =
8379            punctual
8380                .iter()
8381                .filter_map(|face| {
8382                    let (_, draws) = generated.iter().find(|(cull, _)| *cull == face.cull)?;
8383                    let by_face = self.shadow_draws[face.cull].frame_mode(self.frame)
8384                        == crcbl_shaders::draw_gen::DrawMode::Faces;
8385                    Some((
8386                        groups[face.view],
8387                        face.tile,
8388                        *draws,
8389                        face_region(by_face, face.face),
8390                    ))
8391                })
8392                .collect();
8393        // The culls those faces draw from, **once each**: a point light's six
8394        // faces draw one visible set, so declaring a face's sources would
8395        // declare the same buffers six times in one pass.
8396        let punctual_sources: Vec<GeneratedDraws> = punctual
8397            .iter()
8398            .map(|face| face.cull)
8399            .collect::<std::collections::BTreeSet<_>>()
8400            .into_iter()
8401            .filter_map(|cull| {
8402                let (_, draws) = generated.iter().find(|(candidate, _)| *candidate == cull)?;
8403                Some(*draws)
8404            })
8405            .collect();
8406        let bucket_draws = BucketDraws {
8407            // Replaced per partition below; the field is what the tile clears
8408            // and the reflective shadow map inherit, and neither binds it.
8409            pipeline: self.shadow_pipeline.single,
8410            layout: self.mesh_pipeline_layout,
8411            indices: self.pool.index_buffer(),
8412            emit: self.emit,
8413            calls: self
8414                .bucket_constants
8415                .iter()
8416                .enumerate()
8417                .map(|(bucket, constant_offset)| {
8418                    let bucket = u32::try_from(bucket)
8419                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8420                    (
8421                        *constant_offset,
8422                        self.primary.draws.args_offset(bucket),
8423                        self.primary.draws.count_offset(bucket),
8424                        self.primary.draws.mesh_args_offset(bucket),
8425                    )
8426                })
8427                .collect(),
8428            region_step: self.region_step,
8429            // Packed per partition, where the partition's buckets are known.
8430            ranges: None,
8431            flat: None,
8432        };
8433        // Kept back for the reflective shadow map below, which is the same
8434        // per-bucket call list under a different pipeline — the depth prepass
8435        // plays exactly this trick with the camera's. Cloned before the pass
8436        // body takes the original.
8437        let bucket_calls = bucket_draws.clone();
8438        // The atlas's own split by material mode: an opaque bucket's tile is
8439        // drawn with no fragment stage in a scene that has a cutout in it. Every
8440        // view draws every partition — one call per bucket, per range of
8441        // buckets, or behind a task stage one flat call, per view, under a
8442        // pipeline per mode.
8443        let tile_partitions = self.depth_partitions(&bucket_draws);
8444
8445        // Counted off the two loops the body below runs, before it takes them:
8446        // every partition's calls per occupied view. `ForwardRenderer::counters`
8447        // is what reports it, and reading it back off the same `Vec`s is what
8448        // makes it move when the tile allocation does.
8449        let recorded = views.len() as u64
8450            * tile_partitions
8451                .iter()
8452                .map(BucketDraws::call_count)
8453                .sum::<u64>();
8454        // And the tile resets beside them, which are direct draws of one
8455        // instance rather than indirect ones: a frame that cleared the whole
8456        // attachment records none, and a frame that loaded it records one per
8457        // tile it redraws.
8458        let clears = if self.shadow_atlas_clears {
8459            0
8460        } else {
8461            views.len() as u64
8462        };
8463
8464        // What the image will hold once this body has run, carried into it so
8465        // that *recording* the pass is not what claims the atlas was drawn — see
8466        // [`ForwardRenderer::shadow_atlas_drawn`].
8467        let ran = Arc::clone(&self.shadow_pass_ran);
8468        let pass_id = self.shadow_pass_id;
8469        // The tiles this pass redraws have to be reset before anything is drawn
8470        // into them, and on a frame that loaded the attachment there is nothing
8471        // else that will — see [`MeshModules::depth_clear_pipeline`]. A frame
8472        // that cleared has already had every tile reset by the attachment, so
8473        // this is `None` and the recording is the one that shipped.
8474        let clear = (!self.shadow_atlas_clears).then_some(self.shadow_clear_pipeline);
8475        // **The reset draw has to bind a group, and only a browser says so.**
8476        // `MeshModules::depth_clear_pipeline` builds this pipeline from
8477        // `mesh_pipeline_layout`, so its layout declares group 0 whether or not
8478        // the one triangle's vertex shader reads a byte of it — and WebGPU
8479        // refuses a draw with any group the *layout* declares left unset, where
8480        // Vulkan and the others only care about what the shader dereferences. An
8481        // unbound reset therefore fails no native run and rejects the whole
8482        // browser frame: `No bind group set at group index 0` arrives when the
8483        // encoder is finished, so every pass recorded after it is thrown away
8484        // with it and the canvas stays at the clear colour.
8485        //
8486        // Any bucket's offset does: the block is what the mesh draws index and
8487        // this draw reads none of it, so what matters is that the offset is one
8488        // the layout accepts rather than which bucket it names.
8489        let clear_layout = bucket_draws.layout;
8490        let clear_offset = bucket_draws
8491            .calls
8492            .first()
8493            .map_or(0, |(constant_offset, ..)| *constant_offset);
8494        pass.execute(move |ctx| {
8495            ran.store(pass_id, Ordering::Relaxed);
8496            let encoder = ctx.encoder();
8497            if let Some(clear) = clear {
8498                encoder.bind_graphics_pipeline(clear);
8499                for (view, tile, _, _) in &views {
8500                    set_shadow_tile(encoder, *tile);
8501                    encoder.bind_group(0, groups[*view], &[clear_offset], clear_layout);
8502                    encoder.draw(0..TILE_CLEAR_VERTICES, 0..1);
8503                }
8504            }
8505            for partition in &tile_partitions {
8506                partition.open(encoder);
8507                for (view, tile, cull, region) in &views {
8508                    set_shadow_tile(encoder, *tile);
8509                    partition.record_region(encoder, groups[*view], &generated[*cull].1, *region);
8510                }
8511            }
8512        });
8513
8514        // --- the reflective shadow map ---
8515        //
8516        // The irradiance probes' updater, first half, recorded
8517        // here because this is where cascade 0's bind group and its
8518        // already-generated draws are. **A pass of its own at its own extent**,
8519        // and [`crate::rsm`]'s header argues why it cannot ride the atlas above:
8520        // one colour attachment there spans the whole 3072² image for data only
8521        // one 768² tile is read from, and it would give all fourteen light tiles
8522        // a fragment stage.
8523        //
8524        // No viewport is set: the graph opens a pass with a full-target viewport
8525        // and scissor already, and every attachment here is the map's own square.
8526        let Some((cascade_group, cascade_draws)) = cascade_zero else {
8527            return (atlas, recorded, clears, None);
8528        };
8529        let extent = rsm::extent();
8530        let sun = RsmTargets {
8531            albedo: graph.create_image("rsm-albedo", rsm::albedo_target(extent)),
8532            normal: graph.create_image("rsm-normal", rsm::normal_target(extent)),
8533            world: graph.create_image("rsm-world", rsm::world_target(extent)),
8534        };
8535        // Its own depth, cleared and discarded: it resolves which surface a
8536        // texel of the map holds and nothing reads it afterwards.
8537        let rsm_depth = graph.create_image("rsm-depth", rsm::depth_target(extent));
8538        let mut rsm = graph
8539            .add_render_pass("rsm")
8540            // **Cleared, and the world target's clear is load-bearing**: `w` is
8541            // the coverage flag `RsmOutput::world` writes, so a texel the pass
8542            // draws nothing into reads back zero there and the gather skips it.
8543            // Without the clear the world origin would stand in for every part
8544            // of the cascade the geometry does not cover.
8545            .clear_color(sun.albedo, [0.0; 4])
8546            .clear_color(sun.normal, [0.0; 4])
8547            .clear_color(sun.world, [0.0; 4])
8548            .clear_depth(rsm_depth)
8549            // The same declarations the cascade above makes, for the same
8550            // reason: every group of the mesh layout names these, and this pass
8551            // binds one of those groups. Unlike the cascade, this one has a
8552            // fragment stage — so the pages really are sampled here.
8553            .read_image(placeholder)
8554            .read_image(reads.occlusion_placeholder)
8555            .read_image(reads.pages.base_color)
8556            .read_image(reads.pages.normal)
8557            .read_image(reads.pages.mro)
8558            .read_image(reads.pages.emissive)
8559            .read_buffer(reads.probes);
8560        if let Some(vertices) = reads.skinned {
8561            rsm = rsm.read_buffer(vertices);
8562        }
8563        // Cascade 0's cluster-selection buffer, which the mesh path's stages
8564        // write — declared on the atlas pass's terms, and only for the one view
8565        // this pass draws.
8566        if let Some(&buffer) = selection.get(CASCADE_ZERO_VIEW) {
8567            rsm = rsm.use_buffer(buffer, ResourceState::ShaderReadWrite);
8568        }
8569        rsm = read_draw_sources(rsm, &cascade_draws, self.emit);
8570        // Split by side, on the colour pass's terms: this stage cuts the alpha
8571        // mask itself, so the only thing it cannot say inside the fragment stage
8572        // is which faces the rasteriser keeps.
8573        let rsm_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
8574        let rsm_recorded: u64 = rsm_partitions.iter().map(BucketDraws::call_count).sum();
8575        rsm.execute(move |ctx| {
8576            let encoder = ctx.encoder();
8577            for partition in &rsm_partitions {
8578                partition.open(encoder);
8579                partition.record(encoder, cascade_group, &cascade_draws);
8580            }
8581        });
8582
8583        // --- the punctual reflective shadow map ---
8584        //
8585        // The irradiance probes' punctual producer: the same
8586        // pipeline and the same per-bucket call list as the pass above, under
8587        // one viewport per shadowed light face instead of one whole map. A spot
8588        // is a tile and a point light is six, which is `shadow::tile_span` — so
8589        // this is the atlas pass's own view loop drawn into a second, much
8590        // smaller set of targets.
8591        //
8592        // **Recorded whether or not the frame lights a punctual face**, unlike
8593        // the map above. The clear is a legitimate answer — a frame with no
8594        // shadowed punctual light has no punctual bounce, and the coverage flag
8595        // in `w` says so at every texel — and a pass that came and went with the
8596        // lights would be a pass list that changes shape with the scene, which
8597        // is what `RENDER_PASSES` and every timing reader are written against.
8598        let punctual_extent = rsm::punctual_extent();
8599        let punctual_targets = RsmTargets {
8600            albedo: graph.create_image("rsm-punctual-albedo", rsm::albedo_target(punctual_extent)),
8601            normal: graph.create_image("rsm-punctual-normal", rsm::normal_target(punctual_extent)),
8602            world: graph.create_image("rsm-punctual-world", rsm::world_target(punctual_extent)),
8603        };
8604        let punctual_depth =
8605            graph.create_image("rsm-punctual-depth", rsm::depth_target(punctual_extent));
8606        let mut punctual_pass = graph
8607            .add_render_pass("rsm-punctual")
8608            // Cleared on the map above's terms, and the world target's clear is
8609            // load-bearing for its reason as well as for one of this map's own:
8610            // the tiles the cascades would hold are drawn into by nothing at
8611            // all, and a coverage flag of zero is what keeps the gather out of
8612            // them.
8613            .clear_color(punctual_targets.albedo, [0.0; 4])
8614            .clear_color(punctual_targets.normal, [0.0; 4])
8615            .clear_color(punctual_targets.world, [0.0; 4])
8616            .clear_depth(punctual_depth)
8617            .read_image(placeholder)
8618            .read_image(reads.occlusion_placeholder)
8619            .read_image(reads.pages.base_color)
8620            .read_image(reads.pages.normal)
8621            .read_image(reads.pages.mro)
8622            .read_image(reads.pages.emissive)
8623            .read_buffer(reads.probes);
8624        if let Some(vertices) = reads.skinned {
8625            punctual_pass = punctual_pass.read_buffer(vertices);
8626        }
8627        // Each face's own cluster-selection buffer, which the mesh path's stages
8628        // write — declared on the atlas pass's terms, and only for the views
8629        // this pass draws.
8630        for face in &punctual {
8631            if let Some(&buffer) = selection.get(face.view) {
8632                punctual_pass = punctual_pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8633            }
8634        }
8635        for draws in &punctual_sources {
8636            punctual_pass = read_draw_sources(punctual_pass, draws, self.emit);
8637        }
8638        let punctual_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
8639        let punctual_recorded = punctual_views.len() as u64
8640            * punctual_partitions
8641                .iter()
8642                .map(BucketDraws::call_count)
8643                .sum::<u64>();
8644        punctual_pass.execute(move |ctx| {
8645            let encoder = ctx.encoder();
8646            // The partition is **outside** the view loop, on the shadow atlas's
8647            // terms: one pipeline bind covers every face of that side.
8648            for partition in &punctual_partitions {
8649                partition.open(encoder);
8650                for (group, tile, draws, region) in &punctual_views {
8651                    set_shadow_tile(encoder, *tile);
8652                    partition.record_region(encoder, *group, draws, *region);
8653                }
8654            }
8655        });
8656
8657        let images = RsmImages {
8658            sun,
8659            punctual: punctual_targets,
8660        };
8661        (
8662            atlas,
8663            recorded + rsm_recorded + punctual_recorded,
8664            clears,
8665            Some(images),
8666        )
8667    }
8668
8669    /// Which lights hold the atlas's light tiles this frame, and where each
8670    /// map was laid out.
8671    ///
8672    /// **The observable topic 45's priority rung otherwise has
8673    /// none for.** A map's *size* leaves no trace in the picture that a golden
8674    /// can hold anyone to: a light demoted to a quarter of a cell draws a
8675    /// slightly softer shadow, which is a perfectly plausible frame and one a
8676    /// re-bless accepts. [`Selection::atlas_rect`](crate::shadow::Selection)
8677    /// off this is what says which level the allocator actually handed out, and
8678    /// `crates/crcbl/tests/mesh_e2e/shadow_tiles.rs` is what reads it.
8679    ///
8680    /// Named for the selection's own subject rather than for its type, because
8681    /// [`Self::shadow_selection`] above is a *buffer* — the cut a cascade
8682    /// descended to — and two accessors of one name is a caller reaching for
8683    /// the wrong one.
8684    ///
8685    /// It is this frame's answer, written by [`Self::begin_frame`]: before the
8686    /// first frame every slot is free.
8687    /// Whether this frame took the shadow atlas as an earlier frame left it,
8688    /// rather than drawing it again.
8689    ///
8690    /// Topic 45's static-caching rung, read back. True means
8691    /// this frame recorded **no** shadow cull and no shadow pass, and every map
8692    /// sampled through [`Self::shadow_lights`]'s rectangles is the one the last
8693    /// frame that did draw put there — so a caller comparing two frames' pass
8694    /// lists, draw counts or GPU timings has to know which of them redrew.
8695    ///
8696    /// Decided by [`Self::begin_frame`] out of everything each group of the
8697    /// atlas is a function of — see `ForwardRenderer::shadow_group_record` —
8698    /// and it answers `false` before the first frame, because no frame has been
8699    /// opened and so none of them has held anything.
8700    ///
8701    /// **Whole-atlas, and since the cadence rung a frame can be neither.** A
8702    /// frame that redraws one map and holds another answers `false` here and
8703    /// `false` from [`Self::shadow_slot_redrawn`] for the maps it held; the two
8704    /// together are what say which.
8705    #[must_use]
8706    pub const fn shadow_atlas_cached(&self) -> bool {
8707        self.shadow_atlas_cached
8708    }
8709
8710    /// Whether this frame redrew cascade `cascade`'s map, rather than keeping
8711    /// the one an earlier frame put there.
8712    ///
8713    /// Topic 45's cadence rung, read back. **The observable
8714    /// that rung otherwise has none for**: a held map draws a shadow lagging its
8715    /// caster by a frame or two, which is a perfectly plausible picture and one
8716    /// a golden accepts — so nothing but this distinguishes a cadence that is
8717    /// working from one that is not running at all.
8718    ///
8719    /// `false` for a `cascade` past [`shadow::CASCADES`] and before the first
8720    /// frame, which is the same answer for the same reason: no map was drawn
8721    /// there.
8722    #[must_use]
8723    pub fn shadow_cascade_redrawn(&self, cascade: usize) -> bool {
8724        cascade < shadow::CASCADES && self.shadow_group_redrawn[cascade]
8725    }
8726
8727    /// Whether this frame redrew the maps of light slot `slot` —
8728    /// [`shadow::Selection::slots`]' index — rather than keeping the ones an
8729    /// earlier frame put there.
8730    ///
8731    /// [`Self::shadow_cascade_redrawn`]'s answer for the light region, and a
8732    /// point light's [`shadow::POINT_FACES`] faces answer together: they cull
8733    /// once and draw one visible set, so they are redrawn or held as one.
8734    #[must_use]
8735    pub fn shadow_slot_redrawn(&self, slot: usize) -> bool {
8736        slot < shadow::LIGHT_SLOTS && self.shadow_group_redrawn[shadow_cull(slot)]
8737    }
8738
8739    /// How many tiles of the atlas this frame redrew.
8740    ///
8741    /// What [`shadow::r_shadow_faces`] is spent in, read back — so a test can
8742    /// say the budget bound rather than that it was configured. A cascade costs
8743    /// one and a point light's cube costs [`shadow::POINT_FACES`].
8744    #[must_use]
8745    pub const fn shadow_faces_redrawn(&self) -> u32 {
8746        self.shadow_faces_redrawn
8747    }
8748
8749    /// Pins the shadow cadence for this renderer, or hands it back to the
8750    /// console.
8751    ///
8752    /// [`Self::set_effect_request`]'s shape at this knob:
8753    /// [`shadow::r_shadow_cadence`] and [`shadow::r_shadow_faces`] are
8754    /// process-global, so they are the *default* rather than the only answer —
8755    /// an application drawing two views at two qualities, or a test that needs a
8756    /// frame nothing else in the process can move, pins its own.
8757    ///
8758    /// [`None`] hands it back, which is what a renderer starts at.
8759    ///
8760    /// Read once per [`Self::begin_frame`], on `ForwardRenderer::frame_effects`'
8761    /// terms: this call decides it and `add_passes` acts on it.
8762    pub const fn set_shadow_cadence(&mut self, cadence: Option<shadow::Cadence>) {
8763        self.shadow_cadence_request = cadence;
8764    }
8765
8766    /// Whether this frame ignored the cadence for at least one map because the
8767    /// region that map covers had moved out from under it.
8768    ///
8769    /// Topic 45's "a moving light or camera cut resets it",
8770    /// made precise: a map is *reset* rather than merely out of date when the
8771    /// centre it is projected from has moved further than the map's own reach —
8772    /// a light further than its own radius, or a cascade's eye further than the
8773    /// sphere that cascade was fitted to. Holding such a map is not a shadow
8774    /// that lags; it is a shadow of somewhere else.
8775    ///
8776    /// A frame whose atlas was **relaid** — a light gained, lost or resized a
8777    /// tile, or shadows were switched on or off — answers `true` as well, and
8778    /// that frame redraws every map it has: the only clear this seam can make
8779    /// covers the whole image, so there is nothing left to hold.
8780    #[must_use]
8781    pub const fn shadow_cadence_reset(&self) -> bool {
8782        self.shadow_cadence_reset
8783    }
8784
8785    #[must_use]
8786    pub const fn shadow_lights(&self) -> &shadow::Selection {
8787        &self.shadow_lights
8788    }
8789
8790    /// The shadow atlas, for a caller that wants to read it back.
8791    ///
8792    /// **The observable this whole slice can otherwise hide behind.** A shadow
8793    /// pass that renders nothing leaves every texel at
8794    /// [`depth::CLEAR`](crcbl_hal::depth::CLEAR) and produces a frame in which
8795    /// everything is lit — which is a perfectly plausible picture and matches
8796    /// any golden blessed from it. Copying this image back and finding a texel
8797    /// that is not the clear value is what distinguishes the two.
8798    ///
8799    /// It is created with
8800    /// [`ImageUsage::TRANSFER_SRC`](crcbl_hal::ImageUsage::TRANSFER_SRC) for
8801    /// exactly that, and its extent is [`shadow::atlas_extent`].
8802    #[must_use]
8803    pub const fn shadow_atlas(&self) -> crcbl_hal::ImageHandle {
8804        self.shadow_atlas
8805    }
8806
8807    /// The view [`shadow_atlas`](Self::shadow_atlas) is bound and imported
8808    /// through, for a reader importing the atlas into a graph of its own.
8809    #[must_use]
8810    pub const fn shadow_atlas_view(&self) -> ImageViewHandle {
8811        self.shadow_atlas_view
8812    }
8813
8814    /// The base-colour page every material row samples through
8815    /// [`GpuMaterial::base_color_texture`](crcbl_shaders::mesh::GpuMaterial::base_color_texture),
8816    /// as the image and the view [`crate::texture`] uploaded.
8817    ///
8818    /// **What a render-to-texture view copies into.** A second camera drawing
8819    /// into an image is only half of a monitor: the surface that *shows* it
8820    /// samples a page layer, and nothing above this crate can name the image
8821    /// that layer lives in.
8822    ///
8823    /// A caller that wants to *write* it wants
8824    /// [`base_color_page_import`](Self::base_color_page_import) instead: the
8825    /// graph can only order a copy against the draws that sample the page while
8826    /// both are declared, and the two declarations have to agree field for
8827    /// field. This one is the raw handles, for a caller that binds or reads them
8828    /// outside a graph.
8829    ///
8830    /// It is created with
8831    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST),
8832    /// because the upload that filled it is a copy, so a per-frame copy into it
8833    /// needs no new usage flag. Its extent is
8834    /// [`PageDesc::extent`](crate::scene::PageDesc::extent) of
8835    /// [`PageKind::BaseColor`] squared and it has one layer per
8836    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of that kind;
8837    /// the description is the caller's, so the caller already knows both. A
8838    /// description naming no base-colour layer gets a 1×1 placeholder instead —
8839    /// see this module's `PAGE_PLACEHOLDER_TEXEL`.
8840    #[must_use]
8841    pub const fn base_color_page(&self) -> UploadedTexture {
8842        self.base_color_page
8843    }
8844
8845    /// What [`add_passes`](Self::add_passes) names the base-colour page in the
8846    /// graph.
8847    ///
8848    /// [`RenderGraph::import_image`] keeps the label of whichever import ran
8849    /// first, so a caller importing the page too passes this rather than a
8850    /// string of its own — otherwise every barrier record and
8851    /// [`dump`](crate::CompiledGraph::dump) line would name the page differently
8852    /// depending on which subsystem got there first.
8853    pub const BASE_COLOR_PAGE_LABEL: &'static str = "base-colour-page";
8854
8855    /// The base-colour page **as this renderer declares it to a graph**.
8856    ///
8857    /// [`add_passes`](Self::add_passes) imports exactly this value under
8858    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL) and declares a read
8859    /// of it on every pass whose bind group names the page, so a caller that
8860    /// writes the page — a render-to-texture view copied into one layer — gets
8861    /// the graph to order its write against those draws.
8862    ///
8863    /// **A caller that writes it imports this value rather than one of its
8864    /// own.** [`RenderGraph::import_image`] hands the second importer the id the
8865    /// first got, which is what puts the write and the reads on one state
8866    /// tracker, and it does that only while the two declarations agree in every
8867    /// field — a disagreement is [`GraphError::ImportDeclarationConflict`] at
8868    /// [`compile`](RenderGraph::compile). Reading the declaration off the
8869    /// renderer that owns the page is what makes them one answer instead of two
8870    /// constants that have to be kept equal by hand.
8871    ///
8872    /// [`InitialClaim::Tracked`] with [`ResourceState::ShaderRead`] both ways:
8873    /// [`crate::texture`] leaves an uploaded page in that state, and the
8874    /// trailing barrier the `final_state` asks for puts it back there at the end
8875    /// of every frame — so the pool's ledger and this declaration are the same
8876    /// answer, which is what `Tracked` has the graph check.
8877    ///
8878    /// [`GraphError::ImportDeclarationConflict`]: crate::graph::GraphError::ImportDeclarationConflict
8879    #[must_use]
8880    pub const fn base_color_page_import(&self) -> ImportedImage {
8881        ImportedImage {
8882            image: self.base_color_page.image,
8883            view: self.base_color_page.view,
8884            format: BASE_COLOR_PAGE_FORMAT,
8885            extent: self.page_extents[PageKind::BaseColor.index()],
8886            initial: ResourceState::ShaderRead,
8887            claim: InitialClaim::Tracked,
8888            final_state: ResourceState::ShaderRead,
8889        }
8890    }
8891
8892    /// Topic 43 §2's **normal** page, the raw handles.
8893    ///
8894    /// [`base_color_page`](Self::base_color_page)'s counterpart, on every one of
8895    /// its terms: one `D2Array` image, one layer per
8896    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of
8897    /// [`PageKind::Normal`], at **that kind's own extent**, and created with
8898    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST) so a
8899    /// per-frame copy into a layer needs no new usage flag. What it is *not* is
8900    /// the same format: it is `Rgba8Unorm`, where the base-colour page is
8901    /// `Rgba8UnormSrgb`, and topic 44's rung 2 is where that
8902    /// is argued.
8903    #[must_use]
8904    pub const fn normal_page(&self) -> UploadedTexture {
8905        self.normal_page
8906    }
8907
8908    /// What [`add_passes`](Self::add_passes) names the normal page in the graph,
8909    /// on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8910    pub const NORMAL_PAGE_LABEL: &'static str = "normal-page";
8911
8912    /// The normal page **as this renderer declares it to a graph**, on
8913    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly
8914    /// — including that a caller writing a layer imports *this* value rather
8915    /// than one of its own, so the write and the draws land on one state
8916    /// tracker.
8917    #[must_use]
8918    pub const fn normal_page_import(&self) -> ImportedImage {
8919        ImportedImage {
8920            image: self.normal_page.image,
8921            view: self.normal_page.view,
8922            format: NORMAL_PAGE_FORMAT,
8923            extent: self.page_extents[PageKind::Normal.index()],
8924            initial: ResourceState::ShaderRead,
8925            claim: InitialClaim::Tracked,
8926            final_state: ResourceState::ShaderRead,
8927        }
8928    }
8929
8930    /// Topic 43 §2's packed
8931    /// **metallic-roughness-occlusion** page, the raw handles.
8932    ///
8933    /// [`normal_page`](Self::normal_page)'s counterpart, on every one of its
8934    /// terms and at the same `Rgba8Unorm` format: a layer of it is glTF's
8935    /// occlusion, roughness and metallic in `r`, `g` and `b`, which are numbers
8936    /// rather than a colour — see this module's `MRO_PAGE_FORMAT`.
8937    #[must_use]
8938    pub const fn mro_page(&self) -> UploadedTexture {
8939        self.mro_page
8940    }
8941
8942    /// What [`add_passes`](Self::add_passes) names the
8943    /// metallic-roughness-occlusion page in the graph, on
8944    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8945    pub const MRO_PAGE_LABEL: &'static str = "metallic-roughness-occlusion-page";
8946
8947    /// The metallic-roughness-occlusion page **as this renderer declares it to a
8948    /// graph**, on [`base_color_page_import`](Self::base_color_page_import)'s
8949    /// terms exactly.
8950    #[must_use]
8951    pub const fn mro_page_import(&self) -> ImportedImage {
8952        ImportedImage {
8953            image: self.mro_page.image,
8954            view: self.mro_page.view,
8955            format: MRO_PAGE_FORMAT,
8956            extent: self.page_extents[PageKind::MetallicRoughnessOcclusion.index()],
8957            initial: ResourceState::ShaderRead,
8958            claim: InitialClaim::Tracked,
8959            final_state: ResourceState::ShaderRead,
8960        }
8961    }
8962
8963    /// Topic 43 §2's **emissive** page, the raw
8964    /// handles.
8965    ///
8966    /// [`base_color_page`](Self::base_color_page)'s counterpart down to the
8967    /// format: an emissive texel is a colour, so this image is
8968    /// `Rgba8UnormSrgb` and the sampler decodes it — see this module's
8969    /// `EMISSIVE_PAGE_FORMAT`.
8970    #[must_use]
8971    pub const fn emissive_page(&self) -> UploadedTexture {
8972        self.emissive_page
8973    }
8974
8975    /// What [`add_passes`](Self::add_passes) names the emissive page in the
8976    /// graph, on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8977    pub const EMISSIVE_PAGE_LABEL: &'static str = "emissive-page";
8978
8979    /// The emissive page **as this renderer declares it to a graph**, on
8980    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly.
8981    #[must_use]
8982    pub const fn emissive_page_import(&self) -> ImportedImage {
8983        ImportedImage {
8984            image: self.emissive_page.image,
8985            view: self.emissive_page.view,
8986            format: EMISSIVE_PAGE_FORMAT,
8987            extent: self.page_extents[PageKind::Emissive.index()],
8988            initial: ResourceState::ShaderRead,
8989            claim: InitialClaim::Tracked,
8990            final_state: ResourceState::ShaderRead,
8991        }
8992    }
8993
8994    /// The model matrix for a cube spinning at `seconds` into the run.
8995    ///
8996    /// Two axes at incommensurable rates, so the animation never repeats and
8997    /// every face comes into view — which is what makes "the cube is spinning"
8998    /// observable rather than a claim about a matrix.
8999    #[must_use]
9000    pub fn spin(seconds: f32) -> Mat4 {
9001        Mat4::from_quat(
9002            Quat::from_axis_angle(Vec3::Y, seconds * 0.9)
9003                * Quat::from_axis_angle(Vec3::X, seconds * 0.55),
9004        )
9005    }
9006
9007    /// The format the tonemap pass renders into.
9008    #[must_use]
9009    pub const fn target_format(&self) -> Format {
9010        self.target_format
9011    }
9012
9013    /// Switches the infinite ground grid on with `style`, or off with [`None`].
9014    ///
9015    /// **Off by default.** Every sample and every golden image predates the
9016    /// grid, so a renderer nobody has called this on records exactly the passes
9017    /// it always did — see [`crate::grid`] for what the pass is and
9018    /// [`add_passes`](Self::add_passes) for where in the frame it lands.
9019    ///
9020    /// The first `Some` builds the pipeline and the uniform ring; later calls
9021    /// only replace the style, and a `None` leaves both built. Releasing them
9022    /// here would mean releasing blocks the frames in flight may still be
9023    /// reading, so they are released by [`destroy`](Self::destroy) alone — the
9024    /// one call that already requires an idle device.
9025    ///
9026    /// # Errors
9027    ///
9028    /// [`HalError`] if the grid's pipeline or its blocks could not be created.
9029    /// Nothing is left switched on when that happens: the grid stays as it was.
9030    pub fn set_ground_grid(
9031        &mut self,
9032        device: &dyn Device,
9033        style: Option<GridStyle>,
9034    ) -> Result<(), HalError> {
9035        let Some(style) = style else {
9036            self.ground_grid_on = false;
9037            return Ok(());
9038        };
9039        let grid = match self.ground_grid.as_mut() {
9040            Some(grid) => grid,
9041            None => {
9042                // Built for the tonemap's target and the scene depth, because
9043                // those are the two attachments the pass is given — see
9044                // `add_passes`. Both are pipeline state, so a renderer whose
9045                // target format changed would need a new `Grid`; nothing in this
9046                // crate changes it after `build`, and `target_format` is kept
9047                // for exactly that reason.
9048                let grid = GroundGrid::new(
9049                    device,
9050                    self.primary.uniforms.len(),
9051                    self.target_format,
9052                    SCENE_DEPTH_FORMAT,
9053                )?;
9054                self.ground_grid.insert(grid)
9055            }
9056        };
9057        grid.set_style(style);
9058        self.ground_grid_on = true;
9059        Ok(())
9060    }
9061
9062    /// The debug draw layer's immediate-mode buffer, to append to.
9063    ///
9064    /// The UI's debug item 5 (`docs/notes/tooling.md`): any system appends lines, boxes,
9065    /// spheres and frusta during the frame, and
9066    /// [`begin_frame`](Self::begin_frame) uploads and clears what is there — so
9067    /// a segment lives exactly the frame it was appended in and nothing has to
9068    /// be un-appended. See [`crate::debug_draw`] for where the pass lands and
9069    /// for the console switch that has to be on before anything is drawn.
9070    ///
9071    /// **Appending is free while the layer is off**, but building the geometry
9072    /// is the caller's: a system whose overlay costs something to compute asks
9073    /// [`DebugDraw::enabled`] first.
9074    pub fn debug_draw(&mut self) -> &mut DebugDraw {
9075        &mut self.debug_draw
9076    }
9077
9078    /// How the ground grid is drawn, or [`None`] where it is switched off.
9079    ///
9080    /// The read-back half of [`set_ground_grid`](Self::set_ground_grid), and the
9081    /// observable a test asking "is the grid on" wants: a renderer that built
9082    /// the grid and then switched it off answers [`None`], because what it draws
9083    /// is what the question is about.
9084    #[must_use]
9085    pub fn ground_grid(&self) -> Option<&GridStyle> {
9086        self.ground_grid
9087            .as_ref()
9088            .filter(|_| self.ground_grid_on)
9089            .map(GroundGrid::style)
9090    }
9091
9092    /// Whether this frame adds [`crate::sky_pass`]'s background pass.
9093    ///
9094    /// [`Sky::NONE`] with no atmosphere is the value a renderer nobody called
9095    /// [`set_sky`](Self::set_sky) or
9096    /// [`set_atmosphere`](Self::set_atmosphere) on holds, and it is checked
9097    /// here rather than left to the shader for the reason [`crate::sky_pass`]
9098    /// gives: a black gradient drawn over [`SCENE_CLEAR`] would *change* those
9099    /// frames, where adding no pass leaves them exactly as they were.
9100    fn draws_sky(&self) -> bool {
9101        self.sky != Sky::NONE || self.atmosphere.is_some()
9102    }
9103
9104    /// Brings [`Self::sky_view`] up to the sun this frame has, a stripe of rows
9105    /// per frame.
9106    ///
9107    /// Called once per [`Self::begin_frame`]. The comparison is on the
9108    /// normalised parameters rather than on the [`Atmosphere`] a caller handed
9109    /// over, so re-setting the same sun spelled a different length is not a
9110    /// rebuild — and a caller that sets the same value every frame, which is
9111    /// the ordinary shape of a scene's update, pays the comparison and nothing
9112    /// else.
9113    ///
9114    /// # The first LUT is marched whole; every later one is marched in stripes
9115    ///
9116    /// A renderer that has no LUT has no sky to draw, so the first march after
9117    /// [`set_atmosphere`](Self::set_atmosphere) runs to completion inside this
9118    /// call and a caller that draws a single frame gets that frame's sky. After
9119    /// that there is always a finished LUT to show, so a sun that moved starts
9120    /// a [`SkyViewBuild`] and this steps it [`SKY_VIEW_BUILD_ROWS`] rows per
9121    /// frame — the frames in between keep drawing the LUT the last completed
9122    /// march produced, and no frame pays the whole march.
9123    ///
9124    /// # A sun that moves again restarts the march rather than finishing it
9125    ///
9126    /// The build in flight is kept only while its own sun is still the one the
9127    /// caller wants; a sun that moved during it is a new build from row zero,
9128    /// because finishing the old one would swap in a LUT for a sun that is
9129    /// already wrong and then immediately start marching again. **A sun that
9130    /// moves every frame therefore never completes a build and goes on showing
9131    /// the last one it finished** — a sky frozen at the sun it last caught up
9132    /// with, rather than a sky that stutters at whatever the march last passed.
9133    /// That is the trade this makes: the frame cost is bounded and the sky
9134    /// lags, where the whole-march rebuild it replaced had the sky exact and
9135    /// the frame cost unbounded. A caller that wants the sky exact stops the
9136    /// sun on a value and leaves it there: the march then completes, and the
9137    /// frames it takes are `SKY_VIEW_HEIGHT` over [`SKY_VIEW_BUILD_ROWS`].
9138    ///
9139    /// **The aerial-perspective LUT is marched in the same steps** — see
9140    /// [`SkyViewBuild`] — so the air in front of the scene arrives on the same
9141    /// frame as the sky and lags the sun by the same frames, never a sun apart
9142    /// from it. A change of [`Atmosphere::km_per_unit`] alone is a new march
9143    /// on the same terms, since it is part of the parameters compared.
9144    fn refresh_sky_view(&mut self) {
9145        let Some(atmosphere) = self.atmosphere else {
9146            self.sky_view = None;
9147            self.sky_view_build = None;
9148            return;
9149        };
9150        let parameters = atmosphere.parameters();
9151        if self
9152            .sky_view
9153            .as_ref()
9154            .is_some_and(|presented| presented.parameters == parameters)
9155        {
9156            self.sky_view_build = None;
9157            return;
9158        }
9159        if self.sky_view.is_none() {
9160            self.sky_view_build = None;
9161            self.sky_view = Some(PresentedSky::new(parameters, SkyView::build(&parameters)));
9162            return;
9163        }
9164        let mut build = match self.sky_view_build.take() {
9165            Some(build) if build.atmosphere() == parameters => build,
9166            _ => SkyViewBuild::start(&parameters),
9167        };
9168        if build.step(SKY_VIEW_BUILD_ROWS) {
9169            self.sky_view = Some(PresentedSky::new(parameters, build.finish()));
9170        } else {
9171            self.sky_view_build = Some(build);
9172        }
9173    }
9174
9175    /// Sets the multiplier the tonemap pass applies before its clamp, clamped
9176    /// into [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`].
9177    ///
9178    /// **The default is [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`]**, which is
9179    /// the value `tonemap.slang` held as a compile-time constant until this
9180    /// became a runtime one — so a renderer nobody calls this on draws the frame
9181    /// it always drew, and every golden image is untouched.
9182    ///
9183    /// It takes effect on the next
9184    /// [`begin_frame`](Self::begin_frame), which is what writes the block: a
9185    /// frame already recorded reads the value it was recorded with.
9186    ///
9187    /// **The clamp is here rather than at the call site** so that no caller can
9188    /// reach a picture it cannot get back from, and so that a control which
9189    /// steps by reading this back and setting a multiple of it — which is what
9190    /// [`exposure`](Self::exposure) is for — cannot wind up past the end and
9191    /// then need as many presses to come back.
9192    pub const fn set_exposure(&mut self, exposure: f32) {
9193        // `max` then `min` rather than `f32::clamp`: `clamp` propagates a NaN,
9194        // and a NaN reaching the block is a frame of NaN pixels with no key to
9195        // press to get out of it. `f32::max` returns the bound instead, so a NaN
9196        // lands on `EXPOSURE_MIN` — dark, and one press from being bright again.
9197        self.exposure = exposure.max(EXPOSURE_MIN).min(EXPOSURE_MAX);
9198    }
9199
9200    /// How far auto-exposure may travel toward its measurement in one frame.
9201    ///
9202    /// **[`None`] is the whole distance**, which is what a renderer nobody
9203    /// calls this on does and what the pass did before adaptation existed — so
9204    /// no golden moved when this arrived. A view that wants the roll asks, and
9205    /// asks *every frame*, because [`ExposureAdaptation`] carries that frame's
9206    /// own delta: this crate has no clock, and the frame time lives where the
9207    /// frame loop is.
9208    ///
9209    /// It takes effect on the next [`begin_frame`](Self::begin_frame), which is
9210    /// what writes the block, and it does nothing at all on a frame that did not
9211    /// ask for [`RenderEffects::AUTO_EXPOSURE`] — the passes that read it are
9212    /// the ones that bit adds.
9213    pub const fn set_exposure_adaptation(&mut self, adaptation: Option<ExposureAdaptation>) {
9214        self.exposure_adaptation = adaptation;
9215    }
9216
9217    /// What [`set_exposure_adaptation`](Self::set_exposure_adaptation) was last
9218    /// handed.
9219    #[must_use]
9220    pub const fn exposure_adaptation(&self) -> Option<ExposureAdaptation> {
9221        self.exposure_adaptation
9222    }
9223
9224    /// Which operator the tonemap pass runs on the exposed scene colour.
9225    ///
9226    /// **The ACES fit by default**, because this renderer shades in linear HDR
9227    /// and the roll-off is what that range is for. What a caller asks *for* here
9228    /// is therefore usually the other one: `tonemap.slang`'s clamp is the
9229    /// identity on `0..=1`, so display-referred content reaches the swapchain
9230    /// exactly, and a fixture that predicts a code value from a host model of
9231    /// the shading needs the frame to stay scene-referred. Every 2D sample in
9232    /// this tree draws through `crate::sprite_pass` and `crate::ui_pass`
9233    /// instead, so none of them reaches this pass at all.
9234    ///
9235    /// It takes effect on the next [`begin_frame`](Self::begin_frame), for
9236    /// [`set_exposure`](Self::set_exposure)'s reason: the block is written
9237    /// there, and a frame already recorded reads the value it was recorded
9238    /// with.
9239    ///
9240    /// **There is nothing to refuse and no `supports_` probe beside it.** The
9241    /// selector is a lane of a uniform block read by a branch every device
9242    /// already runs, so unlike the wireframe there is no second pipeline for a
9243    /// device to decline to build.
9244    pub const fn set_tonemap_curve(&mut self, curve: tonemap::TonemapCurve) {
9245        self.tonemap_curve = curve;
9246    }
9247
9248    /// The operator in force, on [`exposure`](Self::exposure)'s terms: the
9249    /// value the next frame will be drawn with.
9250    #[must_use]
9251    pub const fn tonemap_curve(&self) -> tonemap::TonemapCurve {
9252        self.tonemap_curve
9253    }
9254
9255    /// How large the internal render target is as a fraction of the extent
9256    /// [`begin_frame`](Self::begin_frame) is handed, clamped to
9257    /// `MIN_RENDER_SCALE..=1.0`.
9258    ///
9259    /// **This is the largest performance knob this renderer has.** Every pass
9260    /// before the upscale costs what its extent costs, so a scale of `0.7` is
9261    /// roughly half the shading work of `1.0`; the UI is composited onto the
9262    /// target afterwards at native resolution, so text stays sharp while the 3D
9263    /// frame gets cheap. `docs/notes/rendering.md` (_What the deleted
9264    /// 48-post-processing plan left behind_) is where that trade is written down.
9265    ///
9266    /// **`1.0` is not a special case with a fast path, it is the absence of the
9267    /// feature.** At full scale the internal extent *is* the caller's, the post
9268    /// chain writes the target directly, and no upscale pass is recorded — which
9269    /// is what makes a renderer nobody has called this on draw the frame it drew
9270    /// before the knob existed, bit for bit.
9271    ///
9272    /// **Above `1.0` is clamped away rather than supported.** Supersampling
9273    /// wants a box or Lanczos reduction and `upscale.slang` is a Catmull-Rom
9274    /// *reconstruction*; running it as a minification filter would alias, which
9275    /// is the opposite of what a caller asking for it wants. A non-finite scale
9276    /// is clamped to `1.0` for the same reason a `NaN` extent would be refused:
9277    /// the failure it produces is a zero-sized target somewhere downstream.
9278    ///
9279    /// Takes effect on the next [`begin_frame`](Self::begin_frame), on
9280    /// [`set_exposure`](Self::set_exposure)'s terms exactly — a frame already
9281    /// recorded is drawn at the scale it was recorded with.
9282    pub fn set_render_scale(&mut self, scale: f32) {
9283        self.render_scale = if scale.is_finite() {
9284            scale.clamp(MIN_RENDER_SCALE, 1.0)
9285        } else {
9286            1.0
9287        };
9288    }
9289
9290    /// The render scale in force, after the clamp
9291    /// [`set_render_scale`](Self::set_render_scale) applied.
9292    ///
9293    /// The read-back half, on [`exposure`](Self::exposure)'s terms.
9294    #[must_use]
9295    pub const fn render_scale(&self) -> f32 {
9296        self.render_scale
9297    }
9298
9299    /// The anisotropy the base-colour page is sampled with, in force from the
9300    /// next [`begin_frame`](Self::begin_frame).
9301    ///
9302    /// Topic 43's filtering rung, the player's half:
9303    /// [`anisotropy_for`](Self::anisotropy_for) is what a renderer nobody has
9304    /// called this on samples with, and this is what a settings row moves it
9305    /// to. Clamped to `1.0..=max_sampler_anisotropy` where the device was
9306    /// granted [`Features::SAMPLER_ANISOTROPY`] and to exactly `1.0` where it
9307    /// was not — the row can turn the filter off or push it to the device's
9308    /// ceiling, and nothing it asks reaches a `create_sampler` that would
9309    /// refuse it. A value that is not a number is the default, on
9310    /// [`set_render_scale`](Self::set_render_scale)'s terms.
9311    ///
9312    /// **A sampler is a resource a bind group holds by handle**, so a new
9313    /// anisotropy is a new sampler, and every group of the mesh layout has to
9314    /// be rebuilt to name it. That happens per frame slot, at the slot's own
9315    /// `begin_frame`, which is the moment the ring guarantees the slot's
9316    /// previous submission has retired — the guarantee every host write in
9317    /// that call already leans on — so a frame in flight goes on naming the
9318    /// sampler it was recorded with, and the replaced sampler is destroyed once
9319    /// no slot names it. This call creates the sampler and nothing else, and
9320    /// asking for the anisotropy already in force creates nothing.
9321    ///
9322    /// # Errors
9323    ///
9324    /// `create_sampler`'s, and the renderer is unchanged — the sampler in force
9325    /// stays in force.
9326    pub fn set_anisotropy(&mut self, device: &dyn Device, anisotropy: f32) -> Result<(), HalError> {
9327        let caps = device.caps();
9328        let ceiling = if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9329            caps.limits.max_sampler_anisotropy
9330        } else {
9331            1.0
9332        };
9333        let wanted = if anisotropy.is_finite() {
9334            anisotropy.clamp(1.0, ceiling)
9335        } else {
9336            Self::anisotropy_for(&caps)
9337        };
9338        // Bit-equal rather than within an epsilon: both sides came out of the
9339        // same clamp, and a row that lands on the value in force must not
9340        // rebuild every group for it.
9341        if wanted.to_bits() == self.anisotropy.to_bits() {
9342            return Ok(());
9343        }
9344        let sampler = Self::create_page_sampler(device, wanted)?;
9345        self.retired_pages
9346            .push(RetiredPage::Sampler(std::mem::replace(
9347                &mut self.base_color_sampler,
9348                sampler,
9349            )));
9350        self.anisotropy = wanted;
9351        Ok(())
9352    }
9353
9354    /// The anisotropy in force, after the clamp
9355    /// [`set_anisotropy`](Self::set_anisotropy) applied.
9356    ///
9357    /// The read-back half, on [`render_scale`](Self::render_scale)'s terms.
9358    #[must_use]
9359    pub const fn anisotropy(&self) -> f32 {
9360        self.anisotropy
9361    }
9362
9363    /// The anisotropy the base-colour page's sampler is created with on a
9364    /// device of `caps`: [`DEFAULT_ANISOTROPY`] clamped to
9365    /// [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) where
9366    /// [`Features::SAMPLER_ANISOTROPY`] was granted, and `1.0` where it was
9367    /// not.
9368    ///
9369    /// **Granted, not supported.** The feature is optional at every open site
9370    /// — [`Features::GPU_DRIVEN`] does not carry it — and a device opened
9371    /// without asking refuses a sampler above one even on hardware that has
9372    /// it, which is the shape every backend's `create_sampler` documents. So
9373    /// the question is what this device was opened *with*, and a caller that
9374    /// wants the plan's default has to name the feature beside the others it
9375    /// asks for. `crcbl-webgpu` withholds the feature and reports a ceiling of
9376    /// one, so a browser samples isotropically until `docs/backlog.md`'s
9377    /// ceiling decision is taken.
9378    #[must_use]
9379    pub fn anisotropy_for(caps: &DeviceCaps) -> f32 {
9380        if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9381            DEFAULT_ANISOTROPY.min(caps.limits.max_sampler_anisotropy)
9382        } else {
9383            1.0
9384        }
9385    }
9386
9387    /// The base-colour page's sampler at `anisotropy`, which the caller has
9388    /// already held to the device — [`anisotropy_for`](Self::anisotropy_for)
9389    /// at build, [`set_anisotropy`](Self::set_anisotropy)'s clamp after.
9390    ///
9391    /// **Trilinear over the whole chain, anisotropic where the device is** —
9392    /// topic 43's filtering rung: a minified surface
9393    /// reads the level its footprint matches instead of shimmering through
9394    /// level 0, a magnified one blends four texels instead of stepping between
9395    /// them, and a surface at a grazing angle keeps its detail along the long
9396    /// axis of its footprint rather than blurring to the short one. A second
9397    /// sampler object rather than sharing the tonemap's, so a capture names
9398    /// each for what it filters.
9399    ///
9400    /// **`Repeat`, not `ClampToEdge`**, and that is what `mesh.slang`'s
9401    /// `TILING_PHYSICAL` needs: a physical UV runs to `world_extent /
9402    /// tile_metres`, past `0..1` on any face wider than one tile, and only a
9403    /// wrapping address mode makes the page tile across it rather than
9404    /// smearing its edge row. `TILING_AUTHORED` is unaffected — its UV is the
9405    /// vertex's, which the meshes author inside `0..1`, so a wrapped and a
9406    /// clamped read return the same nearest texel for it.
9407    fn create_page_sampler(
9408        device: &dyn Device,
9409        anisotropy: f32,
9410    ) -> Result<SamplerHandle, HalError> {
9411        device.create_sampler(&SamplerDesc {
9412            label: Some("material base colour"),
9413            mag_filter: FilterMode::Linear,
9414            min_filter: FilterMode::Linear,
9415            mip_filter: FilterMode::Linear,
9416            address_mode: [SamplerAddressMode::Repeat; 3],
9417            anisotropy,
9418            ..SamplerDesc::default()
9419        })
9420    }
9421
9422    /// The extent a frame handed `target` is actually drawn at.
9423    ///
9424    /// Rounds rather than truncates, and floors at one texel in each dimension:
9425    /// a zero here would reach a transient image description, and an image of
9426    /// zero extent is a device error rather than a small frame. A caller who
9427    /// minimised the window already hands a zero extent through, and that path
9428    /// is unchanged — `max(1)` on a zero is one either way.
9429    fn internal_extent(&self, target: (u32, u32)) -> (u32, u32) {
9430        if self.render_scale >= 1.0 {
9431            return target;
9432        }
9433        let scale = f64::from(self.render_scale);
9434        (
9435            ((f64::from(target.0) * scale).round() as u32).max(1),
9436            ((f64::from(target.1) * scale).round() as u32).max(1),
9437        )
9438    }
9439
9440    /// The exposure in force, after the clamp
9441    /// [`set_exposure`](Self::set_exposure) applied.
9442    ///
9443    /// The read-back half, on [`ground_grid`](Self::ground_grid)'s terms: what a
9444    /// caller wants is the number the frame is drawn with, not the one it asked
9445    /// for — which is also what makes a multiplicative step land on the end of
9446    /// the range rather than run past it.
9447    #[must_use]
9448    pub const fn exposure(&self) -> f32 {
9449        self.exposure
9450    }
9451
9452    /// Whether `device` can draw the wireframe view at all.
9453    ///
9454    /// The question [`set_wireframe`](Self::set_wireframe) answers with an
9455    /// error, asked **before** anything is switched on — so an application can
9456    /// tell its user that this device has no wireframe rather than binding a key
9457    /// that fails, and can say so once at start-up instead of on every press.
9458    /// WebGPU has no line fill mode at all, so the browser is the case this
9459    /// exists for and not a hypothetical.
9460    ///
9461    /// An associated function rather than a method: it is a fact about the
9462    /// device, and a caller wants it before it has decided anything.
9463    #[must_use]
9464    pub fn supports_wireframe(device: &dyn Device) -> bool {
9465        device.caps().supports(Features::POLYGON_MODE_LINE)
9466    }
9467
9468    /// Asks every camera's cull to drop what is hidden or too small to see —
9469    /// topic 03 §3.3's occlusion cull and its
9470    /// small-feature test. See [`crate::occlusion_cull`].
9471    ///
9472    /// [`OcclusionCulling::occlusion`] **changes no pixel**: the first phase
9473    /// guesses from the previous frame's depth, the second tests every rejected
9474    /// instance against this frame's, and only the second's rejections are
9475    /// dropped. [`OcclusionCulling::small_feature_pixels`] does change pixels,
9476    /// and is off unless a threshold is named.
9477    ///
9478    /// Taken from the next [`begin_frame`](Self::begin_frame), and combined with
9479    /// the `r_occlusion_cull` and `r_small_feature_px` console switches — either
9480    /// side turning a cull on turns it on. A wireframe frame culls by the frustum
9481    /// alone, because a wireframe shows the edges a depth test would hide.
9482    pub fn set_occlusion_culling(&mut self, culling: OcclusionCulling) {
9483        self.occlusion_culling = culling;
9484    }
9485
9486    /// Whether a point light's shadow cull tags each caster with the faces of
9487    /// its cube it reaches, so each face draws only those — **on** by default.
9488    ///
9489    /// Off is the cull this replaced: one test against the light's box, and
9490    /// every caster in it drawn into all six faces for the rasteriser to clip.
9491    /// The two write the same atlas, texel for texel — the six faces' pyramids
9492    /// tile the box, so a caster a face drops has no texel in that face's tile —
9493    /// and the switch exists so a test can hold them against each other and a
9494    /// price can be read off both.
9495    pub fn set_point_face_culls(&mut self, on: bool) {
9496        self.point_face_culls = on;
9497    }
9498
9499    /// **A test hook**: from the next [`begin_frame`](Self::begin_frame),
9500    /// rewrites every block the shadow atlas's depth pass is fed with `tamper`
9501    /// on its way to the GPU, or stops doing so with [`None`] — the default,
9502    /// and the only value a frame outside a test runs under.
9503    ///
9504    /// Applied **after** the atlas cache has read the blocks, so the rewrite is
9505    /// invisible to the decision whether to redraw a map and visible only to the
9506    /// depth pass that draws it. That is what makes it a probe of the shaders:
9507    /// `crcbl`'s `mesh_e2e` `shadow_block_reads` draws the atlas with each
9508    /// [`UniformsReader::ColourOnly`] entry of [`FRAME_UNIFORMS_READERS`]
9509    /// perturbed through here and holds the depth to the untampered frame's, bit
9510    /// for bit. It reaches the atlas's views alone — not the probe updater's
9511    /// shadows-off writes, which draw nothing into the atlas.
9512    pub fn set_shadow_view_tamper(&mut self, tamper: Option<fn(&mut mesh::FrameUniforms)>) {
9513        self.shadow_view_tamper = tamper;
9514    }
9515
9516    /// What [`set_occlusion_culling`](Self::set_occlusion_culling) last asked
9517    /// for, before the console switches and the wireframe are applied.
9518    #[must_use]
9519    pub const fn occlusion_culling(&self) -> OcclusionCulling {
9520        self.occlusion_culling
9521    }
9522
9523    /// The culls the next frame runs: [`occlusion_culling`](Self::occlusion_culling)
9524    /// with the console switches applied, and nothing on a wireframe frame.
9525    #[must_use]
9526    pub fn resolved_occlusion_culling(&self) -> OcclusionCulling {
9527        if self.wireframe_on {
9528            return OcclusionCulling::OFF;
9529        }
9530        let console_pixels = crate::occlusion_cull::r_small_feature_px.get_f32();
9531        OcclusionCulling {
9532            occlusion: self.occlusion_culling.occlusion
9533                || crate::occlusion_cull::r_occlusion_cull.get_bool(),
9534            small_feature_pixels: self
9535                .occlusion_culling
9536                .small_feature_pixels
9537                .or((console_pixels > 0.0).then_some(console_pixels)),
9538        }
9539    }
9540
9541    /// Draws the scene's triangles as lines, or goes back to filling them.
9542    ///
9543    /// **Off by default.** Every sample and every golden image predates the
9544    /// view, so a renderer nobody has called this on records exactly the frame
9545    /// it always did.
9546    ///
9547    /// # What it is, and what it is not
9548    ///
9549    /// The **colour pass** alone changes fill mode. The depth prepass and the
9550    /// shadow cascades keep drawing filled triangles, because they are what the
9551    /// occlusion pair and the shadow lookups read and depth drawn as lines is
9552    /// depth with holes in it. So a wireframe frame is the same geometry, the
9553    /// same shading and the same lights, rasterised as edges: what was inside a
9554    /// triangle becomes the clear colour, and what was on its edge stays lit.
9555    ///
9556    /// # It is built on the first `true`
9557    ///
9558    /// The pipeline is compiled here rather than beside the filled one at
9559    /// [`with_scene`](Self::with_scene), and that is the trade this
9560    /// call makes: one pipeline compile on the first press — a hitch, in a view
9561    /// the user just asked for — against a second compile in the start-up of
9562    /// every sample, golden run and headless test that never asks for one. Later
9563    /// calls only flip the switch, and a `false` leaves the pipeline built, for
9564    /// [`set_ground_grid`](Self::set_ground_grid)'s reason: releasing something
9565    /// the frames in flight may still be recording against is what
9566    /// [`destroy`](Self::destroy) — which already requires an idle device — is
9567    /// for.
9568    ///
9569    /// # Errors
9570    ///
9571    /// [`HalError::UnsupportedFeatures`] naming
9572    /// [`Features::POLYGON_MODE_LINE`](crcbl_hal::Features::POLYGON_MODE_LINE)
9573    /// when `on` is `true` on a device that has not got it — ask
9574    /// [`supports_wireframe`](Self::supports_wireframe) first. Refused rather
9575    /// than quietly filled: a caller who asked for a wireframe and got a solid
9576    /// frame back with no error has no way to tell that from a wireframe of a
9577    /// solid-looking model.
9578    ///
9579    /// [`HalError`] from the pipeline otherwise. **Nothing is left switched on
9580    /// when either happens**: the view stays as it was.
9581    pub fn set_wireframe(&mut self, device: &dyn Device, on: bool) -> Result<(), HalError> {
9582        if !on {
9583            self.wireframe_on = false;
9584            return Ok(());
9585        }
9586        if self.wireframe_pipeline.is_none() {
9587            if !Self::supports_wireframe(device) {
9588                return Err(HalError::UnsupportedFeatures {
9589                    missing: Features::POLYGON_MODE_LINE,
9590                });
9591            }
9592            let modules = MeshModules::new(device, self.emit, self.culls_clusters)?;
9593            let [single, double] = MeshModules::sided(|cull| {
9594                modules.color_pipeline(
9595                    device,
9596                    self.mesh_pipeline_layout,
9597                    PolygonMode::Line,
9598                    cull,
9599                    "wireframe",
9600                )
9601            });
9602            modules.destroy(device);
9603            // **Both or neither.** A caller that got one twin back would draw a
9604            // frame missing every double-sided surface and nothing would say
9605            // so; released here rather than kept, because `destroy` is what
9606            // releases what this field holds and it holds nothing yet.
9607            let pipelines = match (single, double) {
9608                (Ok(single), Ok(double)) => SidedPipelines { single, double },
9609                (Ok(built), Err(error)) | (Err(error), Ok(built)) => {
9610                    device.destroy_graphics_pipeline(built);
9611                    return Err(error);
9612                }
9613                (Err(error), Err(_)) => return Err(error),
9614            };
9615            self.wireframe_pipeline = Some(pipelines);
9616        }
9617        self.wireframe_on = true;
9618        Ok(())
9619    }
9620
9621    /// Whether the colour pass draws lines instead of filled triangles.
9622    ///
9623    /// The read-back half of [`set_wireframe`](Self::set_wireframe), and the
9624    /// observable a test asking "is this frame a wireframe" wants: a renderer
9625    /// that built the pipeline and then switched it off answers `false`, because
9626    /// what it draws is what the question is about.
9627    #[must_use]
9628    pub const fn wireframe(&self) -> bool {
9629        self.wireframe_on
9630    }
9631
9632    /// Draws each surface's **world-space** normal instead of shading it, so a
9633    /// modeller can see whether the normals a document carries are sane.
9634    ///
9635    /// **Off by default**, on [`set_wireframe`](Self::set_wireframe)'s terms: it
9636    /// is a tool's view of a document, and every sample and every golden image
9637    /// predates it. It takes effect on the next
9638    /// [`begin_frame`](Self::begin_frame), which is what writes the block.
9639    ///
9640    /// # What the colours mean
9641    ///
9642    /// The conventional encoding, `n * 0.5 + 0.5` into RGB: +X reads red, +Y
9643    /// green, +Z blue, and a face whose winding was inverted reads the
9644    /// **complement** of the colour it should have. A missing or degenerate
9645    /// normal reads as whatever the vertex data actually holds rather than as the
9646    /// plausible shading a light would have given it, which is the point.
9647    ///
9648    /// # World space, not view space
9649    ///
9650    /// The two diagnose different things and this one is world space, so a face
9651    /// keeps its colour while the camera orbits: "is this face inverted" is then
9652    /// something a modeller *sees*, instead of inferring it from a picture that
9653    /// re-colours whenever they move. View-space normals answer the other
9654    /// question — is this normal smooth, is this seam split — by re-colouring on
9655    /// purpose, and they are not a thing this block could express anyway: it
9656    /// carries `view_proj` and no separate view matrix, so there is no rotation in
9657    /// the shader to take a normal into eye space with.
9658    ///
9659    /// # It builds nothing and adds no pass
9660    ///
9661    /// Unlike the wireframe, which needs a second pipeline and so a device that
9662    /// can build one: this is one lane of the frame's uniform block — see
9663    /// [`FrameUniforms::NORMALS_VIEW_ON`] — read by a branch in the fragment
9664    /// stage every device already runs. There is nothing to refuse and nothing to
9665    /// release, which is why it cannot fail and there is no `supports_` probe
9666    /// beside it.
9667    ///
9668    /// The tonemap still applies: at
9669    /// [`DEFAULT_EXPOSURE`](crcbl_shaders::tonemap::DEFAULT_EXPOSURE) its operator
9670    /// is the identity on `0..=1` and the encoded normal reaches the swapchain
9671    /// exactly, and at any other exposure the picture is scaled per channel — so
9672    /// which channel dominates a face never changes, but a caller reading exact
9673    /// values wants [`set_exposure`](Self::set_exposure) left alone.
9674    ///
9675    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
9676    pub const fn set_normals_view(&mut self, on: bool) {
9677        self.normals_view = on;
9678    }
9679
9680    /// Sets the exponential height fog the colour pass composites over every
9681    /// shaded surface.
9682    ///
9683    /// Topic 43 §4's cheapest large win: distance
9684    /// reads as distance, a valley fills while a hilltop stays clear, and it
9685    /// costs four numbers in a block every pipeline already binds.
9686    ///
9687    /// # It adds no pass and cannot fail
9688    ///
9689    /// On [`set_normals_view`](Self::set_normals_view)'s terms exactly — two
9690    /// rows of the frame's uniform block, read by arithmetic in the fragment
9691    /// stage every device already runs. There is nothing to build, so there is
9692    /// nothing to refuse and no `supports_` probe beside it.
9693    ///
9694    /// # Off is exactly off
9695    ///
9696    /// [`Fog::NONE`] is the default and a zero density is an *exact* identity,
9697    /// not an approximate one: the optical depth is zero, its transmittance is
9698    /// exactly one, and `mesh.slang` composites as `lit * t + fog * (1 - t)`
9699    /// rather than as a `lerp`, which at `t == 1` would return
9700    /// `fog + (lit - fog)` and lose the low bits of an HDR radiance far from
9701    /// the fog colour. So this feature moves no frame it is not switched on
9702    /// for.
9703    ///
9704    /// # What it does not fog
9705    ///
9706    /// The screen-space reflections `ssr_blur.slang` adds **after** this pass,
9707    /// which arrive unfogged onto an already-fogged surface — see
9708    /// `docs/backlog.md`. Fog is applied where the radiance is finished, and
9709    /// the reflection composite is one pass later.
9710    pub const fn set_fog(&mut self, fog: Fog) {
9711        self.fog = fog;
9712    }
9713
9714    /// Lights the scene with a gradient sky, on top of whatever ambient and
9715    /// irradiance grid it already has.
9716    ///
9717    /// Topic 43 §8's rung. [`Sky`] is three
9718    /// radiances — zenith, horizon, ground — and what reaches a surface is that
9719    /// gradient projected onto the L1 basis the probe grid already uses, so a
9720    /// surface facing up receives the sky and one facing down the ground's
9721    /// bounce. Three colours, no extra pass.
9722    ///
9723    /// # It adds no pass and cannot fail
9724    ///
9725    /// On [`set_fog`](Self::set_fog)'s terms exactly — three rows of the
9726    /// frame's uniform block and three dot products in a fragment stage every
9727    /// device already runs. Nothing to build, so nothing to refuse and no
9728    /// `supports_` probe beside it.
9729    ///
9730    /// # Off is exactly off
9731    ///
9732    /// [`Sky::NONE`] is the default and a black gradient projects to every
9733    /// coefficient zero — each is a product with a zero factor — so the
9734    /// fragment stage adds `max(0, 0)` and the ambient sum is the one it was
9735    /// before this existed, bit for bit.
9736    ///
9737    /// # What it does not do
9738    ///
9739    /// **Draw anything.** The background is still the scene target's clear
9740    /// colour, and a scene lit by a sky it cannot see is what this rung leaves
9741    /// behind until the pass that draws the gradient lands. The environment
9742    /// `ssr.slang` falls back to on a missed ray is still the probe grid's, so
9743    /// a mirror under a sky still reflects whatever the probes hold.
9744    pub const fn set_sky(&mut self, sky: Sky) {
9745        self.sky = sky;
9746    }
9747
9748    /// Replaces the gradient with Hillaire's atmosphere, or `None` to put the
9749    /// gradient back.
9750    ///
9751    /// Topic 43 §8. A frame with an atmosphere takes
9752    /// it for all three of the things a sky is: the background the sky pass
9753    /// draws, the L1 ambient term `mesh.slang` adds, and the environment
9754    /// `ssr.slang` falls back to when a ray hits nothing. The
9755    /// [`Sky`] a caller may also have set is not read on those frames.
9756    ///
9757    /// # What it costs
9758    ///
9759    /// **A march on the host, not on the device.** The first
9760    /// [`begin_frame`](Self::begin_frame) after this is called marches
9761    /// [`crcbl_shaders::atmosphere::SkyView`] whole, which is tens of
9762    /// milliseconds of CPU — a renderer with no LUT has no sky, so that one is
9763    /// paid where it is asked for. Every later move of the sun is marched
9764    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame with the last finished LUT still
9765    /// drawn, so no frame after the first pays the whole march;
9766    /// `refresh_sky_view` is where that is written down, including what a sun
9767    /// that moves *every* frame gets. A frame whose
9768    /// sun has not moved costs the comparison that finds nothing to do and
9769    /// nothing else: the LUT's two projections are cached beside it. The device
9770    /// pays four buffer loads and a blend, which is what the gradient pays.
9771    ///
9772    /// # Off is exactly off
9773    ///
9774    /// `None` is the default, and a renderer nobody calls this on writes the
9775    /// same block, adds the same passes and draws the same frame it did before
9776    /// this existed — `sky.slang`'s arm is
9777    /// [`crcbl_shaders::sky::ATMOSPHERE_OFF`], which is exactly zero.
9778    ///
9779    /// # What it does not do
9780    ///
9781    /// **Draw the sun.** The LUT holds the scattered sky and not the disc, as
9782    /// the paper's does; the sun itself is the [`DirectionalLight`] the forward
9783    /// pass already shades with, and pointing the two the same way is the
9784    /// caller's job.
9785    ///
9786    /// **Put the air in front of a surface.** That is the paper's third LUT and
9787    /// this engine's froxel column, and neither reads this.
9788    pub fn set_atmosphere(&mut self, atmosphere: Option<Atmosphere>) {
9789        self.atmosphere = atmosphere;
9790    }
9791
9792    /// The bodies of water every view draws — `docs/plan/55-water.md`'s rung 1,
9793    /// and this crate's `water` module for how.
9794    ///
9795    /// Replaces whatever was set before. Each body is meshed here, by
9796    /// [`crcbl_water::surface_mesh`], and the result is uploaded to each frame
9797    /// slot as that slot next begins, so the call touches no device and a frame
9798    /// still in flight keeps the buffers it was submitted with.
9799    ///
9800    /// # Off is exactly off
9801    ///
9802    /// An empty slice is the default, and a renderer with no bodies records no
9803    /// water pass at all: the frame it draws is the one it drew before this
9804    /// existed, bit for bit. Water is content, not a
9805    /// [`RenderEffects`] bit, on [`set_sky`](Self::set_sky)'s terms.
9806    ///
9807    /// # Errors
9808    ///
9809    /// [`crcbl_water::BodyError`] for the first body that cannot be meshed —
9810    /// too few points, a non-finite coordinate, an outline that crosses itself,
9811    /// a negative coefficient — and then **nothing is replaced**: the bodies set
9812    /// before this call go on drawing.
9813    pub fn set_water(
9814        &mut self,
9815        bodies: &[crcbl_water::WaterBody],
9816    ) -> Result<(), crcbl_water::BodyError> {
9817        self.water.set(bodies)
9818    }
9819
9820    /// The bodies of water this renderer draws, as they were last set.
9821    #[must_use]
9822    pub fn water(&self) -> &[crcbl_water::WaterBody] {
9823        self.water.bodies()
9824    }
9825
9826    /// The field of grass every view draws — `docs/plan/57-grass.md`'s rungs G1
9827    /// and G3, and this crate's `grass` module for how.
9828    ///
9829    /// Replaces whatever was set before. The field's ground, cover map, blade
9830    /// table and per-tile blocks are uploaded here, and the buffers a dispatch
9831    /// writes are created here; a field replaced while a frame is in flight
9832    /// leaves its resources alive until the ring has come round, so the call is
9833    /// safe at any point between frames.
9834    ///
9835    /// # Off is exactly off
9836    ///
9837    /// [`None`] is the default, and a renderer with no field records no grass
9838    /// pass at all: the frame it draws is the one it drew before this existed,
9839    /// bit for bit. Grass is content, not a [`RenderEffects`] bit, on
9840    /// [`set_water`](Self::set_water)'s terms.
9841    ///
9842    /// # Errors
9843    ///
9844    /// [`crate::grass::SetError::Field`] for a description the field itself
9845    /// refuses — no tiles, a zero texel scale, an empty blade table — and then
9846    /// **nothing is replaced**: the field set before this call goes on drawing.
9847    /// [`crate::grass::SetError::Hal`] for a seam call that failed, on the same
9848    /// terms.
9849    pub fn set_grass(
9850        &mut self,
9851        device: &dyn Device,
9852        queue: QueueHandle,
9853        field: Option<&crate::grass::GrassField>,
9854    ) -> Result<(), crate::grass::SetError> {
9855        self.grass.set(device, queue, field)
9856    }
9857
9858    /// The field of grass this renderer draws, as it was last set.
9859    #[must_use]
9860    pub fn grass(&self) -> Option<&crate::grass::GrassField> {
9861        self.grass.field()
9862    }
9863
9864    /// The two buffers the grass generation pass writes, or [`None`] for a
9865    /// renderer with no field.
9866    ///
9867    /// What `crcbl`'s `render_e2e` copies back to check the placement blade by
9868    /// blade and to read each slot's instance count, on
9869    /// [`froxel_buffers`](Self::froxel_buffers)' terms — see
9870    /// [`crate::grass::GrassBuffers`] for the layout. They hold whatever the
9871    /// last frame that generated left there, which for a field nobody has drawn
9872    /// yet is undefined rather than empty.
9873    #[must_use]
9874    pub fn grass_buffers(&self) -> Option<crate::grass::GrassBuffers> {
9875        self.grass.buffers()
9876    }
9877
9878    /// The two authored wind layers `docs/plan/56-wind.md`'s decision 1 names,
9879    /// as the GPU copy of the field samples them.
9880    ///
9881    /// [`None`] restores the calm placeholder: one texel of no deflection and
9882    /// one of zero intensity, which is what makes a field with no weather set
9883    /// stand still. A replaced pair waits for the ring exactly as a replaced
9884    /// field does.
9885    ///
9886    /// # Errors
9887    ///
9888    /// [`crate::grass::WindLayerError`] for a layer that is not four bytes a
9889    /// texel of the grid it came with, or a seam call that failed.
9890    pub fn set_wind_layers(
9891        &mut self,
9892        device: &dyn Device,
9893        queue: QueueHandle,
9894        layers: Option<&crate::grass::WindLayers>,
9895    ) -> Result<(), crate::grass::WindLayerError> {
9896        self.grass.set_wind_layers(device, queue, layers)
9897    }
9898
9899    /// The wind's uniform block for the frames from here on —
9900    /// `crcbl_wind::WindField::gpu_params`, which is where the authoritative
9901    /// `f64` formula is narrowed to `f32`.
9902    ///
9903    /// Everything in it is camera-relative or already wrapped, so a caller
9904    /// writes it once per frame from the field's own state and never from a
9905    /// world-scale coordinate. The default is a base speed of zero, which is
9906    /// calm.
9907    pub const fn set_wind(&mut self, params: crcbl_shaders::wind::WindParams) {
9908        self.wind = params;
9909    }
9910
9911    /// The wind block this renderer writes, as it was last set.
9912    #[must_use]
9913    pub const fn wind(&self) -> crcbl_shaders::wind::WindParams {
9914        self.wind
9915    }
9916
9917    /// The atmosphere this renderer draws, if it has one.
9918    #[must_use]
9919    pub const fn atmosphere(&self) -> Option<Atmosphere> {
9920        self.atmosphere
9921    }
9922
9923    /// Draws each cluster tinted by the DAG level it was decimated to, instead
9924    /// of shading it.
9925    ///
9926    /// **The picture cluster LOD's whole claim rests on**: one mesh spanning
9927    /// several levels across its own surface is a statement a test can assert
9928    /// and nobody can see, and this is what makes it visible. The mesh path
9929    /// tints per cluster; the two indirect paths select one level per instance
9930    /// and have no per-cluster level at all, so they draw one flat grey — which
9931    /// is the comparison rather than a shortfall.
9932    ///
9933    /// Costs what [`set_normals_view`](Self::set_normals_view) costs: one lane
9934    /// of the frame's uniform block, read by a branch every device already runs.
9935    /// Nothing to build, nothing to refuse, nothing to release.
9936    ///
9937    /// **Wins over the normals view when both are on**, because the two share a
9938    /// lane and the fragment stage tests this one first.
9939    pub const fn set_lod_view(&mut self, on: bool) {
9940        self.lod_view = on;
9941    }
9942
9943    /// Whether the colour pass tints clusters by their DAG level.
9944    ///
9945    /// **What was asked for, not what is drawn.** The three debug views share
9946    /// one lane and resolve in one order, so a renderer with this and
9947    /// [`set_heatmap`](Self::set_heatmap) both on draws the heatmap and still
9948    /// answers `true` here — the caller's setting is what a caller's toggle has
9949    /// to read back, and [`debug_view`](Self::debug_view) is what says which one
9950    /// the frame actually took.
9951    #[must_use]
9952    pub const fn lod_view(&self) -> bool {
9953        self.lod_view
9954    }
9955
9956    /// Shades each cluster by the **projected screen-space error** the LOD
9957    /// selection judged it on, instead of shading it.
9958    ///
9959    /// The LOD tint's sibling, and the other half of topic 25's
9960    /// pair: [`set_lod_view`](Self::set_lod_view) answers "which level am I
9961    /// looking at", and this answers "how close to the budget is this, and where
9962    /// is the selection about to switch". The number is the one
9963    /// `draw_gen.slang`'s `group_is_expanded` compared against the budget — a
9964    /// cluster's *producing* group's error, projected from this frame's eye at
9965    /// this frame's pixels per unit.
9966    ///
9967    /// # What the colours mean
9968    ///
9969    /// A ramp that climbs in luminance from a cold floor to white, with a hue
9970    /// break at each of the two budgets: the hold budget where the hysteresis
9971    /// band starts, and the expand budget at the top, which is white. So the two
9972    /// budgets draw themselves as contour lines across the surface, and
9973    /// "brighter is closer to switching" reads even in a greyscale screenshot.
9974    /// `mesh_cluster.slang`'s `HEAT_UNDER_LOW` carries the ramp in full, and
9975    /// `crcbl_shaders`' `the_heatmap_ramp_climbs_in_luminance` is what holds it
9976    /// to being readable as an ordering.
9977    ///
9978    /// A cluster nothing simplified — the original surface, at the bottom of the
9979    /// DAG — costs exactly zero and takes the ramp's floor.
9980    ///
9981    /// # Mesh path only, and that is the capability rather than a shortfall
9982    ///
9983    /// A per-cluster error exists only where selection is per cluster.
9984    /// [`GeometryPath::IndirectCount`] and [`GeometryPath::IndirectPerBatch`]
9985    /// choose one level per *instance*, so there is no per-cluster number for
9986    /// them to shade by and `mesh.slang`'s vertex stage writes the same flat grey
9987    /// the LOD tint gets. Standing the two beside each other is the comparison.
9988    ///
9989    /// # It builds nothing and adds no pass
9990    ///
9991    /// One lane of the frame's uniform block, on
9992    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly — plus one
9993    /// storage-buffer read in the mesh stage, which the mesh path's layout
9994    /// already carries. Nothing to build, nothing to refuse, nothing to release.
9995    ///
9996    /// **Wins over both the LOD tint and the normals view when several are on**;
9997    /// see [`debug_view`](Self::debug_view), which is that order stated once.
9998    ///
9999    /// [`GeometryPath::IndirectCount`]: crcbl_hal::GeometryPath::IndirectCount
10000    /// [`GeometryPath::IndirectPerBatch`]: crcbl_hal::GeometryPath::IndirectPerBatch
10001    pub const fn set_heatmap(&mut self, on: bool) {
10002        self.heatmap = on;
10003    }
10004
10005    /// Whether the colour pass shades clusters by their projected error.
10006    ///
10007    /// **What was asked for, not what is drawn**, on
10008    /// [`lod_view`](Self::lod_view)'s terms.
10009    #[must_use]
10010    pub const fn heatmap(&self) -> bool {
10011        self.heatmap
10012    }
10013
10014    /// Draws the ambient-occlusion channel alone, as grey, instead of shading.
10015    ///
10016    /// One is white and fully occluded is black — the buffer the forward pass
10017    /// multiplies its ambient term by, shown as itself. **This is how the AO
10018    /// ladder — GTAO against the eight-tap hemisphere — is compared at all:** a
10019    /// composited frame shows occlusion times albedo times ambient, and a
10020    /// difference in the first is not separable from a difference in the other
10021    /// two by looking at the result.
10022    ///
10023    /// # What it draws with occlusion switched off
10024    ///
10025    /// White, everywhere. A frame without
10026    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 white image in place of
10027    /// a computed channel, and this view shows that image rather than pretending
10028    /// to a channel nothing computed — "no occlusion was computed" and "nothing
10029    /// occludes here" are the same value to the shading, and the view does not
10030    /// get to disagree with the shading about it.
10031    ///
10032    /// # It builds nothing and adds no pass
10033    ///
10034    /// One lane of the frame's uniform block, on
10035    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly. Unlike the
10036    /// tint and the heatmap it needs nothing from the geometry stage, so it
10037    /// draws on every [`GeometryPath`] rather than on
10038    /// the mesh-shader one alone.
10039    ///
10040    /// **Wins over every other view when several are on**; see
10041    /// [`debug_view`](Self::debug_view), which is that order stated once.
10042    pub const fn set_occlusion_view(&mut self, on: bool) {
10043        self.occlusion_view = on;
10044    }
10045
10046    /// Whether the colour pass draws the occlusion channel instead of shading.
10047    ///
10048    /// **What was asked for, not what is drawn**, on
10049    /// [`lod_view`](Self::lod_view)'s terms.
10050    #[must_use]
10051    pub const fn occlusion_view(&self) -> bool {
10052        self.occlusion_view
10053    }
10054
10055    /// Draws each fragment's motion vector instead of shading it.
10056    ///
10057    /// The two components are stretched by
10058    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) and centred
10059    /// on grey, into red and green, with blue left at zero. A pixel at rest is
10060    /// grey in both channels to within one half-float step —
10061    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) says why
10062    /// not exactly — and a surface travelling right and down the screen
10063    /// brightens both.
10064    ///
10065    /// # It is the motion-vector target's only reader today
10066    ///
10067    /// The forward pass writes a motion vector into a third colour attachment on
10068    /// every frame — see [`crate::targets::motion`] — and no pass reads it
10069    /// yet; TAA (`docs/backlog.md`) is the first that will. This
10070    /// view is therefore what says the subtraction behind it is the right one,
10071    /// which is why it exists ahead of a consumer.
10072    ///
10073    /// # It builds nothing and adds no pass
10074    ///
10075    /// One lane of the frame's uniform block, on
10076    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10077    /// the occlusion view it needs nothing from the geometry stage that a
10078    /// shaded frame does not already produce — so it draws on every
10079    /// [`GeometryPath`].
10080    ///
10081    /// **Wins over every other view when several are on**; see
10082    /// [`debug_view`](Self::debug_view), which is that order stated once.
10083    pub const fn set_motion_view(&mut self, on: bool) {
10084        self.motion_view = on;
10085    }
10086
10087    /// Whether the colour pass draws the motion vector instead of shading.
10088    ///
10089    /// **What was asked for, not what is drawn**, on
10090    /// [`lod_view`](Self::lod_view)'s terms.
10091    #[must_use]
10092    pub const fn motion_view(&self) -> bool {
10093        self.motion_view
10094    }
10095
10096    /// Draws the occlusion channel's **bent direction** instead of shading.
10097    ///
10098    /// The three channels beside the visibility scalar, passed through as the
10099    /// colour: the conventional `n * 0.5 + 0.5`, so +X reads red, +Y green and
10100    /// +Z blue, which is the mapping
10101    /// [`set_normals_view`](Self::set_normals_view) already uses for a surface
10102    /// normal. A fragment the occlusion pass had no direction for reads as the
10103    /// mid grey the zero sentinel encodes to.
10104    ///
10105    /// # What it is for
10106    ///
10107    /// The bent direction is what the ambient term is sampled *along*, and a
10108    /// composited frame cannot show it: ambient times albedo times a
10109    /// direction-dependent irradiance is one colour, and a direction that is
10110    /// subtly wrong looks like a lighting choice. This draws the direction
10111    /// alone, which is how a corner that leans the wrong way out of its own
10112    /// wall is a thing a reviewer sees rather than infers.
10113    ///
10114    /// # What it draws with occlusion switched off
10115    ///
10116    /// Mid grey, everywhere. A frame without
10117    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 placeholder holding
10118    /// [`BENT_NORMAL_NONE`](crcbl_shaders::ssao::BENT_NORMAL_NONE) in those
10119    /// three channels, and this view shows that image rather than pretending to
10120    /// a direction nothing computed — which is the same answer the shading
10121    /// takes, since `mesh.slang` reads that sentinel as "use the shading
10122    /// normal".
10123    ///
10124    /// # It builds nothing and adds no pass
10125    ///
10126    /// One lane of the frame's uniform block, on
10127    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10128    /// the occlusion view it needs nothing from the geometry stage — so it
10129    /// draws on every [`GeometryPath`].
10130    ///
10131    /// **Wins over every other view when several are on**; see
10132    /// [`debug_view`](Self::debug_view), which is that order stated once.
10133    pub const fn set_bent_normal_view(&mut self, on: bool) {
10134        self.bent_normal_view = on;
10135    }
10136
10137    /// Whether the colour pass draws the bent direction instead of shading.
10138    ///
10139    /// **What was asked for, not what is drawn**, on
10140    /// [`lod_view`](Self::lod_view)'s terms.
10141    #[must_use]
10142    pub const fn bent_normal_view(&self) -> bool {
10143        self.bent_normal_view
10144    }
10145
10146    /// Tints the shaded picture by the **cascade** each sun-lit fragment's
10147    /// shadow was sampled from.
10148    ///
10149    /// Topic 45's eighth decision made the cascade switch a
10150    /// band rather than a step, and this is the picture that band is judged in:
10151    /// each fragment's shading multiplied by
10152    /// [`CASCADE_TINTS`](crcbl_shaders::mesh::CASCADE_TINTS) of the cascade it
10153    /// selected, and inside the band by the *blend* of the two — the same weight
10154    /// the visibility itself was mixed with. So the boundary reads as a
10155    /// gradient, and a seam where two cascades disagree shows up as a step in
10156    /// the gradient rather than as a ring somebody has to already suspect.
10157    ///
10158    /// # It keeps the shaded picture, which is why it loses to every other view
10159    ///
10160    /// Every other view replaces the frame; this one multiplies it, so the geometry
10161    /// stays readable underneath and the shadow the cascades produced is still
10162    /// in the picture being coloured. That is also what puts it last in
10163    /// [`debug_view`](Self::debug_view)'s order: with a replacing view on there
10164    /// is no shading left for a tint to reach.
10165    ///
10166    /// # What it draws where no cascade covers a fragment
10167    ///
10168    /// Nothing at all —
10169    /// [`CASCADE_TINT_NONE`](crcbl_shaders::mesh::CASCADE_TINT_NONE) is white.
10170    /// A surface facing away from the sun and one past the last cascade's reach
10171    /// are both that, because neither was sampled through a cascade, and a
10172    /// frame drawn without [`RenderEffects::SHADOWS`](crate::RenderEffects::SHADOWS) is
10173    /// white everywhere for the same reason. Colouring those would be inventing
10174    /// a cascade for a pixel no map covers.
10175    ///
10176    /// # It builds nothing and adds no pass
10177    ///
10178    /// One lane of the frame's uniform block, on
10179    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10180    /// the occlusion view it needs nothing from the geometry stage — so it draws
10181    /// on every [`GeometryPath`].
10182    pub const fn set_cascade_view(&mut self, on: bool) {
10183        self.cascade_view = on;
10184    }
10185
10186    /// Whether the colour pass tints the picture by the sun's cascades.
10187    ///
10188    /// **What was asked for, not what is drawn**, on
10189    /// [`lod_view`](Self::lod_view)'s terms — and here that gap is the usual
10190    /// case rather than the corner one: this view loses to every other one, so a
10191    /// renderer with any of them also on answers `true` here and draws that one.
10192    #[must_use]
10193    pub const fn cascade_view(&self) -> bool {
10194        self.cascade_view
10195    }
10196
10197    /// Draws the **shadow atlas itself** over the finished frame: the
10198    /// `D32Float` image `crate::shadow` budgets, letterboxed at its own aspect,
10199    /// each texel's stored depth as a grey and a border round every occupied
10200    /// slot.
10201    ///
10202    /// Sundial's atlas viewer, and the answer to a
10203    /// question no other view can be asked: which slot holds which map, and
10204    /// which slots hold nothing. A tile that was never rendered into, or
10205    /// rendered at the wrong viewport, lights a scene *fully* — so the frame it
10206    /// produces is plausible and every golden blessed from it passes. Here it is
10207    /// a rectangle that is visibly empty.
10208    ///
10209    /// # It is a pass, and it is the only debug view that is
10210    ///
10211    /// Every other view rides in one lane of the frame's uniform block and is a
10212    /// branch in `mesh.slang`, because every other view is a function of the
10213    /// fragment being shaded. The atlas is not: it is one image the whole frame
10214    /// shares. So this switch adds `crate::atlas_view`'s full-screen pass to
10215    /// the frame instead — after the tonemap, in display space, for that
10216    /// module's reason — and the frame block is byte-identical either way.
10217    ///
10218    /// # Where it resolves, and what it costs when it is off
10219    ///
10220    /// Below every replacing view and above
10221    /// [`set_cascade_view`](Self::set_cascade_view)'s tint — see
10222    /// [`debug_view`](Self::debug_view), which is that order stated once. A
10223    /// frame that resolved anything else records **no pass**, no pipeline bind
10224    /// and no block read, which is what makes the off position bit-identical on
10225    /// `crate::sky_pass`'s terms.
10226    pub const fn set_atlas_view(&mut self, on: bool) {
10227        self.atlas_view = on;
10228    }
10229
10230    /// Whether the frame draws the shadow atlas over the picture.
10231    ///
10232    /// **What was asked for, not what is drawn**, on
10233    /// [`lod_view`](Self::lod_view)'s terms: a renderer with a replacing view
10234    /// also on answers `true` here and draws that one.
10235    #[must_use]
10236    pub const fn atlas_view(&self) -> bool {
10237        self.atlas_view
10238    }
10239
10240    /// Pins the eye topic 25's selection is projected from, so the
10241    /// cut stops following the camera.
10242    ///
10243    /// [`None`] is the default and means "the camera's own eye", which is what
10244    /// every frame before this existed did. `Some(eye)` selects detail for a
10245    /// viewer standing at `eye` while the frame is still drawn, culled and lit
10246    /// from wherever the camera actually is.
10247    ///
10248    /// # What it is for
10249    ///
10250    /// Per-cluster LOD is only checkable from somewhere other than the point
10251    /// that chose it. Looked at from the selecting eye, a cut that is far too
10252    /// coarse and a cut that is exactly right produce the same silhouette —
10253    /// that is what a screen-space error budget *means* — so the one viewpoint
10254    /// where a wrong cut cannot be seen is the viewpoint every unfrozen frame is
10255    /// judged from. Pin the eye and fly away from it, and the boundaries between
10256    /// levels become geometry a reviewer can walk up to and look at edge-on.
10257    ///
10258    /// # Only the selection freezes
10259    ///
10260    /// The frame has three places a viewer position is read, and this moves
10261    /// exactly one of them:
10262    ///
10263    /// * **the selection** — `draw_gen.slang`'s `select_level`, which reads
10264    ///   `DrawGenParams::camera_position` and is the only thing that decides the
10265    ///   cut. It writes the group hysteresis state that the mesh path's
10266    ///   amplification stage then descends, so freezing this one field freezes
10267    ///   the cut on the per-cluster path and the two indirect paths alike. This
10268    ///   is what moves.
10269    /// * **the frustum culls** — `cull.slang`'s instance test and
10270    ///   `mesh_cluster.slang`'s per-cluster one, whose planes are extracted from
10271    ///   the frame's own view-projection and never read a camera position at
10272    ///   all. Unaffected, and it has to be: a frame culled against a frustum the
10273    ///   reviewer has flown out of would draw nothing.
10274    /// * **the normal cone** — `mesh_cluster.slang`'s `cluster_survives`, which
10275    ///   reads [`FrameUniforms::camera_position`] and asks which way a cluster
10276    ///   faces *relative to the viewer*. That question is about the eye the
10277    ///   picture is drawn from, not the eye it was selected for; frozen, a
10278    ///   reviewer who flew round to the other side of the face would have every
10279    ///   cluster now facing them rejected for facing away from a viewpoint
10280    ///   nobody is standing at. It stays live.
10281    ///
10282    /// The split is not new. `DrawGenParams::camera_position` and
10283    /// [`FrameUniforms::camera_position`] are already separate fields carrying
10284    /// different values on a shadow cascade — that one holds the sun while this
10285    /// one stays the camera, because detail is denominated in the camera's
10286    /// pixels and facing is asked about the light. This freezes the same seam
10287    /// from the other side, and needs no new binding, no new shader input and no
10288    /// shader change of any kind.
10289    ///
10290    /// # It freezes the cascades' selection too
10291    ///
10292    /// [`begin_frame`](Self::begin_frame) hands the same eye to every shadow
10293    /// cascade's draw generator, because a cascade selects detail for the
10294    /// *camera* — see [`SHADOW_LOD_BIAS`]. A frozen camera cut over a live
10295    /// shadow cut would be a shadow silhouette sliding under a fixed one, which
10296    /// is a difference in the picture that belongs to neither.
10297    ///
10298    /// # The heatmap reads the live eye, and says so
10299    ///
10300    /// [`set_heatmap`](Self::set_heatmap) shades a cluster by its producing
10301    /// group's projected error, computed in the mesh stage from
10302    /// [`FrameUniforms::camera_position`] — the eye that stays live. So under a
10303    /// frozen selection the two overlays answer different questions: the cut is
10304    /// the one chosen at the pinned eye, and the heat is what the error would be
10305    /// if it were chosen from here now. That is readable — flying towards the
10306    /// face brightens the clusters the frozen cut is not refining, which is the
10307    /// selection's sensitivity made visible — but it does mean the ramp's
10308    /// contours stop coinciding with the level boundaries while frozen.
10309    /// [`set_lod_view`](Self::set_lod_view) is the overlay that composes
10310    /// unconditionally: a cluster's level is a property of the cut and of
10311    /// nothing else.
10312    ///
10313    /// Carrying the pinned eye into the mesh stage as well would need a second
10314    /// position in the frame block, which is a new shader input in every backend
10315    /// for one overlay's benefit; `docs/backlog.md` holds that trade-off.
10316    ///
10317    /// [`FrameUniforms::camera_position`]: crcbl_shaders::mesh::FrameUniforms::camera_position
10318    pub const fn set_frozen_selection_eye(&mut self, eye: Option<Vec3>) {
10319        self.frozen_selection_eye = eye;
10320    }
10321
10322    /// Where the selection is pinned, or [`None`] while it follows the camera.
10323    ///
10324    /// The read-back half of
10325    /// [`set_frozen_selection_eye`](Self::set_frozen_selection_eye), and what a
10326    /// debug panel says "frozen at" out of — "frozen" without the position is a
10327    /// row nobody can act on.
10328    #[must_use]
10329    pub const fn frozen_selection_eye(&self) -> Option<Vec3> {
10330        self.frozen_selection_eye
10331    }
10332
10333    /// Which of the debug views the next frame will actually draw.
10334    ///
10335    /// **The one place the precedence is decided**, and every other statement of
10336    /// it in this crate reads it back from here. The switches ride in one float
10337    /// lane of the frame block — see
10338    /// [`FrameUniforms::HEATMAP_VIEW_ON`](crcbl_shaders::mesh::FrameUniforms::HEATMAP_VIEW_ON)
10339    /// — and the shaders test the outermost threshold first, so a sentinel for
10340    /// an outer view clears every threshold below it. Resolving here rather than
10341    /// letting each caller guess is what stops "which view is on" being answered
10342    /// differently by a menu row, a debug panel and the picture.
10343    #[must_use]
10344    pub const fn debug_view(&self) -> DebugView {
10345        if self.bent_normal_view {
10346            DebugView::BentNormal
10347        } else if self.motion_view {
10348            DebugView::Motion
10349        } else if self.occlusion_view {
10350            DebugView::AmbientOcclusion
10351        } else if self.heatmap {
10352            DebugView::Heatmap
10353        } else if self.lod_view {
10354            DebugView::LodTint
10355        } else if self.normals_view {
10356            DebugView::Normals
10357        } else if self.atlas_view {
10358            // **Below every view above it, and above the tint below.**
10359            //
10360            // Below, because every branch before this one is a question about
10361            // the *picture* — a cluster's error, a surface's normal, the
10362            // occlusion channel — and this one is not a picture of the scene at
10363            // all. A caller who left the atlas up and then asked for normals has
10364            // asked to look at the frame again, and the frame is what the branch
10365            // above draws; the atlas is one keystroke away and is not lost by
10366            // being deferred to.
10367            //
10368            // Above, because the cascade tint multiplies the shaded picture and
10369            // this replaces it: a tint on a frame the atlas overwrote would be a
10370            // tint on the atlas, which is a colour standing for nothing.
10371            DebugView::ShadowAtlas
10372        } else if self.cascade_view {
10373            // **Innermost, and the only view that sits below the others rather
10374            // than above them.** Every branch before this one draws something
10375            // *instead of* the shaded picture and returns before the shading; a
10376            // cascade tint is a multiply on that shading, so there is nothing
10377            // for it to modulate while one of them is showing and a caller with
10378            // both on has asked for the picture the outer one draws. The lane
10379            // says the same thing from the other end — the cascade sentinel is
10380            // negative, so it clears none of the shaders' thresholds — and
10381            // `crcbl_shaders`'
10382            // `the_cascade_view_threshold_lies_below_every_replacing_view` is
10383            // what holds that half.
10384            DebugView::Cascades
10385        } else {
10386            DebugView::Shaded
10387        }
10388    }
10389
10390    /// [`debug_view`](Self::debug_view) as the value the frame block's lane
10391    /// carries.
10392    const fn debug_view_lane(&self) -> f32 {
10393        match self.debug_view() {
10394            DebugView::BentNormal => mesh::FrameUniforms::BENT_NORMAL_VIEW_ON,
10395            DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
10396            DebugView::AmbientOcclusion => mesh::FrameUniforms::OCCLUSION_VIEW_ON,
10397            DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
10398            DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
10399            DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
10400            DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
10401            // **The off sentinel, and it is not an omission.** This view is a
10402            // pass rather than a branch in `mesh.slang` — see
10403            // [`crate::atlas_view`] — so the colour pass draws exactly the
10404            // shaded picture it always drew and the pass afterwards replaces it.
10405            // A lane of its own would be a threshold no shader tests.
10406            DebugView::ShadowAtlas | DebugView::Shaded => mesh::FrameUniforms::NORMALS_VIEW_OFF,
10407        }
10408    }
10409
10410    /// Whether the colour pass draws world-space normals instead of shading.
10411    ///
10412    /// The read-back half of [`set_normals_view`](Self::set_normals_view), on
10413    /// [`wireframe`](Self::wireframe)'s terms: what it draws is what the question
10414    /// is about.
10415    #[must_use]
10416    pub const fn normals_view(&self) -> bool {
10417        self.normals_view
10418    }
10419
10420    /// The cull and draw-argument passes, and the buffers they produce.
10421    ///
10422    /// What a caller reads the culling statistics out of — topic 03 §3.6's
10423    /// delayed readback ring is [`DrawGen::visible_count`] — and what
10424    /// `crcbl-vk`'s end-to-end suite copies back to check the generated
10425    /// arguments against the draws this pass used to record itself.
10426    #[must_use]
10427    pub const fn draws(&self) -> &DrawGen {
10428        &self.primary.draws
10429    }
10430
10431    /// `frame`'s auto-exposure measurement: the bins the histogram pass filled
10432    /// and the exposure the reduce wrote out of them.
10433    ///
10434    /// What `crcbl`'s `mesh_e2e` copies back to check the histogram bin by bin
10435    /// against `crcbl_shaders::exposure`, on [`draws`](Self::draws)' terms — see
10436    /// [`ExposureBuffers`]. Both hold whatever the last frame that measured left
10437    /// there, so a frame drawn without
10438    /// [`RenderEffects::AUTO_EXPOSURE`](crate::RenderEffects::AUTO_EXPOSURE)
10439    /// hands back the frame before it rather than nothing.
10440    ///
10441    /// # Panics
10442    ///
10443    /// If `frame` is not a slot this renderer was built with.
10444    #[must_use]
10445    pub fn exposure_buffers(&self, frame: usize) -> ExposureBuffers {
10446        self.primary.auto_exposure.buffers(frame)
10447    }
10448
10449    /// `frame`'s froxel column: the buffers the froxel volume's
10450    /// three passes write, and the block they read.
10451    ///
10452    /// What `crcbl`'s `mesh_e2e` copies back to check the column froxel by
10453    /// froxel against `crcbl_shaders::volumetric`, on
10454    /// [`draws`](Self::draws)' terms — see [`FroxelBuffers`].
10455    ///
10456    /// # Panics
10457    ///
10458    /// If `frame` is not a slot this renderer was built with.
10459    #[must_use]
10460    pub fn froxel_buffers(&self, frame: usize) -> FroxelBuffers {
10461        self.primary.volumetric.buffers(frame)
10462    }
10463
10464    /// The three layers a caller supplies to the toggle resolution order — see
10465    /// [`crate::effects`].
10466    ///
10467    /// Read back rather than only written, so a caller changing one layer does
10468    /// not have to remember the other two: take this, edit the field it owns,
10469    /// hand it back to [`set_effect_request`](Self::set_effect_request).
10470    #[must_use]
10471    pub const fn effect_request(&self) -> EffectRequest {
10472        self.effect_request
10473    }
10474
10475    /// Replaces all three requested layers, and resolves them at the next
10476    /// [`begin_frame`](Self::begin_frame).
10477    ///
10478    /// **The frame in flight does not move.** `begin_frame` freezes what it
10479    /// resolved and [`add_passes`](Self::add_passes) records that, because the
10480    /// two halves of a frame have to agree about which culls were parametrised:
10481    /// `begin_frame` skips a shadow cull's parameter write when shadows are off
10482    /// and `add_passes` skips its dispatch, and a request landing between the two
10483    /// would dispatch a cull against numbers nothing zeroed.
10484    pub const fn set_effect_request(&mut self, request: EffectRequest) {
10485        self.effect_request = request;
10486    }
10487
10488    /// Replaces the **camera** layer with what `stack` asks for, and leaves the
10489    /// other three where they are.
10490    ///
10491    /// The file half of [`crate::stack`] reaching the renderer: a view that has
10492    /// a render stack writes it here, and the player's `[engine.video]` clamp,
10493    /// the antialiasing rung they picked and any programmatic override are
10494    /// untouched — which is the property that makes the four layers four rather
10495    /// than one. A caller that wants to move more than this layer builds an
10496    /// [`EffectRequest`] and uses
10497    /// [`set_effect_request`](Self::set_effect_request).
10498    ///
10499    /// **The frame in flight does not move**, on `set_effect_request`'s terms
10500    /// and for its reason: this writes the request and
10501    /// [`begin_frame`](Self::begin_frame) is what resolves it.
10502    pub const fn set_camera_stack(&mut self, stack: &CameraStack) {
10503        self.effect_request.camera = stack.compile();
10504    }
10505
10506    /// What the frame the last [`begin_frame`](Self::begin_frame) opened draws.
10507    ///
10508    /// The resolved set, not a layer: every effect in it has survived the
10509    /// camera's stack, the player's quality clamp, any programmatic override and
10510    /// the device — which is the one question a test asking "did this frame have
10511    /// shadows in it" wants answered.
10512    ///
10513    /// [`RenderEffects::all`] before the first frame, which is what a renderer
10514    /// nobody has changed would draw.
10515    #[must_use]
10516    pub const fn effects(&self) -> RenderEffects {
10517        self.frame_effects
10518    }
10519
10520    /// What a frame begun **now** would draw: the whole order applied to the
10521    /// current request.
10522    ///
10523    /// [`effects`](Self::effects)' question one frame earlier, and the one a
10524    /// caller reporting its own configuration wants — a debug panel built at
10525    /// startup has no frame behind it yet, and printing what the last one drew
10526    /// would print a default.
10527    ///
10528    /// **A debug view takes the antialiasing resolve off** — either tier of it
10529    /// — whatever the four layers said. Those views are readouts rather than
10530    /// pictures — a pixel's colour *is* the cluster's projected error or its
10531    /// DAG level, read back against a legend — and a filter that blends two
10532    /// clusters' shades invents a ramp position no cluster occupies.
10533    /// `apps/quarry`'s heatmap and LOD tests are the consumers that count a
10534    /// frame's distinct colours.
10535    #[must_use]
10536    pub fn resolved_effects(&self) -> RenderEffects {
10537        let resolved = self.effect_request.resolve(self.device_effects);
10538        if matches!(self.debug_view(), DebugView::Shaded) {
10539            resolved
10540        } else {
10541            // **Both tiers**, because the slot is what a readout cannot have
10542            // rather than one filter in particular.
10543            resolved.difference(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2))
10544        }
10545    }
10546
10547    /// Which tonemap operator the next frame runs:
10548    /// [`tonemap_curve`](Self::tonemap_curve)'s answer for a shaded frame, and
10549    /// the clamp for a readout.
10550    ///
10551    /// **[`resolved_effects`](Self::resolved_effects)' argument, applied to the
10552    /// operator instead of to the resolve.** A debug view's pixels *are* data —
10553    /// an encoded normal, an occlusion channel, a cascade's colour code — and a
10554    /// curve is a monotone remapping of every one of them. `apps/alcove`'s
10555    /// `--bent-view` reads a normal back and compares it against the geometry's
10556    /// own, which under ACES is 49 code values out; the clamp is the identity on
10557    /// `0..=1`, so it is the operator that leaves a readout readable. A caller
10558    /// that wants a curved readout has none, deliberately: there is no reading
10559    /// it would make easier.
10560    #[must_use]
10561    pub const fn resolved_tonemap_curve(&self) -> tonemap::TonemapCurve {
10562        if matches!(self.debug_view(), DebugView::Shaded) {
10563            self.tonemap_curve
10564        } else {
10565            tonemap::TonemapCurve::Clamp
10566        }
10567    }
10568
10569    /// Which effects this **device** permits, which is the fourth layer and
10570    /// clamps last.
10571    ///
10572    /// Every one of them today — see [`ForwardRenderer::device_effects`], which
10573    /// is where that is argued per effect rather than asserted.
10574    #[must_use]
10575    pub const fn device_effects(&self) -> RenderEffects {
10576        self.device_effects
10577    }
10578
10579    /// Which [`GeometryPath`] this renderer was **built for** — not what the
10580    /// device reports, but what it actually built.
10581    ///
10582    /// The device may prefer a path below its capability ceiling when a higher
10583    /// one uses emulation. This reports the preference actually built, rather
10584    /// than the ceiling: [`GeometryPath::MeshShader`] here means
10585    /// `build` created a mesh pipeline out of `mesh_cluster.slang` and its
10586    /// cluster buffers, and created **no** raster pipeline for the pass to fall
10587    /// back to. So a frame this renderer drew came out of a mesh stage, and a
10588    /// silent degradation is not a state it has — which is the claim a golden
10589    /// image on its own could never make, because a fall-through draws the same
10590    /// picture.
10591    #[must_use]
10592    pub const fn geometry_path(&self) -> GeometryPath {
10593        match self.emit {
10594            EmitTail::Mesh => GeometryPath::MeshShader,
10595            EmitTail::Count => GeometryPath::IndirectCount,
10596            EmitTail::PerBatch => GeometryPath::IndirectPerBatch,
10597        }
10598    }
10599
10600    /// Whether this renderer **built** §3.5's per-cluster cull — an
10601    /// amplification stage in front of the mesh stage, rejecting a surviving
10602    /// instance's back-facing and off-screen clusters.
10603    ///
10604    /// `false` on the two indirect tails, which draw index ranges and have no
10605    /// stage to put it in, and on a device with `Features::MESH_SHADER` and no
10606    /// `Features::TASK_SHADER` — a real and supported state, not a degradation:
10607    /// that device draws every cluster of every surviving instance and the
10608    /// picture is the same one.
10609    ///
10610    /// The instance cull runs on every path either way, and is unaffected by
10611    /// this.
10612    ///
10613    /// It is asked of the renderer rather than of the device for
10614    /// [`ForwardRenderer::geometry_path`]'s reason: this reports what was
10615    /// built, so `true` means
10616    /// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count)'s
10617    /// cluster word is a number the frame produced rather than the zero the
10618    /// clearing pass left.
10619    #[must_use]
10620    pub const fn culls_clusters(&self) -> bool {
10621        self.culls_clusters
10622    }
10623
10624    /// Whether this renderer can choose **which level** of a
10625    /// [`Geometry::Dag`] mesh an object is drawn at, and therefore whether
10626    /// [`ForwardRenderer::add_instance`] may be given one at all.
10627    ///
10628    /// Topic 25's selection happens in the amplification stage where
10629    /// there is one, and in the cull pass where the tail is indirect and a level
10630    /// is an ordinary index range. **One device shape has neither**: a mesh stage
10631    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
10632    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) draws through
10633    /// `mesh_cluster.slang`'s un-amplified `meshMain`, which emits every cluster
10634    /// of the bucket — and a DAG's bucket is every level end to end, so the frame
10635    /// is several overlapping copies of one surface. That is a real and supported
10636    /// device state rather than a degradation, so this reports it instead of
10637    /// refusing to build.
10638    ///
10639    /// A [`Geometry::Flat`] mesh is one level and is unaffected: its clusters
10640    /// carry [`ClusterSelect::ALWAYS`] and every path draws it from every camera,
10641    /// which is why this is asked only before placing a DAG.
10642    ///
10643    /// Asked of the renderer rather than of the device for
10644    /// [`ForwardRenderer::culls_clusters`]' reason: it reports what was built.
10645    ///
10646    /// [`ClusterSelect::ALWAYS`]: crcbl_shaders::cluster_select::ClusterSelect::ALWAYS
10647    #[must_use]
10648    pub const fn selects_levels(&self) -> bool {
10649        !self.emit.is_mesh() || self.culls_clusters
10650    }
10651
10652    /// Which frame-in-flight slot the last [`ForwardRenderer::begin_frame`]
10653    /// rotated to, which is the slot every per-frame buffer is indexed by.
10654    #[must_use]
10655    pub const fn frame(&self) -> usize {
10656        self.frame
10657    }
10658
10659    /// What the last [`add_passes`](Self::add_passes) recorded, and what it
10660    /// cannot know.
10661    ///
10662    /// Zero draws until a frame has been built: this reports what was recorded,
10663    /// not what a frame would record.
10664    ///
10665    /// # The triangles are [`None`] here, on every geometry path
10666    ///
10667    /// Every draw this renderer records except the full-screen passes' and the
10668    /// debug draw layer's is **indirect**:
10669    /// the instance count and the index range live in the argument buffer
10670    /// `draw_gen.slang` wrote, so the CPU records the call and learns nothing
10671    /// about what it covered. That is true of
10672    /// [`GeometryPath::MeshShader`] and of
10673    /// both indirect tails alike — the three differ in which call is recorded,
10674    /// not in who decides the counts — so
10675    /// [`FrameCounters::triangles`](crate::counters::FrameCounters::triangles)
10676    /// is [`None`] whatever the device supports. Nothing counts a triangle on
10677    /// the GPU either, and a cluster count times a nominal triangles-per-cluster
10678    /// would read as authoritative and be neither.
10679    ///
10680    /// # The instances drawn come back off the GPU, a few frames late
10681    ///
10682    /// [`FrameCounters::drawn`](crate::counters::FrameCounters::drawn) is
10683    /// `cull.slang`'s survivor count, off [`crate::cull_stats`]'s delayed ring,
10684    /// plus the frame's direct draws — the ones here whose instance the CPU
10685    /// knows about, and the ones that are also in
10686    /// [`instances`](crate::counters::FrameCounters::instances). So the pair is
10687    /// comparable: the same quantity submitted and kept.
10688    ///
10689    /// **The camera's cull alone.** The shadow culls test other frustums and
10690    /// their survivors are counted into buffers of their own; adding them here
10691    /// would give a "drawn" larger than "submitted" on any frame with a shadow
10692    /// in it.
10693    ///
10694    /// It is [`None`] — the row says `indirect` — for the first few frames of a
10695    /// renderer's life, while the ring has not come round, and for good on a
10696    /// device that would not give out a readback.
10697    /// [`cull_frame`](crate::counters::FrameCounters::cull_frame) is which frame
10698    /// the number is about whenever there is one.
10699    ///
10700    /// [`FrameCounters::instances`](crate::counters::FrameCounters::instances)
10701    /// is known and is the plan's "submitted" half: the live instances
10702    /// [`add_passes`](Self::add_passes) hands the cull dispatches, plus the
10703    /// frame's direct draws — every full-screen pass's triangle and the debug
10704    /// draw layer's line list.
10705    #[must_use]
10706    pub fn counters(&self) -> FrameCounters {
10707        if self.recorded_draws == 0 {
10708            return FrameCounters::default();
10709        }
10710        let stats = self.cull_stats();
10711        let direct = self.direct_draws();
10712        FrameCounters {
10713            draws: self.recorded_draws,
10714            instances: self.instances.len() as u64 + direct,
10715            // Each direct draw is submitted and drawn, and none of them is in
10716            // the cull's count — they are draws of one instance, added on both
10717            // sides so the two halves of the row measure the same thing. Off the
10718            // frame that *was* recorded rather than off a constant, so a frame
10719            // with an effect switched off does not count a triangle it never
10720            // submitted.
10721            // Less what the occlusion cull's second phase rejected, which were
10722            // survivors of the frustum and were not drawn.
10723            drawn: stats
10724                .map(|stats| stats.instances.saturating_sub(stats.occlusion.late_rejects) + direct),
10725            triangles: None,
10726            // The survivors alone: the panel row is "clusters drawn", and the
10727            // frustum and cone rejection counts beside them are a different
10728            // question — `CullStats::clusters` carries all three for a caller
10729            // that wants the split, which `apps/quarry`'s own panel row is.
10730            clusters: stats
10731                .and_then(|stats| stats.clusters)
10732                .map(|cull| cull.survivors),
10733            cull_frame: stats.map(|stats| stats.frame),
10734        }
10735    }
10736
10737    /// The draws this renderer records **directly** — the ones whose instance
10738    /// the CPU knows about, as opposed to the indirect calls whose counts live
10739    /// in a buffer a shader wrote.
10740    ///
10741    /// Every full-screen pass's over-sized triangle, plus the debug draw
10742    /// layer's line list on a frame that has one. One instance each, which is
10743    /// why [`counters`](Self::counters) adds this to both halves of its
10744    /// submitted/drawn pair.
10745    fn direct_draws(&self) -> u64 {
10746        self.recorded_fullscreen * FULLSCREEN_DRAWS
10747            + self.recorded_debug_draw
10748            + self.recorded_tile_clears
10749            + self.recorded_water_draws
10750    }
10751
10752    /// What the camera's cull kept, on the frame the ring has reached.
10753    ///
10754    /// Topic 03 §3.6's one permitted readback, and [`None`] until it has come
10755    /// round — see [`crate::cull_stats`] for the latency and for what makes it
10756    /// free of any wait. [`counters`](Self::counters) is where this reaches the
10757    /// panel; it is exposed on its own because the frame number and the cluster
10758    /// word are both things a test asserts about directly.
10759    #[must_use]
10760    pub fn cull_stats(&self) -> Option<crate::cull_stats::CullStats> {
10761        self.cull_stats.as_ref().and_then(CullStatsRing::latest)
10762    }
10763
10764    /// Describes the imported swapchain image the frame ends in.
10765    ///
10766    /// A helper rather than something every caller writes, because getting
10767    /// `initial`/`final_state` wrong is exactly the hand-written barrier this
10768    /// slice removed: an acquired image's contents are undefined, and the
10769    /// compositor may only be handed one in [`ResourceState::Present`].
10770    #[must_use]
10771    pub fn present_target(
10772        image: crcbl_hal::ImageHandle,
10773        view: ImageViewHandle,
10774        format: Format,
10775        extent: (u32, u32),
10776    ) -> ImportedImage {
10777        ImportedImage {
10778            image,
10779            view,
10780            format,
10781            extent,
10782            initial: ResourceState::Undefined,
10783            // The acquire's semaphore, not a barrier, is what orders this frame
10784            // after the last use of the image — which is what makes `Undefined`
10785            // honest here and what makes it uncheckable. See `InitialClaim`.
10786            claim: InitialClaim::Acquired,
10787            final_state: ResourceState::Present,
10788        }
10789    }
10790
10791    /// Releases everything, in dependency order. The device must be idle.
10792    pub fn destroy(self, device: &dyn Device) {
10793        if let Some(stats) = self.cull_stats {
10794            stats.destroy(device);
10795        }
10796        // The cameras first: their groups name the scene's buffers, pages and
10797        // atlas below, and they own nothing the scene's groups name.
10798        for view in self.views.into_iter().flatten() {
10799            view.destroy(device);
10800        }
10801        self.primary.destroy(device);
10802        // After every view, whose grass and water groups name these buffers.
10803        self.grass.destroy(device);
10804        self.water.destroy(device);
10805        device.destroy_sampler(self.sampler);
10806        device.destroy_graphics_pipeline(self.tonemap_pipeline);
10807        device.destroy_pipeline_layout(self.tonemap_pipeline_layout);
10808        device.destroy_bind_group_layout(self.tonemap_layout);
10809
10810        for pipelines in [
10811            self.shadow_pipeline,
10812            self.depth_masked_pipeline,
10813            self.rsm_pipeline,
10814        ] {
10815            device.destroy_graphics_pipeline(pipelines.single);
10816            device.destroy_graphics_pipeline(pipelines.double);
10817        }
10818        device.destroy_graphics_pipeline(self.shadow_clear_pipeline);
10819        for groups in self.shadow_groups {
10820            for group in groups {
10821                device.destroy_bind_group(group);
10822            }
10823        }
10824        for buffers in self.shadow_uniforms {
10825            for buffer in buffers {
10826                device.destroy_buffer(buffer);
10827            }
10828        }
10829        for buffers in self.shadow_selection {
10830            for buffer in buffers {
10831                device.destroy_buffer(buffer);
10832            }
10833        }
10834        for draws in self.shadow_draws {
10835            draws.destroy(device);
10836        }
10837        device.destroy_sampler(self.shadow_sampler);
10838        device.destroy_image_view(self.shadow_atlas_view);
10839        device.destroy_image(self.shadow_atlas);
10840        device.destroy_image_view(self.shadow_placeholder_view);
10841        device.destroy_image(self.shadow_placeholder);
10842
10843        if let Some(grid) = self.ground_grid {
10844            grid.destroy(device);
10845        }
10846        // Nothing to release on a renderer nobody drew a segment through — see
10847        // [`crate::debug_draw`], whose pipeline is built on first use.
10848        self.debug_draw.destroy(device);
10849        self.atlas_viewer.destroy(device);
10850        self.ambient_occlusion_placeholder.destroy(device);
10851        self.contact_shadow_placeholder.destroy(device);
10852        self.probe_visibility_placeholder.destroy(device);
10853        if let Some(captured) = self.probe_visibility {
10854            captured.destroy(device);
10855        }
10856        self.specular_dfg.destroy(device);
10857        self.ltc_table.destroy(device);
10858        self.normal_page.destroy(device);
10859        self.mro_page.destroy(device);
10860        self.emissive_page.destroy(device);
10861
10862        device.destroy_graphics_pipeline(self.mesh_pipeline.single);
10863        device.destroy_graphics_pipeline(self.mesh_pipeline.double);
10864        // The one place the wireframe pair is released — `set_wireframe(.., false)`
10865        // deliberately is not, because this call is the one that requires an
10866        // idle device.
10867        if let Some(pipelines) = self.wireframe_pipeline {
10868            device.destroy_graphics_pipeline(pipelines.single);
10869            device.destroy_graphics_pipeline(pipelines.double);
10870        }
10871        device.destroy_pipeline_layout(self.mesh_pipeline_layout);
10872        device.destroy_bind_group_layout(self.mesh_layout);
10873        self.base_color_page.destroy(device);
10874        device.destroy_sampler(self.base_color_sampler);
10875        for retired in self.retired_pages {
10876            retired.destroy(device);
10877        }
10878        device.destroy_buffer(self.draw_constants);
10879        if let Some(clusters) = self.clusters {
10880            clusters.destroy(device);
10881        }
10882        // Before the probe table, because its bind groups name that table's
10883        // rows — the same ordering the light grid is under above.
10884        if let Some(gather) = self.probe_gather {
10885            gather.destroy(device);
10886        }
10887        self.probes.destroy(device);
10888        self.materials.destroy(device);
10889        self.instances.destroy(device);
10890        self.pool.destroy(device);
10891    }
10892}
10893
10894/// What the shadow pass a frame recorded would leave the image holding, held
10895/// until the frame after can say whether its body ran.
10896///
10897/// Topic 45's static-caching rung, per group: recording a pass
10898/// is not drawing one, so nothing here is believed until
10899/// [`ForwardRenderer::shadow_pass_ran`] carries this [`ShadowCommit::id`] back
10900/// out of the graph.
10901#[derive(Clone, Debug)]
10902struct ShadowCommit {
10903    /// The [`ForwardRenderer::shadow_pass_id`] the body publishes.
10904    id: u64,
10905    /// `[group]`: what the group's entry of
10906    /// [`ForwardRenderer::shadow_group_held`] becomes for every group the pass
10907    /// redraws, and [`None`] for the groups it holds.
10908    groups: Vec<Option<(u64, Vec3, f32)>>,
10909    /// The layout the pass draws under, where it clears the whole attachment —
10910    /// and [`None`] where it loads, because a loading pass leaves every tile it
10911    /// does not redraw exactly as it found it.
10912    layout: Option<Vec<shadow::TileRect>>,
10913}
10914
10915/// The shader modules a mesh pipeline is built from, with its entry points
10916/// already resolved.
10917///
10918/// **A type rather than a run of locals in `build`** because there are now two
10919/// callers: `build`, which makes the colour pipeline and its depth-only twin,
10920/// and [`ForwardRenderer::set_wireframe`], which makes the colour pipeline again
10921/// in [`PolygonMode::Line`] long after `build` released its modules. The
10922/// alternative was a second copy of a descriptor that names two modules, their
10923/// entry points, the colour targets and a depth state — the pair that drifts.
10924///
10925/// Short-lived: created, used to build pipelines, and [`MeshModules::destroy`]ed
10926/// in the same function. A module is not needed once the pipeline exists.
10927struct MeshModules {
10928    /// `mesh.slang`'s module — the vertex stage on the indirect path, and the
10929    /// fragment stage on both.
10930    mesh: ShaderModuleHandle,
10931    /// `vertexMain`, unused on the mesh-shader path.
10932    vertex: &'static str,
10933    /// `depthVertexMain`, which [`MeshModules::depth_pipeline`] takes in
10934    /// [`MeshModules::vertex`]'s place: the same transform off stream 0 of the
10935    /// vertex pool and no attribute region at all. Unused on the mesh-shader
10936    /// path, where the geometry stage is `mesh_cluster.slang`'s either way.
10937    depth_vertex: &'static str,
10938    /// `depthClearVertexMain`, which [`MeshModules::depth_clear_pipeline`]
10939    /// builds the tile clear from: three corners off `SV_VertexID` and no input
10940    /// at all, so it resets one tile of the atlas without reading a vertex.
10941    ///
10942    /// **The same stage on every path**, unlike the two above: a device with a
10943    /// mesh stage still has a vertex stage, and a clear that produced no
10944    /// geometry is a primitive, not a cluster.
10945    depth_clear_vertex: &'static str,
10946    fragment: &'static str,
10947    /// `depthMaskedFragmentMain`, which [`MeshModules::depth_masked_pipeline`]
10948    /// puts *behind* [`MeshModules::vertex`] — the alpha mask and no target at
10949    /// all.
10950    ///
10951    /// **The same stage on both paths**, unlike the two vertex entry points
10952    /// above: it reads `mesh.slang`'s own `VertexOutput`, which is what
10953    /// `vertexMain` writes on the raster path and what `mesh_cluster.slang`'s
10954    /// mesh stage writes on the mesh one. So the cutout is one comparison in one
10955    /// place rather than one per geometry path.
10956    depth_masked_fragment: &'static str,
10957    /// `rsmFragmentMain`, which [`MeshModules::rsm_pipeline`] takes in
10958    /// [`MeshModules::fragment`]'s place: the same geometry stage, three targets
10959    /// describing the surface rather than shading it.
10960    ///
10961    /// **The reason the shaded stage above is looked up by name.** A module with
10962    /// two fragment entry points has no unambiguous one, which is what `entry`
10963    /// answers `None` for.
10964    rsm_fragment: &'static str,
10965    /// `mesh_cluster.slang`'s, on the mesh-shader path alone.
10966    cluster: Option<ClusterStages>,
10967}
10968
10969/// The geometry half of a mesh-shader pipeline: `mesh_cluster.slang`'s module
10970/// and the stages taken out of it.
10971struct ClusterStages {
10972    /// The module the mesh stage is built from, and the one the task stage is,
10973    /// which are **two modules rather than one**.
10974    ///
10975    /// `mesh_cluster.slang` compiles to a combined module carrying every entry
10976    /// point and to one module per stage, and these are the per-stage ones. A
10977    /// module holding a task entry point and its mesh partner carries two
10978    /// `TaskPayloadWorkgroupEXT` variables — the task writes one, the mesh stage
10979    /// reads the other — and an NVIDIA driver then delivers a payload of zeroes,
10980    /// which draws cluster 0 of instance slot 0 of every bucket and nothing
10981    /// else. See `crcbl_shaders::EntryPoint`.
10982    mesh_module: ShaderModuleHandle,
10983    /// The task stage's own module, on the same terms. [`None`] exactly when
10984    /// [`task`](Self::task) is.
10985    task_module: Option<ShaderModuleHandle>,
10986    /// Which of the module's two mesh entry points this path builds — the
10987    /// amplified one where the device has a task stage to feed it.
10988    mesh: &'static str,
10989    /// §3.5's per-cluster cull, where the device has the stage to run it in.
10990    /// [`None`] is not a degradation: `meshMain` draws the same picture out of
10991    /// the same clusters, having rejected none of them, which is what a device
10992    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
10993    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) gets.
10994    task: Option<&'static str>,
10995}
10996
10997impl MeshModules {
10998    /// **Three targets, one fragment stage.** `mesh.slang`'s `FragmentOutput`
10999    /// writes the shaded colour, then topic 47's
11000    /// reflectivity channel, then topic 43 §9's motion
11001    /// vector — and both pipeline shapes name that same entry point, so each
11002    /// target is one more element of this array and not a second pipeline, a
11003    /// second entry point or a new interpolant. The refusal the AO section
11004    /// records was about the depth prepass, which has no fragment stage and no
11005    /// colour target at all; it does not reach this array.
11006    ///
11007    /// Element order is `SV_Target` order, and each format is the one the
11008    /// matching `TransientImageDesc` creates: a pipeline built for a format the
11009    /// attachment is not in is a validation error on WebGPU and a silent
11010    /// reinterpretation elsewhere.
11011    const COLOR_TARGETS: [ColorTargetState; 3] = [
11012        ColorTargetState::opaque(Format::Rgba16Float),
11013        ColorTargetState::opaque(Format::Rgba8Unorm),
11014        ColorTargetState::opaque(MOTION_FORMAT),
11015    ];
11016
11017    /// **Three targets again, and a different three.** `mesh.slang`'s
11018    /// `RsmOutput` writes the surface's diffuse albedo, its world normal encoded
11019    /// `n * 0.5 + 0.5`, and its world position with a coverage flag in `w` —
11020    /// which is what the irradiance probes' gather needs of a
11021    /// texel and nothing more.
11022    ///
11023    /// Element order is `SV_Target` order and each format is the one the
11024    /// matching description in [`crate::rsm`] creates: a pipeline built for a
11025    /// format the attachment is not in is a validation error on WebGPU and a
11026    /// silent reinterpretation elsewhere. `the_targets_carry_the_formats_the_shader_writes`
11027    /// in that module is the other half of the pair.
11028    const RSM_TARGETS: [ColorTargetState; 3] = [
11029        ColorTargetState::opaque(Format::Rgba16Float),
11030        ColorTargetState::opaque(Format::Rgba8Unorm),
11031        ColorTargetState::opaque(Format::Rgba32Float),
11032    ];
11033
11034    /// Invocations per mesh workgroup, which is `mesh_cluster.slang`'s
11035    /// `[numthreads(THREADS, 1, 1)]` — and `THREADS` is
11036    /// `MAX_CLUSTER_VERTICES`, one lane per vertex a cluster can hold.
11037    ///
11038    /// Taken from the crate that owns the shader source rather than written
11039    /// out, as
11040    /// [`MeshPipelineDesc::mesh_workgroup_size`](crcbl_hal::MeshPipelineDesc::mesh_workgroup_size)
11041    /// requires: only Metal reads this field, so a literal that disagreed with
11042    /// the shader would launch the wrong number of threads on one backend and
11043    /// nowhere else.
11044    const MESH_WORKGROUP_SIZE: [u32; 3] =
11045        [crcbl_shaders::meshlet::MAX_CLUSTER_VERTICES as u32, 1, 1];
11046
11047    /// Invocations per task workgroup: `taskMain` is
11048    /// `[numthreads(TASK_LANES, 1, 1)]`, one lane per (cluster, instance slot)
11049    /// pair of its chunk. Taken from the crate that owns the shader, on
11050    /// [`MESH_WORKGROUP_SIZE`](Self::MESH_WORKGROUP_SIZE)'s terms.
11051    const TASK_WORKGROUP_SIZE: [u32; 3] = [crcbl_shaders::meshlet::TASK_LANES, 1, 1];
11052
11053    /// Loads whichever modules `emit` needs and resolves their entry points.
11054    ///
11055    /// # Errors
11056    ///
11057    /// [`HalError::ShaderCompilation`] if the committed manifest names no such
11058    /// entry point, and [`HalError`] from either module. A failure after the
11059    /// first module was created releases it rather than leaking it.
11060    fn new(device: &dyn Device, emit: EmitTail, culls_clusters: bool) -> Result<Self, HalError> {
11061        // Entry points resolved before the module exists: a manifest that
11062        // disagreed with the SPIR-V would otherwise fail inside the descriptor
11063        // literal, with the module already created and nothing holding it.
11064        //
11065        // **The vertex stage is named rather than looked up by stage**, for
11066        // `mesh_cluster.slang`'s reason below: since the depth-only stage landed
11067        // this module has two vertex entry points, and a stage lookup answers
11068        // `None` for two matches. Which of the two a pipeline names is the whole
11069        // of what the split-stream vertex pool bought.
11070        let vertex = named_entry(&MESH, "vertexMain", Stage::Vertex)?;
11071        let depth_vertex = named_entry(&MESH, "depthVertexMain", Stage::Vertex)?;
11072        let depth_clear_vertex = named_entry(&MESH, "depthClearVertexMain", Stage::Vertex)?;
11073        // **Named rather than looked up by stage, on the vertex entry points'
11074        // terms exactly.** Since the irradiance probes' updater
11075        // landed, this module has *two* fragment entry points — the shaded one
11076        // and `rsmFragmentMain` — and `entry` answers `None` for two matches, so
11077        // a stage lookup here refuses the build outright with "exposes no
11078        // unambiguous Fragment entry point".
11079        let fragment = named_entry(&MESH, "fragmentMain", Stage::Fragment)?;
11080        let depth_masked_fragment = named_entry(&MESH, "depthMaskedFragmentMain", Stage::Fragment)?;
11081        let rsm_fragment = named_entry(&MESH, "rsmFragmentMain", Stage::Fragment)?;
11082        // **Named rather than looked up by stage**, because the module has two
11083        // mesh entry points and a stage lookup would refuse an ambiguous one —
11084        // see `named_entry`. Which of the two this names is the whole of the
11085        // amplification decision.
11086        let cluster_stages = emit
11087            .is_mesh()
11088            .then(|| {
11089                let mesh = named_entry(
11090                    &MESH_CLUSTER,
11091                    if culls_clusters {
11092                        "amplifiedMeshMain"
11093                    } else {
11094                        "meshMain"
11095                    },
11096                    Stage::Mesh,
11097                )?;
11098                let task = culls_clusters
11099                    .then(|| named_entry(&MESH_CLUSTER, "taskMain", Stage::Task))
11100                    .transpose()?;
11101                Ok::<_, HalError>((mesh, task))
11102            })
11103            .transpose()?;
11104
11105        let mesh = device.create_shader_module(&ShaderModuleDesc {
11106            label: Some("mesh.slang"),
11107            spirv: MESH.spirv(),
11108            wgsl: MESH.wgsl(),
11109            msl: MESH.msl(),
11110            // **Both containers, and still one module.** A DXIL container holds
11111            // exactly one entry point, so this is a list where its three
11112            // neighbours are single artifacts; the backend that consumes it
11113            // picks the container named by the stage it is building. Nothing
11114            // here branches on a backend, and the three that ignore DXIL see
11115            // the same module they always did.
11116            dxil: &MESH.dxil_containers(),
11117        })?;
11118        let cluster = match cluster_stages {
11119            None => None,
11120            Some((cluster_mesh, task)) => {
11121                // **The mesh stage's module is `mesh_cluster.slang`; the
11122                // fragment stage's is still `mesh.slang`'s.** A pipeline takes a
11123                // module per stage, so the shading — Lambert, the GGX lobe, the
11124                // material row, the page sample — is the same code both paths
11125                // run rather than a copy that agrees today.
11126                // `mesh_cluster.slang`'s header carries the argument, and its
11127                // `VertexOutput` is what the two agree through.
11128                // **One module per stage, each carrying that stage's own
11129                // SPIR-V.** Only the SPIR-V differs between them: MSL is one
11130                // artifact per source whatever the stage, and a DXIL container
11131                // is already per entry point, so both are handed over unchanged
11132                // and the backends that read them see what they always did.
11133                let stage_module = |entry_point: &str| {
11134                    device.create_shader_module(&ShaderModuleDesc {
11135                        label: Some("mesh_cluster.slang"),
11136                        // The combined module where this stage has none of its
11137                        // own, which is every stage of every other shader.
11138                        spirv: MESH_CLUSTER
11139                            .spirv_for(entry_point)
11140                            .unwrap_or_else(|| MESH_CLUSTER.spirv()),
11141                        // `None`, and it is the whole reason this is a second
11142                        // file: WGSL cannot express a mesh stage at all.
11143                        wgsl: MESH_CLUSTER.wgsl(),
11144                        msl: MESH_CLUSTER.msl(),
11145                        dxil: &MESH_CLUSTER.dxil_containers(),
11146                    })
11147                };
11148                let mesh_module = match stage_module(cluster_mesh) {
11149                    Ok(module) => module,
11150                    Err(error) => {
11151                        device.destroy_shader_module(mesh);
11152                        return Err(error);
11153                    }
11154                };
11155                let task_module = match task.map(stage_module).transpose() {
11156                    Ok(module) => module,
11157                    Err(error) => {
11158                        device.destroy_shader_module(mesh);
11159                        device.destroy_shader_module(mesh_module);
11160                        return Err(error);
11161                    }
11162                };
11163                Some(ClusterStages {
11164                    mesh_module,
11165                    task_module,
11166                    mesh: cluster_mesh,
11167                    task,
11168                })
11169            }
11170        };
11171        Ok(Self {
11172            mesh,
11173            vertex,
11174            depth_vertex,
11175            depth_clear_vertex,
11176            fragment,
11177            depth_masked_fragment,
11178            rsm_fragment,
11179            cluster,
11180        })
11181    }
11182
11183    /// The rasteriser state every pipeline shape here shares, because the only
11184    /// things that differ between them are which stage produces the geometry and
11185    /// which side of it survives.
11186    ///
11187    /// [`CullMode::Back`] is what a single-sided bucket asks for, and it has
11188    /// been on from the first mesh. The cube's winding is asserted by
11189    /// `crcbl-shaders`' own tests, so a face that vanished would be a *test*
11190    /// failure rather than a debugging session — and a mesh drawn without
11191    /// culling would let a winding mistake survive into P7's geometry pool. The
11192    /// mesh stage emits its corner triples in the index buffer's own order, so
11193    /// the winding it produces is the same one.
11194    ///
11195    /// [`CullMode::None`] is what a double-sided bucket asks for — glTF 2.0
11196    /// §3.9.6's first half — and the twin built with it is the only way a back
11197    /// face reaches `mesh.slang` at all. See [`SidedPipelines`].
11198    fn primitive(polygon_mode: PolygonMode, cull_mode: CullMode) -> PrimitiveState {
11199        PrimitiveState {
11200            cull_mode,
11201            polygon_mode,
11202            ..PrimitiveState::default()
11203        }
11204    }
11205
11206    /// What a pipeline built with `cull` adds to its label, so a capture and
11207    /// `crcbl_hal::null`'s recorder tell a [`SidedPipelines::double`] twin from
11208    /// the [`SidedPipelines::single`] it was built beside.
11209    ///
11210    /// Empty for the culling modes, because those pipelines' labels are the ones
11211    /// every existing capture and every test lookup already names.
11212    fn side_label(cull: CullMode) -> &'static str {
11213        match cull {
11214            CullMode::None => " double-sided",
11215            CullMode::Front | CullMode::Back => "",
11216        }
11217    }
11218
11219    /// Both sides of one pipeline shape, single-sided first, **created and not
11220    /// yet unwrapped**.
11221    ///
11222    /// The results rather than the pair, because that is the discipline `build`
11223    /// keeps for every pipeline it makes: everything is created while the
11224    /// modules are alive, the modules are released once, and only then is each
11225    /// successful result handed to rollback before any error is propagated. A
11226    /// helper that unwrapped here would have to drop a handle it had already
11227    /// created when its twin failed, and nothing would ever destroy it.
11228    fn sided(
11229        mut build: impl FnMut(CullMode) -> Result<GraphicsPipelineHandle, HalError>,
11230    ) -> [Result<GraphicsPipelineHandle, HalError>; 2] {
11231        [build(CullMode::Back), build(CullMode::None)]
11232    }
11233
11234    /// Milestone 3's depth test, and the seam's default is already reversed-Z:
11235    /// `Greater` against `D32Float`, writes on. The clear value that agrees with
11236    /// it comes from the graph (`PassBuilder::clear_depth`), and the projection
11237    /// matrix that agrees with **both** comes from [`crate::camera`].
11238    fn depth_stencil() -> Option<DepthStencilState> {
11239        Some(DepthStencilState::default())
11240    }
11241
11242    /// The colour pass's depth state, which is not the same shape as
11243    /// [`MeshModules::depth_stencil`] because the depth prepass has already
11244    /// drawn this geometry.
11245    ///
11246    /// **Filled: [`DepthStencilState::equal_depth_read_only`], so the shading is
11247    /// paid for once per pixel.** The prepass runs the same draws through
11248    /// `depthVertexMain` — or, on the mesh path, through the very same geometry
11249    /// stage — so the depth already in the attachment is this pass's own answer,
11250    /// and a `GreaterOrEqual` test with writes off keeps exactly the fragments
11251    /// that would have won the write. What it removes is the clustered-forward
11252    /// shading of every fragment a nearer one goes on to cover.
11253    ///
11254    /// **Lines: the writing default, because a wireframe is not the geometry the
11255    /// prepass drew.** [`PolygonMode::Line`] rasterises the triangle's edges,
11256    /// and an edge pixel's depth is interpolated along the line rather than
11257    /// across the face, so testing it for equality against a filled prepass
11258    /// rejects most of the wireframe. That frame keeps the pass shape this pass
11259    /// had before the prepass existed — see the colour pass's depth attachment,
11260    /// which branches on the same condition.
11261    fn color_depth_stencil(polygon_mode: PolygonMode) -> Option<DepthStencilState> {
11262        match polygon_mode {
11263            PolygonMode::Fill => Some(DepthStencilState::equal_depth_read_only(Format::D32Float)),
11264            _ => Self::depth_stencil(),
11265        }
11266    }
11267
11268    /// The colour pass's pipeline, filled or wireframe, culling back faces or
11269    /// nothing.
11270    ///
11271    /// `label` names the caller — `"forward"` for the frame's own, `"wireframe"`
11272    /// for [`ForwardRenderer::set_wireframe`]'s — and [`MeshModules::side_label`]
11273    /// names the side, so a capture tells all four apart.
11274    fn color_pipeline(
11275        &self,
11276        device: &dyn Device,
11277        layout: PipelineLayoutHandle,
11278        polygon_mode: PolygonMode,
11279        cull: CullMode,
11280        label: &str,
11281    ) -> Result<GraphicsPipelineHandle, HalError> {
11282        let primitive = Self::primitive(polygon_mode, cull);
11283        let depth_stencil = Self::color_depth_stencil(polygon_mode);
11284        let side = Self::side_label(cull);
11285        let fragment = Some(ShaderEntry {
11286            module: self.mesh,
11287            entry_point: self.fragment,
11288        });
11289        match self.cluster.as_ref() {
11290            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11291                label: Some(&format!("{label}{side} mesh cluster")),
11292                layout,
11293                task: cluster
11294                    .task
11295                    .zip(cluster.task_module)
11296                    .map(|(entry_point, module)| ShaderEntry {
11297                        module,
11298                        entry_point,
11299                    }),
11300                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11301                mesh: ShaderEntry {
11302                    module: cluster.mesh_module,
11303                    entry_point: cluster.mesh,
11304                },
11305                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11306                fragment,
11307                primitive,
11308                depth_stencil,
11309                multisample: MultisampleState::default(),
11310                color_targets: &Self::COLOR_TARGETS,
11311            }),
11312            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11313                label: Some(&format!("{label}{side} mesh")),
11314                layout,
11315                vertex: ShaderEntry {
11316                    module: self.mesh,
11317                    entry_point: self.vertex,
11318                },
11319                fragment,
11320                primitive,
11321                depth_stencil,
11322                multisample: MultisampleState::default(),
11323                color_targets: &Self::COLOR_TARGETS,
11324            }),
11325        }
11326    }
11327
11328    /// The depth-only twin of [`MeshModules::color_pipeline`], built out of the
11329    /// same modules and the same layout: no fragment stage, no colour target,
11330    /// and a vertex stage that fetches stream 0 of the vertex pool alone.
11331    ///
11332    /// **The transform is identical and the fetch is not, which is the point.**
11333    /// Topic 18 asks for a shadow pass "identical on every `GeometryPath` —
11334    /// depth pass plus whatever emit tail the device selected", and what makes
11335    /// that work is a frame block whose `view_proj` is the cascade's matrix
11336    /// rather than a second transform path: a cascade that disagreed with the
11337    /// colour pass about where a vertex is would produce shadows that do not
11338    /// line up with their casters, which is indistinguishable from a bias
11339    /// problem. `depthVertexMain` is that same clip position written the same
11340    /// way, with everything the discarded varyings needed — the attribute
11341    /// region and the previous frame's position — left unread;
11342    /// topic 43 §2 split the pool for exactly this
11343    /// pass, and this is where it is spent.
11344    ///
11345    /// **The mesh-shader path still runs the colour pipeline's geometry
11346    /// stage.** `mesh_cluster.slang` emits one `VertexOutput`, so a depth-only
11347    /// mesh stage is a second entry point in that module and its own rung; a
11348    /// device with a mesh stage goes on reading whole vertices here.
11349    ///
11350    /// Always [`PolygonMode::Fill`]: it fills the shadow atlas and the depth
11351    /// prepass, and depth drawn as lines is depth with holes in it — which the
11352    /// occlusion pair would read as geometry that is not there.
11353    fn depth_pipeline(
11354        &self,
11355        device: &dyn Device,
11356        layout: PipelineLayoutHandle,
11357        cull: CullMode,
11358    ) -> Result<GraphicsPipelineHandle, HalError> {
11359        let primitive = Self::primitive(PolygonMode::Fill, cull);
11360        let side = Self::side_label(cull);
11361        match self.cluster.as_ref() {
11362            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11363                label: Some(&format!("shadow cascade{side} mesh cluster")),
11364                layout,
11365                task: cluster
11366                    .task
11367                    .zip(cluster.task_module)
11368                    .map(|(entry_point, module)| ShaderEntry {
11369                        module,
11370                        entry_point,
11371                    }),
11372                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11373                mesh: ShaderEntry {
11374                    module: cluster.mesh_module,
11375                    entry_point: cluster.mesh,
11376                },
11377                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11378                fragment: None,
11379                primitive,
11380                depth_stencil: Self::depth_stencil(),
11381                multisample: MultisampleState::default(),
11382                color_targets: &[],
11383            }),
11384            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11385                label: Some(&format!("shadow cascade{side}")),
11386                layout,
11387                vertex: ShaderEntry {
11388                    module: self.mesh,
11389                    entry_point: self.depth_vertex,
11390                },
11391                fragment: None,
11392                primitive,
11393                depth_stencil: Self::depth_stencil(),
11394                multisample: MultisampleState::default(),
11395                color_targets: &[],
11396            }),
11397        }
11398    }
11399
11400    /// [`MeshModules::depth_pipeline`] with an alpha mask in it: the same depth
11401    /// state and the same absent colour targets, `depthMaskedFragmentMain`
11402    /// behind the geometry stage, and [`MeshModules::vertex`] in
11403    /// [`MeshModules::depth_vertex`]'s place.
11404    ///
11405    /// Topic 43 §3's cutout, in the two passes that
11406    /// write depth without shading. A masked instance drawn through the pipeline
11407    /// above writes its full silhouette: it occludes itself through the hole it
11408    /// can see through, and it casts the shadow of a leaf that has none.
11409    ///
11410    /// **The vertex stage is the colour pass's, and it has to be.** A cutout
11411    /// needs the UV, which lives in the attribute region `depthVertexMain`
11412    /// exists not to read — so this stage reads a whole vertex, exactly as
11413    /// [`MeshModules::rsm_pipeline`] does beside it and for the same reason.
11414    /// What that buys is one fragment entry point for both geometry paths: the
11415    /// mesh path already emits `mesh.slang`'s `VertexOutput`, so the mask is
11416    /// compared in one place rather than once per path.
11417    ///
11418    /// **Which draws are recorded with it is the bucket's own material mode**,
11419    /// not the frame's — see [`ForwardRenderer::depth_partitions`]. A scene that
11420    /// masks nothing has no bucket in this partition, records through the
11421    /// pipeline above with no fragment stage anywhere, and costs exactly what it
11422    /// cost before this one existed; a scene that masks one mesh pays the
11423    /// fragment stage for that mesh's draws alone.
11424    fn depth_masked_pipeline(
11425        &self,
11426        device: &dyn Device,
11427        layout: PipelineLayoutHandle,
11428        cull: CullMode,
11429    ) -> Result<GraphicsPipelineHandle, HalError> {
11430        let primitive = Self::primitive(PolygonMode::Fill, cull);
11431        let side = Self::side_label(cull);
11432        let fragment = Some(ShaderEntry {
11433            module: self.mesh,
11434            entry_point: self.depth_masked_fragment,
11435        });
11436        match self.cluster.as_ref() {
11437            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11438                label: Some(&format!("shadow cascade masked{side} mesh cluster")),
11439                layout,
11440                task: cluster
11441                    .task
11442                    .zip(cluster.task_module)
11443                    .map(|(entry_point, module)| ShaderEntry {
11444                        module,
11445                        entry_point,
11446                    }),
11447                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11448                mesh: ShaderEntry {
11449                    module: cluster.mesh_module,
11450                    entry_point: cluster.mesh,
11451                },
11452                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11453                fragment,
11454                primitive,
11455                depth_stencil: Self::depth_stencil(),
11456                multisample: MultisampleState::default(),
11457                color_targets: &[],
11458            }),
11459            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11460                label: Some(&format!("shadow cascade masked{side}")),
11461                layout,
11462                vertex: ShaderEntry {
11463                    module: self.mesh,
11464                    entry_point: self.vertex,
11465                },
11466                fragment,
11467                primitive,
11468                depth_stencil: Self::depth_stencil(),
11469                multisample: MultisampleState::default(),
11470                color_targets: &[],
11471            }),
11472        }
11473    }
11474
11475    /// The reflective shadow map's pipeline: the colour pipeline's geometry
11476    /// stage, `rsmFragmentMain` in the shaded stage's place, and
11477    /// [`MeshModules::RSM_TARGETS`] in [`MeshModules::COLOR_TARGETS`]'s.
11478    ///
11479    /// The irradiance probes' updater draws the sun's near
11480    /// cascade a second time through this — see [`crate::rsm`], which owns the
11481    /// attachments, and `ForwardRenderer::add_shadow_pass`, which records the
11482    /// pass out of that cascade's own bind group and its own already-generated
11483    /// draws.
11484    ///
11485    /// **[`MeshModules::vertex`] and not [`MeshModules::depth_vertex`]**, unlike
11486    /// the cascade this rides beside: a fragment stage that writes a world
11487    /// position, a normal and an albedo needs the varyings `depthVertexMain`
11488    /// exists to leave unread. On the mesh path it is the very same geometry
11489    /// stage the colour pass runs, for the reason `depth_pipeline` gives.
11490    ///
11491    /// **Its own depth, written**, rather than the colour pass's read-only
11492    /// equality test: nothing has drawn this view's depth before it, and the
11493    /// pass is what decides which surface a texel of the map holds.
11494    fn rsm_pipeline(
11495        &self,
11496        device: &dyn Device,
11497        layout: PipelineLayoutHandle,
11498        cull: CullMode,
11499    ) -> Result<GraphicsPipelineHandle, HalError> {
11500        let primitive = Self::primitive(PolygonMode::Fill, cull);
11501        let side = Self::side_label(cull);
11502        let fragment = Some(ShaderEntry {
11503            module: self.mesh,
11504            entry_point: self.rsm_fragment,
11505        });
11506        match self.cluster.as_ref() {
11507            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11508                label: Some(&format!("rsm{side} mesh cluster")),
11509                layout,
11510                task: cluster
11511                    .task
11512                    .zip(cluster.task_module)
11513                    .map(|(entry_point, module)| ShaderEntry {
11514                        module,
11515                        entry_point,
11516                    }),
11517                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11518                mesh: ShaderEntry {
11519                    module: cluster.mesh_module,
11520                    entry_point: cluster.mesh,
11521                },
11522                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11523                fragment,
11524                primitive,
11525                depth_stencil: Self::depth_stencil(),
11526                multisample: MultisampleState::default(),
11527                color_targets: &Self::RSM_TARGETS,
11528            }),
11529            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11530                label: Some(&format!("rsm{side}")),
11531                layout,
11532                vertex: ShaderEntry {
11533                    module: self.mesh,
11534                    entry_point: self.vertex,
11535                },
11536                fragment,
11537                primitive,
11538                depth_stencil: Self::depth_stencil(),
11539                multisample: MultisampleState::default(),
11540                color_targets: &Self::RSM_TARGETS,
11541            }),
11542        }
11543    }
11544
11545    /// The pipeline that resets one tile of the shadow atlas, so a pass can keep
11546    /// some tiles and redraw others.
11547    ///
11548    /// Topic 45's cadence rung needs a tile cleared on its own,
11549    /// and the attachment's [`LoadOp`] cannot do it — a clear there covers the
11550    /// whole image, and the region-bounded forms are not portable. This is the
11551    /// portable statement of the same thing: `mesh.slang`'s
11552    /// `depthClearVertexMain` covers the viewport the shadow pass has already
11553    /// set over the tile, and the depth state below writes
11554    /// [`depth::CLEAR`](crcbl_hal::depth) over whatever was there.
11555    ///
11556    /// **[`CompareOp::Always`] and writes on**, which is the pair that makes it a
11557    /// clear rather than a draw: the tile holds the previous frame's depths, and
11558    /// under the engine's [`CompareOp::Greater`] a clear value of zero would
11559    /// fail against every one of them and leave the tile exactly as it was.
11560    ///
11561    /// **[`CullMode::None`]**, unlike [`MeshModules::primitive`]: the triangle
11562    /// is generated from `SV_VertexID` rather than wound by an artist, so a
11563    /// culling rule meant for scene geometry would decide whether the clear
11564    /// happens at all.
11565    ///
11566    /// **A vertex pipeline on every path**, including the mesh-shader one: a
11567    /// device with a mesh stage still has a vertex stage, and the clear has no
11568    /// clusters to descend.
11569    fn depth_clear_pipeline(
11570        &self,
11571        device: &dyn Device,
11572        layout: PipelineLayoutHandle,
11573    ) -> Result<GraphicsPipelineHandle, HalError> {
11574        device.create_graphics_pipeline(&GraphicsPipelineDesc {
11575            label: Some("shadow tile clear"),
11576            // The mesh layout, so binding this pipeline in the middle of the
11577            // shadow pass does not disturb the bind group the draws around it
11578            // are recorded with. The stage reads none of it.
11579            layout,
11580            vertex: ShaderEntry {
11581                module: self.mesh,
11582                entry_point: self.depth_clear_vertex,
11583            },
11584            fragment: None,
11585            primitive: PrimitiveState {
11586                cull_mode: CullMode::None,
11587                polygon_mode: PolygonMode::Fill,
11588                ..PrimitiveState::default()
11589            },
11590            depth_stencil: Some(DepthStencilState {
11591                depth_compare: CompareOp::Always,
11592                ..DepthStencilState::default()
11593            }),
11594            multisample: MultisampleState::default(),
11595            color_targets: &[],
11596        })
11597    }
11598
11599    /// Releases every module. The pipelines built from them stay valid.
11600    fn destroy(self, device: &dyn Device) {
11601        device.destroy_shader_module(self.mesh);
11602        if let Some(cluster) = self.cluster {
11603            device.destroy_shader_module(cluster.mesh_module);
11604            if let Some(task) = cluster.task_module {
11605                device.destroy_shader_module(task);
11606            }
11607        }
11608    }
11609}
11610
11611/// The entry point for `stage`, or an error naming the shader.
11612///
11613/// Unreachable in practice — `crcbl-shaders`' own tests assert both modules
11614/// expose both stages — but the alternative is an `expect` in engine code.
11615fn entry(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&'static str, HalError> {
11616    shader.entry_point(stage).ok_or_else(|| {
11617        HalError::ShaderCompilation(format!(
11618            "{}.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and its \
11619             manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11620            shader.name()
11621        ))
11622    })
11623}
11624
11625/// The entry point called `name`, checked to be `stage`'s.
11626///
11627/// [`entry`] cannot serve `mesh_cluster.slang`: it has **two** mesh entry
11628/// points — one behind the amplification stage and one without it — and a
11629/// lookup by stage answers `None` for two matches rather than picking one, for
11630/// the good reason that picking one would draw the wrong geometry.
11631///
11632/// The stage is still checked rather than taken on trust: a name that resolved
11633/// to the wrong stage would be a pipeline built with an amplification stage in
11634/// its mesh slot, and the failure would arrive as a driver error rather than as
11635/// this sentence.
11636pub(crate) fn named_entry(
11637    shader: &crcbl_shaders::Shader,
11638    name: &'static str,
11639    stage: Stage,
11640) -> Result<&'static str, HalError> {
11641    let found = shader
11642        .entry_points()
11643        .iter()
11644        .find(|entry| entry.name() == name && entry.stage() == stage);
11645    found.map(crcbl_shaders::EntryPoint::name).ok_or_else(|| {
11646        HalError::ShaderCompilation(format!(
11647            "{}.slang exposes no {stage:?} entry point called `{name}`; the committed SPIR-V and \
11648             its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11649            shader.name()
11650        ))
11651    })
11652}
11653
11654// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
11655#[cfg(all(test, not(target_arch = "wasm32")))]
11656mod tests {
11657    mod instance_upload;
11658    mod load_service;
11659    mod page_reload;
11660    mod shadow_reach;
11661
11662    use super::*;
11663    use crate::effects::{Antialiasing, EffectOverride};
11664    use crate::scene::{
11665        DEMO_CUBE, DEMO_DUNES, DEMO_OPEN_BOX, DEMO_PYRAMID, DEMO_TEXTURED, DEMO_TINTED,
11666        DEMO_UNTINTED,
11667    };
11668    use crcbl_hal::null::{Event, NullInstance, ObjectKind, Recorder};
11669    use crcbl_hal::{DeviceDesc, DrawIndirect, Features, Instance, QueueKind};
11670
11671    #[test]
11672    fn refused_mesh_color_pipelines_release_successful_depth_pipelines() {
11673        let recorder = Recorder::new();
11674        let mut limits = crcbl_hal::Limits::desktop();
11675        limits.max_color_attachments = 2;
11676        let features = Features::COMPUTE | Features::MESH_SHADER;
11677        let instance = NullInstance::new(crcbl_hal::DeviceCaps { features, limits })
11678            .with_recorder(recorder.clone());
11679        let device = instance
11680            .create_device(&DeviceDesc {
11681                label: None,
11682                adapter: crcbl_hal::AdapterId(0),
11683                required_features: features,
11684                optional_features: Features::empty(),
11685                compatible_surface: None,
11686            })
11687            .unwrap();
11688        let queue = device.queue(QueueKind::Graphics).unwrap();
11689        let before = recorder.total_live_objects();
11690        let error = ForwardRenderer::with_scene_on_path(
11691            device.as_ref(),
11692            queue,
11693            Format::Rgba8UnormSrgb,
11694            &scene::demo(),
11695            GeometryPath::MeshShader,
11696        )
11697        .expect_err("three-target color pipelines must be refused");
11698        assert!(
11699            error
11700                .to_string()
11701                .contains("3 colour targets exceeds max_color_attachments 2"),
11702            "{error}"
11703        );
11704        assert!(
11705            recorder.events().iter().any(|event| matches!(
11706                event,
11707                Event::Created {
11708                    kind: ObjectKind::GraphicsPipeline,
11709                    ..
11710                }
11711            )),
11712            "the refusal must exercise cleanup of successful pipelines"
11713        );
11714        assert_eq!(
11715            recorder.total_live_objects(),
11716            before,
11717            "partial pipeline construction leaked resources"
11718        );
11719        recorder.assert_valid();
11720    }
11721
11722    #[test]
11723    fn exact_geometry_path_overrides_preference_and_default_keeps_it() {
11724        let recorder = Recorder::new();
11725        let instance = NullInstance::gpu_driven()
11726            .with_geometry_preference(GeometryPath::IndirectPerBatch)
11727            .with_recorder(recorder.clone());
11728        let device = instance
11729            .create_device(&DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)))
11730            .unwrap();
11731        let queue = device.queue(QueueKind::Graphics).unwrap();
11732        assert_eq!(device.caps().geometry_path(), GeometryPath::IndirectCount);
11733        let default = ForwardRenderer::with_scene(
11734            device.as_ref(),
11735            queue,
11736            Format::Rgba8UnormSrgb,
11737            &scene::demo(),
11738        )
11739        .unwrap();
11740        assert_eq!(default.geometry_path(), GeometryPath::IndirectPerBatch);
11741        default.destroy(device.as_ref());
11742        recorder.clear();
11743        let mut exact = ForwardRenderer::with_scene_on_path(
11744            device.as_ref(),
11745            queue,
11746            Format::Rgba8UnormSrgb,
11747            &scene::demo(),
11748            GeometryPath::IndirectCount,
11749        )
11750        .unwrap();
11751        assert_eq!(exact.geometry_path(), GeometryPath::IndirectCount);
11752        let rendered = frame(device.as_ref(), &mut exact, queue);
11753        let commands = commands_in_pass(&recorder, "forward");
11754        assert!(commands.iter().any(|command| matches!(
11755            command,
11756            crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
11757        )));
11758        assert!(
11759            !commands
11760                .iter()
11761                .any(|command| matches!(command, crcbl_hal::null::Command::DrawIndexedIndirect(_)))
11762        );
11763        rendered.finish(device.as_ref(), exact);
11764    }
11765
11766    /// **A device with a draw index draws a range of buckets per call, and one
11767    /// without it a call per bucket** — both indirect tails, read off the
11768    /// recorded stream of a whole frame.
11769    ///
11770    /// The ranged frame records one bind and one multi-draw per range in the
11771    /// depth prepass, whose draws together cover every bucket exactly once,
11772    /// and no count draw anywhere; the per-bucket frame records the call per
11773    /// bucket it always did. Both frames' counters are what they recorded.
11774    #[test]
11775    fn a_draw_index_puts_the_geometry_passes_on_a_call_per_range() {
11776        use crcbl_hal::null::Command;
11777
11778        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
11779            for ranged in [false, true] {
11780                let optional = if ranged {
11781                    Features::GPU_DRIVEN | Features::DRAW_INDEX
11782                } else {
11783                    DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features
11784                };
11785                let (recorder, device, queue) = open_with(optional);
11786                let mut renderer = ForwardRenderer::with_scene_on_path(
11787                    device.as_ref(),
11788                    queue,
11789                    Format::Rgba8UnormSrgb,
11790                    &scene::demo(),
11791                    path,
11792                )
11793                .expect("the demo scene builds");
11794                assert_eq!(renderer.range_limit.is_some(), ranged, "{path:?}");
11795                let buckets = renderer.bucket_modes.len();
11796                assert!(buckets > 1, "one bucket packs into one call either way");
11797                let rendered = frame(device.as_ref(), &mut renderer, queue);
11798
11799                let commands = commands_in_pass(&recorder, "depth-prepass");
11800                let binds = commands
11801                    .iter()
11802                    .filter(|command| matches!(command, Command::BindGroup { slot: 0, .. }))
11803                    .count();
11804                let draws: Vec<u32> = commands
11805                    .iter()
11806                    .filter_map(|command| match command {
11807                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
11808                        Command::DrawIndexedIndirectCount(draw) => {
11809                            assert!(!ranged, "{path:?}: a ranged pass records no count draw");
11810                            assert_eq!(draw.max_draw_count, 1);
11811                            Some(1)
11812                        }
11813                        _ => None,
11814                    })
11815                    .collect();
11816                assert_eq!(binds, draws.len(), "{path:?}: one bind per call");
11817                assert_eq!(
11818                    draws.iter().sum::<u32>() as usize,
11819                    buckets,
11820                    "{path:?}: every bucket drawn once"
11821                );
11822                if ranged {
11823                    assert!(
11824                        draws.len() < buckets,
11825                        "{path:?}: {draws:?} is a call per bucket over {buckets} buckets"
11826                    );
11827                } else {
11828                    assert_eq!(draws, vec![1; buckets], "{path:?}");
11829                }
11830                assert!(
11831                    !recorder
11832                        .commands()
11833                        .iter()
11834                        .any(|command| ranged
11835                            && matches!(command, Command::DrawIndexedIndirectCount(_))),
11836                    "{path:?}: a ranged frame records no count draw"
11837                );
11838                assert_eq!(
11839                    renderer.counters().draws,
11840                    recorded_draws(&recorder) as u64,
11841                    "{path:?}, ranged {ranged}"
11842                );
11843                rendered.finish(device.as_ref(), renderer);
11844                recorder.assert_valid();
11845            }
11846        }
11847    }
11848
11849    /// **A scene holding every material mode draws each pipeline's buckets as
11850    /// one ranged call**, because the bucket table is numbered mode-major: the
11851    /// depth prepass records one call per depth pipeline and the colour pass
11852    /// one per sided pipeline, on both indirect tails.
11853    ///
11854    /// Numbered mesh by mesh, the same scene alternates modes bucket by bucket
11855    /// and every partition's runs are one bucket long, so the prepass would
11856    /// record a call per bucket — the counts below are what tell the two
11857    /// numberings apart, and the sums are what say every bucket still drew.
11858    #[test]
11859    fn every_mode_partition_of_a_ranged_frame_is_one_call() {
11860        use crcbl_hal::null::Command;
11861        use crcbl_shaders::mesh::GpuMaterial;
11862
11863        let scene = {
11864            let mut scene = crate::scene::demo();
11865            while scene.materials.len() < 4 {
11866                scene.materials.push(GpuMaterial::UNTINTED);
11867            }
11868            let rows = [
11869                0,
11870                GpuMaterial::ALPHA_MODE_MASK,
11871                GpuMaterial::DOUBLE_SIDED,
11872                GpuMaterial::MODE_MASK,
11873            ];
11874            for (row, flags) in scene.materials.iter_mut().zip(rows) {
11875                row.flags = flags;
11876            }
11877            scene
11878        };
11879        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
11880            let (recorder, device, queue) = open_with(Features::GPU_DRIVEN | Features::DRAW_INDEX);
11881            let mut renderer = ForwardRenderer::with_scene_on_path(
11882                device.as_ref(),
11883                queue,
11884                Format::Rgba8UnormSrgb,
11885                &scene,
11886                path,
11887            )
11888            .expect("the four-mode demo builds");
11889            assert!(renderer.range_limit.is_some(), "{path:?}");
11890            let buckets = renderer.bucket_modes.len();
11891            let per_mode = buckets / DEPTH_MODES.len();
11892            assert_eq!(
11893                per_mode * DEPTH_MODES.len(),
11894                buckets,
11895                "{path:?}: four twins"
11896            );
11897            assert!(
11898                per_mode > 1,
11899                "{path:?}: a mode of one bucket is one call under either numbering"
11900            );
11901            let rendered = frame(device.as_ref(), &mut renderer, queue);
11902
11903            let draws = |label: &str| -> Vec<u32> {
11904                commands_in_pass(&recorder, label)
11905                    .iter()
11906                    .filter_map(|command| match command {
11907                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
11908                        _ => None,
11909                    })
11910                    .collect()
11911            };
11912            let prepass = draws("depth-prepass");
11913            assert_eq!(
11914                prepass,
11915                vec![u32::try_from(per_mode).expect("a few buckets"); DEPTH_MODES.len()],
11916                "{path:?}: one call per depth pipeline, each a whole mode"
11917            );
11918            let forward = draws("forward");
11919            assert_eq!(
11920                forward,
11921                vec![u32::try_from(2 * per_mode).expect("a few buckets"); 2],
11922                "{path:?}: one call per sided pipeline, each two adjacent modes"
11923            );
11924            rendered.finish(device.as_ref(), renderer);
11925            recorder.assert_valid();
11926        }
11927    }
11928
11929    /// **Behind an amplification stage the mesh tail records one flat call per
11930    /// partition, and without one a range of buckets per call on a device with
11931    /// a draw index and a call per bucket without** — read off the recorded
11932    /// stream of a whole frame.
11933    ///
11934    /// The flat calls are [`flat_dispatch_calls`]: one structure each, the
11935    /// colour pass's sided segments in region 0, under the segment's first
11936    /// bucket's block — whatever the bucket count, and whether or not the
11937    /// device granted a draw index, which the flat call does not read. Without
11938    /// the stage the colour pass's calls, unrolled a structure at a time, are
11939    /// exactly the per-bucket dispatches [`mesh_dispatch_calls`] names — every
11940    /// bucket's own extents, each once. Either way the counters are what the
11941    /// frame recorded.
11942    #[test]
11943    fn the_mesh_tail_records_a_flat_call_per_partition_behind_a_task_stage() {
11944        use crcbl_hal::null::Command;
11945
11946        // `None` is the demo scene; `Some(n)` is `n` copies of its cube, one
11947        // bucket each, in one material mode — so one run of `n` buckets.
11948        for cubes in [None, Some(4), Some(33)] {
11949            for task in [Features::TASK_SHADER, Features::empty()] {
11950                for ranged in [false, true] {
11951                    let case = format!("{cubes:?} cubes, {task:?}, ranged {ranged}");
11952                    let recorder = Recorder::new();
11953                    let optional = if ranged {
11954                        task | Features::DRAW_INDEX
11955                    } else {
11956                        task
11957                    };
11958                    let (device, queue) = open_mesh_path(&recorder, optional);
11959                    let mut scene = scene::demo();
11960                    if let Some(cubes) = cubes {
11961                        scene.meshes = vec![scene.meshes[DEMO_CUBE].clone(); cubes as usize];
11962                        scene.capacities.meshes = cubes;
11963                        scene.capacities.vertices =
11964                            cubes * crcbl_shaders::mesh::CUBE_VERTEX_COUNT as u32;
11965                        scene.capacities.indices =
11966                            cubes * crcbl_shaders::mesh::CUBE_INDEX_COUNT as u32;
11967                    }
11968                    let mut renderer = ForwardRenderer::with_scene_on_path(
11969                        device.as_ref(),
11970                        queue,
11971                        Format::Rgba8UnormSrgb,
11972                        &scene,
11973                        GeometryPath::MeshShader,
11974                    )
11975                    .expect("the mesh renderer builds");
11976                    assert_eq!(renderer.range_limit.is_some(), ranged, "{case}");
11977                    assert_eq!(renderer.culls_clusters(), !task.is_empty(), "{case}");
11978                    let buckets = renderer.bucket_constants.len();
11979                    assert!(buckets > 1, "one bucket packs into one call either way");
11980                    let rendered = frame(device.as_ref(), &mut renderer, queue);
11981
11982                    let commands = commands_in_pass(&recorder, "forward");
11983                    let bound: Vec<u32> = commands
11984                        .iter()
11985                        .filter_map(|command| match command {
11986                            Command::BindGroup {
11987                                slot: 0,
11988                                dynamic_offsets,
11989                                ..
11990                            } => Some(dynamic_offsets[0]),
11991                            _ => None,
11992                        })
11993                        .collect();
11994                    let calls: Vec<DrawIndirect> = commands
11995                        .iter()
11996                        .filter_map(|command| match command {
11997                            Command::DrawMeshTasksIndirect(draw) => Some(*draw),
11998                            Command::DrawMeshTasks { .. }
11999                            | Command::DrawIndexedIndirect(_)
12000                            | Command::DrawIndexedIndirectCount(_) => {
12001                                panic!("{case}: the mesh tail recorded {command:?}")
12002                            }
12003                            _ => None,
12004                        })
12005                        .collect();
12006                    assert_eq!(bound.len(), calls.len(), "{case}: one bind per call");
12007                    assert!(
12008                        calls
12009                            .iter()
12010                            .all(|call| call.stride
12011                                == crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32),
12012                        "{case}: one structure a bucket, or a flat call's one"
12013                    );
12014                    if task.is_empty() {
12015                        // Each call a structure at a time: what a call per
12016                        // bucket would have recorded for the buckets it
12017                        // stands for.
12018                        let mut unrolled: Vec<DrawIndirect> = calls
12019                            .iter()
12020                            .flat_map(|call| {
12021                                (0..call.draw_count).map(|draw| DrawIndirect {
12022                                    offset: call.offset + u64::from(draw) * u64::from(call.stride),
12023                                    draw_count: 1,
12024                                    ..*call
12025                                })
12026                            })
12027                            .collect();
12028                        unrolled.sort_by_key(|draw| draw.offset);
12029                        assert_eq!(
12030                            unrolled,
12031                            mesh_dispatch_calls(&renderer),
12032                            "{case}: every bucket's own extents, each once"
12033                        );
12034                        let counts: Vec<u32> = calls.iter().map(|call| call.draw_count).collect();
12035                        match (ranged, cubes) {
12036                            (false, _) => assert_eq!(counts, vec![1; buckets], "{case}"),
12037                            (true, Some(cubes)) => assert_eq!(counts, vec![cubes], "{case}"),
12038                            (true, None) => assert!(
12039                                calls.len() < buckets,
12040                                "{case}: {counts:?} is a call per bucket over {buckets} buckets"
12041                            ),
12042                        }
12043                    } else {
12044                        let (expected, firsts) = flat_dispatch_calls(
12045                            &renderer,
12046                            crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED,
12047                        );
12048                        assert_eq!(calls, expected, "{case}: one flat call per sided partition");
12049                        assert_eq!(
12050                            bound,
12051                            firsts
12052                                .iter()
12053                                .map(|&bucket| renderer.bucket_constants[bucket as usize])
12054                                .collect::<Vec<_>>(),
12055                            "{case}: each under its segment's first bucket's block"
12056                        );
12057                    }
12058                    assert_eq!(
12059                        renderer.counters().draws,
12060                        recorded_draws(&recorder) as u64,
12061                        "{case}"
12062                    );
12063                    rendered.finish(device.as_ref(), renderer);
12064                    recorder.assert_valid();
12065                }
12066            }
12067        }
12068    }
12069
12070    /// **Draw `d` of a ranged mesh call reads the words bucket `first + d`'s own
12071    /// block carries**, in every draw region.
12072    ///
12073    /// The host half of `mesh_cluster.slang`'s "One call for a range of
12074    /// buckets": a ranged call binds its first bucket's block alone, and the
12075    /// SPIR-V stages add the draw index to its `start_at` and `bucket` and to
12076    /// the two table words it names. So each bucket's block has to sit one word
12077    /// past the one before in all four, and the table words have to hold the
12078    /// bucket's own cluster base and count — read out of the bytes that reached
12079    /// the device, since a block written wrong leaves the renderer's fields
12080    /// right.
12081    #[test]
12082    fn a_mesh_block_names_the_words_a_ranged_draw_reads() {
12083        let recorder = Recorder::new();
12084        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
12085        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12086            .expect("the mesh renderer builds");
12087        let blocks = recorder
12088            .buffer_bytes(renderer.draw_constants)
12089            .expect("the blocks are live");
12090        let tables = recorder
12091            .buffer_bytes(renderer.primary.draws.tables())
12092            .expect("the tables are live");
12093        let word = |bytes: &[u8], at: usize| {
12094            u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes"))
12095        };
12096        let buckets = renderer.bucket_constants.len();
12097        assert!(buckets > 1, "a range needs two buckets to step between");
12098        let bucket_count = u32::try_from(buckets).expect("a few buckets");
12099        let stride = renderer.bucket_constants[1] - renderer.bucket_constants[0];
12100        let block = |region: u32, bucket: u32| {
12101            let at = ((region * bucket_count + bucket) * stride) as usize;
12102            let field = |index: usize| word(&blocks, at + index * 4);
12103            crcbl_shaders::meshlet::ClusterDrawConstants {
12104                start_at: field(0),
12105                cluster_base: field(1),
12106                cluster_count: field(2),
12107                bucket: field(3),
12108                group_stride: field(4),
12109                level_groups_at: field(5),
12110                cluster_base_at: field(6),
12111                cluster_count_at: field(7),
12112                chunk_starts_at: field(8),
12113                chunk_starts_end: field(9),
12114            }
12115        };
12116        let mut bases = Vec::new();
12117        for region in 0..crcbl_shaders::draw_gen::DRAW_REGIONS {
12118            let first = block(region, 0);
12119            for bucket in 0..bucket_count {
12120                let own = block(region, bucket);
12121                assert_eq!(
12122                    word(&tables, own.cluster_base_at as usize * 4),
12123                    own.cluster_base,
12124                    "region {region} bucket {bucket}: the base word holds the base"
12125                );
12126                assert_eq!(
12127                    word(&tables, own.cluster_count_at as usize * 4),
12128                    own.cluster_count,
12129                    "region {region} bucket {bucket}: the count word holds the count"
12130                );
12131                // What draw `bucket` of a call bound at bucket 0's block reads
12132                // — and a flat call's workgroup that found bucket `bucket` by
12133                // searching the chunk starts from bucket 0's word to the
12134                // region's end.
12135                assert_eq!(
12136                    (
12137                        first.start_at + bucket,
12138                        first.bucket + bucket,
12139                        first.cluster_base_at + bucket,
12140                        first.cluster_count_at + bucket,
12141                        first.group_stride,
12142                        first.level_groups_at,
12143                        first.chunk_starts_at + bucket,
12144                        first.chunk_starts_end,
12145                    ),
12146                    (
12147                        own.start_at,
12148                        own.bucket,
12149                        own.cluster_base_at,
12150                        own.cluster_count_at,
12151                        own.group_stride,
12152                        own.level_groups_at,
12153                        own.chunk_starts_at,
12154                        own.chunk_starts_end,
12155                    ),
12156                    "region {region} bucket {bucket}"
12157                );
12158                assert_eq!(
12159                    own.chunk_starts_at,
12160                    crcbl_shaders::draw_gen::chunk_start_word(
12161                        renderer.primary.draws.visible_capacity(),
12162                        bucket_count,
12163                        region,
12164                        bucket,
12165                    ),
12166                    "region {region} bucket {bucket}: the word draw_gen writes its chunks' start into"
12167                );
12168                assert_eq!(
12169                    own.chunk_starts_end - own.chunk_starts_at,
12170                    bucket_count - bucket,
12171                    "region {region} bucket {bucket}: the search ends at the region's end word"
12172                );
12173                if region == 0 {
12174                    bases.push(own.cluster_base);
12175                }
12176            }
12177        }
12178        assert!(
12179            bases.windows(2).any(|pair| pair[0] != pair[1]),
12180            "the buckets' meshes start at different clusters, so a range reading its \
12181             first bucket's base for every draw would be seen: {bases:?}"
12182        );
12183        renderer.destroy(device.as_ref());
12184        recorder.assert_valid();
12185    }
12186
12187    #[test]
12188    fn exact_geometry_path_builds_supported_tails_and_refuses_missing_features_without_allocating()
12189    {
12190        for features in [
12191            Features::GPU_DRIVEN,
12192            Features::COMPUTE | Features::MESH_SHADER,
12193        ] {
12194            let recorder = Recorder::new();
12195            let instance = NullInstance::new(crcbl_hal::DeviceCaps {
12196                features,
12197                limits: crcbl_hal::Limits::desktop(),
12198            })
12199            .with_recorder(recorder.clone());
12200            let device = instance
12201                .create_device(&DeviceDesc {
12202                    label: None,
12203                    adapter: crcbl_hal::AdapterId(0),
12204                    required_features: Features::COMPUTE,
12205                    optional_features: features,
12206                    compatible_surface: None,
12207                })
12208                .expect("null device opens");
12209            let queue = device.queue(QueueKind::Graphics).unwrap();
12210            for (path, required) in [
12211                (GeometryPath::IndirectPerBatch, Features::empty()),
12212                (GeometryPath::IndirectCount, Features::DRAW_INDIRECT_COUNT),
12213                (GeometryPath::MeshShader, Features::MESH_SHADER),
12214            ] {
12215                recorder.clear();
12216                let result = ForwardRenderer::with_scene_on_path(
12217                    device.as_ref(),
12218                    queue,
12219                    Format::Rgba8UnormSrgb,
12220                    &scene::demo(),
12221                    path,
12222                );
12223                if features.contains(required) {
12224                    let renderer = result.expect("supported exact tail builds");
12225                    assert_eq!(renderer.geometry_path(), path);
12226                    renderer.destroy(device.as_ref());
12227                } else {
12228                    assert!(
12229                        matches!(result, Err(HalError::UnsupportedFeatures { missing }) if missing == required)
12230                    );
12231                    assert!(
12232                        recorder.events().is_empty(),
12233                        "unsupported selection must not touch device objects"
12234                    );
12235                }
12236                recorder.assert_valid();
12237            }
12238        }
12239    }
12240
12241    pub(super) fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
12242        open_with(DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features)
12243    }
12244
12245    /// [`open`] asking for `optional_features` instead of
12246    /// [`DeviceDesc::for_adapter`]'s.
12247    ///
12248    /// The null preset *has* more than the default request asks for, and a
12249    /// granted feature set is the intersection of the two — so this is how a test
12250    /// reaches a device with something the ordinary one lacks. What it exists for
12251    /// is [`Features::POLYGON_MODE_LINE`]: with the default request, `open`'s
12252    /// device has no line fill mode, which is the other half of the wireframe
12253    /// pair of tests below.
12254    fn open_with(optional_features: Features) -> (Recorder, Box<dyn Device>, QueueHandle) {
12255        let recorder = Recorder::new();
12256        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
12257        let adapter = instance.adapters().remove(0);
12258        let device = instance
12259            .create_device(&DeviceDesc {
12260                optional_features,
12261                ..DeviceDesc::for_adapter(adapter.id)
12262            })
12263            .expect("the null backend always opens");
12264        let queue = device.queue(QueueKind::Graphics).expect("always present");
12265        (recorder, device, queue)
12266    }
12267
12268    /// Puts one of [`scene::demo`]'s meshes in the frame the way a caller does.
12269    ///
12270    /// **Insertion order is what the caller decides**, and it is load-bearing:
12271    /// the slot an object lands in is topic 25's hysteresis key. So
12272    /// every test below places its objects in the order the frame used to hold
12273    /// them — the cube first, wherever there is one.
12274    fn place_demo(
12275        renderer: &mut ForwardRenderer,
12276        mesh: usize,
12277        material: usize,
12278        transform: Mat4,
12279    ) -> InstanceHandle {
12280        renderer
12281            .add_instance(&InstanceDesc {
12282                mesh,
12283                material,
12284                transform,
12285            })
12286            .expect("a pool of thousands has room for a handful of objects")
12287    }
12288
12289    /// [`scene::demo`]'s cube, placed **first** so it takes the pool slot it has
12290    /// always had.
12291    ///
12292    /// `begin_frame` used to write this object for every caller; the tests below
12293    /// that are about a frame with something in it place it themselves now.
12294    pub(super) fn place_cube(renderer: &mut ForwardRenderer, transform: Mat4) -> InstanceHandle {
12295        place_demo(renderer, DEMO_CUBE, DEMO_UNTINTED, transform)
12296    }
12297
12298    /// The whole renderer builds and tears down against a backend with no
12299    /// driver, which is what makes it testable on every CI leg.
12300    #[test]
12301    fn the_forward_renderer_builds_and_leaks_nothing() {
12302        let (recorder, device, queue) = open();
12303        let before = recorder.total_live_objects();
12304        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12305            .expect("the null backend accepts every descriptor");
12306        assert_eq!(renderer.target_format(), Format::Rgba8UnormSrgb);
12307        assert!(recorder.total_live_objects() > before);
12308        renderer.destroy(device.as_ref());
12309        assert_eq!(
12310            recorder.total_live_objects(),
12311            before,
12312            "every object created must be destroyed"
12313        );
12314        recorder.assert_valid();
12315    }
12316
12317    /// The uniform ring really rotates, or a spinning cube is a
12318    /// read-after-write hazard across submissions.
12319    #[test]
12320    fn the_uniform_ring_rotates() {
12321        let (_, device, queue) = open();
12322        let mut renderer =
12323            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12324        let camera = Camera::default();
12325        let light = DirectionalLight::default();
12326
12327        let mut seen = Vec::new();
12328        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12329            renderer
12330                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12331                .expect("write");
12332            seen.push(renderer.primary.uniforms[renderer.frame]);
12333        }
12334        assert_ne!(
12335            seen[0], seen[1],
12336            "consecutive frames must not share a buffer"
12337        );
12338        assert_eq!(seen[0], seen[FRAMES_IN_FLIGHT], "and the ring must wrap");
12339        renderer.destroy(device.as_ref());
12340    }
12341
12342    /// **The tonemap's block is a ring too, and it carries the exposure the
12343    /// caller set.**
12344    ///
12345    /// The bytes are the observable rather than the field, because the field is
12346    /// what a renderer that never wired the block up would also have: the claim
12347    /// is that the number reaches the buffer `tonemap.slang` reads, and only the
12348    /// null recorder's write log can say so.
12349    ///
12350    /// The default is checked first — a renderer nobody has called
12351    /// [`ForwardRenderer::set_exposure`] on writes the value the shader's
12352    /// `EXPOSURE` constant held, under
12353    /// [`ForwardRenderer::set_tonemap_curve`]'s own default.
12354    #[test]
12355    fn the_tonemap_block_holds_the_exposure_and_rotates_with_the_frame() {
12356        let (recorder, device, queue) = open();
12357        let mut renderer =
12358            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12359        let camera = Camera::default();
12360        let light = DirectionalLight::default();
12361
12362        renderer
12363            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12364            .expect("write");
12365        assert_eq!(
12366            recorder
12367                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12368                .expect("begin_frame wrote the block"),
12369            crcbl_shaders::tonemap::TonemapParams {
12370                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12371                curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12372                auto_exposure: false,
12373                coverage_alpha: false,
12374            }
12375            .to_bytes(),
12376            "an untouched renderer must write the exposure the constant used to hold, \
12377             under the operator this renderer starts on",
12378        );
12379
12380        // A value that is neither the default nor a bound, so a block left at
12381        // either would fail.
12382        renderer.set_exposure(3.5);
12383        let mut slots = Vec::new();
12384        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12385            renderer
12386                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12387                .expect("write");
12388            slots.push(renderer.primary.tonemap_uniforms[renderer.frame]);
12389            assert_eq!(
12390                recorder
12391                    .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12392                    .expect("begin_frame wrote the block"),
12393                crcbl_shaders::tonemap::TonemapParams {
12394                    exposure: 3.5,
12395                    curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12396                    auto_exposure: false,
12397                    coverage_alpha: false,
12398                }
12399                .to_bytes(),
12400                "the frame's own block must carry the exposure in force",
12401            );
12402        }
12403        assert_ne!(
12404            slots[0], slots[1],
12405            "consecutive frames must not share a block"
12406        );
12407        assert_eq!(slots[0], slots[FRAMES_IN_FLIGHT], "and the ring must wrap");
12408
12409        renderer.destroy(device.as_ref());
12410    }
12411
12412    /// **The curve reaches the block, and a caller can move it off the
12413    /// default.**
12414    ///
12415    /// The selector is a lane of the same ring the exposure rides in, and a lane
12416    /// nothing wrote would read as
12417    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp)
12418    /// whatever a caller asked for — a setter that compiles, a frame that looks
12419    /// right, and a curve that never runs. Since the renderer now *starts* on
12420    /// the fit, that failure would read as a working default, so the check runs
12421    /// in both directions: the untouched block carries the fit, and asking for
12422    /// the clamp changes the bytes on every frame of the ring.
12423    #[test]
12424    fn the_tonemap_block_carries_the_curve_a_caller_selected() {
12425        use crcbl_shaders::tonemap::TonemapCurve;
12426
12427        let (recorder, device, queue) = open();
12428        let mut renderer =
12429            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12430        let camera = Camera::default();
12431        let light = DirectionalLight::default();
12432
12433        assert_eq!(
12434            renderer.tonemap_curve(),
12435            TonemapCurve::Aces,
12436            "a renderer nobody configured must run the operator the goldens were blessed under",
12437        );
12438        renderer
12439            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12440            .expect("write");
12441        let by_default = recorder
12442            .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12443            .expect("begin_frame wrote the block");
12444
12445        renderer.set_tonemap_curve(TonemapCurve::Clamp);
12446        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Clamp);
12447        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12448            renderer
12449                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12450                .expect("write");
12451            let written = recorder
12452                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12453                .expect("begin_frame wrote the block");
12454            assert_eq!(
12455                written,
12456                crcbl_shaders::tonemap::TonemapParams {
12457                    exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12458                    curve: TonemapCurve::Clamp,
12459                    auto_exposure: false,
12460                    coverage_alpha: false,
12461                }
12462                .to_bytes(),
12463                "every frame of the ring must carry the selected curve",
12464            );
12465            assert_ne!(
12466                written, by_default,
12467                "and it must differ from the block a default renderer writes",
12468            );
12469        }
12470
12471        // **A readout runs the clamp whatever was selected**, and the selection
12472        // survives it: the caller's curve is still the caller's, the frame's is
12473        // the identity, and the shaded frame after gets the curve back. Asked of
12474        // the fit, which is the selection a readout has something to lose under.
12475        renderer.set_tonemap_curve(TonemapCurve::Aces);
12476        renderer.set_normals_view(true);
12477        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Aces);
12478        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Clamp);
12479        renderer
12480            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12481            .expect("write");
12482        assert_eq!(
12483            recorder
12484                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12485                .expect("begin_frame wrote the block"),
12486            crcbl_shaders::tonemap::TonemapParams {
12487                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12488                curve: TonemapCurve::Clamp,
12489                auto_exposure: false,
12490                coverage_alpha: false,
12491            }
12492            .to_bytes(),
12493            "a debug view's block must carry the clamp, since its pixels are data",
12494        );
12495        renderer.set_normals_view(false);
12496        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Aces);
12497
12498        renderer.destroy(device.as_ref());
12499    }
12500
12501    /// **The exposure is clamped where it is set**, so no caller can reach a
12502    /// frame it cannot get back from.
12503    ///
12504    /// Each case is a different way of leaving the range, and the NaN one is the
12505    /// reason [`ForwardRenderer::set_exposure`] does not use `f32::clamp`: that
12506    /// propagates a NaN into the block, which is a frame of NaN pixels with no
12507    /// key to press to escape it.
12508    #[test]
12509    fn the_exposure_setter_clamps_to_a_range_a_caller_can_come_back_from() {
12510        let (_, device, queue) = open();
12511        let mut renderer =
12512            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12513        assert!(
12514            (renderer.exposure() - crcbl_shaders::tonemap::DEFAULT_EXPOSURE).abs() < f32::EPSILON,
12515            "the default is {}",
12516            renderer.exposure(),
12517        );
12518
12519        for (asked, expected) in [
12520            (2.0, 2.0),
12521            (EXPOSURE_MAX * 4.0, EXPOSURE_MAX),
12522            (f32::INFINITY, EXPOSURE_MAX),
12523            (EXPOSURE_MIN / 4.0, EXPOSURE_MIN),
12524            (0.0, EXPOSURE_MIN),
12525            (-8.0, EXPOSURE_MIN),
12526            (f32::NEG_INFINITY, EXPOSURE_MIN),
12527            (f32::NAN, EXPOSURE_MIN),
12528        ] {
12529            renderer.set_exposure(asked);
12530            assert!(
12531                (renderer.exposure() - expected).abs() < f32::EPSILON,
12532                "{asked} was clamped to {}, not {expected}",
12533                renderer.exposure(),
12534            );
12535        }
12536
12537        renderer.destroy(device.as_ref());
12538    }
12539
12540    /// **The debug views resolve in one order, however they are set.**
12541    ///
12542    /// Every one of them rides in one float lane and the shaders test the
12543    /// outermost threshold first, so a renderer with two switches on draws
12544    /// exactly one picture — and which one has to be a rule rather than
12545    /// whichever branch a caller's setter happened to run last. Every
12546    /// combination of the switches is walked, because a precedence written as an
12547    /// `if` chain is right for most of them by accident: a chain in the wrong
12548    /// order agrees with this one on every combination where at most one switch
12549    /// is set.
12550    ///
12551    /// **The two innermost views are the exception the walk is worth most for.**
12552    /// [`DebugView::Cascades`] keeps the shaded picture rather than replacing
12553    /// it, so it resolves *last* and its sentinel runs the other way down the
12554    /// lane; [`DebugView::ShadowAtlas`] resolves just above it and carries the
12555    /// *off* sentinel, because it is a pass rather than a branch. Every
12556    /// combination where either is set beside a replacing view is a combination
12557    /// an order written any other way answers differently, and there is no
12558    /// single-switch case that could tell them apart.
12559    ///
12560    /// [`ForwardRenderer::debug_view`] is asserted beside the lane, so the value
12561    /// a panel reads back and the value the shader branches on cannot drift —
12562    /// they are the same function.
12563    #[test]
12564    fn the_debug_views_resolve_in_one_order_however_they_are_set() {
12565        // `w` of the second `float4` of the block — the lane
12566        // `the_normals_view_moves_the_ambients_last_lane_and_no_other_byte`
12567        // spells out, and for its reason.
12568        const AMBIENT_W: usize = 64 + 16 + 12;
12569
12570        let (recorder, device, queue) = open();
12571        let mut renderer =
12572            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12573        let camera = Camera::default();
12574        let light = DirectionalLight::default();
12575
12576        for bent in [false, true] {
12577            for motion in [false, true] {
12578                for occlusion in [false, true] {
12579                    for heatmap in [false, true] {
12580                        for lod in [false, true] {
12581                            for normals in [false, true] {
12582                                for (atlas, cascades) in
12583                                    [false, true].into_iter().flat_map(|atlas| {
12584                                        [false, true].map(|cascades| (atlas, cascades))
12585                                    })
12586                                {
12587                                    renderer.set_bent_normal_view(bent);
12588                                    renderer.set_motion_view(motion);
12589                                    renderer.set_occlusion_view(occlusion);
12590                                    renderer.set_heatmap(heatmap);
12591                                    renderer.set_lod_view(lod);
12592                                    renderer.set_normals_view(normals);
12593                                    renderer.set_atlas_view(atlas);
12594                                    renderer.set_cascade_view(cascades);
12595                                    let set = format!(
12596                                        "bent={bent} motion={motion} occlusion={occlusion} \
12597                                 heatmap={heatmap} lod={lod} normals={normals} \
12598                                 atlas={atlas} cascades={cascades}"
12599                                    );
12600                                    // Each switch reads back what it was set to, whatever
12601                                    // the others are: a caller's toggle is about the
12602                                    // caller's setting, and only `debug_view` is about the
12603                                    // picture.
12604                                    assert_eq!(renderer.bent_normal_view(), bent);
12605                                    assert_eq!(renderer.motion_view(), motion);
12606                                    assert_eq!(renderer.occlusion_view(), occlusion);
12607                                    assert_eq!(renderer.heatmap(), heatmap);
12608                                    assert_eq!(renderer.lod_view(), lod);
12609                                    assert_eq!(renderer.normals_view(), normals);
12610                                    assert_eq!(renderer.atlas_view(), atlas);
12611                                    assert_eq!(renderer.cascade_view(), cascades);
12612
12613                                    let expected = if bent {
12614                                        DebugView::BentNormal
12615                                    } else if motion {
12616                                        DebugView::Motion
12617                                    } else if occlusion {
12618                                        DebugView::AmbientOcclusion
12619                                    } else if heatmap {
12620                                        DebugView::Heatmap
12621                                    } else if lod {
12622                                        DebugView::LodTint
12623                                    } else if normals {
12624                                        DebugView::Normals
12625                                    } else if atlas {
12626                                        // **Below every replacing view above and
12627                                        // above the tint below**, which is the
12628                                        // half of this order no single-switch
12629                                        // case reaches: with a replacing view
12630                                        // also set the frame is that view's, and
12631                                        // with the tint also set the frame is the
12632                                        // atlas.
12633                                        DebugView::ShadowAtlas
12634                                    } else if cascades {
12635                                        // **Last, which is the half of this order a
12636                                        // chain in any other arrangement would get
12637                                        // right by accident.** The cascade tint is a
12638                                        // multiply on the shaded picture, so every
12639                                        // combination that also names a replacing
12640                                        // view has to resolve to *that* view — and
12641                                        // those are exactly the combinations an
12642                                        // `if cascades` written one line higher
12643                                        // would answer differently.
12644                                        DebugView::Cascades
12645                                    } else {
12646                                        DebugView::Shaded
12647                                    };
12648                                    assert_eq!(renderer.debug_view(), expected, "{set}");
12649
12650                                    renderer
12651                                        .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12652                                        .expect("write");
12653                                    let block = recorder
12654                                        .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12655                                        .expect("begin_frame wrote the block");
12656                                    let sentinel = match expected {
12657                                        DebugView::BentNormal => {
12658                                            mesh::FrameUniforms::BENT_NORMAL_VIEW_ON
12659                                        }
12660                                        DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
12661                                        DebugView::AmbientOcclusion => {
12662                                            mesh::FrameUniforms::OCCLUSION_VIEW_ON
12663                                        }
12664                                        DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
12665                                        DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
12666                                        DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
12667                                        DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
12668                                        // **The atlas view carries the *off*
12669                                        // sentinel**, which is what makes this
12670                                        // assertion say something rather than
12671                                        // restate `debug_view_lane`: the colour
12672                                        // pass draws the shaded picture and
12673                                        // `crate::atlas_view`'s pass replaces
12674                                        // it, so a lane of its own here would be
12675                                        // a threshold no shader tests.
12676                                        DebugView::ShadowAtlas | DebugView::Shaded => {
12677                                            mesh::FrameUniforms::NORMALS_VIEW_OFF
12678                                        }
12679                                    };
12680                                    assert_eq!(
12681                                        &block[AMBIENT_W..AMBIENT_W + 4],
12682                                        &sentinel.to_le_bytes(),
12683                                        "{set} resolved to {expected:?}, and the lane says otherwise"
12684                                    );
12685                                    // And the resolve comes off for every one of them:
12686                                    // these frames are read back as data, so their colours
12687                                    // have to stay the ones the shader wrote — see
12688                                    // `resolved_effects`. The whole slot rather than one
12689                                    // tier of it, because which tier the default carries
12690                                    // is not what this is about.
12691                                    assert_eq!(
12692                                        renderer.effects().intersects(Antialiasing::SLOT),
12693                                        expected == DebugView::Shaded,
12694                                        "{set}"
12695                                    );
12696                                }
12697                            }
12698                        }
12699                    }
12700                }
12701            }
12702        }
12703
12704        renderer.destroy(device.as_ref());
12705    }
12706
12707    /// **The atlas viewer records one pass, and only on the frame it is the view
12708    /// showing.**
12709    ///
12710    /// The mechanism no other check in this file can see. Every other debug view
12711    /// is a lane of the frame block, so
12712    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`] observes it
12713    /// by reading four bytes; this one is a *pass*, and "the pass was recorded"
12714    /// is a claim about the command stream and about nothing else. A switch that
12715    /// resolved correctly and recorded nothing would satisfy every other
12716    /// assertion in this module and draw the frame unchanged.
12717    ///
12718    /// Three arms, and the third is the one that makes the first two mean
12719    /// something:
12720    ///
12721    /// * off — no pass at all, which is what makes the off position
12722    ///   bit-identical for every golden in this workspace;
12723    /// * on — the pass, with the full-screen triangle in it;
12724    /// * on **beside a replacing view** — no pass, because
12725    ///   [`ForwardRenderer::debug_view`] resolved to that view and the atlas is
12726    ///   not what this frame draws. That is the half a `self.atlas_view` read at
12727    ///   the recording site would get wrong while passing both arms above.
12728    ///
12729    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`]: fn@the_debug_views_resolve_in_one_order_however_they_are_set
12730    /// **The shadow atlas viewer replaces the tonemap and the ground grid, and
12731    /// the draw count follows.**
12732    ///
12733    /// The viewer fills every display pixel with a `DontCare` load, so a
12734    /// tonemapped frame or a grid recorded under it is stored and discarded.
12735    /// The pass counts go red if either comes back; the counter goes red if
12736    /// `counters` still charges the frame for the triangles it no longer
12737    /// records.
12738    #[test]
12739    fn the_atlas_viewer_replaces_the_display_passes_and_the_count_follows() {
12740        let (recorder, device, queue) = open();
12741        let mut renderer =
12742            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12743        renderer
12744            .set_ground_grid(device.as_ref(), Some(GridStyle::default()))
12745            .expect("the null backend builds every pipeline");
12746        renderer.set_atlas_view(true);
12747        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
12748
12749        let viewing = frame(device.as_ref(), &mut renderer, queue);
12750        let opened = |label: &str| {
12751            recorder
12752                .commands()
12753                .iter()
12754                .filter(|command| {
12755                    matches!(command.opens_pass(), Some((_, Some(recorded))) if recorded == label)
12756                })
12757                .count()
12758        };
12759        assert_eq!(opened(crate::atlas_view::LABEL), 1);
12760        assert_eq!(opened("tonemap"), 0, "the viewer discards the tonemap");
12761        assert_eq!(opened("grid"), 0, "and the grid drawn over it");
12762        assert_eq!(
12763            renderer.counters().draws,
12764            recorded_draws(&recorder) as u64,
12765            "the counter charges the frame for exactly the draws it recorded"
12766        );
12767        viewing.finish(device.as_ref(), renderer);
12768    }
12769
12770    #[test]
12771    fn the_atlas_viewer_records_its_pass_only_when_it_is_the_view_showing() {
12772        use crcbl_hal::null::Command;
12773
12774        let (recorder, device, queue) = open();
12775        let device = device.as_ref();
12776        let mut renderer =
12777            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
12778        let (camera, sun) = (Camera::default(), DirectionalLight::default());
12779
12780        // How many times the viewer's pass was opened since `from`, which is
12781        // where the previous arm's commands ended.
12782        let opened = |from: usize| {
12783            recorder.commands()[from..]
12784                .iter()
12785                .filter(|command| {
12786                    matches!(
12787                        command.opens_pass(),
12788                        Some((_, Some(recorded))) if recorded == crate::atlas_view::LABEL
12789                    )
12790                })
12791                .count()
12792        };
12793
12794        let shaded = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12795        assert_eq!(
12796            opened(0),
12797            0,
12798            "a frame drawing the shaded picture recorded the atlas viewer's pass"
12799        );
12800        let after_shaded = recorder.commands().len();
12801        shaded.release(device);
12802
12803        renderer.set_atlas_view(true);
12804        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
12805        let viewing = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12806        assert_eq!(
12807            opened(after_shaded),
12808            1,
12809            "the atlas viewer is on and its pass was not recorded exactly once"
12810        );
12811        // And what it recorded is the over-sized triangle and nothing else: a
12812        // pass that bound a pipeline and drew no vertices would open above and
12813        // leave the frame the tonemap wrote.
12814        let drawn: Vec<(u32, u32)> = commands_in_pass(&recorder, crate::atlas_view::LABEL)
12815            .into_iter()
12816            .filter_map(|command| match command {
12817                Command::Draw {
12818                    vertices,
12819                    instances,
12820                } => Some((
12821                    vertices.end - vertices.start,
12822                    instances.end - instances.start,
12823                )),
12824                _ => None,
12825            })
12826            .collect();
12827        assert_eq!(drawn, vec![(crate::atlas_view::FULLSCREEN_VERTICES, 1)]);
12828        let after_viewing = recorder.commands().len();
12829        viewing.release(device);
12830
12831        // The switch left on, and a replacing view asked for over the top of it.
12832        renderer.set_normals_view(true);
12833        assert_eq!(
12834            renderer.debug_view(),
12835            DebugView::Normals,
12836            "the atlas view does not lose to a replacing view, so the arm below asks nothing"
12837        );
12838        let normals = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12839        assert_eq!(
12840            opened(after_viewing),
12841            0,
12842            "the frame resolved to the normals view and still recorded the atlas viewer's \
12843             pass over the top of it"
12844        );
12845        normals.release(device);
12846
12847        renderer.destroy(device);
12848    }
12849
12850    /// **The heatmap moves the ambient's last lane and no other byte**, and
12851    /// switching it off puts the block back.
12852    ///
12853    /// The normals view's assertion below, for the outermost of the three: the
12854    /// overlay costs one lane, so every golden image ever blessed is untouched
12855    /// by the feature existing. The `lod_params` row the heatmap reads is
12856    /// written every frame whether it is on or not — it is the numbers the
12857    /// selection used — so this compares two frames of the *same* camera and
12858    /// budget, where that row is equal on both sides and any byte outside the
12859    /// lane is a real difference.
12860    #[test]
12861    fn the_heatmap_moves_the_ambients_last_lane_and_no_other_byte() {
12862        const AMBIENT_W: usize = 64 + 16 + 12;
12863
12864        // Held for the whole comparison, and it is not this check's own knob:
12865        // `r_shadow_filter` and `r_shadow_split` land in the block's
12866        // `shadow_filter` row on every `begin_frame`, and the filter checks in
12867        // this module move them under this lock while `cargo test` runs the
12868        // module's checks as threads of one process. Two frames read either side
12869        // of such a move differ at that row, which is outside every lane below —
12870        // one run in twelve, measured 2026-09-04.
12871        let _filter = shadow_filter_switch();
12872        let (recorder, device, queue) = open();
12873        let mut renderer =
12874            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12875        let camera = Camera::default();
12876        let light = DirectionalLight::default();
12877        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
12878            renderer
12879                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12880                .expect("write");
12881            recorder
12882                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12883                .expect("begin_frame wrote the block")
12884        };
12885
12886        assert!(
12887            !renderer.heatmap(),
12888            "the heatmap has to be off in a renderer nobody has asked",
12889        );
12890        let shaded = block(&mut renderer);
12891        assert_eq!(
12892            &shaded[AMBIENT_W..AMBIENT_W + 4],
12893            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
12894            "an untouched renderer must write the value every golden image was blessed with",
12895        );
12896
12897        renderer.set_heatmap(true);
12898        let heatmap = block(&mut renderer);
12899        assert_eq!(
12900            &heatmap[AMBIENT_W..AMBIENT_W + 4],
12901            &mesh::FrameUniforms::HEATMAP_VIEW_ON.to_le_bytes(),
12902            "the switch has to reach the lane the mesh stage branches on",
12903        );
12904        let outside: Vec<usize> = shaded
12905            .iter()
12906            .zip(heatmap.iter())
12907            .enumerate()
12908            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
12909            .map(|(at, _)| at)
12910            .collect();
12911        assert!(
12912            outside.is_empty(),
12913            "the frame block changed at {outside:?}, which is outside the heatmap's own lane",
12914        );
12915
12916        renderer.set_heatmap(false);
12917        assert_eq!(
12918            block(&mut renderer),
12919            shaded,
12920            "switching the view off has to put the block back, not just stop reporting it",
12921        );
12922
12923        renderer.destroy(device.as_ref());
12924    }
12925
12926    /// **The normals view moves one lane of the frame block and nothing else.**
12927    ///
12928    /// The mechanism, at the level a null device can observe it: which bytes of
12929    /// the buffer `mesh.slang` reads changed. A field on the renderer would say
12930    /// only that a flag moved; the block is what the shader actually branches on.
12931    ///
12932    /// Four claims, and each rules out a different way of passing wrongly:
12933    ///
12934    /// * an untouched renderer writes [`FrameUniforms::NORMALS_VIEW_OFF`] — which
12935    ///   is what makes every golden image untouched by this feature;
12936    /// * switching on writes [`FrameUniforms::NORMALS_VIEW_ON`] into the lane the
12937    ///   shader reads, at the offset `std140` puts it at rather than at one this
12938    ///   test picked;
12939    /// * **those four bytes are the only ones that moved**, so the switch did not
12940    ///   come at the cost of the ambient colour beside it or of any matrix;
12941    /// * and switching off puts the block back exactly, so the view is a toggle
12942    ///   rather than a one-way door.
12943    ///
12944    /// [`FrameUniforms::NORMALS_VIEW_OFF`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_OFF
12945    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
12946    #[test]
12947    fn the_normals_view_moves_the_ambients_last_lane_and_no_other_byte() {
12948        // `w` of the second `float4` of the block: one `float4x4`, one `float4`,
12949        // then three floats of ambient colour. Spelled as the sum rather than as
12950        // `92` so that a member arriving before it is a compile-time question
12951        // about `FrameUniforms`' own layout and not a silent read of a matrix.
12952        const AMBIENT_W: usize = 64 + 16 + 12;
12953
12954        // Held for the whole comparison, and it is not this check's own knob:
12955        // `r_shadow_filter` and `r_shadow_split` land in the block's
12956        // `shadow_filter` row on every `begin_frame`, and the filter checks in
12957        // this module move them under this lock while `cargo test` runs the
12958        // module's checks as threads of one process. Two frames read either side
12959        // of such a move differ at that row, which is outside every lane below —
12960        // one run in twelve, measured 2026-09-04.
12961        let _filter = shadow_filter_switch();
12962        let (recorder, device, queue) = open();
12963        let mut renderer =
12964            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12965        let camera = Camera::default();
12966        let light = DirectionalLight::default();
12967        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
12968            renderer
12969                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12970                .expect("write");
12971            recorder
12972                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12973                .expect("begin_frame wrote the block")
12974        };
12975
12976        assert!(
12977            !renderer.normals_view(),
12978            "the normals view has to be off in a renderer nobody has asked",
12979        );
12980        let shaded = block(&mut renderer);
12981        assert_eq!(
12982            &shaded[AMBIENT_W..AMBIENT_W + 4],
12983            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
12984            "an untouched renderer must write the value every golden image was blessed with",
12985        );
12986
12987        renderer.set_normals_view(true);
12988        assert!(renderer.normals_view());
12989        let normals = block(&mut renderer);
12990        assert_eq!(
12991            &normals[AMBIENT_W..AMBIENT_W + 4],
12992            &mesh::FrameUniforms::NORMALS_VIEW_ON.to_le_bytes(),
12993            "the switch has to reach the lane the fragment stage branches on",
12994        );
12995        // The bytes that moved, and they all have to be inside the lane — not
12996        // *all* of the lane, because `0.0f` and `1.0f` share their two low bytes
12997        // and an equality against the whole range would be a test about IEEE 754
12998        // rather than about the block.
12999        let outside: Vec<usize> = shaded
13000            .iter()
13001            .zip(normals.iter())
13002            .enumerate()
13003            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
13004            .map(|(at, _)| at)
13005            .collect();
13006        assert!(
13007            outside.is_empty(),
13008            "the frame block changed at {outside:?}, which is outside the normals view's own lane",
13009        );
13010
13011        renderer.set_normals_view(false);
13012        assert!(!renderer.normals_view());
13013        assert_eq!(
13014            block(&mut renderer),
13015            shaded,
13016            "switching the view off has to put the block back, not just stop reporting it",
13017        );
13018
13019        renderer.destroy(device.as_ref());
13020    }
13021
13022    /// **A frame uploads the instances a caller moved, and a frame nobody moved
13023    /// anything in uploads nothing at all.**
13024    ///
13025    /// The second half is the stronger claim and it is the one that needed the
13026    /// cube to become an ordinary instance: `begin_frame` used to take the
13027    /// cube's transform as an argument and write it into the pool every frame,
13028    /// so that slot was dirty in every ring slot forever and a motionless scene
13029    /// paid a spinning one's transfer. The bytes were identical, so no golden
13030    /// image could ever have shown it — the recorder's write log is the only
13031    /// place the difference is visible.
13032    ///
13033    /// The pyramid is here so that "only the one that moved" is a claim about a
13034    /// choice: with one instance in the array, uploading it and uploading
13035    /// everything are the same event.
13036    #[test]
13037    fn only_the_instance_that_moved_is_uploaded() {
13038        let (recorder, device, queue) = open();
13039        let mut renderer =
13040            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13041        let instance_buffers = renderer.instances.buffers().to_vec();
13042        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
13043        place_demo(
13044            &mut renderer,
13045            DEMO_PYRAMID,
13046            DEMO_UNTINTED,
13047            Mat4::from_translation(Vec3::X),
13048        );
13049
13050        // Both instances are dirty in *every* slot when they are inserted, so
13051        // the first frames upload both however well delta upload works. The ring
13052        // has to be walked right through before an upload is evidence about the
13053        // delta rather than about initialisation.
13054        let frame = |renderer: &mut ForwardRenderer| {
13055            renderer
13056                .begin_frame(
13057                    device.as_ref(),
13058                    &Camera::default(),
13059                    &DirectionalLight::default(),
13060                    (64, 48),
13061                )
13062                .expect("write");
13063        };
13064        for _ in 0..FRAMES_IN_FLIGHT {
13065            frame(&mut renderer);
13066        }
13067        let instance_writes = |from: usize| -> Vec<(u64, usize)> {
13068            recorder
13069                .events()
13070                .into_iter()
13071                .skip(from)
13072                .filter_map(|event| match event {
13073                    crcbl_hal::null::Event::BufferWritten {
13074                        buffer,
13075                        offset,
13076                        len,
13077                    } if instance_buffers.contains(&buffer) => Some((offset, len)),
13078                    _ => None,
13079                })
13080                .collect()
13081        };
13082
13083        let before = recorder.events().len();
13084        frame(&mut renderer);
13085        assert_eq!(
13086            instance_writes(before),
13087            [],
13088            "a frame in which nothing moved must upload no instance bytes at all"
13089        );
13090
13091        let before = recorder.events().len();
13092        let model = ForwardRenderer::spin(1.25);
13093        renderer.set_instance(
13094            cube,
13095            &InstanceDesc {
13096                mesh: DEMO_CUBE,
13097                material: DEMO_UNTINTED,
13098                transform: model,
13099            },
13100        );
13101        frame(&mut renderer);
13102        assert_eq!(
13103            renderer
13104                .instances
13105                .get(cube)
13106                .expect("the cube is live")
13107                .transform,
13108            model.to_cols_array(),
13109            "the model matrix must land in the instance, not the uniform block"
13110        );
13111        let cube_at = u64::from(renderer.instances.index(cube).expect("the cube is live"))
13112            * crcbl_shaders::mesh::INSTANCE_STRIDE as u64;
13113        assert_eq!(
13114            instance_writes(before),
13115            [(cube_at, crcbl_shaders::mesh::INSTANCE_STRIDE)],
13116            "a steady-state frame must upload exactly the one instance that changed"
13117        );
13118
13119        renderer.destroy(device.as_ref());
13120        recorder.assert_valid();
13121    }
13122
13123    /// **An object takes one pool slot, a rewrite keeps it, and a removal gives
13124    /// it back for the next object to reuse.**
13125    ///
13126    /// The three-call bookkeeping every caller of the instance API depends on,
13127    /// checked on the pool rather than on the recorder. A `set_instance` that
13128    /// inserted instead would take a fresh slot per call — the pool exhausted in
13129    /// a few thousand frames of a caller that writes a transform per frame, which
13130    /// is what every sample does — and every slot it abandoned would stay
13131    /// **live**, so the frame would draw a copy of the object at each transform
13132    /// it had ever been given. Neither is something a golden image would show
13133    /// until the pool ran out.
13134    ///
13135    /// `only_the_instance_that_moved_is_uploaded` is the delta half of this and
13136    /// reads the recorder; this is the bookkeeping half and reads the pool, which
13137    /// is where an abandoned slot would still be counted.
13138    ///
13139    /// Run over every mesh of [`scene::demo`], because the DAG is the one whose
13140    /// slot carries topic 25's hysteresis state — the reuse below is
13141    /// exactly what [`ForwardRenderer::add_instance`] documents as inheriting a
13142    /// previous occupant's expanded groups.
13143    #[test]
13144    fn an_object_takes_one_slot_and_a_removal_gives_it_back() {
13145        for mesh in [DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES] {
13146            let (recorder, device, queue) = open();
13147            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
13148                .expect("built");
13149            // The null backend takes an indirect tail, so the DAG is placeable
13150            // here; the arm that cannot select a level refuses before an
13151            // application ever calls this.
13152            assert!(
13153                renderer.selects_levels(),
13154                "an indirect tail chooses a level for every mesh, DAG included"
13155            );
13156            // What the pool holds before anything is placed, which is nothing: a
13157            // renderer places no object of its own any more.
13158            let resident = renderer.instances.len();
13159            assert_eq!(resident, 0, "a fresh renderer holds no objects");
13160
13161            let first = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
13162            let handle = place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13163            assert_eq!(
13164                renderer.instances.len(),
13165                resident + 1,
13166                "mesh {mesh}: add_instance takes one slot"
13167            );
13168
13169            // The rewrite is the whole test: the same handle, the same slot
13170            // count, and the new transform in it.
13171            let second = Mat4::from_translation(Vec3::new(-4.0, 5.0, -6.0));
13172            renderer.set_instance(
13173                handle,
13174                &InstanceDesc {
13175                    mesh,
13176                    material: DEMO_UNTINTED,
13177                    transform: second,
13178                },
13179            );
13180            assert_eq!(
13181                renderer.instances.len(),
13182                resident + 1,
13183                "mesh {mesh}: set_instance must rewrite its instance, not insert a second"
13184            );
13185            assert_eq!(
13186                renderer.instances.slot_count(),
13187                u32::try_from(resident + 1).expect("a handful of instances"),
13188                "mesh {mesh}: set_instance must not have reached past the slot it holds"
13189            );
13190            assert_eq!(
13191                renderer
13192                    .instances
13193                    .get(handle)
13194                    .unwrap_or_else(|| panic!("mesh {mesh}: the instance is live"))
13195                    .transform,
13196                second.to_cols_array(),
13197                "mesh {mesh}: set_instance must have written the second transform"
13198            );
13199
13200            // And a removal gives the slot back, so a caller toggling an object
13201            // is not a leak either.
13202            renderer.remove_instance(handle);
13203            assert_eq!(
13204                renderer.instances.len(),
13205                resident,
13206                "mesh {mesh}: remove_instance must free the slot rather than hide the object"
13207            );
13208            place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13209            assert_eq!(
13210                renderer.instances.slot_count(),
13211                u32::try_from(resident + 1).expect("a handful of instances"),
13212                "mesh {mesh}: the object after a removal must reuse the freed slot"
13213            );
13214
13215            renderer.destroy(device.as_ref());
13216            recorder.assert_valid();
13217        }
13218    }
13219
13220    /// **The description resolves to the ids the renderer used to hand itself**:
13221    /// one table entry per description mesh, in description order, with the DAG
13222    /// occupying one per level after them — and every level's vertex base
13223    /// measured from level 0's, which is zero.
13224    ///
13225    /// Upload order is what decides a mesh id, and `cull.slang` reads a bounding
13226    /// box out of the entry the *instance* names. So a description walked in
13227    /// another order, or a DAG whose levels landed among the flat meshes, would
13228    /// leave every instance naming a mesh that is not its own: the cube culled
13229    /// against the pyramid's box, the dunes patch drawn as an open box. Every
13230    /// one of those is a frame that still looks like a frame.
13231    ///
13232    /// The bases are asserted against the table bytes rather than against
13233    /// `ResidentMesh`, because the table is what the GPU reads.
13234    #[test]
13235    fn the_description_resolves_to_the_ids_it_was_written_in() {
13236        let (recorder, device, queue) = open();
13237        let renderer =
13238            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13239
13240        assert_eq!(
13241            renderer.mesh_ids,
13242            [0, 1, 2, 3],
13243            "the four description meshes take the first four table entries, in order"
13244        );
13245
13246        // The DAG's coarser levels follow level 0, so a cut that spans them
13247        // reads entries the flat meshes never occupied.
13248        let scene = scene::demo();
13249        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13250            panic!("the demo description's fourth mesh is the DAG");
13251        };
13252        let level_ids: Vec<u32> = (0..dag.levels.len())
13253            .map(|level| renderer.mesh_ids[DEMO_DUNES] + level as u32)
13254            .collect();
13255        assert!(
13256            level_ids
13257                .iter()
13258                .all(|&id| id > renderer.mesh_ids[DEMO_OPEN_BOX]),
13259            "every dunes level is past the flat residents: {level_ids:?}"
13260        );
13261
13262        // **Level 0 is at the pool's own first vertex**, which is what makes
13263        // every `ClusterSelect::vertex_base` a non-negative offset from it — the
13264        // sum the mesh stage forms with the instance's own base.
13265        let entries: Vec<crcbl_shaders::mesh::GpuMesh> = level_ids
13266            .iter()
13267            .map(|&id| mesh_entry(&recorder, &renderer, id))
13268            .collect();
13269        let level_zero = entries[0].base_vertex;
13270        assert_eq!(
13271            level_zero,
13272            mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_OPEN_BOX]).base_vertex
13273                + crcbl_shaders::mesh::OPEN_BOX_VERTEX_COUNT as u32,
13274            "the DAG starts where the last flat resident ends"
13275        );
13276        let bases: Vec<u32> = entries
13277            .iter()
13278            .map(|entry| {
13279                entry
13280                    .base_vertex
13281                    .checked_sub(level_zero)
13282                    .expect("a level below level 0 would wrap the offset a cluster carries")
13283            })
13284            .collect();
13285        assert_eq!(
13286            bases[0], 0,
13287            "level 0 is the base every other is measured from"
13288        );
13289        assert!(
13290            bases.windows(2).all(|pair| pair[0] < pair[1]),
13291            "each level starts past the one below it: {bases:?}"
13292        );
13293
13294        renderer.destroy(device.as_ref());
13295        recorder.assert_valid();
13296    }
13297
13298    /// **A description that is not [`scene::demo`]: five meshes and two DAGs.**
13299    ///
13300    /// [`ForwardRenderer::with_scene`] is written for any mesh count and any
13301    /// number of DAGs, and until this nothing had put either through it — every
13302    /// golden image and every end-to-end run is `scene::demo()`, whose four
13303    /// meshes hold one DAG between them.
13304    ///
13305    /// What only a second DAG exercises is the **concatenation**: `level_groups`
13306    /// is every DAG's groups laid end to end and a DAG reaches its own run
13307    /// through the `first_group` offset handed to `ClusterDag::selection_records`,
13308    /// which is zero for the first one and therefore invisible while there is
13309    /// only one. A second DAG whose records still named the first's groups would
13310    /// descend a hierarchy belonging to another surface — a cut that is a
13311    /// plausible picture and matches no assertion the CPU makes about the frame.
13312    ///
13313    /// On the mesh path, because that is where the offset is *used*: an indirect
13314    /// tail takes a uniform cut and builds no [`ClusterSelect`] records at all.
13315    ///
13316    /// [`ClusterSelect`]: crcbl_shaders::cluster_select::ClusterSelect
13317    #[test]
13318    fn a_second_dag_reaches_its_own_groups_and_not_the_first_s() {
13319        use crcbl_shaders::cluster_select::{CLUSTER_SELECT_STRIDE, ClusterSelect};
13320
13321        let recorder = Recorder::new();
13322        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
13323
13324        // The engine has one DAG, so a second one is a second copy of it. That
13325        // is the whole point: two DAGs whose *groups* are alike is the case
13326        // where reaching the wrong run still produces a cut, and so the case a
13327        // frame comparison could never catch.
13328        let mut scene = scene::demo();
13329        let mut again = scene.meshes[DEMO_DUNES].clone();
13330        again.label = "dunes again".into();
13331        scene.meshes.push(again);
13332        // Room for the second copy. Doubling rather than measuring, because the
13333        // number that matters is that the description carries its own sizes at
13334        // all — see `Capacities`, which is the caller's to choose.
13335        scene.capacities.vertices *= 2;
13336        scene.capacities.indices *= 2;
13337        let second_dag = scene.meshes.len() - 1;
13338
13339        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13340            panic!("the demo description's fourth mesh is the DAG");
13341        };
13342        let levels = dag.levels.len();
13343        let groups = dag.level_groups().len();
13344        assert!(groups > 0, "a DAG with no groups would select nothing");
13345
13346        let mut renderer =
13347            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13348                .expect("a five-mesh description with two DAGs is one this can make resident");
13349
13350        // Every level of both is its own table entry, laid down in description
13351        // order, so the second DAG's level 0 is a whole hierarchy past the
13352        // first's.
13353        assert_eq!(
13354            renderer.mesh_ids.len(),
13355            scene.meshes.len(),
13356            "one id per description mesh, whatever the count"
13357        );
13358        assert_eq!(
13359            renderer.mesh_ids[second_dag],
13360            renderer.mesh_ids[DEMO_DUNES] + levels as u32,
13361            "the second DAG's level 0 starts past every level of the first"
13362        );
13363
13364        // **The hysteresis state is per instance per resident group**, and
13365        // `group_stride` is what says how many groups that is. One DAG made this
13366        // number a single hierarchy's; two is what tells a stride that sums from
13367        // one that took the first answer it found.
13368        assert_eq!(
13369            renderer.primary.draws.group_stride(),
13370            u32::try_from(groups * 2).expect("a few dozen groups per DAG"),
13371            "every resident DAG's groups are in the stride, not just the first's"
13372        );
13373
13374        // The records themselves: which group each cluster produces and which
13375        // contains it, as the amplification stage reads them.
13376        let clusters = renderer
13377            .clusters
13378            .as_ref()
13379            .expect("the mesh path builds a cluster pool");
13380        let selection = recorder
13381            .buffer_bytes(clusters.selection())
13382            .expect("the selection records are live");
13383        // Entries are laid down in description order, a flat mesh taking one and
13384        // a DAG one per level — so the second DAG's start a hierarchy past the
13385        // first's, which start past the three flat residents.
13386        let first_entry = DEMO_DUNES;
13387        let record = |entry: usize| -> Vec<ClusterSelect> {
13388            let range = clusters.range(entry).expect("one range per entry");
13389            (range.base..range.base + range.count)
13390                .map(|cluster| {
13391                    let at = cluster as usize * CLUSTER_SELECT_STRIDE;
13392                    ClusterSelect::from_bytes(
13393                        selection[at..at + CLUSTER_SELECT_STRIDE]
13394                            .try_into()
13395                            .expect("one whole record"),
13396                    )
13397                })
13398                .collect()
13399        };
13400        // The named group of every record that has one, per DAG — and the count,
13401        // because a comparison over an empty set is a check that cannot fail.
13402        let named = |base: usize| -> Vec<u32> {
13403            (base..base + levels)
13404                .flat_map(record)
13405                .flat_map(|select| {
13406                    let producer = (select.flags & ClusterSelect::HAS_PRODUCER != 0)
13407                        .then_some(select.producer_group);
13408                    let container = (select.flags & ClusterSelect::HAS_CONTAINER != 0)
13409                        .then_some(select.container_group);
13410                    producer.into_iter().chain(container)
13411                })
13412                .collect()
13413        };
13414        let boundary = u32::try_from(groups).expect("a few dozen groups per DAG");
13415        let first = named(first_entry);
13416        let second = named(first_entry + levels);
13417        assert!(
13418            !first.is_empty() && first.len() == second.len(),
13419            "the two copies must name the same number of groups: {} against {}",
13420            first.len(),
13421            second.len()
13422        );
13423        assert!(
13424            first.iter().all(|&group| group < boundary),
13425            "the first DAG's records stay inside its own run: {first:?}"
13426        );
13427        assert!(
13428            second
13429                .iter()
13430                .all(|&group| (boundary..boundary * 2).contains(&group)),
13431            "the second DAG's records must name the groups past the first's, and \
13432             `first_group` is the only thing that puts them there: {second:?}"
13433        );
13434
13435        // And both are placeable through the runtime API, which is what a
13436        // description of a shape no `set_*` method names is *for*.
13437        let place = |renderer: &mut ForwardRenderer, mesh: usize, x: f32| {
13438            renderer
13439                .add_instance(&InstanceDesc {
13440                    mesh,
13441                    material: DEMO_UNTINTED,
13442                    transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)),
13443                })
13444                .expect("the pool has room")
13445        };
13446        let near = place(&mut renderer, DEMO_DUNES, -64.0);
13447        let far = place(&mut renderer, second_dag, 64.0);
13448        let index = |handle| {
13449            renderer
13450                .instances
13451                .index(handle)
13452                .expect("a just-added instance is live")
13453        };
13454        assert_ne!(
13455            index(near),
13456            index(far),
13457            "two instances take two slots, and the index is the hysteresis key"
13458        );
13459        assert_eq!(
13460            renderer.instances.get(far).expect("live").mesh,
13461            renderer.mesh_ids[second_dag],
13462            "an InstanceDesc's mesh index resolves through the description, not through \
13463             a table id the caller cannot know"
13464        );
13465
13466        renderer.destroy(device.as_ref());
13467        recorder.assert_valid();
13468    }
13469
13470    /// **A description the renderer cannot make resident is refused before the
13471    /// first device object exists**, so a rejection leaks nothing.
13472    ///
13473    /// `build` hands the geometry pool and the material table to the rollback
13474    /// and then creates a dozen objects with `?` between them. A check that ran
13475    /// part way down that list would be a new early exit on the wrong side of a
13476    /// handover, and the pool would go with it — which is exactly the leak
13477    /// `Rollback` exists to prevent and which
13478    /// `the_forward_renderer_builds_and_leaks_nothing` cannot see, because it
13479    /// only walks the happy path.
13480    ///
13481    /// Each arm below is a *different* refusal, so a check that stopped running
13482    /// would show up as one arm leaking rather than as all of them — and each
13483    /// names a fragment of the message it must be refused *with*, or an arm
13484    /// would pass on some other check's answer.
13485    /// **A description with no meshes is refused by name**, before anything
13486    /// is created, rather than reaching the mesh table's sizing with nothing
13487    /// to size it from.
13488    #[test]
13489    fn a_scene_with_no_meshes_is_refused_by_name() {
13490        let (recorder, device, queue) = open();
13491        let before = recorder.total_live_objects();
13492        let mut scene = scene::demo();
13493        scene.meshes.clear();
13494        let error =
13495            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13496                .expect_err("a scene of no meshes must be refused");
13497        assert!(
13498            error.to_string().contains("at least one mesh"),
13499            "the refusal says what is missing: {error}"
13500        );
13501        assert_eq!(
13502            recorder.total_live_objects(),
13503            before,
13504            "the refusal created something"
13505        );
13506    }
13507
13508    #[test]
13509    fn a_refused_description_creates_nothing_at_all() {
13510        /// One way of writing a description the renderer cannot build, and the
13511        /// words that say it was this refusal rather than another.
13512        type Break = (&'static str, fn(&mut SceneDesc<'static>), &'static str);
13513
13514        let cases: [Break; 9] = [
13515            (
13516                "a row naming a layer the page has not got",
13517                |scene| {
13518                    scene.materials[DEMO_TEXTURED].base_color_texture = 7;
13519                },
13520                "material row 2 samples base-colour page layer 7",
13521            ),
13522            // And the same on the two kinds rung 3 added, because `check_scene`
13523            // reads a different column of the row for each: a check written per
13524            // kind is only worth what its arms cover, and a column nobody broke
13525            // here could be read out of the wrong material field for ever.
13526            // `demo` names no layer of either, so any index at all is past the
13527            // end.
13528            (
13529                "a row naming a packed-page layer the page has not got",
13530                |scene| {
13531                    scene.materials[DEMO_TEXTURED].metallic_roughness_occlusion_texture = 3;
13532                },
13533                "material row 2 samples metallic-roughness-occlusion page layer 3",
13534            ),
13535            (
13536                "a row naming an emissive layer the page has not got",
13537                |scene| {
13538                    scene.materials[DEMO_TEXTURED].emissive_texture = 3;
13539                },
13540                "material row 2 samples emissive page layer 3",
13541            ),
13542            // The one page refusal a caller can actually spell: `push_layer`
13543            // takes bytes it cannot measure against the extent.
13544            (
13545                "a page layer of the wrong length",
13546                |scene| {
13547                    scene.page = scene::PageDesc::empty();
13548                    scene
13549                        .page
13550                        .set_extent(PageKind::BaseColor, scene::PAGE_EXTENT);
13551                    scene.page.push_layer(PageKind::BaseColor, vec![0x00; 4]);
13552                    scene.materials[DEMO_TEXTURED].base_color_texture = scene::CHECKER_LAYER;
13553                },
13554                "base-colour page layer 0 carries 4 bytes",
13555            ),
13556            (
13557                "a DAG level with no vertices",
13558                |scene| {
13559                    let Geometry::Dag { levels, .. } = &mut scene.meshes[DEMO_DUNES].geometry
13560                    else {
13561                        panic!("the demo description's fourth mesh is the DAG");
13562                    };
13563                    levels.pop();
13564                },
13565                "vertex array(s) for a DAG of",
13566            ),
13567            // The four capacities, each of which is a pool a caller sized and
13568            // a description outgrew. Written as a capacity the description is
13569            // too large for rather than as a description too large for the
13570            // default, because that is the shape of the mistake: the numbers on
13571            // `Capacities` are the ones an application picks.
13572            (
13573                "more vertices than the pool holds",
13574                |scene| {
13575                    scene.capacities.vertices = 1;
13576                },
13577                "the vertex pool holds 1 and the description needs",
13578            ),
13579            (
13580                "more indices than the pool holds",
13581                |scene| {
13582                    scene.capacities.indices = 1;
13583                },
13584                "the index pool holds 1 and the description needs",
13585            ),
13586            (
13587                "more meshes than the table holds",
13588                |scene| {
13589                    scene.capacities.meshes = 1;
13590                },
13591                "the mesh table holds 1 and the description needs",
13592            ),
13593            (
13594                "more material rows than the table holds",
13595                |scene| {
13596                    scene.capacities.materials = 2;
13597                },
13598                "the material table holds 2 and the description needs 3",
13599            ),
13600        ];
13601
13602        for (what, break_it, says) in cases {
13603            let (recorder, device, queue) = open();
13604            let before = recorder.total_live_objects();
13605            let mut scene = scene::demo();
13606            break_it(&mut scene);
13607            let error =
13608                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13609                    .expect_err(&format!("{what} must be refused"));
13610            assert!(
13611                matches!(error, HalError::InvalidDescriptor(_)),
13612                "{what} must be refused as an invalid descriptor, not as {error:?}"
13613            );
13614            assert!(
13615                error.to_string().contains(says),
13616                "{what} must be refused with a message saying so, and this one says {error}"
13617            );
13618            assert_eq!(
13619                recorder.total_live_objects(),
13620                before,
13621                "{what} was refused after something had been created, and the rollback \
13622                 is the only thing that could have released it"
13623            );
13624            recorder.assert_valid();
13625        }
13626
13627        // **And the refusal that is not free**, which is the half of the
13628        // handover every arm above walks past: `check_scene` settles what the
13629        // whole description says, and what one mesh's *bytes* say is the pool's,
13630        // which only sees them one upload at a time. Vertex bytes that are not a
13631        // whole number of vertices reach `MeshPool::upload` — so the third of
13632        // the four meshes is refused with the pool created, two device-local
13633        // buffers in it and the first two meshes already staged into them.
13634        // `build_geometry` is what releases that, and it can only do so because
13635        // the pool is not the rollback's until it has returned.
13636        let (recorder, device, queue) = open();
13637        let before = recorder.total_live_objects();
13638        // So the count below is this build's and not `open`'s.
13639        recorder.clear();
13640        let mut scene = scene::demo();
13641        let Geometry::Flat { vertices, .. } = &mut scene.meshes[DEMO_OPEN_BOX].geometry else {
13642            panic!("the demo description's third mesh is flat");
13643        };
13644        vertices.to_mut().push(0);
13645        let error =
13646            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13647                .expect_err("a mesh of part of a vertex must be refused");
13648        assert!(
13649            error.to_string().contains("is not a whole number of"),
13650            "the pool's own refusal reaches the caller with its numbers, and this \
13651             one says {error}"
13652        );
13653        assert!(
13654            recorder
13655                .events()
13656                .iter()
13657                .any(|event| matches!(event, crcbl_hal::null::Event::Created { .. })),
13658            "this arm is evidence about the rollback only if the refusal came after \
13659             something had been created"
13660        );
13661        assert_eq!(
13662            recorder.total_live_objects(),
13663            before,
13664            "a mesh refused part way through the list left the geometry pool behind, \
13665             which is exactly what `build_geometry` being self-cleaning is for"
13666        );
13667        recorder.assert_valid();
13668    }
13669
13670    /// **The one capacity a description cannot be checked against, and the one
13671    /// an application is expected to handle while it runs.**
13672    ///
13673    /// Every other number on [`scene::Capacities`] sizes something the
13674    /// description fills once, so `check_scene` refuses an over-large one before
13675    /// a device object exists. Objects are placed at any point in a renderer's
13676    /// life, so the only honest answer for that one is the error
13677    /// [`ForwardRenderer::add_instance`] returns — and it returns
13678    /// [`InstancePoolError`] rather than a [`HalError`], so the capacity and
13679    /// what is in it survive to the caller that chose them.
13680    ///
13681    /// It also gives [`Capacities::instances`](scene::Capacities::instances) a
13682    /// value of its own rather than the default, which is what makes the pool
13683    /// fillable at all: a renderer that ignored the number the description
13684    /// carries and reserved the default would draw every frame in the tree
13685    /// identically and refuse nothing here.
13686    #[test]
13687    fn a_full_instance_pool_reaches_the_application_that_sized_it() {
13688        let (recorder, device, queue) = open();
13689        let mut scene = scene::demo();
13690        scene.capacities.instances = 2;
13691        let mut renderer =
13692            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13693                .expect("a scene with room for two objects builds");
13694        let place = |renderer: &mut ForwardRenderer| {
13695            renderer.add_instance(&InstanceDesc {
13696                mesh: DEMO_CUBE,
13697                material: DEMO_UNTINTED,
13698                transform: Mat4::IDENTITY,
13699            })
13700        };
13701        place(&mut renderer).expect("the first of two");
13702        place(&mut renderer).expect("the second of two");
13703        let error = place(&mut renderer).expect_err("a third object has no slot to go in");
13704        assert!(
13705            matches!(
13706                error,
13707                InstancePoolError::PoolFull {
13708                    capacity: 2,
13709                    in_use: 2
13710                }
13711            ),
13712            "a full pool must reach the caller as a full pool, with the capacity it \
13713             chose; this arrived as {error}"
13714        );
13715        renderer.destroy(device.as_ref());
13716        recorder.assert_valid();
13717    }
13718
13719    /// **One mesh and one material row is a scene, and it draws.**
13720    ///
13721    /// The floor is gone. `with_scene` used to refuse anything shorter than
13722    /// [`scene::demo`] — four meshes and three rows — because the five `set_*`
13723    /// demo wrappers named those entries by position, and the renderer's own
13724    /// `dunes_clusters` and `dunes_level_buckets` indexed the description at
13725    /// `DEMO_DUNES` besides. So an application's own description was not merely
13726    /// refused: with the check removed it would have panicked out of `build`.
13727    ///
13728    /// A frame is recorded rather than only a build, because that is where the
13729    /// positional indexing was: the bucket table, the cluster ranges and the
13730    /// draw-argument blocks are all one-per-description-mesh, and a renderer that
13731    /// still assumed four would come apart here rather than at `with_scene`.
13732    #[test]
13733    fn a_description_smaller_than_the_demo_is_a_scene() {
13734        use std::borrow::Cow;
13735
13736        let scene = SceneDesc {
13737            meshes: vec![scene::MeshDesc {
13738                label: Cow::Borrowed("the only mesh"),
13739                geometry: Geometry::Flat {
13740                    vertices: Cow::Owned(crcbl_shaders::mesh::cube_vertex_bytes()),
13741                    uv_range: crcbl_shaders::mesh::demo_uv_range(),
13742                    indices: Cow::Owned(crcbl_shaders::mesh::cube_indices()),
13743                    clusters: crcbl_shaders::meshlet::cube_clusters(),
13744                    flags: 0,
13745                },
13746            }],
13747            materials: vec![mesh::GpuMaterial::UNTINTED],
13748            page: scene::PageDesc::empty(),
13749            probes: scene::ProbeGrid::default(),
13750            capacities: scene::Capacities::default(),
13751        };
13752        assert!(
13753            scene.meshes.len() < scene::demo().meshes.len()
13754                && scene.materials.len() < scene::demo().materials.len(),
13755            "this description must be smaller than the demo's in both, or it says nothing \
13756             about the floor"
13757        );
13758
13759        let (recorder, device, queue) = open();
13760        let mut renderer =
13761            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13762                .expect("one mesh and one row is a description the renderer can hold");
13763        assert_eq!(
13764            renderer.mesh_ids,
13765            [0],
13766            "the one description mesh takes the one table entry"
13767        );
13768        assert_eq!(
13769            renderer.bucket_constants.len(),
13770            1,
13771            "one bucket per description mesh, and there is one"
13772        );
13773        renderer
13774            .add_instance(&InstanceDesc {
13775                mesh: 0,
13776                material: 0,
13777                transform: Mat4::IDENTITY,
13778            })
13779            .expect("an empty pool has room for the only object");
13780        let recorded = frame(device.as_ref(), &mut renderer, queue);
13781        assert_eq!(
13782            commands_in_pass(&recorder, "forward")
13783                .into_iter()
13784                .filter(|command| matches!(
13785                    command,
13786                    crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
13787                ))
13788                .count(),
13789            1,
13790            "a one-mesh scene records the one bucket's indirect call"
13791        );
13792        recorded.finish(device.as_ref(), renderer);
13793    }
13794
13795    /// **A description that exactly fills what it reserved is built, not
13796    /// refused.**
13797    ///
13798    /// The other side of the capacity check, and the side nothing else in the
13799    /// tree can fail on: every other scene reserves far more than it holds, so a
13800    /// comparison written `>=` instead of `>` would pass the whole suite and
13801    /// refuse only the application that had sized its pools exactly right.
13802    ///
13803    /// The two capacities asserted here are the two a caller can size without
13804    /// re-deriving anything the renderer knows: one mesh table entry per
13805    /// [`Geometry::levels`], which is what that method is documented to answer,
13806    /// and one row per material. The four rows share one comparison, so they
13807    /// stand or fall together.
13808    #[test]
13809    fn a_description_that_exactly_fits_its_capacities_is_built() {
13810        let (recorder, device, queue) = open();
13811        let mut scene = scene::demo();
13812        scene.capacities.meshes = scene
13813            .meshes
13814            .iter()
13815            .map(|desc| u32::try_from(desc.geometry.levels()).expect("a few levels"))
13816            .sum();
13817        scene.capacities.materials =
13818            u32::try_from(scene.materials.len()).expect("a few material rows");
13819        let renderer =
13820            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13821                .expect("a description that fits exactly is not too large for itself");
13822        renderer.destroy(device.as_ref());
13823        recorder.assert_valid();
13824    }
13825
13826    /// **The level tables cover every mesh-table slot an instance can name**,
13827    /// not only the slots the description filled.
13828    ///
13829    /// `draw_gen.slang`'s `mesh_levels_of` reads `gen.mesh_levels_at + mesh *
13830    /// MESH_LEVELS_WORDS` with no bound, and says in its own doc comment that
13831    /// "every entry an instance can name is filled". An instance's mesh id is a
13832    /// bare table index, so a table sized to the description alone makes that
13833    /// read land in whatever the packer put next for any slot the description
13834    /// left empty.
13835    ///
13836    /// Growing the capacity by a known number of slots grows the tables buffer
13837    /// by exactly what those slots occupy: one `MeshLevels` record and one
13838    /// `level_meshes` word each. The arithmetic is the assertion, so nothing
13839    /// here is a number to keep in step by hand.
13840    #[test]
13841    fn the_level_tables_cover_every_slot_the_mesh_table_has() {
13842        const EXTRA: u32 = 4;
13843
13844        let sized = |extra: u32| {
13845            let (recorder, device, queue) = open();
13846            let mut scene = scene::demo();
13847            scene.capacities.meshes += extra;
13848            let renderer =
13849                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13850                    .expect("a description with room to spare");
13851            let size = recorder
13852                .buffer_bytes(renderer.primary.draws.tables())
13853                .expect("the table buffer is live")
13854                .len();
13855            renderer.destroy(device.as_ref());
13856            recorder.assert_valid();
13857            size
13858        };
13859
13860        let grown = sized(EXTRA) - sized(0);
13861        let want = EXTRA as usize * (crcbl_shaders::level_select::MESH_LEVELS_STRIDE + 4);
13862        assert_eq!(
13863            grown, want,
13864            "{EXTRA} more table slots must add {EXTRA} more selection records and {EXTRA} more \
13865             level words, and added {grown} bytes"
13866        );
13867    }
13868
13869    /// The property the whole arrangement exists for: the pool's second
13870    /// resident is **not** at base vertex zero, so a frame containing it is a
13871    /// frame that fails if the base is lost between the pool and the shader.
13872    ///
13873    /// Read out of the **mesh table** rather than out of a renderer field,
13874    /// because the table is where a generated draw's index range comes from:
13875    /// `draw_gen.slang` builds every argument structure out of these bytes and
13876    /// nothing on the CPU is consulted.
13877    ///
13878    /// Without this the pass is back where it started — one mesh, base 0, and a
13879    /// base-vertex bug that no picture can show.
13880    #[test]
13881    fn the_second_mesh_lands_past_the_first() {
13882        let (recorder, device, queue) = open();
13883        let renderer =
13884            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13885        let cube = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_CUBE]);
13886        let pyramid = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_PYRAMID]);
13887
13888        assert_eq!(cube.base_vertex, 0, "the cube is first");
13889        assert_eq!(
13890            pyramid.base_vertex as usize,
13891            crcbl_shaders::mesh::CUBE_VERTEX_COUNT,
13892            "the pyramid must start where the cube ends, or the pools are not \
13893             suballocating at all"
13894        );
13895        assert_eq!(
13896            pyramid.index_count as usize,
13897            crcbl_shaders::mesh::PYRAMID_INDEX_COUNT,
13898            "and the entry carries the whole range, which is what the draw-argument \
13899             pass builds its arguments out of"
13900        );
13901        // And the two buckets read different constant blocks, or both would walk
13902        // the same run of instances.
13903        assert_ne!(
13904            renderer.bucket_constants[DEMO_CUBE], renderer.bucket_constants[DEMO_PYRAMID],
13905            "each bucket needs a block of its own"
13906        );
13907        renderer.destroy(device.as_ref());
13908    }
13909
13910    /// **Each bucket's block points at that bucket's own run**, and the runs do
13911    /// not overlap.
13912    ///
13913    /// This is what replaced "the block names an instance": a draw covers
13914    /// however many instances survived culling, so what it can say for itself is
13915    /// only where to find its slice of the survivors. Two buckets naming one
13916    /// start word would draw each other's objects — with the *right* geometry,
13917    /// because the index range comes from the arguments, which is exactly the
13918    /// kind of plausible wrong picture a golden image struggles with.
13919    ///
13920    /// Read out of the bytes that reached the device rather than out of the
13921    /// renderer's own fields, because the failure is a block written wrong and
13922    /// the field would still be right.
13923    #[test]
13924    fn each_bucket_walks_its_own_run_of_survivors() {
13925        let (recorder, device, queue) = open();
13926        let renderer =
13927            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13928        let blocks = recorder
13929            .buffer_bytes(renderer.draw_constants)
13930            .expect("the blocks are live");
13931        let start_word_at = |offset: u32| {
13932            let at = offset as usize;
13933            u32::from_le_bytes(blocks[at..at + 4].try_into().expect("four bytes"))
13934        };
13935
13936        let draws = &renderer.primary.draws;
13937        let cube = start_word_at(renderer.bucket_constants[DEMO_CUBE]);
13938        let pyramid = start_word_at(renderer.bucket_constants[DEMO_PYRAMID]);
13939        // **Behind the survivors, their routes and the runs**, which share the
13940        // buffer: a block naming a word inside the runs would have the draw read
13941        // an instance index as its start, and one inside the survivor list or
13942        // the routes a start that is the same instances in a different order, or
13943        // a bucket number — both of which draw a plausible picture.
13944        assert_eq!(
13945            cube,
13946            draws.runs_at() + draws.visible_capacity(),
13947            "the first bucket's start word is the first word past one capacity of runs"
13948        );
13949        assert_eq!(
13950            pyramid,
13951            cube + (DEMO_PYRAMID - DEMO_CUBE) as u32,
13952            "and the second's is a word later — a start per bucket, not a run per bucket"
13953        );
13954        assert_eq!(
13955            cube,
13956            draws.bucket_start_word(DEMO_CUBE as u32),
13957            "the block carries what `DrawGen::bucket_start_word` says, because a reader \
13958             copying a run back uses that accessor and the shader uses this block"
13959        );
13960        renderer.destroy(device.as_ref());
13961    }
13962
13963    /// **An instance's record carries its material's mode**, in the bits
13964    /// `draw_gen.slang` routes by.
13965    ///
13966    /// The host half of the per-bucket split, and the half no picture and no
13967    /// pipeline bind can show: the bucket table can be perfectly twinned and
13968    /// every partition bound to the right pipeline while every instance still
13969    /// answers mode zero, in which case the masked twins are empty, the cutout
13970    /// partition draws nothing, and a cutout casts a solid shadow. The record is
13971    /// where that is decided.
13972    ///
13973    /// Both directions, so the check is shown to discriminate: the opaque
13974    /// instance's mode bits have to be **clear**, or a writer that set them
13975    /// unconditionally would satisfy a one-sided assertion. And the two records
13976    /// are asserted to differ in `flags` and nothing else, so this is about the
13977    /// mode rather than about two unrelated instances.
13978    #[test]
13979    fn an_instances_record_carries_its_materials_mode() {
13980        let masked_scene = {
13981            let mut scene = crate::scene::demo();
13982            scene.materials[DEMO_TINTED].flags = crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
13983            scene
13984        };
13985        let (recorder, device, queue) = open();
13986        let device = device.as_ref();
13987        let mut renderer =
13988            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &masked_scene)
13989                .expect("the null backend accepts the demo description");
13990        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
13991        let opaque = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
13992        let masked = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
13993
13994        let record = |handle: InstanceHandle| {
13995            renderer
13996                .instances
13997                .get(handle)
13998                .expect("the instance was inserted and is live")
13999        };
14000        let opaque = record(opaque);
14001        let masked = record(masked);
14002        assert_eq!(
14003            opaque.material_mode(),
14004            0,
14005            "an opaque material's instance carries no mode bits, or every instance in the tree \
14006             routes to a cutout bucket"
14007        );
14008        assert_eq!(
14009            masked.material_mode(),
14010            crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK,
14011            "and a masked material's instance carries its mode, or it scatters into the opaque \
14012             twin and the depth passes write its full silhouette"
14013        );
14014        assert_eq!(
14015            mesh::GpuInstance {
14016                flags: opaque.flags,
14017                material: opaque.material,
14018                ..masked
14019            },
14020            opaque,
14021            "the two records differ in the mode bits and the material id and in nothing else"
14022        );
14023
14024        renderer.destroy(device);
14025        recorder.assert_valid();
14026    }
14027
14028    /// **A scene whose materials are all opaque gets exactly the bucket table
14029    /// it had before material modes existed** — one bucket per (mesh, level),
14030    /// and no twin.
14031    ///
14032    /// The zero-cost half of the per-bucket split, and the one a null device can
14033    /// state exactly. A bucket is not free: every pass records one indirect call
14034    /// per bucket per view, and every generator holds a run start per bucket. So
14035    /// a table that twinned unconditionally would double the recorded draws of
14036    /// every demo and every golden in this tree, none of which mask anything.
14037    ///
14038    /// The oracle is [`level_buckets`](ForwardRenderer::level_buckets), which is
14039    /// built from a mesh's own level count rather than from the table's length —
14040    /// so a build that emitted a twin per mesh has more buckets than levels and
14041    /// this says so. And the twinned scenes below are asserted to be exactly as
14042    /// many times as long as they hold modes, or the comparison would pass on a
14043    /// renderer that had stopped twinning at all.
14044    ///
14045    /// # A twin per mode the scene **holds**, not per mode that exists
14046    ///
14047    /// [`DEPTH_MODES`] has four entries and a bucket is not free — every pass
14048    /// records one indirect call per bucket — so the rule that matters is which
14049    /// values the description's own materials carry. Two rows of two modes are
14050    /// two twins whichever two they are, and the pair below says so both ways:
14051    /// three modes across three rows is three, and three rows collapsed onto two
14052    /// *values* is two even though between them they set both mode bits.
14053    #[test]
14054    fn an_all_opaque_scene_keeps_one_bucket_per_mesh_level() {
14055        use crcbl_shaders::mesh::GpuMaterial;
14056
14057        let (recorder, device, queue) = open();
14058        let device = device.as_ref();
14059        let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
14060        // The uniform-cut path, where a DAG is one bucket per level. The mesh
14061        // path folds a DAG into one bucket and reports no level buckets at all,
14062        // which would leave the oracle below empty.
14063        assert!(
14064            !renderer.emit.is_mesh(),
14065            "this preset built a mesh-shader path, whose level buckets are empty"
14066        );
14067        let levels: usize = (0..crate::scene::demo().meshes.len())
14068            .map(|mesh| renderer.level_buckets(mesh).len())
14069            .sum();
14070        assert!(levels > 0, "the demo has meshes, so it has levels");
14071        assert_eq!(
14072            renderer.bucket_constants.len(),
14073            levels,
14074            "an all-opaque scene's bucket table is one bucket per (mesh, level) and no mode \
14075             twin: {levels} level(s) against {} bucket(s)",
14076            renderer.bucket_constants.len()
14077        );
14078        assert_eq!(
14079            renderer.bucket_modes,
14080            vec![0; levels],
14081            "and every one of them draws the OPAQUE mode"
14082        );
14083        let opaque_meshes = renderer.draw_tables.bucket_meshes.clone();
14084        let opaque_level_buckets: Vec<Vec<u32>> = (0..crate::scene::demo().meshes.len())
14085            .map(|mesh| renderer.level_buckets(mesh).to_vec())
14086            .collect();
14087        renderer.destroy(device);
14088        recorder.assert_valid();
14089
14090        // Every arrangement worth stating, as the modes its material rows carry
14091        // and the number of twins that has to produce. The demo has three rows;
14092        // a fourth is appended where four distinct modes are wanted, which
14093        // nothing instances and which therefore changes nothing but the mode
14094        // set.
14095        for (rows, modes, what) in [
14096            (
14097                vec![GpuMaterial::ALPHA_MODE_MASK, 0, 0],
14098                2,
14099                "one masked row beside two opaque ones",
14100            ),
14101            (
14102                vec![GpuMaterial::DOUBLE_SIDED, 0, 0],
14103                2,
14104                "one double-sided row beside two opaque ones",
14105            ),
14106            (
14107                vec![GpuMaterial::ALPHA_MODE_MASK, GpuMaterial::DOUBLE_SIDED, 0],
14108                3,
14109                "a masked row, a double-sided one and an opaque one",
14110            ),
14111            (
14112                vec![
14113                    GpuMaterial::ALPHA_MODE_MASK,
14114                    GpuMaterial::DOUBLE_SIDED,
14115                    GpuMaterial::ALPHA_MODE_MASK,
14116                ],
14117                2,
14118                "three rows carrying two mode values between them — both mode bits are set \
14119                 somewhere and neither row is opaque, so a rule counting bits rather than \
14120                 values would say three",
14121            ),
14122            (
14123                vec![
14124                    0,
14125                    GpuMaterial::ALPHA_MODE_MASK,
14126                    GpuMaterial::DOUBLE_SIDED,
14127                    GpuMaterial::MODE_MASK,
14128                ],
14129                4,
14130                "one row of each mode, which is the only arrangement that pays for four",
14131            ),
14132        ] {
14133            let scene = {
14134                let mut scene = crate::scene::demo();
14135                while scene.materials.len() < rows.len() {
14136                    scene.materials.push(GpuMaterial::UNTINTED);
14137                }
14138                for (row, flags) in scene.materials.iter_mut().zip(&rows) {
14139                    row.flags = *flags;
14140                }
14141                scene
14142            };
14143            let (recorder, device, queue) = open();
14144            let device = device.as_ref();
14145            let twinned =
14146                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
14147                    .expect("the null backend accepts the demo description");
14148            assert_eq!(
14149                twinned.bucket_constants.len(),
14150                modes * levels,
14151                "{what}: {modes} mode(s) over {levels} level(s) is {} bucket(s), and the table \
14152                 has {}",
14153                modes * levels,
14154                twinned.bucket_constants.len()
14155            );
14156            // The modes present, as a set — which is the claim, since the order
14157            // is `DEPTH_MODES`' and the count above already pins the length.
14158            let held: std::collections::BTreeSet<u32> =
14159                twinned.bucket_modes.iter().copied().collect();
14160            let want: std::collections::BTreeSet<u32> = rows.iter().copied().collect();
14161            assert_eq!(
14162                held, want,
14163                "{what}: the table twins the modes its materials carry and no others"
14164            );
14165            for mode in &held {
14166                assert_eq!(
14167                    twinned
14168                        .bucket_modes
14169                        .iter()
14170                        .filter(|held| *held == mode)
14171                        .count(),
14172                    levels,
14173                    "{what}: every mode present gets every mesh's levels once"
14174                );
14175            }
14176            // **Mode-major**: each held mode is one contiguous run of the
14177            // all-opaque table, in `DEPTH_MODES` order, so a pipeline's
14178            // partition is one range of buckets.
14179            let held_in_order: Vec<u32> = DEPTH_MODES
14180                .into_iter()
14181                .filter(|mode| held.contains(mode))
14182                .collect();
14183            assert_eq!(
14184                twinned.bucket_modes,
14185                held_in_order
14186                    .iter()
14187                    .flat_map(|mode| std::iter::repeat_n(*mode, levels))
14188                    .collect::<Vec<_>>(),
14189                "{what}: every bucket of one mode is contiguous, modes in DEPTH_MODES order"
14190            );
14191            assert_eq!(
14192                twinned.draw_tables.bucket_meshes,
14193                opaque_meshes.repeat(held_in_order.len()),
14194                "{what}: each mode's run is the all-opaque table, mesh by mesh"
14195            );
14196            for (mesh, opaque) in opaque_level_buckets.iter().enumerate() {
14197                assert_eq!(
14198                    twinned.level_buckets(mesh),
14199                    opaque.as_slice(),
14200                    "{what}: mesh {mesh}'s level buckets are the first mode's run"
14201                );
14202            }
14203            // And the `(mesh, mode) → bucket` lookup the scatter routes through
14204            // sends every key to its mode's run, at the mesh's own offset.
14205            let lookup = crcbl_shaders::draw_gen::bucket_lookup(
14206                &twinned.draw_tables.bucket_meshes,
14207                &twinned.bucket_modes,
14208            )
14209            .expect("a small lookup");
14210            for (slot, mode) in held_in_order.iter().enumerate() {
14211                for (offset, mesh) in opaque_meshes.iter().enumerate() {
14212                    let key = 1 + (*mesh * crcbl_shaders::draw_gen::MATERIAL_MODES + *mode);
14213                    assert_eq!(
14214                        lookup[key as usize] as usize,
14215                        slot * levels + offset,
14216                        "{what}: mesh {mesh} in mode {mode}"
14217                    );
14218                }
14219            }
14220            twinned.destroy(device);
14221            recorder.assert_valid();
14222        }
14223    }
14224
14225    /// **The two pyramids differ in exactly one field, and it is the material
14226    /// id — which names a row holding a different colour and a different
14227    /// roughness.**
14228    ///
14229    /// The whole of what §3.2's table buys, stated as the two things that have
14230    /// to be true at once. Placed at the *same* transform, so "differ only in
14231    /// material" is literal rather than nearly: same mesh id, same matrix, same
14232    /// flags, and a `GpuInstance` comparison that would fail on any other
14233    /// field. And the ids they carry name rows the device actually holds —
14234    /// asserted on the bytes in the buffer, because a table the renderer agrees
14235    /// with itself about is not a table a shader can read.
14236    ///
14237    /// The two rows are asserted to differ, or the pair would be evidence of
14238    /// nothing: two instances naming two rows of the same colour draw the same
14239    /// picture whether or not either id was ever used.
14240    #[test]
14241    fn the_two_pyramids_differ_only_in_their_material() {
14242        let (recorder, device, queue) = open();
14243        let mut renderer =
14244            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14245        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14246        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14247        let tinted_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14248
14249        let instance = |handle: InstanceHandle| {
14250            renderer
14251                .instances
14252                .get(handle)
14253                .expect("the instance was inserted and is live")
14254        };
14255        let plain = instance(plain_handle);
14256        let tinted = instance(tinted_handle);
14257        assert_ne!(
14258            plain.material, tinted.material,
14259            "the two pyramids must not share a material row"
14260        );
14261        assert_eq!(
14262            mesh::GpuInstance {
14263                material: tinted.material,
14264                ..plain
14265            },
14266            tinted,
14267            "the two instances must differ in the material id and in nothing else"
14268        );
14269
14270        let bytes = recorder
14271            .buffer_bytes(renderer.materials.buffer())
14272            .expect("the table is live");
14273        let row = |index: u32| {
14274            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14275            mesh::GpuMaterial::from_bytes(
14276                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14277                    .try_into()
14278                    .expect("one row"),
14279            )
14280        };
14281        assert_eq!(
14282            row(plain.material),
14283            mesh::GpuMaterial::UNTINTED,
14284            "the plain pyramid's row must be the factor that changes nothing"
14285        );
14286        assert_eq!(
14287            row(tinted.material),
14288            mesh::GpuMaterial {
14289                base_color: scene::PYRAMID_TINT,
14290                roughness: scene::PYRAMID_ROUGHNESS,
14291                ..mesh::GpuMaterial::UNTINTED
14292            },
14293            "the tinted pyramid's row must be the tint and the tighter lobe"
14294        );
14295        // The shading half of that row, on its own: a roughness equal to the
14296        // neutral row's would leave `crcbl`'s render e2e comparing one lobe
14297        // against itself, and that test would go green on a shader that had
14298        // never read the column.
14299        assert_ne!(
14300            row(plain.material).roughness,
14301            row(tinted.material).roughness,
14302            "the two rows must differ in roughness, or the highlight the render e2e measures \
14303             is not attributable to the material"
14304        );
14305        assert_ne!(
14306            row(plain.material),
14307            row(tinted.material),
14308            "two rows holding the same colour would make the pair prove nothing"
14309        );
14310        // And the tint is the *only* thing that differs between them: a row that
14311        // also changed its page layer would make this pair evidence about two
14312        // columns at once, which is what the third pyramid exists to avoid.
14313        assert_eq!(
14314            row(plain.material).base_color_texture,
14315            row(tinted.material).base_color_texture,
14316            "the factor pair must sample the same page layer"
14317        );
14318
14319        // And the second pyramid leaves the frame the way the first does: the
14320        // instance is removed, not a draw skipped.
14321        renderer.remove_instance(tinted_handle);
14322        assert!(
14323            renderer.instances.get(tinted_handle).is_none(),
14324            "the instance must be given back, or an object nobody asked for stays in the scene"
14325        );
14326
14327        renderer.destroy(device.as_ref());
14328    }
14329
14330    /// **The same claim one column along: the plain and textured pyramids
14331    /// differ in exactly one field, and the rows it names differ in exactly one
14332    /// column — the base-colour page layer.**
14333    ///
14334    /// [`the_two_pyramids_differ_only_in_their_material`]'s argument for §3.2's
14335    /// *texture indices* rather than its *factors*. The factors of the two rows
14336    /// are asserted **equal** here, which is the half that makes the pair
14337    /// evidence about the texture at all: a textured row that also carried a
14338    /// tint would draw a different picture for a reason the frame could not
14339    /// distinguish from the tinted pyramid's.
14340    ///
14341    /// The layer numbers are asserted against the page the renderer actually
14342    /// uploaded, so a row naming a layer that does not exist is caught here
14343    /// rather than as an out-of-range sample on a device.
14344    #[test]
14345    fn the_textured_pyramid_differs_only_in_its_page_layer() {
14346        let (recorder, device, queue) = open();
14347        let mut renderer =
14348            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14349        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14350        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14351        let textured_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TEXTURED, at);
14352
14353        let instance = |handle: InstanceHandle| {
14354            renderer
14355                .instances
14356                .get(handle)
14357                .expect("the instance was inserted and is live")
14358        };
14359        let plain = instance(plain_handle);
14360        let textured = instance(textured_handle);
14361        assert_ne!(
14362            plain.material, textured.material,
14363            "the two pyramids must not share a material row"
14364        );
14365        assert_eq!(
14366            mesh::GpuInstance {
14367                material: textured.material,
14368                ..plain
14369            },
14370            textured,
14371            "the two instances must differ in the material id and in nothing else"
14372        );
14373
14374        let bytes = recorder
14375            .buffer_bytes(renderer.materials.buffer())
14376            .expect("the table is live");
14377        let row = |index: u32| {
14378            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14379            mesh::GpuMaterial::from_bytes(
14380                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14381                    .try_into()
14382                    .expect("one row"),
14383            )
14384        };
14385        assert_eq!(
14386            row(plain.material).base_color,
14387            row(textured.material).base_color,
14388            "the texture pair must share a factor, or the pair is evidence about both columns"
14389        );
14390        assert_eq!(
14391            row(plain.material).base_color_texture,
14392            mesh::GpuMaterial::NO_PAGE
14393        );
14394        assert_eq!(
14395            row(textured.material).base_color_texture,
14396            scene::CHECKER_LAYER
14397        );
14398        assert_ne!(
14399            row(plain.material),
14400            row(textured.material),
14401            "two rows naming the same layer would make the pair prove nothing"
14402        );
14403        // The layer that number names is a layer the page has, and it is not
14404        // one flat colour — a checker of one repeated texel would pass every
14405        // assertion above and draw the picture the untextured row draws.
14406        let page = scene::demo().page;
14407        let layers = page.layers(PageKind::BaseColor);
14408        assert!(
14409            (scene::CHECKER_LAYER as usize) < layers.len(),
14410            "layer {} is past the end of a {}-layer page, which is an out-of-range sample \
14411             nothing below the seam would report",
14412            scene::CHECKER_LAYER,
14413            layers.len()
14414        );
14415        let checker = &layers[scene::CHECKER_LAYER as usize];
14416        assert!(
14417            checker
14418                .as_chunks::<4>()
14419                .0
14420                .iter()
14421                .any(|texel| texel != &checker[..4]),
14422            "a flat checker layer would shade the textured row exactly as the untextured \
14423             one shades, and the pair would prove nothing"
14424        );
14425
14426        renderer.remove_instance(textured_handle);
14427        assert!(
14428            renderer.instances.get(textured_handle).is_none(),
14429            "the instance must be given back, or an object nobody asked for stays in the scene"
14430        );
14431
14432        renderer.destroy(device.as_ref());
14433    }
14434
14435    /// **A [`PageKind`] nothing names costs one texel**, not `extent² × 4` bytes
14436    /// and a third again for its chain.
14437    ///
14438    /// This is what row (d) bought, and it is the half of it no picture can
14439    /// show: the frame a scene with no normal map draws is byte-identical either
14440    /// way, because `mesh.slang` returns before it fetches. What changes is the
14441    /// image the renderer created, and the copies into it are where that is
14442    /// visible. `crcbl/tests/mesh_e2e/normal_map.rs`'s
14443    /// `no_normal_map_returns_the_surface_normal_exactly_and_the_neutral_texel_does_not`
14444    /// is the device-side half saying the frame did not move.
14445    ///
14446    /// [`scene::demo`] is the scene: every one of its rows carries
14447    /// [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) in the normal column, and it is
14448    /// the description every golden in this tree is a variation of.
14449    ///
14450    /// # Sabotage
14451    ///
14452    /// The empty-kind arm of the upload loop uploading a full 64² neutral layer
14453    /// and its chain instead of the placeholder — the shape this replaced. Red
14454    /// on 2026-09-06 with `"a description with no normal map must upload the
14455    /// one-texel placeholder, and this copied 7 level(s) at [Extent3d { width:
14456    /// 64, height: 64, depth_or_layers: 1 }, … ] — a burned neutral layer costs
14457    /// extent² × 4 bytes and a third again for its chain, on every scene in the
14458    /// tree"`.
14459    #[test]
14460    fn a_page_kind_nothing_names_costs_one_texel() {
14461        use crcbl_hal::null::Command;
14462
14463        let scene = scene::demo();
14464        assert!(
14465            scene
14466                .materials
14467                .iter()
14468                .all(|row| row.normal_texture == mesh::GpuMaterial::NO_PAGE),
14469            "a row naming a normal layer would make the description one that *does* name \
14470             the page, and this test would be about the other case"
14471        );
14472        assert!(
14473            scene.page.layers(PageKind::Normal).is_empty()
14474                && scene.page.extent(PageKind::BaseColor) > 1,
14475            "the description must name no normal layer while naming base-colour ones, or \
14476             a placeholder-sized copy says nothing about which page it landed in"
14477        );
14478
14479        let (recorder, device, queue) = open();
14480        let renderer =
14481            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14482                .expect("a description naming no normal page is one this can make resident");
14483
14484        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14485            .commands()
14486            .into_iter()
14487            .filter_map(|command| match command {
14488                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14489                    Some(copy)
14490                }
14491                _ => None,
14492            })
14493            .collect();
14494        let extents: Vec<crcbl_hal::Extent3d> =
14495            copies.iter().map(|copy| copy.image_extent).collect();
14496        assert_eq!(
14497            extents,
14498            vec![crcbl_hal::Extent3d::d2(1, 1)],
14499            "a description with no normal map must upload the one-texel placeholder, and \
14500             this copied {} level(s) at {extents:?} — a burned neutral layer costs \
14501             extent² × 4 bytes and a third again for its chain, on every scene in the tree",
14502            copies.len()
14503        );
14504
14505        // The placeholder is one layer, and the graph declaration says so: a
14506        // caller importing this page to write a layer of its own would get
14507        // `ImportDeclarationConflict` against an extent that was not 1×1.
14508        assert_eq!(
14509            renderer.normal_page_import().extent,
14510            (1, 1),
14511            "the declaration names the placeholder's extent, not the base-colour page's"
14512        );
14513        renderer.destroy(device.as_ref());
14514    }
14515
14516    /// **A page and a material table that are the caller's own, not
14517    /// [`scene::demo`]'s**: a different extent per kind, more layers than the
14518    /// demo page holds, a normal page the demo does not have at all, and rows
14519    /// past the three the demo writes.
14520    ///
14521    /// Every other scene in the tree is `scene::demo()` — with a mesh appended,
14522    /// at most — so until this nothing had put an app-supplied *layer* or an
14523    /// app-supplied *row* through [`ForwardRenderer::with_scene`] at all. A
14524    /// build that uploaded the demo's two layers and stopped, or that inserted
14525    /// its three rows and stopped, would leave every golden byte-identical and
14526    /// pass every other assertion in this module: the demo scene cannot tell a
14527    /// table filled from the description from one filled up to the description's
14528    /// third row.
14529    ///
14530    /// Read off the recorder rather than off the description, because the
14531    /// description is the input. The copies are what reached the image and the
14532    /// table buffer is what the shader indexes, and neither is a restatement of
14533    /// what was handed in.
14534    #[test]
14535    fn an_app_page_and_table_reach_the_device_whole() {
14536        use crcbl_hal::null::Command;
14537
14538        /// Not [`scene::PAGE_EXTENT`], so an extent that had been compiled in
14539        /// rather than read off the page shows up as a copy of the wrong size.
14540        const APP_EXTENT: u32 = 4;
14541
14542        /// **Not [`APP_EXTENT`]**, which is the whole of what row (d)'s per-kind
14543        /// extent bought: a renderer that still sized the normal page from the
14544        /// base-colour page's number would copy this layer at 4² and the copy
14545        /// list below would say so.
14546        const APP_NORMAL_EXTENT: u32 = 2;
14547        let layer_bytes = APP_EXTENT as usize * APP_EXTENT as usize * 4;
14548
14549        // Three base-colour layers, each flat and each a value of its own: a
14550        // build that uploaded one layer twice, or that stopped short, is a
14551        // different sequence of copies. Then one normal layer at the other
14552        // extent, which the demo scene has no page for at all.
14553        let mut page = scene::PageDesc::empty();
14554        page.set_extent(PageKind::BaseColor, APP_EXTENT);
14555        page.set_extent(PageKind::Normal, APP_NORMAL_EXTENT);
14556        let app_layers: Vec<u32> = [0x11_u8, 0x22, 0x33]
14557            .into_iter()
14558            .map(|value| page.push_layer(PageKind::BaseColor, vec![value; layer_bytes]))
14559            .collect();
14560        let app_normal = page.push_layer(
14561            PageKind::Normal,
14562            scene::PageDesc::NEUTRAL_NORMAL
14563                .repeat(APP_NORMAL_EXTENT as usize * APP_NORMAL_EXTENT as usize),
14564        );
14565
14566        let mut scene = scene::demo();
14567        scene.page = page;
14568        // One row per appended layer, and each with a factor of its own as well,
14569        // so a row that landed at another row's id is not a row that happens to
14570        // look like it. The last of them names the normal layer too, so the
14571        // table carries a row through both pages.
14572        for (nth, &layer) in app_layers.iter().enumerate() {
14573            let shade = 0.25 * (nth as f32 + 1.0);
14574            let last = nth + 1 == app_layers.len();
14575            scene.materials.push(mesh::GpuMaterial {
14576                base_color: [shade, shade, shade, 1.0],
14577                base_color_texture: layer,
14578                normal_texture: if last {
14579                    app_normal
14580                } else {
14581                    mesh::GpuMaterial::NO_PAGE
14582                },
14583                ..mesh::GpuMaterial::UNTINTED
14584            });
14585        }
14586        assert!(
14587            scene.materials.len() > scene::demo().materials.len()
14588                && scene.page.layers(PageKind::BaseColor).len()
14589                    > scene::demo().page.layers(PageKind::BaseColor).len(),
14590            "the description under test must exceed the demo's in both, or this is a \
14591             demo test wearing another name"
14592        );
14593        assert_eq!(
14594            scene::demo().page.extent(PageKind::Normal),
14595            0,
14596            "the demo scene must name no normal page, or the normal copies below are \
14597             evidence about the demo's page rather than the caller's"
14598        );
14599
14600        let (recorder, device, queue) = open();
14601        let mut renderer =
14602            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14603                .expect("a page and a table of the caller's own are ones this can make resident");
14604
14605        // The page, layer by layer. Filtered by image because the build uploads
14606        // the ambient-occlusion placeholder through the same path.
14607        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14608            .commands()
14609            .into_iter()
14610            .filter_map(|command| match command {
14611                Command::CopyBufferToImage(copy)
14612                    if copy.image == renderer.base_color_page.image =>
14613                {
14614                    Some(copy)
14615                }
14616                _ => None,
14617            })
14618            .collect();
14619        // Every layer goes up with its chain — three levels for this extent —
14620        // so the copies are layer-major, level-minor, each at its level's own
14621        // extent.
14622        let levels = crcbl_hal::Extent3d::d2(APP_EXTENT, APP_EXTENT)
14623            .full_mip_levels(crcbl_hal::ImageType::D2);
14624        assert_eq!(levels, 3, "a 4² page has three levels down to one texel");
14625        let layer_count = u32::try_from(scene.page.layers(PageKind::BaseColor).len())
14626            .expect("a page of a few layers");
14627        assert_eq!(
14628            copies
14629                .iter()
14630                .map(|copy| (
14631                    copy.image_subresource.base_layer,
14632                    copy.image_subresource.mip
14633                ))
14634                .collect::<Vec<(u32, u32)>>(),
14635            (0..layer_count)
14636                .flat_map(|layer| (0..levels).map(move |level| (layer, level)))
14637                .collect::<Vec<(u32, u32)>>(),
14638            "every level of every layer the description carries must be copied into the page, \
14639             in order"
14640        );
14641        assert!(
14642            copies.iter().all(|copy| {
14643                let side = crate::mip::level_extent(APP_EXTENT, copy.image_subresource.mip);
14644                copy.image_extent == crcbl_hal::Extent3d::d2(side, side)
14645            }),
14646            "the page is the extent the caller wrote, not the demo's, halved per level: \
14647             {copies:?}"
14648        );
14649
14650        // The normal page, at **its own** extent. One layer, two levels for a
14651        // 2² image, and every copy sized from `APP_NORMAL_EXTENT` — a renderer
14652        // that carried one extent for both kinds would put this layer up at 4².
14653        let normal_copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14654            .commands()
14655            .into_iter()
14656            .filter_map(|command| match command {
14657                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14658                    Some(copy)
14659                }
14660                _ => None,
14661            })
14662            .collect();
14663        let normal_levels = crcbl_hal::Extent3d::d2(APP_NORMAL_EXTENT, APP_NORMAL_EXTENT)
14664            .full_mip_levels(crcbl_hal::ImageType::D2);
14665        assert_eq!(
14666            normal_copies
14667                .iter()
14668                .map(|copy| (
14669                    copy.image_subresource.base_layer,
14670                    copy.image_subresource.mip,
14671                    copy.image_extent
14672                ))
14673                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14674            (0..normal_levels)
14675                .map(|level| {
14676                    let side = crate::mip::level_extent(APP_NORMAL_EXTENT, level);
14677                    (0, level, crcbl_hal::Extent3d::d2(side, side))
14678                })
14679                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14680            "the normal page is the extent the caller wrote for *that* kind, halved per \
14681             level: {normal_copies:?}"
14682        );
14683        assert_eq!(
14684            renderer.normal_page_import().extent,
14685            (APP_NORMAL_EXTENT, APP_NORMAL_EXTENT),
14686            "the graph declaration names the normal page's own extent, or a caller \
14687             importing it to write a layer gets ImportDeclarationConflict"
14688        );
14689        assert_eq!(
14690            renderer.base_color_page_import().extent,
14691            (APP_EXTENT, APP_EXTENT),
14692            "and the base-colour declaration names its own, which is a different number"
14693        );
14694
14695        // The table, row by row, out of the buffer `mesh.slang` indexes.
14696        let bytes = recorder
14697            .buffer_bytes(renderer.materials.buffer())
14698            .expect("the table is live");
14699        let row = |id: u32| {
14700            let at = id as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14701            mesh::GpuMaterial::from_bytes(
14702                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14703                    .try_into()
14704                    .expect("one row"),
14705            )
14706        };
14707        assert_eq!(
14708            renderer.material_ids.len(),
14709            scene.materials.len(),
14710            "one id per description row, whatever the count"
14711        );
14712        for (index, wrote) in scene.materials.iter().enumerate() {
14713            assert_eq!(
14714                &row(renderer.material_ids[index]),
14715                wrote,
14716                "description row {index} must be the row its id names"
14717            );
14718        }
14719
14720        // And a caller can place an object through a row only its own
14721        // description has, which is the whole point of the rows being the
14722        // caller's.
14723        let last = scene.materials.len() - 1;
14724        let handle = renderer
14725            .add_instance(&InstanceDesc {
14726                mesh: DEMO_CUBE,
14727                material: last,
14728                transform: Mat4::IDENTITY,
14729            })
14730            .expect("an empty pool of thousands has room for one object");
14731        assert_eq!(
14732            renderer
14733                .instances
14734                .get(handle)
14735                .expect("a just-added instance is live")
14736                .material,
14737            renderer.material_ids[last],
14738            "an InstanceDesc's material index resolves through the description, not \
14739             through a table id the caller cannot know"
14740        );
14741
14742        renderer.destroy(device.as_ref());
14743        recorder.assert_valid();
14744    }
14745
14746    /// **The frame records two compute dispatches and exactly one indirect draw
14747    /// per bucket — whatever is in the scene.**
14748    ///
14749    /// The property topic 03 opens with, checked on the recorded command stream:
14750    /// adding the pyramid adds an instance and changes no command. A pass that
14751    /// had kept a draw per object would record one command here and two there,
14752    /// which is what this used to assert and what the indirect path replaced.
14753    ///
14754    /// It also pins the arguments each call names: bucket `n` reads the `n`-th
14755    /// argument structure and the `n`-th count, at the stride every API fixed.
14756    /// Two calls pointing at one structure is a frame that draws one object
14757    /// twice.
14758    #[test]
14759    fn the_frame_records_one_indirect_call_per_bucket_whatever_the_scene_holds() {
14760        use crcbl_hal::null::Command;
14761
14762        for pyramid in [None, Some(Mat4::from_translation(Vec3::X))] {
14763            let (recorder, device, queue) = open();
14764            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
14765                .expect("built");
14766            // The cube in both scenes, so the difference between them is the
14767            // pyramid alone. It also keeps both frames non-empty, and an empty
14768            // one would be a weaker comparison than this claims: `cull`'s
14769            // dispatch covers no workgroups when the pool is empty, and the pass
14770            // records nothing rather than a dispatch of zero — see
14771            // [`DrawGen::add_passes`].
14772            place_cube(&mut renderer, Mat4::IDENTITY);
14773            if let Some(at) = pyramid {
14774                place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14775            }
14776            let frame = frame(device.as_ref(), &mut renderer, queue);
14777
14778            let stride = crcbl_shaders::draw_gen::DRAW_ARGS_SIZE as u32;
14779            let expected: Vec<(u32, u64, u64)> = (0..renderer.bucket_constants.len())
14780                .map(|bucket| {
14781                    (
14782                        renderer.bucket_constants[bucket],
14783                        bucket as u64 * u64::from(stride),
14784                        bucket as u64 * 4,
14785                    )
14786                })
14787                .collect();
14788
14789            // The dynamic offset last bound before each draw, paired with the
14790            // offsets that draw read its arguments and its count from.
14791            let mut offset = None;
14792            let mut seen: Vec<(u32, u64, u64)> = Vec::new();
14793            let mut dispatches = 0;
14794            for command in recorder.commands() {
14795                if matches!(command, Command::Dispatch { .. }) {
14796                    dispatches += 1;
14797                }
14798            }
14799            for command in commands_in_pass(&recorder, "forward") {
14800                match command {
14801                    Command::BindGroup {
14802                        slot: 0,
14803                        dynamic_offsets,
14804                        ..
14805                    } => offset = dynamic_offsets.first().copied(),
14806                    Command::DrawIndexedIndirectCount(draw) => {
14807                        assert_eq!(draw.stride, stride, "sizeof(VkDrawIndexedIndirectCommand)");
14808                        assert_eq!(
14809                            draw.max_draw_count, 1,
14810                            "one argument structure per bucket, so one is the ceiling"
14811                        );
14812                        seen.push((
14813                            offset.expect("a draw is preceded by its constant block"),
14814                            draw.args_offset,
14815                            draw.count_offset,
14816                        ));
14817                    }
14818                    Command::DrawIndexed { .. } => {
14819                        panic!("the forward pass must not record a CPU-counted draw any more")
14820                    }
14821                    _ => {}
14822                }
14823            }
14824            assert_eq!(
14825                dispatches,
14826                DrawGen::DISPATCHES as usize * (1 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
14827                "the clearing pass, the cull pass and the draw-argument pass's three, in \
14828                 front of the draws — once for the camera and once per shadow cascade — plus \
14829                 topic 18's one clustering dispatch, which is the camera's alone because a \
14830                 cascade shades nothing, plus the resolve's own"
14831            );
14832            assert_eq!(
14833                seen, expected,
14834                "with pyramid = {pyramid:?}, the pass must record one indirect call per \
14835                 bucket, each pointing at its own arguments, its own count and its own \
14836                 block"
14837            );
14838
14839            frame.finish(device.as_ref(), renderer);
14840        }
14841    }
14842
14843    /// **The two `GeometryPath` arms record different calls and nothing else
14844    /// differs.**
14845    ///
14846    /// A device with a GPU-side count takes it from GPU memory; one without —
14847    /// Metal, whose API has multi-draw-indirect and no count buffer — reads each
14848    /// bucket's one argument structure unconditionally. Same buckets, same
14849    /// arguments, same block: the tail is the only thing that moves, which is
14850    /// what topic 03 means by "the lesser path is
14851    /// a constraint on data layout, not a separate renderer".
14852    ///
14853    /// Both presets are run here rather than only the one this machine has,
14854    /// because the arm a device never selects is the arm nothing tests.
14855    #[test]
14856    fn each_geometry_path_records_its_own_indirect_call() {
14857        use crcbl_hal::null::Command;
14858
14859        for (preset, path, counted) in [
14860            (
14861                NullInstance::gpu_driven(),
14862                GeometryPath::IndirectCount,
14863                true,
14864            ),
14865            (
14866                NullInstance::portable(),
14867                GeometryPath::IndirectPerBatch,
14868                false,
14869            ),
14870        ] {
14871            let recorder = Recorder::new();
14872            let instance = preset.with_recorder(recorder.clone());
14873            let adapter = instance.adapters().remove(0);
14874            assert_eq!(
14875                adapter.caps.geometry_path(),
14876                path,
14877                "the preset must select the path this arm is about"
14878            );
14879            // `DeviceDesc::for_adapter` requires a timeline semaphore, which the
14880            // portable preset does not have; the forward pass does not need one
14881            // either, so this asks for what it uses. The optional set matters:
14882            // a device is opened with the features it *asked* for, and the path
14883            // is derived from those rather than from the adapter's.
14884            let device = instance
14885                .create_device(&DeviceDesc {
14886                    label: None,
14887                    adapter: adapter.id,
14888                    required_features: Features::COMPUTE,
14889                    optional_features: Features::GPU_DRIVEN,
14890                    compatible_surface: None,
14891                })
14892                .expect("the null backend always opens");
14893            assert_eq!(
14894                device.caps().geometry_path(),
14895                path,
14896                "and the opened device still selects it"
14897            );
14898            let queue = device.queue(QueueKind::Graphics).expect("always present");
14899            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
14900                .expect("built");
14901            let frame = frame(device.as_ref(), &mut renderer, queue);
14902
14903            let mut counted_calls = 0;
14904            let mut per_batch_calls = 0;
14905            for command in commands_in_pass(&recorder, "forward") {
14906                match command {
14907                    Command::DrawIndexedIndirectCount(_) => counted_calls += 1,
14908                    Command::DrawIndexedIndirect(draw) => {
14909                        assert_eq!(
14910                            draw.draw_count, 1,
14911                            "one argument structure per bucket, read unconditionally"
14912                        );
14913                        per_batch_calls += 1;
14914                    }
14915                    _ => {}
14916                }
14917            }
14918            let buckets = renderer.bucket_constants.len();
14919            let (expected_counted, expected_per_batch) =
14920                if counted { (buckets, 0) } else { (0, buckets) };
14921            assert_eq!(
14922                (counted_calls, per_batch_calls),
14923                (expected_counted, expected_per_batch),
14924                "{path:?} must record one call of its own kind per bucket and none of the other"
14925            );
14926
14927            frame.finish(device.as_ref(), renderer);
14928        }
14929    }
14930
14931    /// Serialises the two checks that move
14932    /// [`r_debug_draw`](crate::debug_draw::r_debug_draw), and puts it back
14933    /// afterwards.
14934    ///
14935    /// A [`ConVar`](crcbl_console::ConVar) is process-global by design, and
14936    /// `cargo test` runs a crate's tests as threads of *one* process: two checks
14937    /// that move the switch are then two writers to one cell, which shows up as
14938    /// a flake rather than as a failure anybody can read.
14939    /// `crcbl::debug_view::for_test` is the same shape one crate up and there
14940    /// for the same reason; this one is smaller because nothing outside these
14941    /// two tests ever writes the cell.
14942    fn debug_draw_switch() -> DebugDrawSwitch {
14943        let guard = DEBUG_DRAW_SWITCH
14944            .lock()
14945            .unwrap_or_else(std::sync::PoisonError::into_inner);
14946        let switch = DebugDrawSwitch { _guard: guard };
14947        switch.set(false);
14948        switch
14949    }
14950
14951    /// What [`debug_draw_switch`] hands back: the switch is this thread's until
14952    /// it drops, and it goes back off when it does.
14953    struct DebugDrawSwitch {
14954        _guard: std::sync::MutexGuard<'static, ()>,
14955    }
14956
14957    impl DebugDrawSwitch {
14958        /// Moves the switch.
14959        fn set(&self, on: bool) {
14960            crate::debug_draw::r_debug_draw
14961                .set(&crcbl_console::Value::Bool(on))
14962                .expect("`r_debug_draw` is a writable bool");
14963        }
14964    }
14965
14966    impl Drop for DebugDrawSwitch {
14967        fn drop(&mut self) {
14968            // Off at both ends, so a check that panicked mid-way does not hand
14969            // the next holder a switched-on layer.
14970            self.set(false);
14971        }
14972    }
14973
14974    /// [`debug_draw_switch`]'s lock.
14975    ///
14976    /// **First of the two**, when a test takes this and [`ssao_blur_switch`]
14977    /// both — see that function for what the opposite order cost.
14978    static DEBUG_DRAW_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
14979
14980    /// Takes `r_ssao_blur_passes` for this thread and puts it back at its
14981    /// default when the guard drops.
14982    ///
14983    /// [`debug_draw_switch`]'s shape exactly, for its reason: a plain
14984    /// `cargo test` run shares one process between tests, and a variable this
14985    /// one left moved is a frame the next test did not ask for.
14986    ///
14987    /// **Every test whose assertion depends on the shape of a frame takes this,
14988    /// not only the one that moves the count.** The variable is a process
14989    /// global and `cargo test` runs this module's tests on threads that share
14990    /// it, so a frame built while
14991    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] holds two blurs
14992    /// carries an `ssao-blur-2` pass, a full-screen triangle and a pipeline bind
14993    /// that the test building it never asked for. Taking the guard both
14994    /// serialises against that test and pins the count for the frames this one
14995    /// builds.
14996    ///
14997    /// Two shapes need it, and the second is easy to miss. A test comparing a
14998    /// frame against a **literal pass list** breaks whenever the count is two.
14999    /// A test comparing **two frames it built itself** — a difference in draws,
15000    /// an equality between pass lists, a "one pass longer" claim — breaks only
15001    /// when the count *moves between them*, which is a narrower window and why
15002    /// this reproduced at roughly one run in eight rather than every run.
15003    ///
15004    /// Both were established by experiment on 2026-09-01 rather than by
15005    /// reading: pinning the count at two reddens the first shape, and making
15006    /// `crate::ssao::blur_passes` alternate reddens the second.
15007    ///
15008    /// **A test taking this and [`debug_draw_switch`] takes that one first.**
15009    /// These are two plain mutexes with no ordering between them, so two tests
15010    /// acquiring both in opposite orders deadlock — which is not a hazard this
15011    /// comment is guessing at: adding the guard to the two debug-draw tests
15012    /// above their existing one did exactly that on 2026-09-01, and turned a
15013    /// 0.2 second suite into one that had not finished in ten minutes. It is
15014    /// invisible in a single-threaded run, where the same suite passes in a
15015    /// second, so `--test-threads=1` is not a check for it.
15016    ///
15017    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`]: fn@a_second_occlusion_blur_is_a_pass_the_frame_records
15018    pub(super) fn ssao_blur_switch() -> SsaoBlurSwitch {
15019        let guard = SSAO_BLUR_SWITCH
15020            .lock()
15021            .unwrap_or_else(std::sync::PoisonError::into_inner);
15022        let switch = SsaoBlurSwitch { _guard: guard };
15023        switch.set(1);
15024        switch
15025    }
15026
15027    /// What [`ssao_blur_switch`] hands back.
15028    pub(super) struct SsaoBlurSwitch {
15029        _guard: std::sync::MutexGuard<'static, ()>,
15030    }
15031
15032    impl SsaoBlurSwitch {
15033        /// Asks for `passes` of them.
15034        fn set(&self, passes: i64) {
15035            crate::ssao::r_ssao_blur_passes
15036                .set(&crcbl_console::Value::Int(passes))
15037                .expect("`r_ssao_blur_passes` is a writable int in range");
15038        }
15039    }
15040
15041    impl Drop for SsaoBlurSwitch {
15042        fn drop(&mut self) {
15043            // Back to the shipping count at both ends, so a check that panicked
15044            // mid-way does not hand the next holder a three-pass frame.
15045            self.set(1);
15046        }
15047    }
15048
15049    /// [`ssao_blur_switch`]'s lock.
15050    static SSAO_BLUR_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15051
15052    /// Takes `r_ssao_split` for this thread and puts it back when the guard
15053    /// drops.
15054    ///
15055    /// [`ssao_blur_switch`]'s shape exactly, for its reason. The seam is what
15056    /// makes the occlusion chain record its second march, so a test about the
15057    /// widest frame a renderer can produce has to hold this as well as the blur
15058    /// count — see `crate::ssao`'s `r_ssao_split`.
15059    pub(super) fn ssao_split_switch() -> SsaoSplitSwitch {
15060        let guard = SSAO_SPLIT_SWITCH
15061            .lock()
15062            .unwrap_or_else(std::sync::PoisonError::into_inner);
15063        let switch = SsaoSplitSwitch { _guard: guard };
15064        switch.set(0.0);
15065        switch
15066    }
15067
15068    /// What [`ssao_split_switch`] hands back.
15069    pub(super) struct SsaoSplitSwitch {
15070        _guard: std::sync::MutexGuard<'static, ()>,
15071    }
15072
15073    impl SsaoSplitSwitch {
15074        /// Asks for a seam at `at`, or for none at zero.
15075        fn set(&self, at: f32) {
15076            crate::ssao::r_ssao_split
15077                .set(&crcbl_console::Value::Float(at))
15078                .expect("`r_ssao_split` is a writable float in range");
15079        }
15080    }
15081
15082    impl Drop for SsaoSplitSwitch {
15083        fn drop(&mut self) {
15084            // Back to the default at both ends, so a check that panicked
15085            // mid-way does not hand the next holder a comparing frame.
15086            self.set(0.0);
15087        }
15088    }
15089
15090    /// [`ssao_split_switch`]'s lock.
15091    static SSAO_SPLIT_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15092
15093    /// Takes `r_shadow_filter` and `r_shadow_split` for this thread and puts
15094    /// them both back at their defaults when the guard drops.
15095    ///
15096    /// [`ssao_split_switch`]'s shape, with two variables under one lock because
15097    /// they are read into one row of one block — `crate::shadow::FILTER_SWITCH`
15098    /// is where that is argued, and why the lock lives there rather than beside
15099    /// this function: `crate::shadow`'s own tests move the same two.
15100    fn shadow_filter_switch() -> ShadowFilterSwitch {
15101        let guard = crate::shadow::FILTER_SWITCH
15102            .lock()
15103            .unwrap_or_else(std::sync::PoisonError::into_inner);
15104        let switch = ShadowFilterSwitch { _guard: guard };
15105        switch.reset();
15106        switch
15107    }
15108
15109    /// What [`shadow_filter_switch`] hands back.
15110    struct ShadowFilterSwitch {
15111        _guard: std::sync::MutexGuard<'static, ()>,
15112    }
15113
15114    impl ShadowFilterSwitch {
15115        /// Asks for `filter` on the near side of the seam.
15116        fn filter(&self, filter: shadow::Filter) {
15117            crate::shadow::r_shadow_filter
15118                .set(&crcbl_console::Value::Enum(filter.label()))
15119                .expect("`r_shadow_filter` is a writable enum in the set");
15120        }
15121
15122        /// Asks for a seam at `at`, or for none at zero.
15123        fn seam(&self, at: f32) {
15124            crate::shadow::r_shadow_split
15125                .set(&crcbl_console::Value::Float(at))
15126                .expect("`r_shadow_split` is a writable float in range");
15127        }
15128
15129        /// Asks for `texels` of constant bias.
15130        fn bias(&self, texels: f32) {
15131            crate::shadow::r_shadow_bias
15132                .set(&crcbl_console::Value::Float(texels))
15133                .expect("`r_shadow_bias` is a writable float in range");
15134        }
15135
15136        /// Asks for `texels` of normal offset.
15137        fn offset(&self, texels: f32) {
15138            crate::shadow::r_shadow_normal_offset
15139                .set(&crcbl_console::Value::Float(texels))
15140                .expect("`r_shadow_normal_offset` is a writable float in range");
15141        }
15142
15143        /// Back to the frame every golden was blessed as.
15144        fn reset(&self) {
15145            self.filter(shadow::shipped_filter());
15146            self.seam(0.0);
15147            self.bias(shipped_float(&crate::shadow::r_shadow_bias));
15148            self.offset(shipped_float(&crate::shadow::r_shadow_normal_offset));
15149        }
15150    }
15151
15152    /// The float `var` declares as its default — what a frame nobody typed at
15153    /// is drawn with, read off the variable rather than written down here.
15154    fn shipped_float(var: &crcbl_console::ConVar) -> f32 {
15155        match var.default() {
15156            crcbl_console::Value::Float(shipped) => *shipped,
15157            other => panic!("`{}` defaults to {other:?}, not to a float", var.name()),
15158        }
15159    }
15160
15161    impl Drop for ShadowFilterSwitch {
15162        fn drop(&mut self) {
15163            // Back to the defaults at both ends, so a check that panicked
15164            // mid-way does not hand the next holder a comparing frame.
15165            self.reset();
15166        }
15167    }
15168
15169    /// Takes `r_ssao_slices` for this thread and puts it back at its default
15170    /// when the guard drops.
15171    ///
15172    /// [`ssao_blur_switch`]'s shape exactly, for its reason: a plain
15173    /// `cargo test` run shares one process between tests, and a variable this
15174    /// one left moved is a frame the next test did not ask for.
15175    fn ssao_slice_switch() -> SsaoSliceSwitch {
15176        let guard = SSAO_SLICE_SWITCH
15177            .lock()
15178            .unwrap_or_else(std::sync::PoisonError::into_inner);
15179        let switch = SsaoSliceSwitch { _guard: guard };
15180        switch.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15181        switch
15182    }
15183
15184    /// What [`ssao_slice_switch`] hands back.
15185    struct SsaoSliceSwitch {
15186        _guard: std::sync::MutexGuard<'static, ()>,
15187    }
15188
15189    impl SsaoSliceSwitch {
15190        /// Asks each pixel for `slices` of them.
15191        fn set(&self, slices: i64) {
15192            crate::ssao::r_ssao_slices
15193                .set(&crcbl_console::Value::Int(slices))
15194                .expect("`r_ssao_slices` is a writable int in range");
15195        }
15196    }
15197
15198    impl Drop for SsaoSliceSwitch {
15199        fn drop(&mut self) {
15200            // Back to the shipping count at both ends, so a check that panicked
15201            // mid-way does not hand the next holder a four-slice frame — which
15202            // is a frame every golden in this workspace was blessed without.
15203            self.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15204        }
15205    }
15206
15207    /// [`ssao_slice_switch`]'s lock.
15208    static SSAO_SLICE_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15209
15210    /// Takes `r_ssao_technique` for this thread and puts it back at its default
15211    /// when the guard drops.
15212    ///
15213    /// [`ssao_blur_switch`]'s shape exactly, for its reason — and this one moves
15214    /// a **pipeline** rather than a lane of a uniform block, so a frame that
15215    /// picked it up from another thread's test gathers through a shader that
15216    /// test never selected.
15217    ///
15218    /// **Its lock lives in `crate::ssao`** rather than beside this function, and
15219    /// it is the one switch here whose does: `ssao`'s own
15220    /// `the_seams_other_side_is_the_technique_that_ships` moves the same
15221    /// variable, and a second mutex would serialise neither against the other.
15222    /// See `crate::ssao::TECHNIQUE_SWITCH` for where it sits in the order.
15223    fn ssao_technique_switch() -> SsaoTechniqueSwitch {
15224        let guard = crate::ssao::TECHNIQUE_SWITCH
15225            .lock()
15226            .unwrap_or_else(std::sync::PoisonError::into_inner);
15227        let switch = SsaoTechniqueSwitch { _guard: guard };
15228        switch.set(shipped_technique_name());
15229        switch
15230    }
15231
15232    /// The technique name the chain ships, and the one
15233    /// [`ssao_technique_switch`] restores.
15234    ///
15235    /// **Read off the variable rather than written down**, which is
15236    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
15237    /// rule about the slice count and for its reason: which value ships is a
15238    /// thing that moves, and a test naming the wrong one would be comparing the
15239    /// shipped configuration against itself.
15240    ///
15241    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
15242    fn shipped_technique_name() -> &'static str {
15243        match crate::ssao::r_ssao_technique.default() {
15244            crcbl_console::Value::Enum(name) => name,
15245            other => panic!("`r_ssao_technique` defaults to {other:?}, not to a technique name"),
15246        }
15247    }
15248
15249    /// A name from the variable's own set that is **not** the one it ships.
15250    ///
15251    /// [`shipped_technique_name`]'s clause from the other side: the tests below
15252    /// need a technique to move the console to, and picking it out of the
15253    /// declared set is what keeps them from naming one the variable does not
15254    /// offer — or, if a third arrived, from silently going on comparing the
15255    /// same two.
15256    fn other_technique_name() -> &'static str {
15257        let crcbl_console::Kind::Enum(names) = crate::ssao::r_ssao_technique.kind() else {
15258            panic!("`r_ssao_technique` is an enum variable");
15259        };
15260        let ships = shipped_technique_name();
15261        names
15262            .iter()
15263            .copied()
15264            .find(|name| *name != ships)
15265            .expect("`r_ssao_technique` offers a technique other than the one it ships")
15266    }
15267
15268    /// What [`ssao_technique_switch`] hands back.
15269    struct SsaoTechniqueSwitch {
15270        _guard: std::sync::MutexGuard<'static, ()>,
15271    }
15272
15273    impl SsaoTechniqueSwitch {
15274        /// Asks for the gather `name` selects.
15275        fn set(&self, name: &'static str) {
15276            crate::ssao::r_ssao_technique
15277                .set(&crcbl_console::Value::Enum(name))
15278                .expect("`r_ssao_technique` is a writable enum in the set");
15279        }
15280    }
15281
15282    impl Drop for SsaoTechniqueSwitch {
15283        fn drop(&mut self) {
15284            // Back to what ships at both ends, so a check that panicked mid-way
15285            // does not hand the next holder a frame gathered through the cheap
15286            // tier — which is a frame no golden in this workspace was blessed
15287            // on.
15288            self.set(shipped_technique_name());
15289        }
15290    }
15291
15292    /// Every draw the recorded stream holds, whichever call recorded it.
15293    ///
15294    /// Not scoped to a pass, unlike [`commands_in_pass`]: what
15295    /// [`ForwardRenderer::counters`] claims is a count over the *whole* frame, so
15296    /// the thing to compare it against is the whole frame.
15297    fn recorded_draws(recorder: &Recorder) -> usize {
15298        use crcbl_hal::null::Command;
15299
15300        recorder
15301            .commands()
15302            .into_iter()
15303            .filter(|command| {
15304                matches!(
15305                    command,
15306                    Command::Draw { .. }
15307                        | Command::DrawIndexed { .. }
15308                        | Command::DrawIndirect(_)
15309                        | Command::DrawIndexedIndirect(_)
15310                        | Command::DrawIndirectCount(_)
15311                        | Command::DrawIndexedIndirectCount(_)
15312                        | Command::DrawMeshTasks { .. }
15313                        | Command::DrawMeshTasksIndirect(_)
15314                )
15315            })
15316            .count()
15317    }
15318
15319    /// **The draw count is what the frame recorded, and the two GPU-side
15320    /// counters are `None` rather than a guess.**
15321    ///
15322    /// Both halves matter and both are checked here against something that
15323    /// moves. The draws are compared with the recorded stream, so a count that
15324    /// forgot the shadow pass's share or the tonemap's triangle fails. The
15325    /// instances are read before and after a pyramid is put in the pool, so a
15326    /// counter wired to a constant — or to the pool's *capacity*, which does not
15327    /// move — fails too.
15328    ///
15329    /// `drawn` and `triangles` are asserted [`None`] **on the frames this test
15330    /// runs**, which are inside [`CULL_STATS_FLOOR`]: nothing has come
15331    /// back off the GPU yet, and a `drawn` that was `Some` here would be a
15332    /// number invented before any readback landed. That is the assertion that
15333    /// catches the tempting version of this method: an instance count taken from
15334    /// the pool and reported as "drawn" would read as a culling win of exactly
15335    /// zero on every frame, which is the number the whole cull exists to change.
15336    /// What happens once the ring *has* come round is the test below.
15337    #[test]
15338    fn the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know() {
15339        let _blurs = ssao_blur_switch();
15340        let (recorder, device, queue) = open();
15341        let mut renderer =
15342            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15343
15344        // Before any frame: nothing recorded, and said as a known zero.
15345        assert_eq!(renderer.counters(), FrameCounters::default());
15346
15347        let first = frame(device.as_ref(), &mut renderer, queue);
15348        let counters = renderer.counters();
15349        assert_eq!(
15350            counters.draws,
15351            recorded_draws(&recorder) as u64,
15352            "the counter and the frame's recorded draws disagree",
15353        );
15354        // Derived from what the frame resolved rather than from a constant, so
15355        // this is still the every-effect frame's count and would follow a frame
15356        // that switched one off.
15357        let fullscreen = fullscreen_passes(
15358            renderer.effects(),
15359            TEST_EXTENT,
15360            false,
15361            renderer.frame_ssao_blurs,
15362        ) * FULLSCREEN_DRAWS;
15363        assert!(
15364            counters.draws > fullscreen,
15365            "a frame that recorded only its full-screen passes drew no scene",
15366        );
15367        assert_eq!(
15368            counters.instances,
15369            renderer.instances.len() as u64 + fullscreen,
15370        );
15371        assert_eq!(
15372            counters.drawn, None,
15373            "the ring has not come round, so there is no survivor count yet",
15374        );
15375        assert_eq!(counters.cull_frame, None, "and no frame to stamp it with");
15376        assert_eq!(counters.triangles, None);
15377        first.release(device.as_ref());
15378
15379        // A second scene: one more instance in the pool, and the counter moves
15380        // with it. The draws do not — one call per bucket whatever the scene
15381        // holds is what §3.3 is about, and this is where that shows.
15382        place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, Mat4::IDENTITY);
15383        recorder.clear();
15384        let second = frame(device.as_ref(), &mut renderer, queue);
15385        let richer = renderer.counters();
15386        assert_eq!(
15387            richer.instances,
15388            counters.instances + 1,
15389            "an instance added to the pool must move the counter",
15390        );
15391        assert_eq!(
15392            richer.draws, counters.draws,
15393            "the recorded call count is independent of what the scene holds",
15394        );
15395        assert_eq!(richer.draws, recorded_draws(&recorder) as u64);
15396
15397        second.finish(device.as_ref(), renderer);
15398    }
15399
15400    /// **Once the ring has come round, `drawn` is a number and it says which
15401    /// frame it is from.**
15402    ///
15403    /// The other half of the test above: `indirect` while the readback is in
15404    /// flight, a count afterwards, and a `cull_frame` naming a frame several
15405    /// behind the one just recorded. The null backend executes no copy, so the
15406    /// *value* here is the full-screen passes' own draws and nothing else — what the cull
15407    /// really kept is asserted against a real GPU, in the umbrella crate's
15408    /// `tests/draw_gen_e2e/`, where a scene is culled on purpose.
15409    ///
15410    /// The frame number is the assertion with teeth here: a ring that read the
15411    /// slot it had just written would report the frame it is on, and a
15412    /// `cull_frame` left at `None` would put a latent number on the panel with
15413    /// nothing to say how old it is.
15414    #[test]
15415    fn the_culling_counters_arrive_a_few_frames_late_and_say_which_frame() {
15416        let (_recorder, device, queue) = open();
15417        let mut renderer =
15418            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15419
15420        let mut frames = Vec::new();
15421        for _ in 0..CULL_STATS_FLOOR {
15422            frames.push(frame(device.as_ref(), &mut renderer, queue));
15423            assert_eq!(
15424                renderer.counters().drawn,
15425                None,
15426                "no readback has even been polled yet, so there is nothing back",
15427            );
15428        }
15429
15430        frames.push(frame(device.as_ref(), &mut renderer, queue));
15431        let counters = renderer.counters();
15432        assert_eq!(
15433            counters.drawn,
15434            Some(
15435                fullscreen_passes(
15436                    renderer.effects(),
15437                    TEST_EXTENT,
15438                    false,
15439                    renderer.frame_ssao_blurs,
15440                ) * FULLSCREEN_DRAWS,
15441            ),
15442            "the survivor count the null backend produced is zero, plus one instance per \
15443             full-screen pass — which is on both sides of the row",
15444        );
15445        assert_eq!(
15446            counters.cull_frame,
15447            Some(1),
15448            "the report is the frame whose copy answered, not the frame just recorded",
15449        );
15450        assert_eq!(renderer.cull_stats().expect("a readback answered").frame, 1,);
15451
15452        for frame in frames {
15453            frame.release(device.as_ref());
15454        }
15455        renderer.destroy(device.as_ref());
15456    }
15457
15458    /// The frames a culling counter cannot possibly have arrived in.
15459    ///
15460    /// Two: the copy is recorded on one frame and the readback for it requested
15461    /// on the next, so the earliest frame that can poll anything is the third.
15462    /// A device that answers its first poll — the null backend, and every native
15463    /// one — reports there; a browser answers later, which is why this is a
15464    /// floor rather than a latency. See [`crate::cull_stats`].
15465    const CULL_STATS_FLOOR: usize = 2;
15466
15467    /// **A light that takes a shadow tile moves the draw count**, because the
15468    /// shadow pass records one call per bucket per occupied view.
15469    ///
15470    /// The observable a `recorded_draws` comparison alone would miss: a
15471    /// `counters` that counted only the colour pass and the tonemap agrees with
15472    /// nothing here, and one that hard-coded the cascades agrees with the first
15473    /// frame and not the second.
15474    #[test]
15475    fn a_light_that_takes_a_shadow_tile_moves_the_draw_count() {
15476        let (recorder, device, queue) = open();
15477        let mut renderer =
15478            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15479
15480        let dark = frame(device.as_ref(), &mut renderer, queue);
15481        let without = renderer.counters().draws;
15482        assert_eq!(without, recorded_draws(&recorder) as u64);
15483        dark.release(device.as_ref());
15484
15485        renderer.set_lights(&[shadowable_spot(0.0)]);
15486        recorder.clear();
15487        let lit = frame(device.as_ref(), &mut renderer, queue);
15488        let with = renderer.counters().draws;
15489        assert!(
15490            with > without,
15491            "a shadow-casting light adds a view and therefore draws: {with} against {without}",
15492        );
15493        assert_eq!(
15494            with,
15495            recorded_draws(&recorder) as u64,
15496            "and the counter still matches the stream",
15497        );
15498        lit.finish(device.as_ref(), renderer);
15499    }
15500
15501    /// Opens a null device offering `optional` on top of the mesh path, and
15502    /// asserts it really selected that path.
15503    ///
15504    /// Asked for rather than merely reported, because a device grants what it
15505    /// enabled: leaving mesh shaders out of the optional set opens a device on
15506    /// an indirect tail and tests nothing.
15507    ///
15508    /// The adapter has [`Features::DRAW_INDEX`] too, which a device is granted
15509    /// only where `optional` asks for it — so a test that does not gets the
15510    /// mesh tail's call per bucket.
15511    fn open_mesh_path(recorder: &Recorder, optional: Features) -> (Box<dyn Device>, QueueHandle) {
15512        let caps = crcbl_hal::DeviceCaps {
15513            features: Features::GPU_DRIVEN
15514                | Features::MESH_SHADER
15515                | Features::TASK_SHADER
15516                | Features::DRAW_INDEX,
15517            limits: crcbl_hal::Limits::desktop(),
15518        };
15519        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
15520        let adapter = instance.adapters().remove(0);
15521        assert_eq!(
15522            adapter.caps.geometry_path(),
15523            GeometryPath::MeshShader,
15524            "a device with mesh shaders selects them, which is the case this is about"
15525        );
15526        let device = instance
15527            .create_device(&DeviceDesc {
15528                label: None,
15529                adapter: adapter.id,
15530                required_features: Features::COMPUTE,
15531                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER | optional,
15532                compatible_surface: None,
15533            })
15534            .expect("the null backend always opens");
15535        assert_eq!(
15536            device.caps().geometry_path(),
15537            GeometryPath::MeshShader,
15538            "and the opened device still selects it"
15539        );
15540        let queue = device.queue(QueueKind::Graphics).expect("always present");
15541        (device, queue)
15542    }
15543
15544    /// **The four material pages are created with the format their contents
15545    /// call for, and it is only a *colour* that is sRGB.**
15546    ///
15547    /// Topic 44's rung 2 calls this the classic PBR bug and
15548    /// says why it survives review: a base-colour texel and an emissive one are
15549    /// sRGB-encoded *colours*, which is what glTF defines them as, and a normal
15550    /// texel and a packed occlusion-roughness-metallic one are *numbers* — so
15551    /// decoding either of those through the sRGB curve is wrong by a gamma and
15552    /// looks merely like a surface bumpier or shinier than the author drew.
15553    /// Nothing in a frame reports it, no golden comparison can name it, and the
15554    /// four constants sit a few lines apart with the wrong one compiling.
15555    ///
15556    /// So this is the whole guard, and it is three claims rather than one: that
15557    /// each constant is the one it should be, that
15558    /// [`PageKind::format`] — which is what the upload loop actually calls —
15559    /// answers with it, and, the half that would otherwise be a check that
15560    /// cannot fail, that the format each page is *created* with is the format
15561    /// its `ImportedImage` declares. A declaration naming a format the image is
15562    /// not in picks the wrong aspects in a barrier.
15563    #[test]
15564    fn the_page_formats_split_colour_from_number() {
15565        assert_eq!(BASE_COLOR_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15566        assert_eq!(EMISSIVE_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15567        assert_eq!(NORMAL_PAGE_FORMAT, Format::Rgba8Unorm);
15568        assert_eq!(MRO_PAGE_FORMAT, Format::Rgba8Unorm);
15569        // Through the dispatch the upload loop actually calls, rather than the
15570        // constants alone: one loop creates every image now, and a `format` arm
15571        // pointed at the wrong constant is the way that loop gets it wrong.
15572        assert_eq!(PageKind::BaseColor.format(), BASE_COLOR_PAGE_FORMAT);
15573        assert_eq!(PageKind::Normal.format(), NORMAL_PAGE_FORMAT);
15574        assert_eq!(
15575            PageKind::MetallicRoughnessOcclusion.format(),
15576            MRO_PAGE_FORMAT
15577        );
15578        assert_eq!(PageKind::Emissive.format(), EMISSIVE_PAGE_FORMAT);
15579        assert_ne!(
15580            BASE_COLOR_PAGE_FORMAT, NORMAL_PAGE_FORMAT,
15581            "a normal page created sRGB decodes every texel through a gamma it never had"
15582        );
15583        assert_ne!(
15584            EMISSIVE_PAGE_FORMAT, MRO_PAGE_FORMAT,
15585            "a packed roughness page created sRGB shades every surface smoother than authored"
15586        );
15587
15588        let (recorder, device, queue) = open();
15589        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15590            .expect("the forward renderer builds on the null backend");
15591        assert_eq!(
15592            renderer.base_color_page_import().format,
15593            BASE_COLOR_PAGE_FORMAT
15594        );
15595        assert_eq!(renderer.normal_page_import().format, NORMAL_PAGE_FORMAT);
15596        assert_eq!(renderer.mro_page_import().format, MRO_PAGE_FORMAT);
15597        assert_eq!(renderer.emissive_page_import().format, EMISSIVE_PAGE_FORMAT);
15598        // And they really are four images, not one bound four times — which is
15599        // the other way a page could be "linear" and still be sampled through
15600        // the sRGB one.
15601        let created = [
15602            renderer.base_color_page(),
15603            renderer.normal_page(),
15604            renderer.mro_page(),
15605            renderer.emissive_page(),
15606        ];
15607        for (at, page) in created.iter().enumerate() {
15608            for other in &created[at + 1..] {
15609                assert_ne!(page.image, other.image, "two page kinds share one image");
15610                assert_ne!(page.view, other.view, "two page kinds share one view");
15611            }
15612        }
15613        // The labels come off the recorder rather than off the handles, so this
15614        // is evidence about what the device was asked to create.
15615        let images: Vec<String> = recorder
15616            .events()
15617            .into_iter()
15618            .filter_map(|event| match event {
15619                Event::Created {
15620                    kind: ObjectKind::Image,
15621                    label: Some(label),
15622                } => Some(label),
15623                _ => None,
15624            })
15625            .collect();
15626        for kind in PageKind::ALL {
15627            let page = kind.upload_label();
15628            assert!(
15629                images.iter().any(|label| label == page),
15630                "no image was created for the {page} page, and it is {images:?} that were"
15631            );
15632        }
15633        renderer.destroy(device.as_ref());
15634    }
15635
15636    /// Compare native argument indices from the shipped entry points with the
15637    /// actual renderer layout. A shared fragment buffer must have the same index
15638    /// even when geometry introduces additional resources in another module.
15639    #[test]
15640    fn mesh_pipeline_buffers_match_native_shader_arguments() {
15641        for optional in [Features::TASK_SHADER, Features::empty()] {
15642            let recorder = Recorder::new();
15643            let (device, queue) = open_mesh_path(&recorder, optional);
15644            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15645                .expect("the mesh renderer builds");
15646            let (_, entries) = recorder
15647                .bind_group_layouts_created()
15648                .into_iter()
15649                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
15650                .expect("the actual mesh layout");
15651            let mut buffers: Vec<_> = entries
15652                .iter()
15653                .filter(|entry| {
15654                    matches!(
15655                        entry.kind,
15656                        BindingKind::UniformBuffer { .. } | BindingKind::StorageBuffer { .. }
15657                    )
15658                })
15659                .collect();
15660            buffers.sort_by_key(|entry| entry.binding);
15661            assert_eq!(buffers.len(), 20, "the native buffer budget is unchanged");
15662            for (source, shader, names) in [
15663                (
15664                    include_str!("../../crcbl-shaders/shaders/mesh.slang"),
15665                    &MESH,
15666                    &["fragmentMain"][..],
15667                ),
15668                (
15669                    include_str!("../../crcbl-shaders/shaders/mesh_cluster.slang"),
15670                    &MESH_CLUSTER,
15671                    &["meshMain", "taskMain", "amplifiedMeshMain"][..],
15672                ),
15673            ] {
15674                let declarations: Vec<_> = source.lines().collect();
15675                let bindings: Vec<_> = declarations
15676                    .windows(2)
15677                    .filter_map(|lines| {
15678                        let binding = lines[0]
15679                            .trim()
15680                            .strip_prefix("[[vk::binding(")?
15681                            .split(',')
15682                            .next()?
15683                            .parse::<u32>()
15684                            .ok()?;
15685                        // The name is the last word before the D3D12 register.
15686                        let name = lines[1]
15687                            .split(" D3D12_REGISTER(")
15688                            .next()?
15689                            .split_whitespace()
15690                            .last()?
15691                            .trim_end_matches(';');
15692                        Some((name, binding))
15693                    })
15694                    .collect();
15695                for name in names {
15696                    let signature = shader
15697                        .msl()
15698                        .expect("committed native shader")
15699                        .lines()
15700                        .find(|line| line.starts_with("[[") && line.contains(&format!(" {name}(")))
15701                        .expect("native entry signature");
15702                    let mut checked = 0;
15703                    for argument in signature.split(", ") {
15704                        let Some((declaration, tail)) = argument.split_once(" [[buffer(") else {
15705                            continue;
15706                        };
15707                        let native: usize = tail.split(')').next().unwrap().parse().unwrap();
15708                        let variable = declaration.split_whitespace().last().unwrap();
15709                        let variable = variable.rsplit_once('_').map_or(variable, |(base, _)| base);
15710                        let binding = bindings
15711                            .iter()
15712                            .find(|(candidate, _)| *candidate == variable)
15713                            .unwrap_or_else(|| panic!("unknown {name} buffer {variable}"))
15714                            .1;
15715                        let expected = buffers
15716                            .iter()
15717                            .position(|entry| entry.binding == binding)
15718                            .expect("shader binding exists in the renderer layout");
15719                        assert_eq!(
15720                            native, expected,
15721                            "{name}: {variable}, logical binding {binding}, native shader vs global layout"
15722                        );
15723                        checked += 1;
15724                    }
15725                    assert!(
15726                        checked >= 10,
15727                        "entry parsing must cover the complete buffer interface"
15728                    );
15729                }
15730            }
15731            renderer.destroy(device.as_ref());
15732        }
15733    }
15734
15735    #[test]
15736    fn the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage() {
15737        let mut declared: Vec<Vec<(u32, BindingKind)>> = Vec::new();
15738        for optional in [Features::TASK_SHADER, Features::empty()] {
15739            let recorder = Recorder::new();
15740            let (device, queue) = open_mesh_path(&recorder, optional);
15741            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15742                .expect("the forward renderer builds on both device shapes");
15743            assert_eq!(
15744                renderer.culls_clusters(),
15745                optional.contains(Features::TASK_SHADER),
15746                "the two arms must actually differ, or this compares a device with itself"
15747            );
15748            let (label, entries) = recorder
15749                .bind_group_layouts_created()
15750                .into_iter()
15751                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
15752                .expect("the mesh pass declares its layout by name");
15753            assert_eq!(label.as_deref(), Some(MESH_LAYOUT_LABEL));
15754            declared.push(
15755                entries
15756                    .iter()
15757                    .map(|entry| (entry.binding, entry.kind))
15758                    .collect(),
15759            );
15760        }
15761
15762        let [amplified, plain] = declared
15763            .try_into()
15764            .unwrap_or_else(|_| unreachable!("two arms were run"));
15765        assert_eq!(
15766            amplified, plain,
15767            "the mesh layout's bindings changed with the task stage, which moves every Metal \
15768             argument-table index above the difference"
15769        );
15770        // These mesh declarations remain present without a task stage.
15771        for binding in [
15772            CLUSTER_CULL_BINDING,
15773            CLUSTER_CULL_STATS_BINDING,
15774            CLUSTER_SELECT_BINDING,
15775            CLUSTER_SELECTION_BINDING,
15776            CLUSTER_GROUP_STATE_BINDING,
15777        ] {
15778            assert!(
15779                plain.iter().any(|(number, _)| *number == binding),
15780                "binding {binding} is declared by mesh_cluster.slang and must be in the layout"
15781            );
15782        }
15783        // Logical gaps consume no native slots. The complete shader union must
15784        // remain sorted, and every mesh-only buffer follows the fragment prefix.
15785        let numbers: Vec<u32> = plain.iter().map(|(binding, _)| *binding).collect();
15786        let expected: Vec<u32> = (0..=8).chain(15..=16).chain(20..=40).collect();
15787        assert_eq!(
15788            numbers, expected,
15789            "the complete sparse shader binding union"
15790        );
15791    }
15792
15793    /// **`Features::TASK_SHADER` is what decides whether §3.5's per-cluster cull
15794    /// is built, and a device without it still draws.**
15795    ///
15796    /// The two capabilities are separate, and the adapter above offers both — so
15797    /// asking for one and not the other is a device state a real driver has and
15798    /// this can reach. Neither arm is a skip:
15799    ///
15800    /// * With the task stage, the renderer builds the amplification stage and
15801    ///   [`ForwardRenderer::culls_clusters`] says so. The null backend refuses a
15802    ///   task stage on a device without the flag, so an arm that computed this
15803    ///   wrongly would fail to build rather than pass quietly. It records one
15804    ///   flat call per partition — [`flat_dispatch_calls`].
15805    /// * Without it, the renderer builds `meshMain` — the un-amplified entry
15806    ///   point — and draws every cluster of every surviving instance, one
15807    ///   indirect dispatch per bucket reading its own extents.
15808    #[test]
15809    fn the_task_stage_is_built_only_where_the_device_has_one() {
15810        use crcbl_hal::null::Command;
15811
15812        for (optional, expected) in [(Features::TASK_SHADER, true), (Features::empty(), false)] {
15813            let recorder = Recorder::new();
15814            let (device, queue) = open_mesh_path(&recorder, optional);
15815            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15816                .expect("the forward renderer builds on both device shapes");
15817            assert_eq!(
15818                device.caps().supports(Features::TASK_SHADER),
15819                expected,
15820                "the device must actually differ between the arms, or both test the same thing"
15821            );
15822            assert_eq!(
15823                renderer.culls_clusters(),
15824                expected,
15825                "the amplification stage is built exactly where the device has one"
15826            );
15827            assert_eq!(
15828                renderer.geometry_path(),
15829                GeometryPath::MeshShader,
15830                "both arms are the mesh path; only the stage in front of it differs"
15831            );
15832
15833            let frame = frame(device.as_ref(), &mut renderer, queue);
15834            // After the frame, because the buffer named is the slot the frame
15835            // rotated to — asking before it names the previous slot's ring
15836            // entry and the comparison is against a buffer nothing drew from.
15837            let expected = if expected {
15838                flat_dispatch_calls(&renderer, crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED).0
15839            } else {
15840                mesh_dispatch_calls(&renderer)
15841            };
15842
15843            let dispatched: Vec<DrawIndirect> = commands_in_pass(&recorder, "forward")
15844                .into_iter()
15845                .filter_map(|command| match command {
15846                    Command::DrawMeshTasksIndirect(draw) => Some(draw),
15847                    _ => None,
15848                })
15849                .collect();
15850            assert_eq!(
15851                dispatched, expected,
15852                "a flat call per partition behind the stage, and a dispatch per bucket reading \
15853                 its own extents without it"
15854            );
15855
15856            frame.finish(device.as_ref(), renderer);
15857        }
15858    }
15859
15860    /// The flat calls a pass splitting the bucket table by the material-mode
15861    /// bits `key` records behind a task stage, in region 0, in partition order
15862    /// — one per segment the table holds buckets of — and each segment's first
15863    /// bucket, whose block the call binds.
15864    ///
15865    /// The offsets from [`crcbl_shaders::draw_gen::flat_args_word`] over the
15866    /// camera generator's own region count rather than from
15867    /// `DrawGen::flat_args_offset`, for [`mesh_dispatch_calls`]' reason.
15868    fn flat_dispatch_calls(renderer: &ForwardRenderer, key: u32) -> (Vec<DrawIndirect>, Vec<u32>) {
15869        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
15870        let buckets = u32::try_from(renderer.bucket_constants.len()).expect("a few buckets");
15871        let regions = renderer.primary.draws.mode().regions();
15872        let segments = crcbl_shaders::draw_gen::flat_segments(&renderer.bucket_modes);
15873        let values: Vec<u32> = if key == crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED {
15874            vec![0, key]
15875        } else {
15876            DEPTH_MODES.to_vec()
15877        };
15878        values
15879            .into_iter()
15880            .filter(|value| {
15881                renderer
15882                    .bucket_modes
15883                    .iter()
15884                    .any(|mode| mode & key == *value)
15885            })
15886            .map(|value| {
15887                let segment = crcbl_shaders::draw_gen::flat_segment(key, value)
15888                    .expect("a split every pass makes");
15889                (
15890                    DrawIndirect {
15891                        args: renderer.primary.draws.mesh_args(renderer.frame),
15892                        offset: u64::from(crcbl_shaders::draw_gen::flat_args_word(
15893                            buckets, regions, 0, segment, 0,
15894                        )) * 4,
15895                        draw_count: 1,
15896                        stride,
15897                    },
15898                    segments[segment as usize].0,
15899                )
15900            })
15901            .unzip()
15902    }
15903
15904    /// The [`DrawIndirect`] the mesh path must record for each bucket, in bucket
15905    /// order.
15906    ///
15907    /// Built from the buffer the draw-argument pass writes and the stride the
15908    /// APIs fixed, so a test comparing against it is asserting that the call
15909    /// reads *this frame's* arguments at *this bucket's* offset — the two ways
15910    /// an indirect dispatch goes wrong while still dispatching something.
15911    ///
15912    /// **The offsets are multiplied out here rather than asked of
15913    /// [`DrawGen::mesh_args_offset`]**, which is the difference between a
15914    /// comparison and a tautology: an offset function that returned zero for
15915    /// every bucket would agree with itself, and three calls onto one structure
15916    /// is a frame that draws one bucket's geometry three times.
15917    fn mesh_dispatch_calls(renderer: &ForwardRenderer) -> Vec<DrawIndirect> {
15918        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
15919        // The extents share a buffer with the one draw count per bucket that
15920        // precedes them, so every offset is that far in. Written out from the
15921        // bucket count here rather than taken from `DrawGen::mesh_args_offset`,
15922        // for the reason above: a base of zero is exactly the mistake this
15923        // comparison exists to catch, and it would agree with itself.
15924        let counts_bytes = renderer.bucket_constants.len() as u64 * 4;
15925        (0..renderer.bucket_constants.len())
15926            .map(|bucket| DrawIndirect {
15927                args: renderer.primary.draws.mesh_args(renderer.frame),
15928                offset: counts_bytes + bucket as u64 * u64::from(stride),
15929                draw_count: 1,
15930                stride,
15931            })
15932            .collect()
15933    }
15934
15935    /// **A device selecting [`GeometryPath::MeshShader`] draws through a mesh
15936    /// pipeline, and records no indirect draw and no index-buffer bind at all.**
15937    ///
15938    /// The three halves are one claim. That it dispatched says the path is
15939    /// wired; that it recorded *no* `DrawIndexedIndirect` of either kind says it
15940    /// did not quietly fall through to a tail that draws the same picture; and
15941    /// that it bound no index buffer says the geometry really came out of the
15942    /// cluster records rather than out of the index pool. Until 2026-08 this
15943    /// device degraded and logged that it had, which is exactly the shape —
15944    /// "not implemented" arriving as a passing frame — the three together rule
15945    /// out.
15946    ///
15947    /// **The extents are not here to be checked, and that is the point.** They
15948    /// are three words the draw-argument pass writes, so what this can pin is
15949    /// the call reading *this* bucket's structure out of *this* frame's buffer
15950    /// — and the CPU-side half of the x extent, the per-bucket cluster table
15951    /// the host uploaded, which the null backend keeps the bytes of. What the
15952    /// GPU then makes of it needs a GPU: `crcbl-vk`'s
15953    /// `the_mesh_dispatch_extent_is_the_culled_instance_count` reads the
15954    /// arguments back.
15955    #[test]
15956    fn a_mesh_shader_device_draws_through_a_mesh_pipeline() {
15957        use crcbl_hal::null::Command;
15958
15959        let recorder = Recorder::new();
15960        let caps = crcbl_hal::DeviceCaps {
15961            features: Features::GPU_DRIVEN | Features::MESH_SHADER,
15962            limits: crcbl_hal::Limits::desktop(),
15963        };
15964        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
15965        let adapter = instance.adapters().remove(0);
15966        assert_eq!(
15967            adapter.caps.geometry_path(),
15968            GeometryPath::MeshShader,
15969            "a device with mesh shaders selects them, which is the case this is about"
15970        );
15971        let device = instance
15972            .create_device(&DeviceDesc {
15973                label: None,
15974                adapter: adapter.id,
15975                required_features: Features::COMPUTE,
15976                // Asked for, because a device reports what it enabled: leaving
15977                // mesh shaders out of the optional set would open a device that
15978                // selects an indirect path outright and test nothing.
15979                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER,
15980                compatible_surface: None,
15981            })
15982            .expect("the null backend always opens");
15983        assert_eq!(
15984            device.caps().geometry_path(),
15985            GeometryPath::MeshShader,
15986            "and the opened device still selects it"
15987        );
15988        let queue = device.queue(QueueKind::Graphics).expect("always present");
15989        let mut renderer =
15990            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15991        assert_eq!(
15992            renderer.geometry_path(),
15993            GeometryPath::MeshShader,
15994            "the renderer must have *built* the mesh path, not merely been offered it"
15995        );
15996        let frame = frame(device.as_ref(), &mut renderer, queue);
15997        let expected = mesh_dispatch_calls(&renderer);
15998        // The table is written once at build, into a host-visible buffer the
15999        // null backend keeps the bytes of — so it is readable whether or not a
16000        // shader ever ran. It shares that buffer with the four other tables the
16001        // draw-argument pass reads, so the region has to be cut out at the
16002        // offset the renderer told the shader about rather than at zero.
16003        let table_bytes = recorder
16004            .buffer_bytes(renderer.primary.draws.tables())
16005            .expect("the table buffer is one of this recorder's buffers");
16006        let clusters_at = renderer.primary.draws.table_offsets().bucket_clusters_at as usize * 4;
16007        let clusters: Vec<u32> = table_bytes[clusters_at..]
16008            .as_chunks::<4>()
16009            .0
16010            .iter()
16011            .take(renderer.bucket_constants.len())
16012            .map(|word| u32::from_le_bytes(*word))
16013            .collect();
16014
16015        let mut dispatched = Vec::new();
16016        let mut index_binds = 0;
16017        for command in commands_in_pass(&recorder, "forward") {
16018            match command {
16019                Command::DrawMeshTasksIndirect(draw) => dispatched.push(draw),
16020                Command::DrawMeshTasks { .. } => panic!(
16021                    "the mesh path recorded a CPU-sized dispatch, which is the extent \
16022                     the instance cull is supposed to have taken over"
16023                ),
16024                Command::DrawIndexedIndirectCount(_) | Command::DrawIndexedIndirect(_) => {
16025                    panic!(
16026                        "the mesh path recorded an indirect draw, which is the silent \
16027                         fall-through this test exists to rule out"
16028                    )
16029                }
16030                Command::BindIndexBuffer { .. } => index_binds += 1,
16031                _ => {}
16032            }
16033        }
16034        assert_eq!(
16035            dispatched, expected,
16036            "one indirect dispatch per bucket, each reading its own argument structure \
16037             out of this frame's buffer"
16038        );
16039        assert_eq!(
16040            clusters.len(),
16041            renderer.bucket_constants.len(),
16042            "one x extent per bucket: {clusters:?}"
16043        );
16044        assert!(
16045            clusters.iter().all(|&count| count > 0),
16046            "a bucket with no clusters dispatches nothing, whatever the arguments say: \
16047             {clusters:?}"
16048        );
16049        // **The x extents are not all the same number**, which is what makes
16050        // the table a statement about each bucket's own mesh. Two
16051        // single-cluster meshes would let a table hard-coded to one cluster
16052        // pass; the open box is five, one per face.
16053        assert_eq!(
16054            clusters[DEMO_OPEN_BOX] as usize,
16055            crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
16056            "the open box dispatches one workgroup per face, and that is the only \
16057             resident whose cluster count is not one: {clusters:?}"
16058        );
16059        assert_eq!(
16060            index_binds, 0,
16061            "a mesh pipeline has no index buffer; binding one would mean the geometry \
16062             came from the index pool after all"
16063        );
16064
16065        frame.finish(device.as_ref(), renderer);
16066    }
16067
16068    /// **The cull pass is told the camera the frame is drawn with**, and how
16069    /// many array elements to walk.
16070    ///
16071    /// Both halves fail silently: a frustum from a different aspect ratio culls
16072    /// geometry that is on screen, and an instance count short of the pool's
16073    /// high-water mark stops testing the instances above a freed slot. Neither
16074    /// is visible in a picture until something disappears from an edge.
16075    #[test]
16076    fn the_cull_pass_gets_this_frame_s_camera_and_every_occupied_slot() {
16077        let (recorder, device, queue) = open();
16078        let mut renderer =
16079            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16080        // The cube first and the pyramid above it, because the second half of
16081        // this test frees the lower slot and asks what the walk still covers.
16082        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16083        place_demo(
16084            &mut renderer,
16085            DEMO_PYRAMID,
16086            DEMO_UNTINTED,
16087            Mat4::from_translation(Vec3::X),
16088        );
16089
16090        let camera = Camera {
16091            eye: Vec3::new(1.6, 1.2, 2.2),
16092            ..Camera::default()
16093        };
16094        let extent = (256u32, 192u32);
16095        renderer
16096            .begin_frame(
16097                device.as_ref(),
16098                &camera,
16099                &DirectionalLight::default(),
16100                extent,
16101            )
16102            .expect("write");
16103
16104        let aspect = extent.0 as f32 / extent.1 as f32;
16105        let expected = crate::cull::Frustum::from_view_projection(camera.view_projection(aspect));
16106        let written = recorder
16107            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16108            .expect("this frame's cull parameters are live");
16109        assert_eq!(
16110            &written[..crcbl_shaders::cull::PARAMS_SIZE],
16111            &crcbl_shaders::cull::Params {
16112                planes: expected.planes.map(|plane| plane.to_array()),
16113                instance_count: 2,
16114                capacity: scene::Capacities::default().instances,
16115                hidden_view: ViewId::PRIMARY.hidden_bit(),
16116                ..crcbl_shaders::cull::Params::default()
16117            }
16118            .to_bytes()[..],
16119            "the cull block must carry this frame's own frustum, the pool's whole \
16120             occupied range, and the visible list's capacity"
16121        );
16122
16123        // And the high-water mark is what is written, not the live count: remove
16124        // the cube and the pyramid above it still has to be tested.
16125        renderer.remove_instance(cube);
16126        renderer
16127            .begin_frame(
16128                device.as_ref(),
16129                &camera,
16130                &DirectionalLight::default(),
16131                extent,
16132            )
16133            .expect("write");
16134        let written = recorder
16135            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16136            .expect("live");
16137        assert_eq!(
16138            u32::from_le_bytes(written[96..100].try_into().expect("four bytes")),
16139            2,
16140            "one live instance, two occupied slots — a walk of one would never \
16141             reach the pyramid"
16142        );
16143
16144        renderer.destroy(device.as_ref());
16145        recorder.assert_valid();
16146    }
16147
16148    /// **Every counter both compute passes add to is zeroed by a pass of its
16149    /// own, before either of them runs.**
16150    ///
16151    /// The two shaders only ever increment, so a counter carrying the previous
16152    /// frame's total makes a bucket's argument structure claim more instances
16153    /// than its run holds — which draws whatever the run's stale tail happens to
16154    /// name.
16155    ///
16156    /// # This once read the bytes back, and no longer can
16157    ///
16158    /// It used to poison every counter with `0xAB` and assert `begin_frame`
16159    /// had written zeroes over them — the poison being the whole test, because
16160    /// the null backend runs no shader and a counter nothing wrote reads as the
16161    /// zero it was created with. The counters are device-local now, so nothing
16162    /// on the host writes them and [`Recorder::buffer_bytes`] holds nothing for
16163    /// them: the zero is a dispatch inside the frame, and a backend that runs no
16164    /// shader cannot observe it at all.
16165    ///
16166    /// So the poison moved to where a shader actually runs — `crcbl-vk`'s
16167    /// `draw_gen` end-to-end fills them with a sentinel and reads back the
16168    /// generated arguments — and what is checkable *here* is the schedule: that
16169    /// the frame contains the clearing pass, that it writes exactly those
16170    /// buffers, and that the graph orders the two accumulating passes after it.
16171    /// Each of the counts below goes red if a buffer is dropped from the
16172    /// clearing pass, and the pass list goes red if the pass leaves the frame.
16173    #[test]
16174    fn every_frame_starts_from_zeroed_counters() {
16175        let (recorder, device, queue) = open();
16176        let mut renderer =
16177            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16178        place_cube(&mut renderer, Mat4::IDENTITY);
16179        let imported = swapchain_image(device.as_ref());
16180        // Twice round the ring, because a slot cleared only on its first use is
16181        // exactly the failure this is about.
16182        for round in 0..FRAMES_IN_FLIGHT * 2 {
16183            renderer
16184                .begin_frame(
16185                    device.as_ref(),
16186                    &Camera::default(),
16187                    &DirectionalLight::default(),
16188                    (64, 48),
16189                )
16190                .expect("write");
16191            let mut graph = crate::RenderGraph::new(queue);
16192            let target = graph.import_image("target", imported);
16193            let pool = crate::TransientPool::new();
16194            renderer.add_passes(&mut graph, &pool, target, (64, 48));
16195            let compiled = graph.compile(&pool).expect("a legal frame");
16196
16197            let clear = &compiled.passes()[0];
16198            assert_eq!(
16199                clear.label(),
16200                "clear-counters",
16201                "round {round}: the zero has to be written before anything adds to it"
16202            );
16203            let barriers = &clear.barriers().buffers;
16204            assert_eq!(
16205                barriers.len(),
16206                3,
16207                "round {round}: the survivor count, the draw arguments, and the buffer \
16208                 holding both the draw counts and the mesh-dispatch arguments, and \
16209                 nothing else: {barriers:?}"
16210            );
16211            assert!(
16212                barriers
16213                    .iter()
16214                    .all(|barrier| barrier.to == ResourceState::ShaderReadWrite),
16215                "round {round}: every one of them is written by this pass: {barriers:?}"
16216            );
16217            // The ones the frame leaves as indirect arguments are the two a
16218            // driver reads; the survivor count rests in a shader read. That
16219            // split is what names them without a handle to compare.
16220            assert_eq!(
16221                barriers
16222                    .iter()
16223                    .filter(|barrier| barrier.from == ResourceState::IndirectArgument)
16224                    .count(),
16225                2,
16226                "round {round}: out of the state a draw read them in: {barriers:?}"
16227            );
16228
16229            let after = |label: &str| {
16230                compiled
16231                    .passes()
16232                    .iter()
16233                    .find(|pass| pass.label() == label)
16234                    .unwrap_or_else(|| panic!("round {round}: no `{label}` pass"))
16235                    .barriers()
16236                    .buffers
16237                    .iter()
16238                    .filter(|barrier| {
16239                        barrier.from == ResourceState::ShaderReadWrite
16240                            && barrier.to == ResourceState::ShaderReadWrite
16241                    })
16242                    .count()
16243            };
16244            assert_eq!(
16245                after("cull"),
16246                1,
16247                "round {round}: the survivor count reaches the cull pass's atomic behind a \
16248                 barrier on the write that zeroed it"
16249            );
16250            assert_eq!(
16251                after("draw-args"),
16252                4,
16253                "round {round}: and so do the draw arguments and the buffer holding the \
16254                 draw counts beside the mesh-dispatch arguments — plus the survivor list, \
16255                 which the cull pass has just written and this pass reads through the same \
16256                 descriptor it scatters the runs into, and `docs/notes/rendering.md`'s \
16257                 hysteresis state, which the clearing pass does *not* zero and which is \
16258                 behind the same kind of barrier for the opposite reason: it is the one \
16259                 buffer here carrying a value out of the previous frame, so what it needs \
16260                 ordering against is that frame rather than this one's clear"
16261            );
16262            // **And the prefix sum and the scatter behind barriers of their own**,
16263            // on every buffer the stage before them wrote. This is what orders
16264            // them on a device that runs undeclared commands in any order — see
16265            // `DrawGen::add_passes` — and what three dispatches in one pass
16266            // silently lacked.
16267            for label in ["draw-starts", "draw-scatter"] {
16268                assert_eq!(
16269                    after(label),
16270                    4,
16271                    "round {round}: `{label}` reads what the pass before it wrote, so every \
16272                     buffer they share is ordered behind a barrier"
16273                );
16274            }
16275
16276            // The compiled graph borrows the renderer's pass bodies, so it has
16277            // to go before the next frame borrows the renderer again.
16278            drop(compiled);
16279        }
16280        renderer.destroy(device.as_ref());
16281        device.destroy_image_view(imported.view);
16282        device.destroy_image(imported.image);
16283        recorder.assert_valid();
16284    }
16285
16286    /// **A frame with no instances leaves out every generator's cull and
16287    /// scatter passes**, and keeps the clear and the two stages that write each
16288    /// bucket's arguments.
16289    ///
16290    /// An empty pass is not a harmless no-op on Metal: the backend opens an
16291    /// encoder for every graph pass and strict validation rejects ending one
16292    /// with no work — see `DrawGen::add_passes`. Each count below goes red if
16293    /// an empty pass comes back, or if a pass a zero-draw frame needs drops out.
16294    #[test]
16295    fn a_frame_with_no_instances_omits_the_empty_draw_generation_passes() {
16296        let (recorder, device, queue) = open();
16297        let mut renderer =
16298            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16299        renderer
16300            .begin_frame(
16301                device.as_ref(),
16302                &Camera::default(),
16303                &DirectionalLight::default(),
16304                (64, 48),
16305            )
16306            .expect("write");
16307        let imported = swapchain_image(device.as_ref());
16308        let mut graph = crate::RenderGraph::new(queue);
16309        let target = graph.import_image("target", imported);
16310        let pool = crate::TransientPool::new();
16311        renderer.add_passes(&mut graph, &pool, target, (64, 48));
16312        let compiled = graph.compile(&pool).expect("a legal frame");
16313
16314        let count = |label: &str| {
16315            compiled
16316                .passes()
16317                .iter()
16318                .filter(|pass| pass.label() == label)
16319                .count()
16320        };
16321        // The camera's generator and one per shadow cascade.
16322        let generators = 1 + shadow::CASCADES;
16323        for label in ["clear-counters", "draw-args", "draw-starts"] {
16324            assert_eq!(
16325                count(label),
16326                generators,
16327                "`{label}` still has work with nothing to draw: the clear erases the \
16328                 previous frame's counts and the argument stages write zero draws"
16329            );
16330        }
16331        for label in ["cull", "draw-scatter"] {
16332            assert_eq!(
16333                count(label),
16334                0,
16335                "`{label}` has no workgroups to dispatch with no instances"
16336            );
16337        }
16338
16339        drop(compiled);
16340        renderer.destroy(device.as_ref());
16341        device.destroy_image_view(imported.view);
16342        device.destroy_image(imported.image);
16343        recorder.assert_valid();
16344    }
16345
16346    /// **The graph transitions the generated arguments into
16347    /// [`ResourceState::IndirectArgument`] before the draws read them**, and the
16348    /// runs into a shader read.
16349    ///
16350    /// The seam calls this the single most important barrier in a GPU-driven
16351    /// frame and says its absence produces "sometimes nothing draws" — which is
16352    /// exactly the failure a golden image on one driver would not catch. It is
16353    /// asserted on the compiled graph, which is pure and needs no device.
16354    #[test]
16355    fn the_graph_barriers_the_arguments_into_place_before_the_draws() {
16356        let _blurs = ssao_blur_switch();
16357        let (recorder, device, queue) = open();
16358        let mut renderer =
16359            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16360        place_cube(&mut renderer, Mat4::IDENTITY);
16361        renderer
16362            .begin_frame(
16363                device.as_ref(),
16364                &Camera::default(),
16365                &DirectionalLight::default(),
16366                (64, 48),
16367            )
16368            .expect("write");
16369
16370        let imported = swapchain_image(device.as_ref());
16371        let mut graph = crate::RenderGraph::new(queue);
16372        let target = graph.import_image("target", imported);
16373        let pool = crate::TransientPool::new();
16374        renderer.add_passes(&mut graph, &pool, target, (64, 48));
16375        let compiled = graph.compile(&pool).expect("a legal frame");
16376
16377        let passes: Vec<String> = compiled
16378            .passes()
16379            .iter()
16380            .map(|pass| pass.label().to_string())
16381            .collect();
16382        // The camera's five compute passes and topic 18's clustering dispatch,
16383        // then five per shadow cascade, then the depth-only pass they feed and
16384        // the colour pass that samples it.
16385        //
16386        // **The clustering pass is after the camera's clearing dispatch**, and
16387        // that is the ordering the overflow counter depends on: the clearing
16388        // pass zeroes the statistics word this one adds to, and both declare
16389        // the same buffer, so the graph is what puts the barrier between them.
16390        let mut expected: Vec<String> = Vec::new();
16391        for cascade in 0..=shadow::CASCADES {
16392            expected.extend(
16393                [
16394                    "clear-counters",
16395                    "cull",
16396                    "draw-args",
16397                    "draw-starts",
16398                    "draw-scatter",
16399                ]
16400                .into_iter()
16401                .map(str::to_string),
16402            );
16403            if cascade == 0 {
16404                expected.push("light-cluster".to_string());
16405            }
16406        }
16407        // And the culling-statistics copy **last**, after every pass that adds
16408        // to the buffer it reads — the cull dispatch, the clustering pass and
16409        // the amplification stage inside the colour pass.
16410        expected.extend(
16411            [
16412                "shadow",
16413                "depth-prepass",
16414                "ssao",
16415                "ssao-blur",
16416                // The reconstruction that ends the occlusion chain, between the
16417                // blur it reads and the pass that binds what it wrote — see
16418                // [`crate::ssao`]'s header on why the first two run smaller than
16419                // the frame and this one does not.
16420                "ssao-upsample",
16421                "forward",
16422                // The pyramid the march climbs, between the pass that wrote
16423                // level 0 and the pass that reads the chain. Two levels at this
16424                // extent, written out for the reason `crate::bloom`'s chain is
16425                // in the toggle test below: a table generated from
16426                // `crate::hiz::levels_for` could not fail.
16427                "hiz-1",
16428                "hiz-2",
16429                "ssr",
16430                "ssr-blur",
16431                "tonemap",
16432                // The resolve `RenderEffects::DEFAULT_STACK` carries, which is
16433                // CMAA2's three rather than FXAA's one —
16434                // `each_effect_toggle_removes_exactly_the_passes_it_owns` is
16435                // where the swap between the two tiers is pinned.
16436                "cmaa2-edges",
16437                "cmaa2-shapes",
16438                "cmaa2-apply",
16439                "cull-stats-readback",
16440            ]
16441            .into_iter()
16442            .map(str::to_string),
16443        );
16444        assert_eq!(
16445            passes, expected,
16446            "each cull's five compute passes come first, and in that order"
16447        );
16448
16449        // **The depth prepass, not the colour pass**, and that is what says the
16450        // prepass really is the first thing to draw from the camera's cull: it is
16451        // where the draw buffers leave the compute pass's writes. The colour pass
16452        // below then needs none of these, because they are already in the state it
16453        // wants — which is the assertion after it.
16454        let prepass = compiled
16455            .passes()
16456            .iter()
16457            .find(|pass| pass.label() == "depth-prepass")
16458            .expect("the pass list above");
16459        let into_indirect = prepass
16460            .barriers()
16461            .buffers
16462            .iter()
16463            .filter(|barrier| barrier.to == ResourceState::IndirectArgument)
16464            .count();
16465        assert_eq!(
16466            into_indirect,
16467            2,
16468            "the arguments and the count, out of the compute pass's writes and into \
16469             the state a draw reads them in: {:?}",
16470            prepass.barriers().buffers
16471        );
16472        assert!(
16473            prepass.barriers().buffers.iter().any(|barrier| {
16474                barrier.from == ResourceState::ShaderReadWrite
16475                    && barrier.to == ResourceState::ShaderRead
16476            }),
16477            "and the runs, which the vertex stage reads: {:?}",
16478            prepass.barriers().buffers
16479        );
16480
16481        let forward = compiled
16482            .passes()
16483            .iter()
16484            .find(|pass| pass.label() == "forward")
16485            .expect("the pass list above");
16486        assert!(
16487            forward
16488                .barriers()
16489                .buffers
16490                .iter()
16491                .all(|barrier| barrier.to != ResourceState::IndirectArgument),
16492            "the prepass draws from the same arguments, so the colour pass finds them \
16493             already in the state it wants — a barrier here would mean something between \
16494             the two put them back: {:?}",
16495            forward.barriers().buffers
16496        );
16497        // What the colour pass *does* still have to be given: the froxel grid,
16498        // which no earlier pass reads.
16499        assert!(
16500            forward.barriers().buffers.iter().any(|barrier| {
16501                barrier.from == ResourceState::ShaderReadWrite
16502                    && barrier.to == ResourceState::ShaderRead
16503            }),
16504            "and the froxel grid, which its fragment stage reads: {:?}",
16505            forward.barriers().buffers
16506        );
16507
16508        let draw_args = compiled
16509            .passes()
16510            .iter()
16511            .find(|pass| pass.label() == "draw-args")
16512            .expect("the pass list above");
16513        assert!(
16514            draw_args.barriers().buffers.iter().any(|barrier| {
16515                barrier.from == ResourceState::ShaderReadWrite
16516                    && barrier.to == ResourceState::ShaderRead
16517            }),
16518            "and the visible list is ordered after the cull pass wrote it: {:?}",
16519            draw_args.barriers().buffers
16520        );
16521
16522        // The compiled graph borrows the renderer's pass bodies, so it has to go
16523        // before the renderer does.
16524        drop(compiled);
16525        renderer.destroy(device.as_ref());
16526        device.destroy_image_view(imported.view);
16527        device.destroy_image(imported.image);
16528        recorder.assert_valid();
16529    }
16530
16531    /// One more frame than the uniform ring is deep, so at least one lap both
16532    /// reuses a slot and follows a lap that already sampled the atlas.
16533    const SHADOW_LAPS: usize = FRAMES_IN_FLIGHT + 1;
16534
16535    /// **Every frame's first barrier on the shadow atlas names what the previous
16536    /// frame left it in**, and the same for its placeholder.
16537    ///
16538    /// # Why this cannot be read off one frame
16539    ///
16540    /// The atlas is neither a transient nor a swapchain image. The pool never
16541    /// hands one out and has no description to size it from, and no acquire
16542    /// semaphore sits between one frame's use of it and the next — so
16543    /// [`ForwardRenderer::add_passes`] *declares* it, and the declaration is what
16544    /// makes the transition true.
16545    ///
16546    /// What it declares is [`imported_state`], the pool's record of what the
16547    /// last graph to *execute* left the image in, so [`InitialClaim::Tracked`]
16548    /// can only ever find the two agreeing for this one import — deliberately,
16549    /// because a declaration and an audit reading one value cannot drift apart
16550    /// the way a renderer-held copy of it could. The audit still has teeth
16551    /// elsewhere in this frame: `ssao-placeholder` and `probes` declare a
16552    /// constant, and `the_guard_still_catches_an_engine_import_that_lies` is
16553    /// what shows it fires on those.
16554    ///
16555    /// So neither mechanism says anything about the barriers on either side of
16556    /// the declaration — whether the frame that ran actually reached the state
16557    /// the ledger now claims, and whether the next frame's first barrier comes
16558    /// out of it — which is what the stream below is for.
16559    ///
16560    /// Declaring [`ResourceState::Undefined`] on a frame after the first is the
16561    /// failure this catches. It expands to `srcStageMask = NONE,
16562    /// srcAccessMask = NONE` (`crcbl_vk::conv::state_masks`), so the transition
16563    /// into the depth-only pass's attachment state orders against nothing — while
16564    /// the previous frame's colour pass is still sampling the very same image.
16565    /// Vulkan reports it as `SYNC-HAZARD-WRITE-AFTER-READ` with
16566    /// `read_barriers: 0`; every other backend resolves it however the driver
16567    /// likes.
16568    ///
16569    /// # Why the command stream is the observable
16570    ///
16571    /// Nothing above the seam can see a wrong declaration: the frame still
16572    /// renders, the golden still matches, and no state is ever read back. So this
16573    /// replays the recorded stream with a tracker, which is the same check a
16574    /// validation layer performs and needs no GPU at all — the shape
16575    /// `crcbl::screenshot`'s
16576    /// `every_readback_barrier_declares_the_state_the_image_is_actually_in` uses.
16577    /// One difference: `Undefined` is **not** waved through after the first
16578    /// touch. It is true for a swapchain image because the acquire's semaphore
16579    /// makes it true, and there is no such semaphore here.
16580    #[test]
16581    fn the_shadow_atlas_enters_each_frame_in_the_state_the_last_one_left_it() {
16582        use crcbl_hal::null::Command;
16583
16584        let (recorder, device, queue) = open();
16585        let device = device.as_ref();
16586        let mut renderer =
16587            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16588        let atlas = renderer.shadow_atlas();
16589        let placeholder = renderer.shadow_placeholder;
16590        let mut pool = crate::TransientPool::new();
16591        let imported = swapchain_image(device);
16592        let mut recorded = Vec::with_capacity(SHADOW_LAPS);
16593
16594        for lap in 0..SHADOW_LAPS {
16595            renderer
16596                .begin_frame(
16597                    device,
16598                    &Camera::default(),
16599                    // **A different sun each lap**, so every lap redraws the
16600                    // atlas: this is a test about the barrier a frame that
16601                    // writes the image declares, and a lap that cached would
16602                    // record no pass and no transition at all. See
16603                    // [`moving_sun`].
16604                    &moving_sun(u32::try_from(lap).expect("a handful of laps")),
16605                    (64, 48),
16606                )
16607                .expect("write");
16608            let mut graph = crate::RenderGraph::new(queue);
16609            let target = graph.import_image("target", imported);
16610            renderer.add_passes(&mut graph, &pool, target, (64, 48));
16611            let compiled = graph.compile(&pool).expect("a legal frame");
16612            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
16613                label: Some("shadow lap"),
16614                queue,
16615            });
16616            compiled
16617                .execute(device, &mut pool, encoder.as_mut(), None)
16618                .expect("the graph executed");
16619            recorded.push(encoder.finish().expect("recording succeeded"));
16620        }
16621
16622        // The two images the renderer owns across frames. A transient's state is
16623        // the pool's business and the fake swapchain image's is the acquire's, so
16624        // neither belongs in here.
16625        let mut tracked = [
16626            (atlas, ResourceState::Undefined),
16627            (placeholder, ResourceState::Undefined),
16628        ];
16629        let mut atlas_writes = 0usize;
16630        let mut named = 0usize;
16631        for command in recorder.commands() {
16632            let Command::Barrier { images, .. } = command else {
16633                continue;
16634            };
16635            for barrier in images {
16636                let Some((_, state)) = tracked
16637                    .iter_mut()
16638                    .find(|(handle, _)| *handle == barrier.image)
16639                else {
16640                    continue;
16641                };
16642                assert_eq!(
16643                    barrier.from, *state,
16644                    "a barrier declared {:?} -> {:?} on an image the frame before it left in \
16645                     {:?}. `Undefined` carries no source scope, so a transition declaring it \
16646                     orders against nothing and the previous frame's sampled read is still in \
16647                     flight underneath it.",
16648                    barrier.from, barrier.to, *state
16649                );
16650                if barrier.image == atlas && barrier.to == ResourceState::DepthStencilWrite {
16651                    atlas_writes += 1;
16652                }
16653                *state = barrier.to;
16654                named += 1;
16655            }
16656        }
16657
16658        // Both halves of the loop above are silent on an empty stream, so the
16659        // shape it walked is asserted rather than assumed: one transition into
16660        // the depth-only pass's attachment state per lap, the last one included.
16661        assert_eq!(
16662            atlas_writes, SHADOW_LAPS,
16663            "{named} barrier(s) named the atlas or its placeholder across {SHADOW_LAPS} laps, \
16664             {atlas_writes} of them taking the atlas into DepthStencilWrite — every lap moved \
16665             the sun, so every lap redraws the atlas, and anything else means the loop above \
16666             asserted on a stream that does not contain the transition it is about"
16667        );
16668        let (_, ended) = tracked[0];
16669        assert_eq!(
16670            ended,
16671            ResourceState::ShaderRead,
16672            "the import promises to hand the atlas back in the state the next frame declares"
16673        );
16674
16675        renderer.destroy(device);
16676        for commands in recorded {
16677            device.destroy_command_buffer(commands);
16678        }
16679        pool.destroy(device);
16680        device.destroy_image_view(imported.view);
16681        device.destroy_image(imported.image);
16682        recorder.assert_valid();
16683    }
16684
16685    /// A renderer with a shadowed spot beside the sun's cascades and a caster
16686    /// for both to draw, which is the smallest scene the atlas cache has
16687    /// anything to say about: without a light tile the only maps are the
16688    /// cascades, and without a caster every tile is a clear.
16689    fn shadow_cache_scene(
16690        device: &dyn Device,
16691        queue: QueueHandle,
16692    ) -> (ForwardRenderer, InstanceHandle) {
16693        let mut renderer =
16694            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16695        // Pinned, on `set_shadow_cadence`'s own terms: the console's two limits
16696        // are process-global and `the_console_moves_both_limits` holds them at
16697        // a four-frame hold and three faces a frame for the length of its
16698        // check. A cache test reading the console inside that window reports
16699        // "did not settle" — seen in the wild on 2026-09-04, and reproduced by
16700        // holding both limits at those values inside the arm's own process,
16701        // which the pin makes harmless.
16702        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
16703        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16704        renderer.set_lights(&[shadowable_spot(-1.0)]);
16705        (renderer, cube)
16706    }
16707
16708    /// Draws one frame and answers whether it drew the shadow atlas, **read two
16709    /// ways that have to agree**.
16710    ///
16711    /// [`ForwardRenderer::shadow_atlas_cached`] is the renderer's own claim and
16712    /// the recorded stream is what the device was actually told; either on its
16713    /// own would be satisfied by a renderer that reported one thing and did the
16714    /// other, which is precisely the failure a cache has. `seen` is the cursor
16715    /// into the cumulative recorder, so each call reads its own frame.
16716    fn drew_the_atlas(
16717        recorder: &Recorder,
16718        seen: &mut usize,
16719        device: &dyn Device,
16720        renderer: &mut ForwardRenderer,
16721        queue: QueueHandle,
16722        camera: &Camera,
16723        sun: &DirectionalLight,
16724    ) -> bool {
16725        let drawn = frame_seen_from(device, renderer, queue, camera, sun);
16726        let claimed = renderer.shadow_atlas_cached();
16727        let commands = recorder.commands();
16728        let opened = commands[*seen..].iter().any(|command| {
16729            command
16730                .opens_pass()
16731                .is_some_and(|(_, label)| label == Some("shadow"))
16732        });
16733        *seen = commands.len();
16734        drawn.release(device);
16735        assert_eq!(
16736            opened,
16737            !claimed,
16738            "the renderer reports cached = {claimed} and its frame {} a pass labelled `shadow`",
16739            if opened { "opened" } else { "opened no" }
16740        );
16741        opened
16742    }
16743
16744    #[test]
16745    fn shadow_preparation_retains_empty_scratch_after_redraw_and_cached_frames() {
16746        let (recorder, device, queue) = open();
16747        let device = device.as_ref();
16748        let (mut renderer, _) = shadow_cache_scene(device, queue);
16749        let camera = Camera::default();
16750        let sun = DirectionalLight::default();
16751        let mut seen = 0;
16752        assert!(drew_the_atlas(
16753            &recorder,
16754            &mut seen,
16755            device,
16756            &mut renderer,
16757            queue,
16758            &camera,
16759            &sun
16760        ));
16761        let capacity = (
16762            renderer.shadow_prepare_views.capacity(),
16763            renderer.shadow_prepare_culls.capacity(),
16764        );
16765        assert!(capacity.0 >= SHADOW_VIEWS && capacity.1 >= SHADOW_CULLS);
16766        assert!(renderer.shadow_prepare_views.is_empty());
16767        assert!(renderer.shadow_prepare_culls.is_empty());
16768        for _ in 0..FRAMES_IN_FLIGHT {
16769            assert!(!drew_the_atlas(
16770                &recorder,
16771                &mut seen,
16772                device,
16773                &mut renderer,
16774                queue,
16775                &camera,
16776                &sun
16777            ));
16778            assert!(renderer.shadow_prepare_views.is_empty());
16779            assert!(renderer.shadow_prepare_culls.is_empty());
16780            assert_eq!(
16781                (
16782                    renderer.shadow_prepare_views.capacity(),
16783                    renderer.shadow_prepare_culls.capacity()
16784                ),
16785                capacity
16786            );
16787        }
16788        for (step, view) in [0, 1, shadow_view(0, 0)].into_iter().enumerate() {
16789            // The spot moves for its own view and the camera for the cascades',
16790            // which are fitted to it: a moved spot alone is no input of theirs.
16791            renderer.set_lights(&[shadowable_spot(-2.0 - step as f32)]);
16792            let camera = Camera {
16793                eye: camera.eye + Vec3::X * 0.1 * (step + 1) as f32,
16794                ..camera
16795            };
16796            let slot = (renderer.frame + 1) % FRAMES_IN_FLIGHT;
16797            let short = device
16798                .create_buffer(&BufferDesc {
16799                    label: Some("refused shadow scratch test upload"),
16800                    size: std::mem::size_of::<f32>() as u64,
16801                    usage: BufferUsage::UNIFORM,
16802                    memory: MemoryLocation::HostUpload,
16803                })
16804                .unwrap();
16805            let original = std::mem::replace(&mut renderer.shadow_uniforms[slot][view], short);
16806            let before = recorder.buffer_bytes(short).unwrap();
16807            let result = renderer.begin_frame(device, &camera, &sun, TEST_EXTENT);
16808            renderer.shadow_uniforms[slot][view] = original;
16809            assert!(
16810                matches!(result, Err(HalError::InvalidDescriptor(ref cause)) if cause.contains("exceeds")),
16811                "observe a refused shadow uniform: {result:?}"
16812            );
16813            assert_eq!(recorder.buffer_bytes(short).unwrap(), before);
16814            assert!(!recorder.events().iter().any(
16815                |event| matches!(event, Event::BufferWritten { buffer, .. } if *buffer == short)
16816            ));
16817            assert!(renderer.shadow_prepare_views.is_empty());
16818            assert!(renderer.shadow_prepare_culls.is_empty());
16819            assert_eq!(
16820                (
16821                    renderer.shadow_prepare_views.capacity(),
16822                    renderer.shadow_prepare_culls.capacity()
16823                ),
16824                capacity
16825            );
16826            let refused_inputs = renderer.shadow_group_inputs.clone();
16827            device.destroy_buffer(short);
16828            recorder.assert_valid();
16829            assert!(drew_the_atlas(
16830                &recorder,
16831                &mut seen,
16832                device,
16833                &mut renderer,
16834                queue,
16835                &camera,
16836                &sun
16837            ));
16838            assert_eq!(renderer.shadow_group_inputs, refused_inputs);
16839            assert!(renderer.shadow_prepare_views.is_empty());
16840            assert!(renderer.shadow_prepare_culls.is_empty());
16841            assert_eq!(
16842                (
16843                    renderer.shadow_prepare_views.capacity(),
16844                    renderer.shadow_prepare_culls.capacity()
16845                ),
16846                capacity
16847            );
16848            assert!(!drew_the_atlas(
16849                &recorder,
16850                &mut seen,
16851                device,
16852                &mut renderer,
16853                queue,
16854                &camera,
16855                &sun
16856            ));
16857        }
16858        renderer.destroy(device);
16859        recorder.assert_valid();
16860        assert_eq!(recorder.total_live_objects(), 0);
16861    }
16862
16863    /// **A frame over a scene nothing moved in does not draw the shadow atlas
16864    /// again**, and what it saves is the whole of the atlas's work.
16865    ///
16866    /// Topic 45's static-caching rung, and the observable it
16867    /// otherwise has none for: the map a cached frame samples is byte for byte
16868    /// the map the frame before it sampled, so no golden image and no readback
16869    /// can tell the two frames apart. The recorded command stream can — and the
16870    /// dispatch count is the half that says the *culls* went with the pass,
16871    /// rather than the frame still paying for the draws it decided not to
16872    /// record.
16873    #[test]
16874    fn a_frame_over_a_still_scene_does_not_draw_the_shadow_atlas_again() {
16875        use crcbl_hal::null::Command;
16876
16877        // The blur count is a process-global console variable, and the frame's
16878        // draw count below includes the full-screen triangle each blur records
16879        // — so a concurrent test holding `r_ssao_blur_passes` at two would move
16880        // it under this one. Held rather than merely read, which is the
16881        // convention that variable's own test set.
16882        let _blurs = ssao_blur_switch();
16883        let (recorder, device, queue) = open();
16884        let device = device.as_ref();
16885        let (mut renderer, _) = shadow_cache_scene(device, queue);
16886        let camera = Camera::default();
16887        let sun = DirectionalLight::default();
16888
16889        let mut seen = 0usize;
16890        let dispatches = |recorder: &Recorder, from: usize| {
16891            recorder.commands()[from..]
16892                .iter()
16893                .filter(|command| matches!(command, Command::Dispatch { .. }))
16894                .count()
16895        };
16896
16897        let at = seen;
16898        assert!(
16899            drew_the_atlas(
16900                &recorder,
16901                &mut seen,
16902                device,
16903                &mut renderer,
16904                queue,
16905                &camera,
16906                &sun
16907            ),
16908            "the first frame of all has to draw the atlas: nothing has put anything in it"
16909        );
16910        let first = dispatches(&recorder, at);
16911        let drawing_draws = renderer.counters().draws;
16912        let buckets = renderer.bucket_constants.len() as u64;
16913        assert!(
16914            renderer.shadow_lights().base_of(0).is_some(),
16915            "the spot must hold a run for the count below to include a light slot's cull"
16916        );
16917        // The camera's own draw generation and topic 18's clustering dispatch,
16918        // plus a generation per cascade and one for the spot's slot.
16919        assert_eq!(
16920            first,
16921            DrawGen::DISPATCHES as usize * (2 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
16922            "the drawing frame did not record the culls this test is about skipping"
16923        );
16924
16925        for round in 0..3 {
16926            let at = seen;
16927            assert!(
16928                !drew_the_atlas(
16929                    &recorder,
16930                    &mut seen,
16931                    device,
16932                    &mut renderer,
16933                    queue,
16934                    &camera,
16935                    &sun
16936                ),
16937                "round {round} redrew an atlas nothing had changed"
16938            );
16939            assert_eq!(
16940                dispatches(&recorder, at),
16941                DrawGen::DISPATCHES as usize + 1 + RESOLVE_DISPATCHES,
16942                "round {round} kept a shadow cull it had no pass to feed"
16943            );
16944            assert_eq!(
16945                drawing_draws - renderer.counters().draws,
16946                (shadow::CASCADES + 1) as u64 * buckets,
16947                "round {round}: the frame's own draw count did not lose exactly the atlas's \
16948                 calls — one per bucket per cascade, and one per bucket for the spot's tile"
16949            );
16950        }
16951
16952        renderer.destroy(device);
16953        recorder.assert_valid();
16954    }
16955
16956    /// A cadence that holds every map one rung down for a frame, with the whole
16957    /// atlas's worth of tiles to spend.
16958    ///
16959    /// Pinned through [`ForwardRenderer::set_shadow_cadence`] rather than set on
16960    /// the console: [`shadow::r_shadow_cadence`] is process-global and the
16961    /// shadow pass is in every frame's pass list, so a test that moved it would
16962    /// change the frame every other test in this module draws.
16963    const HOLD_TWO: shadow::Cadence = shadow::Cadence {
16964        hold: 2,
16965        faces: shadow::TILES,
16966    };
16967
16968    /// How the shadow pass loaded its depth attachment, over the commands from
16969    /// `from` on, and [`None`] where the frame recorded no such pass.
16970    ///
16971    /// **The observable the tile clear otherwise has none for.** A frame that
16972    /// kept a tile and a frame that redrew every one of them sample maps that
16973    /// may be identical, so nothing in the picture separates them; this is the
16974    /// declaration that says which the device was told.
16975    fn shadow_pass_depth_load(recorder: &Recorder, from: usize) -> Option<LoadOp> {
16976        use crcbl_hal::null::Command;
16977
16978        recorder.commands()[from..].iter().find_map(|command| {
16979            let Command::BeginRenderPass {
16980                label,
16981                depth_stencil_attachment,
16982                ..
16983            } = command
16984            else {
16985                return None;
16986            };
16987            if label.as_deref() != Some("shadow") {
16988                return None;
16989            }
16990            depth_stencil_attachment
16991                .as_ref()
16992                .map(|attachment| attachment.depth_load)
16993        })
16994    }
16995
16996    /// Direct draws recorded inside the shadow pass, over the commands from
16997    /// `from` on — which is one per tile the pass reset itself, the atlas's
16998    /// geometry being drawn indirectly.
16999    fn tile_clears_in_the_shadow_pass(recorder: &Recorder, from: usize) -> usize {
17000        use crcbl_hal::null::Command;
17001
17002        let mut inside = false;
17003        let mut clears = 0;
17004        for command in &recorder.commands()[from..] {
17005            if let Some((_, label)) = command.opens_pass() {
17006                inside = label == Some("shadow");
17007                continue;
17008            }
17009            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
17010                inside = false;
17011                continue;
17012            }
17013            if inside && matches!(command, Command::Draw { .. }) {
17014                clears += 1;
17015            }
17016        }
17017        clears
17018    }
17019
17020    /// **The far cascade is redrawn every second frame and the near one every
17021    /// frame**, on a scene where the eye moves and so every map is out of date.
17022    ///
17023    /// Topic 45's cadence rung, and the observable it otherwise
17024    /// has none for: a held map draws a shadow one frame behind its caster,
17025    /// which is a plausible picture and one a golden accepts.
17026    ///
17027    /// The eye moves by a fraction of a cascade's own reach, so no frame is a
17028    /// reset — that is asserted rather than assumed, because a reset would make
17029    /// every frame redraw everything and this test would pass by having
17030    /// switched the cadence off.
17031    #[test]
17032    fn the_far_cascade_is_held_on_the_frames_between_its_turns() {
17033        let _blurs = ssao_blur_switch();
17034        let (recorder, device, queue) = open();
17035        let device = device.as_ref();
17036        let (mut renderer, _) = shadow_cache_scene(device, queue);
17037        let sun = DirectionalLight::default();
17038        renderer.set_shadow_cadence(Some(HOLD_TWO));
17039
17040        const FRAMES: usize = 8;
17041        let mut near = 0;
17042        let mut far = 0;
17043        for step in 0..FRAMES {
17044            #[expect(
17045                clippy::cast_precision_loss,
17046                reason = "a handful of frames, and the step is what is wanted"
17047            )]
17048            let camera = Camera {
17049                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17050                ..Camera::default()
17051            };
17052            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17053            assert_eq!(
17054                renderer.shadow_cadence_reset(),
17055                step == 0,
17056                "frame {step}: only the first frame has an atlas to lay out, and a reset \
17057                 after it would redraw everything and leave nothing for the cadence to hold"
17058            );
17059            near += usize::from(renderer.shadow_cascade_redrawn(0));
17060            far += usize::from(renderer.shadow_cascade_redrawn(1));
17061            drawn.release(device);
17062        }
17063        assert_eq!(
17064            near, FRAMES,
17065            "the near cascade is fitted to the eye and is on the top rung: every frame"
17066        );
17067        assert_eq!(
17068            far,
17069            FRAMES / 2,
17070            "the far cascade is one rung down, so every second frame"
17071        );
17072
17073        renderer.destroy(device);
17074        recorder.assert_valid();
17075    }
17076
17077    /// **A frame that keeps a tile loads the attachment and resets the tiles it
17078    /// redraws itself**, and a frame that keeps none clears it — which is what
17079    /// shipped.
17080    ///
17081    /// The half of the cadence a redraw count cannot see: holding a tile is only
17082    /// worth anything if the tile survives, and the one clear this seam has
17083    /// covers the whole image. A frame that loaded and reset nothing would draw
17084    /// into tiles still holding the last frame's depths, and under reversed-Z a
17085    /// caster that moved away would go on occluding.
17086    #[test]
17087    fn a_frame_that_keeps_a_tile_loads_the_attachment_and_resets_the_rest() {
17088        let _blurs = ssao_blur_switch();
17089        let (recorder, device, queue) = open();
17090        let device = device.as_ref();
17091        let (mut renderer, _) = shadow_cache_scene(device, queue);
17092        let sun = DirectionalLight::default();
17093
17094        // The first frame lays the atlas out, so it clears and redraws
17095        // everything whatever the console says.
17096        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17097        first.release(device);
17098        assert_eq!(
17099            shadow_pass_depth_load(&recorder, 0),
17100            Some(LoadOp::Clear),
17101            "the frame that lays the atlas out has nothing to keep"
17102        );
17103        assert_eq!(
17104            tile_clears_in_the_shadow_pass(&recorder, 0),
17105            0,
17106            "and so resets no tile of its own"
17107        );
17108
17109        renderer.set_shadow_cadence(Some(HOLD_TWO));
17110        let mut seen = recorder.commands().len();
17111        let mut loaded = 0;
17112        for step in 1..4 {
17113            #[expect(
17114                clippy::cast_precision_loss,
17115                reason = "a handful of frames, and the step is what is wanted"
17116            )]
17117            let camera = Camera {
17118                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17119                ..Camera::default()
17120            };
17121            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17122            let load = shadow_pass_depth_load(&recorder, seen).expect("a shadow pass");
17123            let clears = tile_clears_in_the_shadow_pass(&recorder, seen);
17124            let faces = renderer.shadow_faces_redrawn() as usize;
17125            if load == LoadOp::Load {
17126                loaded += 1;
17127                assert_eq!(
17128                    clears, faces,
17129                    "frame {step} loaded the attachment and reset {clears} of the {faces} \
17130                     tiles it redrew"
17131                );
17132                assert!(
17133                    faces < shadow::TILES,
17134                    "frame {step} loaded an attachment while redrawing every tile"
17135                );
17136            } else {
17137                assert_eq!(
17138                    clears, 0,
17139                    "frame {step} cleared the attachment and reset {clears} tiles again"
17140                );
17141            }
17142            seen = recorder.commands().len();
17143            drawn.release(device);
17144        }
17145        assert!(
17146            loaded > 0,
17147            "no frame kept a tile, so nothing here is about the load path"
17148        );
17149
17150        renderer.destroy(device);
17151        recorder.assert_valid();
17152    }
17153
17154    /// A point light costs the budget every face it draws, not one.
17155    ///
17156    /// **The half of the budget its name is about.** `shadow_faces_redrawn` is
17157    /// a sum over the groups a frame redrew of the maps each of them owns, and
17158    /// a point light owns [`shadow::POINT_FACES`] of them. Every other check
17159    /// here is built on the sun and a spot, which own one map each — so a face
17160    /// count that answered `1` for every group would satisfy all of them, and
17161    /// did: collapsing it passed the whole of `crcbl-render` and the mesh e2e
17162    /// suite. This is what binds on the difference.
17163    #[test]
17164    fn a_point_light_costs_the_budget_every_face_it_draws() {
17165        let _blurs = ssao_blur_switch();
17166        let (_recorder, device, queue) = open();
17167        let device = device.as_ref();
17168        let mut renderer =
17169            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17170        let _cube = place_cube(&mut renderer, Mat4::IDENTITY);
17171        renderer.set_lights(&[shadowable_point(-1.0)]);
17172        let sun = DirectionalLight::default();
17173
17174        // Every group is forced on the first frame — the image has held none of
17175        // them — so this counts what a full redraw actually costs.
17176        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
17177        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17178        first.release(device);
17179        let point_faces = u32::try_from(shadow::POINT_FACES).expect("a handful of faces");
17180        assert!(
17181            renderer.shadow_lights().base_of(0).is_some(),
17182            "the point must hold a run of tiles, or there is no multi-face group to count"
17183        );
17184        assert!(
17185            renderer.shadow_faces_redrawn() >= point_faces,
17186            "a frame that redrew a point light's whole cube reported {} faces, fewer than the \
17187             {point_faces} it owns — so the budget is counting groups rather than the maps they \
17188             draw, and a cube would slip past a budget of one",
17189            renderer.shadow_faces_redrawn()
17190        );
17191    }
17192
17193    /// **A frame never redraws more tiles than the budget allows**, and every
17194    /// map still gets its turn.
17195    ///
17196    /// The starvation half is what makes this more than an inequality: a
17197    /// schedule that spent the budget on the same maps every frame would satisfy
17198    /// the bound and never draw the rest at all.
17199    #[test]
17200    fn the_face_budget_bounds_a_frame_and_starves_no_map() {
17201        let _blurs = ssao_blur_switch();
17202        let (recorder, device, queue) = open();
17203        let device = device.as_ref();
17204        let (mut renderer, _) = shadow_cache_scene(device, queue);
17205        let sun = DirectionalLight::default();
17206
17207        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17208        first.release(device);
17209        assert!(
17210            renderer.shadow_lights().base_of(0).is_some(),
17211            "the spot must hold a run, or the budget has only the cascades to bind on"
17212        );
17213
17214        // One tile a frame: the two cascades and the spot's map cannot all fit,
17215        // so something is held on every frame of the run below.
17216        const BUDGET: u32 = 1;
17217        renderer.set_shadow_cadence(Some(shadow::Cadence {
17218            hold: 1,
17219            faces: BUDGET as usize,
17220        }));
17221        const FRAMES: usize = 12;
17222        let mut drew = [0usize; 3];
17223        for step in 1..=FRAMES {
17224            #[expect(
17225                clippy::cast_precision_loss,
17226                reason = "a handful of frames, and the step is what is wanted"
17227            )]
17228            let camera = Camera {
17229                eye: Camera::default().eye + Vec3::X * 0.02 * step as f32,
17230                ..Camera::default()
17231            };
17232            // The spot drifts too: its map is not fitted to the camera, so a
17233            // moving eye alone leaves it up to date and asking for nothing.
17234            #[expect(
17235                clippy::cast_precision_loss,
17236                reason = "a handful of frames, and the step is what is wanted"
17237            )]
17238            renderer.set_lights(&[shadowable_spot(-1.0 + 0.01 * step as f32)]);
17239            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17240            assert!(
17241                renderer.shadow_faces_redrawn() <= BUDGET,
17242                "frame {step} redrew {} tiles against a budget of {BUDGET}",
17243                renderer.shadow_faces_redrawn()
17244            );
17245            drew[0] += usize::from(renderer.shadow_cascade_redrawn(0));
17246            drew[1] += usize::from(renderer.shadow_cascade_redrawn(1));
17247            drew[2] += usize::from(renderer.shadow_slot_redrawn(0));
17248            drawn.release(device);
17249        }
17250        for (map, count) in drew.iter().enumerate() {
17251            assert!(
17252                *count > 0,
17253                "map {map} was never redrawn in {FRAMES} frames under a budget of \
17254                 {BUDGET}: {drew:?}"
17255            );
17256        }
17257
17258        renderer.destroy(device);
17259        recorder.assert_valid();
17260    }
17261
17262    /// **A light that jumps further than its own radius resets the cadence**,
17263    /// and one that drifts inside it does not.
17264    ///
17265    /// Topic 45's "a moving light or camera cut resets it",
17266    /// made precise: a map whose centre has moved past the map's own reach is
17267    /// not a frame out of date, it is about somewhere else — so it is redrawn on
17268    /// the frame that notices rather than when its turn comes round. Both arms,
17269    /// because a reset that fired on every move would be the cadence switched
17270    /// off.
17271    #[test]
17272    fn a_light_that_jumps_past_its_own_radius_resets_the_cadence() {
17273        let _blurs = ssao_blur_switch();
17274        let (recorder, device, queue) = open();
17275        let device = device.as_ref();
17276        let (mut renderer, _) = shadow_cache_scene(device, queue);
17277        let sun = DirectionalLight::default();
17278        let camera = Camera::default();
17279        // The coarsest hold there is, so a redraw of the spot's map on the
17280        // frames below is the reset and not its turn.
17281        renderer.set_shadow_cadence(Some(shadow::Cadence {
17282            hold: 8,
17283            faces: shadow::TILES,
17284        }));
17285
17286        let mut settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17287        settle.release(device);
17288        for _ in 0..2 {
17289            settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17290            settle.release(device);
17291        }
17292        assert!(
17293            !renderer.shadow_cadence_reset(),
17294            "the scene has settled, so nothing is about somewhere else"
17295        );
17296
17297        // A drift well inside the light's own radius: out of date, not moved.
17298        renderer.set_lights(&[shadowable_spot(-1.0 + 0.5)]);
17299        let drifted = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17300        drifted.release(device);
17301        assert!(
17302            !renderer.shadow_cadence_reset(),
17303            "a light that moved a sixteenth of its radius is a map a frame out of date"
17304        );
17305
17306        // And a jump past it. `shadowable_spot`'s radius is what the reach is
17307        // taken from, so this is a light standing where its own map says
17308        // nothing.
17309        renderer.set_lights(&[shadowable_spot(-1.0 + 40.0)]);
17310        let jumped = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17311        jumped.release(device);
17312        assert!(
17313            renderer.shadow_cadence_reset(),
17314            "a light that jumped five times its own radius must not hold its map"
17315        );
17316        assert!(
17317            renderer.shadow_slot_redrawn(0),
17318            "and the reset is only a reset if the map is actually redrawn"
17319        );
17320
17321        renderer.destroy(device);
17322        recorder.assert_valid();
17323    }
17324
17325    /// **A console knob about *sampling* the atlas does not redraw it.**
17326    ///
17327    /// `r_shadow_filter` and `r_shadow_split` decide how the colour pass reads
17328    /// a map, and `r_shadow_bias` and `r_shadow_normal_offset` how far from a
17329    /// receiver it reads — and not one byte of what the depth pass writes into
17330    /// it is any of theirs. Yet the
17331    /// shadow views' blocks are the frame's block spread, and the cache record
17332    /// is those blocks' bytes — so until the views zeroed the row, a person
17333    /// typing `r_shadow_filter box` redrew every map in the atlas for nothing,
17334    /// and in this crate's own test process the filter tests moving that cell
17335    /// redrew the atlas under `each_thing_the_atlas_is_drawn_from_redraws_it`
17336    /// once in every five or six workspace runs on 2026-09-04. Holding the lock
17337    /// here is what makes the move below the only one in flight.
17338    #[test]
17339    fn a_moved_shadow_filter_leaves_a_still_atlas_alone() {
17340        let switch = shadow_filter_switch();
17341        let (recorder, device, queue) = open();
17342        let device = device.as_ref();
17343        let (mut renderer, _) = shadow_cache_scene(device, queue);
17344        let camera = Camera::default();
17345        let sun = DirectionalLight::default();
17346        let mut seen = 0usize;
17347        assert!(
17348            drew_the_atlas(
17349                &recorder,
17350                &mut seen,
17351                device,
17352                &mut renderer,
17353                queue,
17354                &camera,
17355                &sun
17356            ),
17357            "the first frame of all draws the atlas"
17358        );
17359        assert!(
17360            !drew_the_atlas(
17361                &recorder,
17362                &mut seen,
17363                device,
17364                &mut renderer,
17365                queue,
17366                &camera,
17367                &sun
17368            ),
17369            "a still second frame has to hold it, or the move below proves nothing"
17370        );
17371
17372        switch.filter(shadow::Filter::Box);
17373        switch.seam(0.5);
17374        assert!(
17375            !drew_the_atlas(
17376                &recorder,
17377                &mut seen,
17378                device,
17379                &mut renderer,
17380                queue,
17381                &camera,
17382                &sun
17383            ),
17384            "`r_shadow_filter` and `r_shadow_split` moved and the atlas was drawn again: a \
17385             sampling knob reached the record of what the maps were drawn from"
17386        );
17387
17388        // The bias pair sits in a different row of the same block, and the
17389        // second row it reaches is `Cascades::params`, which is rebuilt every
17390        // frame — so this is the arm that says the *whole* row is kept out of
17391        // the record rather than the one lane the filter is in.
17392        switch.bias(8.0);
17393        switch.offset(8.0);
17394        assert!(
17395            !drew_the_atlas(
17396                &recorder,
17397                &mut seen,
17398                device,
17399                &mut renderer,
17400                queue,
17401                &camera,
17402                &sun
17403            ),
17404            "`r_shadow_bias` and `r_shadow_normal_offset` moved and the atlas was drawn again: \
17405             the bias row reached the record of what the maps were drawn from"
17406        );
17407
17408        renderer.destroy(device);
17409        recorder.assert_valid();
17410    }
17411
17412    /// **Every input the atlas is drawn from redraws it**, one at a time.
17413    ///
17414    /// The half that stops "cached everything, for ever" from passing every
17415    /// assertion above. Each arm moves exactly one thing and asserts the next
17416    /// frame draws again — and then holds still and asserts it stops, so an arm
17417    /// cannot pass by having broken the cache outright.
17418    ///
17419    /// The camera is in here because it is not obvious: a shadow map is drawn
17420    /// from a light, not from the eye. But a cascade is fitted to the camera's
17421    /// own frustum, and every shadow cull selects a DAG's detail at the camera's
17422    /// pixels — `SHADOW_LOD_BIAS` — so a moved eye is a different cascade, and a
17423    /// different light map wherever a DAG is in the light's cull.
17424    /// `shadow_reach`'s tests are the other half: what a moved eye or a moved
17425    /// caster must *not* redraw.
17426    ///
17427    /// `settles` is how many still frames it takes to go quiet again, and it is
17428    /// two for exactly one arm: `InstancePool`'s carry-forward puts a moved
17429    /// instance's `previous_transform` back at rest on the frame *after* the
17430    /// move, and that is a write, which is a change this record cannot tell
17431    /// from any other. See `InstancePool::take_written`, which says so.
17432    #[test]
17433    fn each_thing_the_atlas_is_drawn_from_redraws_it() {
17434        let camera = Camera::default();
17435        let sun = DirectionalLight::default();
17436        let moved_camera = Camera {
17437            eye: camera.eye + Vec3::X * 4.0,
17438            ..camera
17439        };
17440        type Change = fn(&mut ForwardRenderer, InstanceHandle);
17441        let arms: [(&str, Change, &Camera, &DirectionalLight, usize); 4] = [
17442            (
17443                "a caster moved",
17444                |renderer, cube| {
17445                    renderer.set_instance(
17446                        cube,
17447                        &InstanceDesc {
17448                            mesh: DEMO_CUBE,
17449                            material: DEMO_UNTINTED,
17450                            transform: Mat4::from_translation(Vec3::X),
17451                        },
17452                    );
17453                },
17454                &camera,
17455                &sun,
17456                2,
17457            ),
17458            (
17459                "a caster removed",
17460                |renderer, cube| renderer.remove_instance(cube),
17461                &camera,
17462                &sun,
17463                1,
17464            ),
17465            (
17466                "the light moved",
17467                |renderer, _| renderer.set_lights(&[shadowable_spot(1.5)]),
17468                &camera,
17469                &sun,
17470                1,
17471            ),
17472            ("the camera moved", |_, _| {}, &moved_camera, &sun, 1),
17473        ];
17474
17475        for (what, change, camera, sun, settles) in arms {
17476            let (recorder, device, queue) = open();
17477            let device = device.as_ref();
17478            let (mut renderer, cube) = shadow_cache_scene(device, queue);
17479            let mut seen = 0usize;
17480            // Two frames, so the atlas is drawn and then held: the arm's own
17481            // assertion is about a frame that would otherwise have cached.
17482            for round in 0..2 {
17483                let drew = drew_the_atlas(
17484                    &recorder,
17485                    &mut seen,
17486                    device,
17487                    &mut renderer,
17488                    queue,
17489                    &Camera::default(),
17490                    &DirectionalLight::default(),
17491                );
17492                assert_eq!(
17493                    drew,
17494                    round == 0,
17495                    "{what}: the still frames before the change did not settle"
17496                );
17497            }
17498
17499            change(&mut renderer, cube);
17500            assert!(
17501                drew_the_atlas(
17502                    &recorder,
17503                    &mut seen,
17504                    device,
17505                    &mut renderer,
17506                    queue,
17507                    camera,
17508                    sun
17509                ),
17510                "{what} and the atlas was not drawn again"
17511            );
17512            // And it goes quiet again in exactly `settles` frames, so the arm
17513            // cannot pass by having broken the cache rather than by having
17514            // invalidated it — and a change that started redrawing for ever
17515            // fails here rather than going unnoticed.
17516            for round in 0..settles {
17517                assert_eq!(
17518                    drew_the_atlas(
17519                        &recorder,
17520                        &mut seen,
17521                        device,
17522                        &mut renderer,
17523                        queue,
17524                        camera,
17525                        sun
17526                    ),
17527                    round + 1 < settles,
17528                    "{what}: the still frames after the change did not settle in {settles}"
17529                );
17530            }
17531
17532            renderer.destroy(device);
17533            recorder.assert_valid();
17534        }
17535    }
17536
17537    /// **A frame with a skinned object in it always redraws the atlas**, and
17538    /// that is a limit written down rather than a gap.
17539    ///
17540    /// A skinned caster's vertices are produced by a compute dispatch into the
17541    /// pool, so there is nothing on the host to compare: the palette a caller
17542    /// hands over is not the geometry, and the geometry is never read back. The
17543    /// honest answer is to redraw, and the dishonest one is a map of a pose the
17544    /// character has left.
17545    #[test]
17546    fn a_frame_with_a_skinned_object_never_caches_the_atlas() {
17547        let (recorder, device, queue) = open();
17548        let device = device.as_ref();
17549        let mut fixture = SkinnedFixture::build(device, queue);
17550        fixture.renderer.set_lights(&[shadowable_spot(-1.0)]);
17551        let imported = swapchain_image_at(device, TEST_EXTENT);
17552        let mut pool = crate::TransientPool::new();
17553
17554        // The same palette and the same plan every lap, so nothing a host-side
17555        // comparison could see has moved.
17556        for lap in 0..3 {
17557            fixture.begin(device);
17558            let mut graph = crate::RenderGraph::new(queue);
17559            let target = graph.import_image("target", imported);
17560            fixture.renderer.add_skinned_passes(
17561                &mut graph,
17562                &pool,
17563                target,
17564                TEST_EXTENT,
17565                &fixture.skinning,
17566            );
17567            let compiled = graph.compile(&pool).expect("a legal frame");
17568            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17569                label: Some("skinned lap"),
17570                queue,
17571            });
17572            compiled
17573                .execute(device, &mut pool, encoder.as_mut(), None)
17574                .expect("the graph executed");
17575            device.destroy_command_buffer(encoder.finish().expect("recording succeeded"));
17576            assert!(
17577                !fixture.renderer.shadow_atlas_cached(),
17578                "lap {lap} held a shadow map of a pose no host-side comparison can vouch for"
17579            );
17580        }
17581
17582        fixture.destroy(device);
17583        pool.destroy(device);
17584        device.destroy_image_view(imported.view);
17585        device.destroy_image(imported.image);
17586        recorder.assert_valid();
17587    }
17588
17589    /// **Switching the shadows off clears the atlas once, and then holds the
17590    /// clear**, which is the same cache answering a frame that draws nothing.
17591    ///
17592    /// The switched-off frame is not itself a cached frame: the pass has to run
17593    /// to write the reversed-Z clear that makes every comparison come back lit,
17594    /// and the image holds the last drawn maps until it does. What *is* cached
17595    /// is every frame after it, and the record for a switched-off frame is
17596    /// deliberately blind to the camera and the casters, because nothing about
17597    /// them reaches an atlas nothing draws into.
17598    #[test]
17599    fn switching_the_shadows_off_clears_the_atlas_once_and_then_holds_it() {
17600        let (recorder, device, queue) = open();
17601        let device = device.as_ref();
17602        let (mut renderer, cube) = shadow_cache_scene(device, queue);
17603        let camera = Camera::default();
17604        let sun = DirectionalLight::default();
17605        let mut seen = 0usize;
17606
17607        assert!(
17608            drew_the_atlas(
17609                &recorder,
17610                &mut seen,
17611                device,
17612                &mut renderer,
17613                queue,
17614                &camera,
17615                &sun
17616            ),
17617            "the first frame draws the maps"
17618        );
17619        renderer.set_effect_request(EffectRequest {
17620            programmatic: EffectOverride::none().force(RenderEffects::SHADOWS, Some(false)),
17621            ..EffectRequest::default()
17622        });
17623        assert!(
17624            drew_the_atlas(
17625                &recorder,
17626                &mut seen,
17627                device,
17628                &mut renderer,
17629                queue,
17630                &camera,
17631                &sun
17632            ),
17633            "the frame that switched the shadows off has to run the pass that clears the maps \
17634             out of the image"
17635        );
17636        assert!(
17637            !drew_the_atlas(
17638                &recorder,
17639                &mut seen,
17640                device,
17641                &mut renderer,
17642                queue,
17643                &camera,
17644                &sun
17645            ),
17646            "a second switched-off frame cleared an atlas that was already clear"
17647        );
17648        // And nothing about the scene reaches a frame that draws no map: the
17649        // caster moves and the atlas is still the clear it was.
17650        renderer.set_instance(
17651            cube,
17652            &InstanceDesc {
17653                mesh: DEMO_CUBE,
17654                material: DEMO_UNTINTED,
17655                transform: Mat4::from_translation(Vec3::X),
17656            },
17657        );
17658        assert!(
17659            !drew_the_atlas(
17660                &recorder,
17661                &mut seen,
17662                device,
17663                &mut renderer,
17664                queue,
17665                &camera,
17666                &sun
17667            ),
17668            "a caster moved with the shadows off, and the frame cleared the atlas over again"
17669        );
17670
17671        renderer.set_effect_request(EffectRequest::default());
17672        assert!(
17673            drew_the_atlas(
17674                &recorder,
17675                &mut seen,
17676                device,
17677                &mut renderer,
17678                queue,
17679                &camera,
17680                &sun
17681            ),
17682            "switching the shadows back on has to draw the maps the clear replaced"
17683        );
17684
17685        renderer.destroy(device);
17686        recorder.assert_valid();
17687    }
17688
17689    /// **A frame the graph refuses leaves the shadow atlas where it was.**
17690    ///
17691    /// [`RenderGraph::compile`] returns a [`Result`], so a frame can be
17692    /// described in full and then thrown away, and
17693    /// [`CompiledGraph::execute`](crate::CompiledGraph::execute) — the only
17694    /// thing that writes the pool's ledger — never runs. That is the case a
17695    /// renderer-held `ResourceState`, stepped forward while the passes were
17696    /// declared, gets wrong: it would already say [`ResourceState::ShaderRead`]
17697    /// for an image no barrier has touched, and [`InitialClaim::Tracked`] cannot
17698    /// object, because with nothing recorded there is nothing to contradict. The
17699    /// guard would be silent on precisely the drift it exists to find, which is
17700    /// why [`imported_state`] reads the ledger instead of a second copy of it.
17701    ///
17702    /// The observable is the first barrier the *next* frame records on the
17703    /// atlas. `Undefined -> DepthStencilWrite` is the transition an image
17704    /// nothing has written needs; `ShaderRead -> DepthStencilWrite` names an old
17705    /// layout the image was never in, which is a layout mismatch on every
17706    /// backend and a discarded image on some.
17707    #[test]
17708    fn a_refused_frame_leaves_the_shadow_atlas_where_it_was() {
17709        use crcbl_hal::null::Command;
17710
17711        let (recorder, device, queue) = open();
17712        let device = device.as_ref();
17713        let mut renderer =
17714            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17715        let atlas = renderer.shadow_atlas();
17716        let placeholder = renderer.shadow_placeholder;
17717        let mut pool = crate::TransientPool::new();
17718        let imported = swapchain_image(device);
17719
17720        // The refused frame: every pass a real frame declares, and beside them
17721        // one transient nothing reads or writes. `compile` answers
17722        // `UnusedTransient` and the whole description — the shadow atlas's
17723        // import included — is dropped without a command being recorded.
17724        renderer
17725            .begin_frame(
17726                device,
17727                &Camera::default(),
17728                &DirectionalLight::default(),
17729                (64, 48),
17730            )
17731            .expect("write");
17732        {
17733            let mut graph = crate::RenderGraph::new(queue);
17734            let target = graph.import_image("target", imported);
17735            renderer.add_passes(&mut graph, &pool, target, (64, 48));
17736            graph.create_image("orphan", crate::targets::scene_color((64, 48)));
17737            let refused = graph
17738                .compile(&pool)
17739                .expect_err("a transient no pass declares");
17740            assert!(
17741                matches!(refused, crate::GraphError::UnusedTransient { .. }),
17742                "the frame has to be refused for the reason this test is about — a graph that \
17743                 compiled would go on to execute and the ledger would be written after all: \
17744                 {refused:?}"
17745            );
17746        }
17747        assert_eq!(
17748            pool.imported_image_use(atlas),
17749            None,
17750            "nothing executed, so the ledger has nothing to say about the atlas — this is the \
17751             emptiness `InitialClaim::Tracked` cannot check against"
17752        );
17753
17754        // And the frame after it, which does run.
17755        renderer
17756            .begin_frame(
17757                device,
17758                &Camera::default(),
17759                &DirectionalLight::default(),
17760                (64, 48),
17761            )
17762            .expect("write");
17763        let mut graph = crate::RenderGraph::new(queue);
17764        let target = graph.import_image("target", imported);
17765        renderer.add_passes(&mut graph, &pool, target, (64, 48));
17766        let compiled = graph.compile(&pool).expect("a legal frame");
17767        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17768            label: Some("frame after a refusal"),
17769            queue,
17770        });
17771        compiled
17772            .execute(device, &mut pool, encoder.as_mut(), None)
17773            .expect("the graph executed");
17774        let commands = encoder.finish().expect("recording succeeded");
17775
17776        // The first barrier each of the two images gets. Only the refused frame
17777        // ran before this one and it recorded nothing, so these are the frame's
17778        // opening transitions.
17779        let mut opened: Vec<(crcbl_hal::ImageHandle, ResourceState, ResourceState)> = Vec::new();
17780        for command in recorder.commands() {
17781            let Command::Barrier { images, .. } = command else {
17782                continue;
17783            };
17784            for barrier in images {
17785                if barrier.image != atlas && barrier.image != placeholder {
17786                    continue;
17787                }
17788                if opened.iter().any(|(image, _, _)| *image == barrier.image) {
17789                    continue;
17790                }
17791                opened.push((barrier.image, barrier.from, barrier.to));
17792            }
17793        }
17794        for (image, from, to) in &opened {
17795            assert_eq!(
17796                *from,
17797                ResourceState::Undefined,
17798                "a barrier declared {from:?} -> {to:?} on an image the refused frame never gave a \
17799                 layout to. The declaration is what makes the transition true, so one that has \
17800                 moved on without an executed frame behind it names a source scope and an old \
17801                 layout the image was never in — and the ledger is empty, so nothing refuses it \
17802                 either. Image {image:?}"
17803            );
17804        }
17805        // The loop above is silent on an empty list and on a short one, and a
17806        // wrong declaration shortens it: an image declared in the state it is
17807        // wanted in needs no transition, so it drops out of the stream
17808        // altogether rather than appearing with the wrong source.
17809        assert_eq!(
17810            opened.len(),
17811            2,
17812            "the atlas and its placeholder are both imported every frame and both are wanted in a \
17813             state they are not in, so both have to be barriered: {opened:?}"
17814        );
17815        assert!(
17816            opened
17817                .iter()
17818                .any(|(image, _, to)| *image == atlas && *to == ResourceState::DepthStencilWrite),
17819            "and the atlas's is the shadow pass taking it as a depth attachment: {opened:?}"
17820        );
17821
17822        renderer.destroy(device);
17823        device.destroy_command_buffer(commands);
17824        pool.destroy(device);
17825        device.destroy_image_view(imported.view);
17826        device.destroy_image(imported.image);
17827        recorder.assert_valid();
17828    }
17829
17830    /// **The import audit still refuses an engine site whose declaration is
17831    /// wrong**, now that the shadow atlas's is read out of the same ledger it is
17832    /// checked against.
17833    ///
17834    /// That pair is deliberately circular and this test is what keeps it from
17835    /// swallowing the guard whole: `shadow-atlas` and `shadow-placeholder` say
17836    /// what [`imported_state`] just read, so [`InitialClaim::Tracked`] can only
17837    /// ever find them agreeing — their safety comes from there being one answer
17838    /// rather than from the check. Every *other* import in the frame declares a
17839    /// constant, and `ssao-placeholder` is the one this drives a ledger entry
17840    /// away from: uploaded into [`ResourceState::ShaderRead`] at build and
17841    /// declared so on every frame, so a graph that leaves it somewhere else is a
17842    /// declaration the next `compile` has to refuse.
17843    #[test]
17844    fn the_guard_still_catches_an_engine_import_that_lies() {
17845        let (recorder, device, queue) = open();
17846        let device = device.as_ref();
17847        let mut renderer =
17848            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17849        let mut pool = crate::TransientPool::new();
17850        let imported = swapchain_image(device);
17851        let occlusion = renderer.ambient_occlusion_placeholder.image;
17852
17853        // A graph of this test's own, which moves the renderer's occlusion
17854        // placeholder somewhere `add_passes` does not expect. Same image handle,
17855        // so the entry it leaves in the ledger is the one the next `compile`
17856        // reads for `ssao-placeholder`.
17857        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17858            label: Some("move the placeholder"),
17859            queue,
17860        });
17861        {
17862            let mut graph = crate::RenderGraph::new(queue);
17863            let moved = graph.import_image(
17864                "moved-placeholder",
17865                ImportedImage {
17866                    image: occlusion,
17867                    view: renderer.ambient_occlusion_placeholder.view,
17868                    format: Format::Rgba8Unorm,
17869                    extent: (1, 1),
17870                    initial: ResourceState::ShaderRead,
17871                    claim: InitialClaim::Tracked,
17872                    final_state: ResourceState::TransferSrc,
17873                },
17874            );
17875            graph
17876                .add_copy_pass("read the placeholder")
17877                .use_image(moved, ResourceState::TransferSrc)
17878                .execute(|_| {});
17879            graph
17880                .compile(&pool)
17881                .expect("a legal frame")
17882                .execute(device, &mut pool, encoder.as_mut(), None)
17883                .expect("the graph executed");
17884        }
17885        let commands = encoder.finish().expect("recording succeeded");
17886        assert_eq!(
17887            pool.imported_image_use(occlusion),
17888            Some(ResourceState::TransferSrc),
17889            "the ledger has to have moved for the frame below to have anything to disagree with"
17890        );
17891
17892        renderer
17893            .begin_frame(
17894                device,
17895                &Camera::default(),
17896                &DirectionalLight::default(),
17897                (64, 48),
17898            )
17899            .expect("write");
17900        let mut graph = crate::RenderGraph::new(queue);
17901        let target = graph.import_image("target", imported);
17902        renderer.add_passes(&mut graph, &pool, target, (64, 48));
17903        let refused = graph
17904            .compile(&pool)
17905            .expect_err("`ssao-placeholder` declares a constant the ledger no longer agrees with");
17906        let crate::GraphError::ImportStateMismatch {
17907            resource,
17908            declared,
17909            left,
17910        } = &refused
17911        else {
17912            panic!("the audit has to name the import it refused, not merely fail: {refused:?}");
17913        };
17914        assert_eq!(resource, "ssao-placeholder");
17915        assert_eq!(*declared, ResourceState::ShaderRead);
17916        assert_eq!(*left, ResourceState::TransferSrc);
17917
17918        renderer.destroy(device);
17919        device.destroy_command_buffer(commands);
17920        pool.destroy(device);
17921        device.destroy_image_view(imported.view);
17922        device.destroy_image(imported.image);
17923        recorder.assert_valid();
17924    }
17925
17926    /// Compiles one frame and names the passes it turned out to be, in order.
17927    ///
17928    /// Compiled and not executed: what a pass costs is not the question here,
17929    /// only which of them the frame declared. Names rather than a count since
17930    /// the toggles landed — a count says a frame lost two passes and a list says
17931    /// *which* two, which is the difference between "the switch did something"
17932    /// and "the switch did the thing it is for".
17933    fn passes_in_a_frame(
17934        device: &dyn Device,
17935        queue: QueueHandle,
17936        renderer: &mut ForwardRenderer,
17937        imported: ImportedImage,
17938        pool: &crate::TransientPool,
17939        extent: (u32, u32),
17940    ) -> Vec<String> {
17941        renderer
17942            .begin_frame(
17943                device,
17944                &Camera::default(),
17945                &DirectionalLight::default(),
17946                extent,
17947            )
17948            .expect("write");
17949        let mut graph = crate::RenderGraph::new(queue);
17950        let target = graph.import_image("target", imported);
17951        renderer.add_passes(&mut graph, pool, target, extent);
17952        graph
17953            .compile(pool)
17954            .expect("a legal frame")
17955            .passes()
17956            .iter()
17957            .map(|pass| pass.label().to_string())
17958            .collect()
17959    }
17960
17961    /// A spot at `x` that [`shadow::Selection`] will give a tile: finite, a
17962    /// radius, a direction and a cone well inside the widest one allowed.
17963    /// A shadowed point light, which is [`shadow::POINT_FACES`] maps rather
17964    /// than one.
17965    ///
17966    /// The spot beside it is one tile and one face, so a scene built only from
17967    /// spots cannot tell a budget counting **faces** from one counting groups —
17968    /// which is what this exists to give a check something to bind on.
17969    fn shadowable_point(x: f32) -> Light {
17970        Light::Point(crate::light::PointLight {
17971            position: Vec3::new(x, 2.0, 0.0),
17972            radius: 8.0,
17973            color: Vec3::ONE,
17974            fill: false,
17975        })
17976    }
17977
17978    fn shadowable_spot(x: f32) -> Light {
17979        Light::Spot(crate::light::SpotLight {
17980            position: Vec3::new(x, 2.0, 0.0),
17981            radius: 8.0,
17982            color: Vec3::ONE,
17983            direction: -Vec3::Y,
17984            inner_angle: 0.3,
17985            outer_angle: 0.6,
17986            fill: false,
17987        })
17988    }
17989
17990    /// The page's anisotropy is the plan's default clamped to the device, and
17991    /// one on a device that was not granted the feature — whatever its limit
17992    /// says.
17993    ///
17994    /// The last arm is the one worth having: `gate_limits_on_features` narrows
17995    /// a declined feature's limit on `crcbl-vk`, but a backend that did not
17996    /// would report sixteen beside an absent feature, and a clamp that read the
17997    /// limit alone would ask for a sampler the device refuses.
17998    #[test]
17999    fn the_anisotropy_is_the_default_clamped_to_what_the_device_granted() {
18000        let caps = |features: Features, max_sampler_anisotropy: f32| DeviceCaps {
18001            features,
18002            limits: crcbl_hal::Limits {
18003                max_sampler_anisotropy,
18004                ..crcbl_hal::Limits::desktop()
18005            },
18006        };
18007        let granted = Features::SAMPLER_ANISOTROPY;
18008        assert!(
18009            (ForwardRenderer::anisotropy_for(&caps(granted, 16.0)) - DEFAULT_ANISOTROPY).abs()
18010                < f32::EPSILON,
18011            "a device above the default gets the default"
18012        );
18013        assert!(
18014            (ForwardRenderer::anisotropy_for(&caps(granted, 4.0)) - 4.0).abs() < f32::EPSILON,
18015            "a device below the default gets its own limit"
18016        );
18017        assert!(
18018            (ForwardRenderer::anisotropy_for(&caps(Features::empty(), 16.0)) - 1.0).abs()
18019                < f32::EPSILON,
18020            "a device that was not granted the feature gets one, whatever its limit says"
18021        );
18022    }
18023
18024    /// A new anisotropy is a new sampler, and every slot moves onto it at its
18025    /// own frame — the old one living until the last slot has left it.
18026    ///
18027    /// Counted on the null recorder rather than looked at: the sampler count
18028    /// rises by one at the call, holds through every slot's frame but the
18029    /// last, and falls back there, while the live group count never moves at
18030    /// all — every rebuilt group replaced one. A rebuild that leaked, one that
18031    /// destroyed a group a slot in flight still held, and one that never
18032    /// happened each move one of those counts; a second lap of the ring
18033    /// creating any group at all would be a rebuild that did not know it was
18034    /// done.
18035    #[test]
18036    fn a_new_anisotropy_moves_each_slot_at_its_own_frame_and_retires_the_old() {
18037        let (recorder, device, queue) =
18038            open_with(Features::GPU_DRIVEN.union(Features::SAMPLER_ANISOTROPY));
18039        let device = device.as_ref();
18040        let mut renderer =
18041            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18042        assert!(
18043            (renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON,
18044            "a renderer nobody has called the setter on samples at the default"
18045        );
18046        let samplers = recorder.live_objects(ObjectKind::Sampler);
18047        let groups = recorder.live_objects(ObjectKind::BindGroup);
18048        let groups_created = || {
18049            recorder
18050                .events()
18051                .iter()
18052                .filter(|event| {
18053                    matches!(
18054                        event,
18055                        Event::Created {
18056                            kind: ObjectKind::BindGroup,
18057                            ..
18058                        }
18059                    )
18060                })
18061                .count()
18062        };
18063
18064        renderer
18065            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18066            .expect("the device allows it");
18067        assert_eq!(
18068            recorder.live_objects(ObjectKind::Sampler),
18069            samplers,
18070            "the value in force creates nothing"
18071        );
18072
18073        renderer
18074            .set_anisotropy(device, 4.0)
18075            .expect("the device allows it");
18076        assert!((renderer.anisotropy() - 4.0).abs() < f32::EPSILON);
18077        assert_eq!(
18078            recorder.live_objects(ObjectKind::Sampler),
18079            samplers + 1,
18080            "the new sampler stands beside the one every slot still names"
18081        );
18082        assert_eq!(
18083            recorder.live_objects(ObjectKind::BindGroup),
18084            groups,
18085            "no group moves until its slot's frame"
18086        );
18087
18088        for round in 0..FRAMES_IN_FLIGHT {
18089            renderer
18090                .begin_frame(
18091                    device,
18092                    &Camera::default(),
18093                    &DirectionalLight::default(),
18094                    (64, 48),
18095                )
18096                .expect("write");
18097            let expected = if round + 1 < FRAMES_IN_FLIGHT {
18098                samplers + 1
18099            } else {
18100                samplers
18101            };
18102            assert_eq!(
18103                recorder.live_objects(ObjectKind::Sampler),
18104                expected,
18105                "round {round}: the replaced sampler lives until the last slot has left it"
18106            );
18107            assert_eq!(
18108                recorder.live_objects(ObjectKind::BindGroup),
18109                groups,
18110                "round {round}: every rebuilt group replaced one"
18111            );
18112        }
18113        let created = groups_created();
18114        for _ in 0..FRAMES_IN_FLIGHT {
18115            renderer
18116                .begin_frame(
18117                    device,
18118                    &Camera::default(),
18119                    &DirectionalLight::default(),
18120                    (64, 48),
18121                )
18122                .expect("write");
18123        }
18124        assert_eq!(
18125            groups_created(),
18126            created,
18127            "a slot already on the sampler in force rebuilds nothing"
18128        );
18129
18130        // The clamp: the device's ceiling above it, off below one, the default
18131        // for a value that is not a number.
18132        let ceiling = device.caps().limits.max_sampler_anisotropy;
18133        renderer
18134            .set_anisotropy(device, ceiling * 4.0)
18135            .expect("clamped to what the device allows");
18136        assert!((renderer.anisotropy() - ceiling).abs() < f32::EPSILON);
18137        renderer
18138            .set_anisotropy(device, 0.0)
18139            .expect("one is the value that turns it off");
18140        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18141        renderer
18142            .set_anisotropy(device, f32::NAN)
18143            .expect("the default is a sampler the device allows");
18144        assert!((renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON);
18145
18146        recorder.assert_valid();
18147        renderer.destroy(device);
18148        assert_eq!(
18149            recorder.live_objects(ObjectKind::Sampler),
18150            0,
18151            "the samplers no slot ever adopted went with the renderer"
18152        );
18153    }
18154
18155    /// A device without the feature samples isotropically whatever is asked:
18156    /// the ceiling is one, so the clamp lands on the value already in force and
18157    /// no sampler is created that `create_sampler` would refuse.
18158    #[test]
18159    fn a_device_without_the_feature_keeps_the_page_isotropic_whatever_is_asked() {
18160        let (recorder, device, queue) = open();
18161        let device = device.as_ref();
18162        assert!(
18163            !device
18164                .caps()
18165                .features
18166                .contains(Features::SAMPLER_ANISOTROPY),
18167            "the default request does not name the feature"
18168        );
18169        let mut renderer =
18170            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18171        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18172        let samplers = recorder.live_objects(ObjectKind::Sampler);
18173
18174        renderer
18175            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18176            .expect("asks for nothing the device lacks");
18177        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18178        assert_eq!(recorder.live_objects(ObjectKind::Sampler), samplers);
18179        renderer.destroy(device);
18180    }
18181
18182    /// The knob clamps to the range it documents, in both directions and on a
18183    /// value that is neither.
18184    ///
18185    /// **The `NaN` arm is the one worth having.** A slider that divided by a
18186    /// zero, or a settings file that carried a nonsense string, reaches this
18187    /// with a value that fails every comparison it is put through — so a naive
18188    /// `clamp` would keep it, `internal_extent` would multiply by it, and the
18189    /// `as u32` below would produce a zero extent and a device error a long way
18190    /// from here.
18191    #[test]
18192    fn the_render_scale_is_clamped_to_the_range_it_documents() {
18193        let (recorder, device, queue) = open();
18194        let device = device.as_ref();
18195        let mut renderer =
18196            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18197
18198        assert!(
18199            (renderer.render_scale() - 1.0).abs() < f32::EPSILON,
18200            "a renderer nobody has called the setter on draws at full scale"
18201        );
18202
18203        renderer.set_render_scale(0.5);
18204        assert!((renderer.render_scale() - 0.5).abs() < f32::EPSILON);
18205
18206        // Above one is supersampling, which this filter is the wrong one for.
18207        renderer.set_render_scale(2.0);
18208        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18209
18210        renderer.set_render_scale(0.01);
18211        assert!((renderer.render_scale() - MIN_RENDER_SCALE).abs() < f32::EPSILON);
18212
18213        renderer.set_render_scale(f32::NAN);
18214        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18215        renderer.set_render_scale(f32::INFINITY);
18216        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18217
18218        renderer.destroy(device);
18219        recorder.assert_valid();
18220    }
18221
18222    /// The internal extent is the target rounded, never zero, and is the target
18223    /// itself at full scale.
18224    ///
18225    /// **The floor is not decoration.** A transient image of zero extent is a
18226    /// device error rather than a small frame, and a 4×3 target at the minimum
18227    /// scale is exactly the arithmetic that would produce one.
18228    #[test]
18229    fn the_internal_extent_rounds_and_never_reaches_zero() {
18230        let (recorder, device, queue) = open();
18231        let device = device.as_ref();
18232        let mut renderer =
18233            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18234
18235        assert_eq!(
18236            renderer.internal_extent((1920, 1080)),
18237            (1920, 1080),
18238            "full scale is the absence of the feature, not a resize by one"
18239        );
18240
18241        renderer.set_render_scale(0.5);
18242        assert_eq!(renderer.internal_extent((1920, 1080)), (960, 540));
18243
18244        // Rounds rather than truncating: 1920 * 0.7 is 1344, and 1080 * 0.7 is
18245        // 756 — both exact — so a target that does *not* divide evenly is what
18246        // shows the rounding. 1281 * 0.7 = 896.7.
18247        renderer.set_render_scale(0.7);
18248        assert_eq!(renderer.internal_extent((1281, 1080)), (897, 756));
18249
18250        renderer.set_render_scale(MIN_RENDER_SCALE);
18251        assert_eq!(renderer.internal_extent((4, 3)), (1, 1));
18252        assert_eq!(
18253            renderer.internal_extent((0, 0)),
18254            (1, 1),
18255            "a minimised window is the caller's zero extent, and this may not \
18256             pass it through as one"
18257        );
18258
18259        renderer.destroy(device);
18260        recorder.assert_valid();
18261    }
18262
18263    /// **The upscale is a pass below full scale and is not there above it**, and
18264    /// the frame is otherwise the same list.
18265    ///
18266    /// This is the observable the knob is: everything else about it — the
18267    /// clamps, the rounding — is arithmetic that could be right while the frame
18268    /// went on being drawn at the caller's extent. What says the feature works
18269    /// is that the pass appears, that it appears **last**, and that switching it
18270    /// off leaves the frame that was there before it existed.
18271    #[test]
18272    fn the_upscale_is_the_last_pass_and_only_below_full_scale() {
18273        let _blurs = ssao_blur_switch();
18274        let (recorder, device, queue) = open();
18275        let device = device.as_ref();
18276        let mut renderer =
18277            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18278        let imported = swapchain_image_at(device, TEST_EXTENT);
18279        let pool = crate::TransientPool::new();
18280
18281        let full = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18282        assert!(
18283            !full.contains(&"upscale".to_string()),
18284            "a frame at full scale has no upscale in it: {full:?}"
18285        );
18286
18287        renderer.set_render_scale(0.5);
18288        let scaled = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18289        assert_eq!(
18290            scaled.iter().filter(|label| *label == "upscale").count(),
18291            1,
18292            "a scaled frame records exactly one upscale: {scaled:?}"
18293        );
18294        // Last of the passes that draw. The statistics copy is genuinely after
18295        // it and says so — see the comment on `add_copy_pass`'s placement.
18296        let upscale = scaled
18297            .iter()
18298            .position(|label| label == "upscale")
18299            .expect("the assertion above");
18300        let tonemap = scaled
18301            .iter()
18302            .position(|label| label == "tonemap")
18303            .expect("every frame tonemaps");
18304        assert!(
18305            upscale > tonemap,
18306            "the upscale carries what the post chain ended with: {scaled:?}"
18307        );
18308
18309        // **The pyramid gets shorter, and that is the evidence the rest of the
18310        // frame really is smaller.** Everything above this is about the last
18311        // pass; a knob that added an upscale while going on rendering at the
18312        // caller's extent would pass every one of those assertions and save
18313        // nothing. `crate::hiz`'s chain is as long as the extent allows, so the
18314        // level count is a number read out of the frame that can only be the
18315        // internal extent's.
18316        let levels = |passes: &[String]| {
18317            passes
18318                .iter()
18319                .filter(|label| label.starts_with("hiz-"))
18320                .count()
18321        };
18322        let internal = renderer.internal_extent(TEST_EXTENT);
18323        assert_eq!(levels(&full), crate::hiz::levels_for(TEST_EXTENT) as usize);
18324        assert_eq!(levels(&scaled), crate::hiz::levels_for(internal) as usize);
18325        assert!(
18326            levels(&scaled) < levels(&full),
18327            "at this extent the halved frame has to lose a level, or this \
18328             assertion is not looking at anything: {scaled:?}"
18329        );
18330
18331        // And nothing else moved: an upscale is a pass added to the frame, not a
18332        // frame rebuilt around one. The pyramid is the one part that is a
18333        // function of the extent, so it is compared by the count above and
18334        // dropped from the list here.
18335        let without_hiz = |passes: &[String]| -> Vec<String> {
18336            passes
18337                .iter()
18338                .filter(|label| !label.starts_with("hiz-") && *label != "upscale")
18339                .cloned()
18340                .collect()
18341        };
18342        assert_eq!(
18343            without_hiz(&scaled),
18344            without_hiz(&full),
18345            "the scaled frame is the full-scale frame, one pass longer and one \
18346             pyramid shorter"
18347        );
18348
18349        renderer.set_render_scale(1.0);
18350        let back = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18351        assert_eq!(
18352            back, full,
18353            "the knob goes back, which is what a settings slider does"
18354        );
18355
18356        renderer.destroy(device);
18357        device.destroy_image_view(imported.view);
18358        device.destroy_image(imported.image);
18359        recorder.assert_valid();
18360    }
18361
18362    /// **A skinned-frame overlay receives the display and depth images at the
18363    /// internal extent, before either resolve reconstructs the target.**
18364    ///
18365    /// The callback's own pass attaches the display and depth it received. That
18366    /// makes matching dimensions a graph invariant rather than a comparison of
18367    /// numbers the callback could have been handed without ever using the
18368    /// images; changing either id to a target-sized image makes compilation
18369    /// refuse the mismatched attachments.
18370    #[test]
18371    fn an_overlay_uses_the_internal_display_and_depth_before_the_resolves() {
18372        let (recorder, device, queue) = open();
18373        let device = device.as_ref();
18374        let mut fixture = SkinnedFixture::build(device, queue);
18375        fixture.renderer.set_render_scale(0.5);
18376        fixture.renderer.set_effect_request(EffectRequest {
18377            antialiasing: Some(Antialiasing::Fxaa),
18378            ..EffectRequest::default()
18379        });
18380        fixture.begin(device);
18381        let internal_extent = fixture.renderer.internal_extent(TEST_EXTENT);
18382
18383        let imported = swapchain_image_at(device, TEST_EXTENT);
18384        let mut pool = crate::TransientPool::new();
18385        {
18386            let mut graph = crate::RenderGraph::new(queue);
18387            let target = graph.import_image("target", imported);
18388            let mut received = None;
18389            fixture.renderer.add_skinned_passes_with_overlay(
18390                &mut graph,
18391                &pool,
18392                target,
18393                TEST_EXTENT,
18394                &fixture.skinning,
18395                |graph, targets| {
18396                    received = Some(targets);
18397                    graph
18398                        .add_render_pass("overlay-probe")
18399                        .color(
18400                            targets.display,
18401                            LoadOp::Load,
18402                            StoreOp::Store,
18403                            crcbl_hal::ClearValue::default(),
18404                        )
18405                        .depth_read(targets.depth)
18406                        .execute(|_| {});
18407                },
18408            );
18409            let received = received.expect("the overlay callback runs while the frame is built");
18410            assert_eq!(
18411                received.internal_extent, internal_extent,
18412                "the overlay receives the extent its display and depth attachments have"
18413            );
18414
18415            let compiled = graph.compile(&pool).expect("the shared attachments match");
18416            let labels: Vec<&str> = compiled.passes().iter().map(|pass| pass.label()).collect();
18417            let overlay = labels
18418                .iter()
18419                .position(|label| *label == "overlay-probe")
18420                .expect("the callback's pass is part of the frame");
18421            let fxaa = labels
18422                .iter()
18423                .position(|label| *label == "fxaa")
18424                .expect("the requested resolve is part of the frame");
18425            let upscale = labels
18426                .iter()
18427                .position(|label| *label == "upscale")
18428                .expect("the half-scale frame reconstructs its target");
18429            assert!(
18430                overlay < fxaa && overlay < upscale,
18431                "the overlay must write display before its resolve and upscale: {labels:?}"
18432            );
18433        }
18434
18435        fixture.destroy(device);
18436        pool.destroy(device);
18437        device.destroy_image_view(imported.view);
18438        device.destroy_image(imported.image);
18439        recorder.assert_valid();
18440    }
18441
18442    /// **[`ForwardRenderer::MAX_PASSES`] bounds the frame, and lands on it.**
18443    ///
18444    /// It is what a caller sizes [`PassTimers`](crate::PassTimers) with, so both
18445    /// halves matter: a bound under the widest frame times part of it and drops
18446    /// the rest, and a bound well over it buys query sets nothing ever writes.
18447    /// A shadowable spot per light slot fills every one of them, which is the
18448    /// most culls a frame can run and so the widest frame there is — it must land
18449    /// exactly on the constant, and the frame with no shadowed light at all must
18450    /// be short of it by exactly the culls those slots would have added.
18451    ///
18452    /// The ground grid is switched on for **both** frames, because the widest
18453    /// frame is the one that has it: it is off by default and not a
18454    /// [`RenderEffects`] bit, so nothing else here would put its pass in. The
18455    /// debug draw layer is on for both frames for the same reason, and it needs
18456    /// a segment appended before each rather than one switch, because
18457    /// [`begin_frame`](ForwardRenderer::begin_frame) clears its buffer.
18458    ///
18459    /// **And the frames are drawn at [`WIDEST_EXTENT`] rather than at
18460    /// [`TEST_EXTENT`], with every effect forced on and the render scale off
18461    /// full.** The bloom chain's length is a function of the extent the frame is
18462    /// drawn at — see [`crate::bloom`] — so the widest frame this renderer
18463    /// records is a *large* one, and a bound checked against a 64×48 frame would
18464    /// sit six passes above what that frame runs and this assertion would have
18465    /// to be a `<=`. It is an `==` on purpose: a bound well over the widest
18466    /// frame buys query sets nothing writes, and only an exact comparison
18467    /// notices.
18468    ///
18469    /// **The render scale is what makes those two requirements compose.** The
18470    /// upscale is a pass only below full scale, and below full scale the chain
18471    /// runs at the *internal* extent — so a frame with both is one whose
18472    /// internal extent is the longest chain's, and whose target is larger than
18473    /// that. Halving a target of 2048×1024 is what arranges it, and the two
18474    /// assertions below check the arrangement rather than trusting it.
18475    ///
18476    /// [`WIDEST_EXTENT`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
18477    #[test]
18478    fn the_pass_bound_is_the_widest_frame_the_renderer_records() {
18479        /// The extent whose bloom chain is the longest [`crate::bloom`] will
18480        /// build: six halvings of 512 leave sixteen by eight, which is still at
18481        /// or above that module's floor. The widest frame is drawn at this,
18482        /// which is why it is the internal one and not the target.
18483        const WIDEST_INTERNAL: (u32, u32) = (1024, 512);
18484        /// Half, so the frame records an upscale and draws at
18485        /// [`WIDEST_INTERNAL`].
18486        const WIDEST_SCALE: f32 = 0.5;
18487        /// The caller's extent: twice [`WIDEST_INTERNAL`] in each dimension.
18488        const WIDEST_EXTENT: (u32, u32) = (WIDEST_INTERNAL.0 * 2, WIDEST_INTERNAL.1 * 2);
18489
18490        let (recorder, device, queue) = open();
18491        let device = device.as_ref();
18492        // **A scene whose probes ask to be updated**, because the widest frame
18493        // is the one with every pass in it and
18494        // the irradiance probes' two are recorded by a volume
18495        // rather than by an effect bit — the ground grid's argument exactly. A
18496        // renderer built on the demo's empty grid records neither, and the bound
18497        // would then be checked against a frame that could not reach it.
18498        let mut scene = scene::demo();
18499        scene.capacities.probes = 1;
18500        scene.probes = scene::ProbeGrid {
18501            volume: crcbl_shaders::probe::ProbeVolume {
18502                origin: [0.0; 3],
18503                inv_spacing: [1.0; 3],
18504                counts: [1, 1, 1],
18505                levels: 1,
18506                steps: crcbl_shaders::probe::ProbeSteps::default(),
18507            },
18508            probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
18509            update: ProbeUpdate::EveryFrame,
18510        };
18511        let mut renderer =
18512            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
18513                .expect("built");
18514        // A maximum-width graph must include actual instances to cull.
18515        place_cube(&mut renderer, Mat4::IDENTITY);
18516        renderer
18517            .set_ground_grid(device, Some(GridStyle::default()))
18518            .expect("the null backend builds every pipeline");
18519        // **And the occlusion cull**, whose late prepass, farthest pyramid and
18520        // three late compute passes are the ground grid's kind of pass: off
18521        // unless a caller asks, and in the widest frame when one does.
18522        renderer.set_occlusion_culling(OcclusionCulling {
18523            occlusion: true,
18524            small_feature_pixels: None,
18525        });
18526        // **A body of water**, on the ground grid's terms: content rather than
18527        // an effect bit, so the widest frame is one a caller gave water to, and
18528        // `Water::PASSES` is in the bound for it.
18529        renderer
18530            .set_water(&[crcbl_water::WaterBody {
18531                outline: vec![[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]],
18532                level: 0.0,
18533                medium: crcbl_water::Medium {
18534                    absorption: [0.4, 0.1, 0.05],
18535                    scattering: [0.01, 0.01, 0.01],
18536                },
18537            }])
18538            .expect("a square meshes");
18539        // **A field of grass**, on the water body's terms exactly: content
18540        // rather than an effect bit, so the widest frame is one a caller gave a
18541        // field to and `Grass::PASSES` is in the bound for it.
18542        renderer
18543            .set_grass(
18544                device,
18545                queue,
18546                Some(
18547                    &crate::grass::GrassField::new(
18548                        [1, 1],
18549                        4.0,
18550                        [-2.0, -2.0],
18551                        50.0,
18552                        crate::grass::Heightfield {
18553                            texels: [4, 4],
18554                            metres_per_texel: 1.0,
18555                            origin: [-2.0, -2.0],
18556                            heights: vec![0.0; 16],
18557                        },
18558                        crate::grass::CoverMap {
18559                            texels: [4, 4],
18560                            metres_per_texel: 1.0,
18561                            origin: [-2.0, -2.0],
18562                            cover: vec![[255, 0]; 16],
18563                        },
18564                        // A shell row and a mesh blade row, so the widest
18565                        // frame records every look's draw the grass pass has.
18566                        [
18567                            crate::grass::BladeLook::Shells,
18568                            crate::grass::BladeLook::Blades,
18569                        ]
18570                        .map(|look| crate::grass::BladeType {
18571                            root_color: [0.05, 0.1, 0.02],
18572                            tip_color: [0.3, 0.5, 0.1],
18573                            height: 0.3,
18574                            half_width: 0.03,
18575                            height_spread: 0.3,
18576                            width_spread: 0.2,
18577                            look,
18578                            style: crate::grass::BladeStyle::PLAIN,
18579                            shape: crate::grass::BladeShape::STRAIGHT,
18580                            clumping: crate::grass::Clumping::NONE,
18581                        })
18582                        .to_vec(),
18583                    )
18584                    .expect("a real field"),
18585                ),
18586            )
18587            .expect("the null backend uploads every map");
18588        renderer.set_render_scale(WIDEST_SCALE);
18589        assert_eq!(
18590            renderer.internal_extent(WIDEST_EXTENT),
18591            WIDEST_INTERNAL,
18592            "the scale has to take the target to the extent whose chain is the \
18593             longest one, or the bound below is checked against a frame that \
18594             could not reach it"
18595        );
18596        // **Both post effects forced on.** Neither is in the default camera
18597        // stack — see [`RenderEffects::DEFAULT_STACK`], which leaves the lens out
18598        // for one reason and the resolve out for another — and the widest frame
18599        // is the one that has every effect in it, the ground grid's argument
18600        // exactly.
18601        renderer.set_effect_request(EffectRequest {
18602            programmatic: EffectOverride::none().force(OUTSIDE_THE_DEFAULT, Some(true)),
18603            ..EffectRequest::default()
18604        });
18605        let imported = swapchain_image_at(device, WIDEST_EXTENT);
18606        let mut pool = crate::TransientPool::new();
18607
18608        // The debug draw layer on for both frames below, because it is a pass
18609        // the bound counts and no effect bit switches on — the ground grid's
18610        // argument again. A segment before each, since `begin_frame` clears the
18611        // buffer: the layer is immediate mode.
18612        let switch = debug_draw_switch();
18613        switch.set(true);
18614        // And the occlusion pair's second blur, for exactly that reason: it is a
18615        // pass [`Ssao::MAX_PASSES`] counts and no effect bit switches on, so a
18616        // frame at the shipping count comes one short of the bound and this test
18617        // would be asserting the bound against a frame that could not reach it.
18618        let blurs = ssao_blur_switch();
18619        blurs.set(i64::from(Ssao::MAX_BLUR_PASSES));
18620        // And the comparison seam, which is the occlusion chain's other
18621        // conditional pass — see `crate::ssao`'s `r_ssao_split`. Held for the
18622        // same reason the blur count is: the bound counts a frame that compares,
18623        // so a frame that does not could never reach it.
18624        let split = ssao_split_switch();
18625        split.set(0.5);
18626        renderer
18627            .debug_draw()
18628            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18629        let bare =
18630            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18631        assert_eq!(
18632            crate::bloom::mips_for(WIDEST_INTERNAL),
18633            crate::bloom::MAX_MIPS,
18634            "the widest frame has to be one whose chain is the longest one there \
18635             is, or the bound below is checked against a frame that could not \
18636             reach it"
18637        );
18638        assert!(
18639            bare < ForwardRenderer::MAX_PASSES as usize,
18640            "a frame with no shadowed light runs {bare} passes, which is already the \
18641             bound of {} — then the bound does not cover the slots this scene left free",
18642            ForwardRenderer::MAX_PASSES
18643        );
18644
18645        // One spot per slot, spaced so no two of them share an influence — the
18646        // list has to fill every slot or the bound below is checked against a
18647        // frame that could not reach it.
18648        #[expect(
18649            clippy::cast_precision_loss,
18650            reason = "a handful of slots, and the value is only a position"
18651        )]
18652        let spots: Vec<Light> = (0..shadow::LIGHT_SLOTS)
18653            .map(|slot| shadowable_spot(1.0 + slot as f32))
18654            .collect();
18655        renderer.set_lights(&spots);
18656        renderer
18657            .debug_draw()
18658            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18659        let widest =
18660            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18661        assert_eq!(
18662            renderer.shadow_lights.slots().iter().flatten().count(),
18663            shadow::LIGHT_SLOTS,
18664            "the spots must actually hold every slot, or this is the bare frame again \
18665             under another name"
18666        );
18667        assert_eq!(
18668            widest,
18669            ForwardRenderer::MAX_PASSES as usize,
18670            "the widest frame is what the bound is for"
18671        );
18672        assert_eq!(
18673            widest - bare,
18674            DrawGen::MAX_PASSES as usize * shadow::LIGHT_SLOTS,
18675            "a filled slot costs a cull's passes and nothing else"
18676        );
18677
18678        renderer.destroy(device);
18679        pool.destroy(device);
18680        device.destroy_image_view(imported.view);
18681        device.destroy_image(imported.image);
18682        recorder.assert_valid();
18683    }
18684
18685    /// **A toggle reaches the recorded frame, and takes exactly its own passes
18686    /// with it.**
18687    ///
18688    /// The observable is the compiled pass list, because the thing that could
18689    /// otherwise be true is that the switch is stored and read by nothing: a
18690    /// renderer holding `SHADOWS` clear and recording every shadow cull anyway
18691    /// draws a frame that looks right, reports the right effect set, and has not
18692    /// switched anything off.
18693    ///
18694    /// So each arm compares the whole list rather than its length. Two passes
18695    /// fewer is satisfied by removing the wrong two, and it is satisfied by a
18696    /// frame that lost its tonemap.
18697    ///
18698    /// The shadow arm is the one that cannot be written by name — a cascade's
18699    /// cull passes are labelled exactly as the camera's are — so it is written as
18700    /// its two halves instead: the count moves by a cull's worth per cascade and
18701    /// per filled light slot, and everything from the `shadow` pass onwards is
18702    /// unchanged. The `shadow` pass itself **stays**, because it is what writes
18703    /// the clear that reads as "fully lit".
18704    #[test]
18705    fn each_effect_toggle_removes_exactly_the_passes_it_owns() {
18706        let _blurs = ssao_blur_switch();
18707        let (recorder, device, queue) = open();
18708        let device = device.as_ref();
18709        let mut renderer =
18710            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18711        place_cube(&mut renderer, Mat4::IDENTITY);
18712        // One shadowed light beside the cascades, so the shadow arm below covers
18713        // a light slot's cull as well as a cascade's.
18714        renderer.set_lights(&[shadowable_spot(-1.0)]);
18715        let imported = swapchain_image(device);
18716        let mut pool = crate::TransientPool::new();
18717
18718        // [`OUTSIDE_THE_DEFAULT`] forced on and then `off` forced off, on
18719        // [`frame_switching_off`]'s terms exactly: the default camera stack
18720        // leaves both of them out — see [`RenderEffects::DEFAULT_STACK`] — so a
18721        // control built on the default alone would have nothing for their arms
18722        // to remove. `force` clears the other side, so an arm whose `off` is one
18723        // of them still resolves to off.
18724        //
18725        // [`frame_switching_off`]: fn@frame_switching_off
18726        let without = |renderer: &mut ForwardRenderer, off: RenderEffects| {
18727            renderer.set_effect_request(EffectRequest {
18728                programmatic: EffectOverride::none()
18729                    .force(OUTSIDE_THE_DEFAULT, Some(true))
18730                    .force(off, Some(false)),
18731                ..EffectRequest::default()
18732            });
18733            passes_in_a_frame(device, queue, renderer, imported, &pool, TEST_EXTENT)
18734        };
18735
18736        let all_on = without(&mut renderer, RenderEffects::empty());
18737        assert_eq!(
18738            renderer.effects(),
18739            RenderEffects::all(),
18740            "the control frame has to be the every-effect one"
18741        );
18742        assert_eq!(
18743            renderer.shadow_lights.slots().iter().flatten().count(),
18744            1,
18745            "the spot must actually hold a slot, or the shadow arm below is only about cascades"
18746        );
18747
18748        // **None of the three leaves anything behind it**, and for the same
18749        // reason: nothing reads what it would have written. The occlusion pair's
18750        // reader binds the 1×1 white placeholder instead — `mesh.slang` clamps
18751        // its `Load` into it — and the reflection pair's and the chain's readers
18752        // both tonemap whatever image they would have read anyway.
18753        //
18754        // The chain's labels are written out rather than built from
18755        // `crate::bloom`'s arithmetic, because a table generated from the code
18756        // under test cannot fail: it is `TEST_EXTENT`'s two levels — two
18757        // downsamples, the one upsample between them, and the composite — and if
18758        // that extent moves this is the assertion that says so.
18759        for (off, gone) in [
18760            (
18761                RenderEffects::AMBIENT_OCCLUSION,
18762                ["ssao", "ssao-blur", "ssao-upsample"].as_slice(),
18763            ),
18764            (
18765                RenderEffects::CONTACT_SHADOWS,
18766                // One pass and no blur — `crate::contact_shadows`'s header says
18767                // why the occlusion pair's second pass has no counterpart here.
18768                ["contact-shadows"].as_slice(),
18769            ),
18770            (
18771                RenderEffects::REFLECTIONS,
18772                // **The pyramid goes with the march**, which is the whole of
18773                // what makes it an optimisation rather than a resource: it is
18774                // recorded on the frames that reflect and on no others. Two
18775                // levels at `TEST_EXTENT`, written out on the chain's terms
18776                // above.
18777                ["hiz-1", "hiz-2", "ssr", "ssr-blur"].as_slice(),
18778            ),
18779            (
18780                RenderEffects::BLOOM,
18781                [
18782                    "bloom-down-1",
18783                    "bloom-down-2",
18784                    "bloom-up-1",
18785                    "bloom-composite",
18786                ]
18787                .as_slice(),
18788            ),
18789            (
18790                RenderEffects::AUTO_EXPOSURE,
18791                // All three go together and the tonemap stays: the pass reads
18792                // the measurement only when the block says to, and the block
18793                // says so on exactly the frames these three ran on.
18794                ["exposure-clear", "exposure-histogram", "exposure-reduce"].as_slice(),
18795            ),
18796        ] {
18797            let labels = without(&mut renderer, off);
18798            assert_eq!(
18799                renderer.effects(),
18800                RenderEffects::all().difference(off),
18801                "{off:?}: the frame must have resolved to the set the request asked for"
18802            );
18803            // **The control frame has to contain what this arm removes**, and
18804            // that is not a restatement of the comparison below: the comparison
18805            // builds `expected` by filtering `gone` out of `all_on`, so an arm
18806            // naming a pass the control never recorded filters nothing, matches,
18807            // and passes whether the effect draws anything or not. Removing the
18808            // resolve pass entirely left this loop green until this assertion
18809            // existed.
18810            for label in gone {
18811                assert!(
18812                    all_on.iter().any(|recorded| recorded == label),
18813                    "{off:?}: the every-effect frame does not record `{label}`, so removing it \
18814                     below proves nothing: {all_on:#?}"
18815                );
18816            }
18817            let expected: Vec<String> = all_on
18818                .iter()
18819                .filter(|label| !gone.contains(&label.as_str()))
18820                .cloned()
18821                .collect();
18822            assert_eq!(
18823                labels, expected,
18824                "{off:?}: the frame must lose {gone:?}, gain nothing in their place, and keep \
18825                 every other pass"
18826            );
18827        }
18828
18829        // **The two antialiasing tiers share one resolve slot**, so neither is
18830        // a plain removal and neither belongs in the loop above: switching
18831        // CMAA2 off while FXAA stays on swaps three passes for one rather than
18832        // losing three, and the loop's "gain nothing in their place" comparison
18833        // is exactly what that violates. Three frames say it instead.
18834        let both = all_on.clone();
18835        let cheap = without(&mut renderer, RenderEffects::CMAA2);
18836        let neither = without(
18837            &mut renderer,
18838            RenderEffects::CMAA2.union(RenderEffects::ANTIALIASING),
18839        );
18840        const CMAA2_PASSES: [&str; 3] = ["cmaa2-edges", "cmaa2-shapes", "cmaa2-apply"];
18841        let resolve_of = |labels: &[String]| -> Vec<String> {
18842            labels
18843                .iter()
18844                .filter(|label| *label == "fxaa" || CMAA2_PASSES.contains(&label.as_str()))
18845                .cloned()
18846                .collect()
18847        };
18848        let without_resolve = |labels: &[String]| -> Vec<String> {
18849            labels
18850                .iter()
18851                .filter(|label| *label != "fxaa" && !CMAA2_PASSES.contains(&label.as_str()))
18852                .cloned()
18853                .collect()
18854        };
18855        assert_eq!(
18856            resolve_of(&both),
18857            CMAA2_PASSES.map(str::to_string).to_vec(),
18858            "with both bits set the higher tier takes the slot and the cheap one \
18859             records nothing"
18860        );
18861        assert_eq!(
18862            resolve_of(&cheap),
18863            vec!["fxaa".to_string()],
18864            "with only the cheap bit set the slot is FXAA's"
18865        );
18866        assert!(
18867            resolve_of(&neither).is_empty(),
18868            "with neither bit set the frame has no resolve at all: {neither:#?}"
18869        );
18870        // And nothing else moved: the tiers swap in one slot rather than
18871        // rebuilding the frame around themselves.
18872        assert_eq!(without_resolve(&both), without_resolve(&cheap));
18873        assert_eq!(without_resolve(&both), without_resolve(&neither));
18874        // The slot is where the ordering argument puts it — directly after the
18875        // last pass that writes the display image, which at this extent is the
18876        // tonemap.
18877        for labels in [&both, &cheap] {
18878            let at = labels
18879                .iter()
18880                .position(|label| label == "tonemap")
18881                .expect("a frame has to reach the swapchain");
18882            assert_eq!(
18883                &labels[at + 1..=at + resolve_of(labels).len()],
18884                resolve_of(labels).as_slice(),
18885                "the resolve must follow the tonemap: {labels:#?}"
18886            );
18887        }
18888
18889        let no_shadows = without(&mut renderer, RenderEffects::SHADOWS);
18890        assert_eq!(
18891            renderer.effects(),
18892            RenderEffects::all().difference(RenderEffects::SHADOWS),
18893        );
18894        assert_eq!(
18895            all_on.len() - no_shadows.len(),
18896            DrawGen::MAX_PASSES as usize * (shadow::CASCADES + 1),
18897            "shadows off must drop a cull's passes per cascade and per filled slot"
18898        );
18899        let from_the_atlas = |labels: &[String]| {
18900            let at = labels
18901                .iter()
18902                .position(|label| label == "shadow")
18903                .expect("the atlas pass is recorded whether or not anything draws into it");
18904            labels[at..].to_vec()
18905        };
18906        assert_eq!(
18907            from_the_atlas(&no_shadows),
18908            from_the_atlas(&all_on),
18909            "only the culls go: the atlas pass and everything after it are unchanged"
18910        );
18911
18912        renderer.destroy(device);
18913        pool.destroy(device);
18914        device.destroy_image_view(imported.view);
18915        device.destroy_image(imported.image);
18916        recorder.assert_valid();
18917    }
18918
18919    /// **The contact march is a pass a frame records only when it was asked
18920    /// for, and the mask it writes is what the forward pass then reads.**
18921    ///
18922    /// Two observables, because either alone is satisfied by a mistake the other
18923    /// one catches:
18924    ///
18925    /// * **The compiled pass list.** `contact-shadows` appears between the
18926    ///   prepass whose depth it marches and the forward pass that binds it, and
18927    ///   appears at all only on the frame that asked. The toggle test above
18928    ///   already says a frame loses this pass and nothing else; what is added
18929    ///   here is *where* it sits, which is the half a set comparison cannot see
18930    ///   — a march recorded after the pass that reads it compiles and draws a
18931    ///   mask nothing ever looks at.
18932    /// * **The forward pass's own barriers.** On the frame that marched, one
18933    ///   more image is transitioned into [`ResourceState::ShaderRead`] before
18934    ///   the forward pass opens than on the frame that did not — which is the
18935    ///   mask leaving the colour attachment it was written as. That is what says
18936    ///   the pass's output reaches the shading, rather than being written into a
18937    ///   transient and dropped while the shader goes on reading the 1×1
18938    ///   placeholder. The placeholder is imported in `ShaderRead` already and
18939    ///   needs no transition, so it contributes nothing to this count and the
18940    ///   difference is exactly the mask.
18941    ///
18942    /// [`RenderEffects::CONTACT_SHADOWS`] is out of the default camera stack
18943    /// while its re-bless is pending — see that constant — so the `on` frame has
18944    /// to force it and the `off` frame is what a view saying nothing draws.
18945    #[test]
18946    fn the_contact_march_is_recorded_only_when_asked_and_its_mask_reaches_the_forward_pass() {
18947        let (recorder, device, queue) = open();
18948        let device = device.as_ref();
18949        let mut renderer =
18950            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18951        let imported = swapchain_image(device);
18952        let mut pool = crate::TransientPool::new();
18953
18954        let frame = |renderer: &mut ForwardRenderer, on: bool| -> (Vec<String>, usize) {
18955            renderer.set_effect_request(EffectRequest {
18956                programmatic: EffectOverride::none()
18957                    .force(RenderEffects::CONTACT_SHADOWS, Some(on)),
18958                ..EffectRequest::default()
18959            });
18960            renderer
18961                .begin_frame(
18962                    device,
18963                    &Camera::default(),
18964                    &DirectionalLight::default(),
18965                    TEST_EXTENT,
18966                )
18967                .expect("write");
18968            let mut graph = crate::RenderGraph::new(queue);
18969            let target = graph.import_image("target", imported);
18970            renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
18971            let compiled = graph.compile(&pool).expect("a legal frame");
18972            let labels: Vec<String> = compiled
18973                .passes()
18974                .iter()
18975                .map(|pass| pass.label().to_string())
18976                .collect();
18977            let readable = compiled
18978                .passes()
18979                .iter()
18980                .find(|pass| pass.label() == "forward")
18981                .expect("every frame draws its geometry")
18982                .barriers()
18983                .images
18984                .iter()
18985                .filter(|barrier| barrier.to == ResourceState::ShaderRead)
18986                .count();
18987            (labels, readable)
18988        };
18989
18990        let (marched, marched_reads) = frame(&mut renderer, true);
18991        assert!(
18992            renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
18993            "the forced frame has to have resolved with the bit set"
18994        );
18995        let (bare, bare_reads) = frame(&mut renderer, false);
18996        assert!(
18997            !renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
18998            "and the control frame without it"
18999        );
19000
19001        assert!(
19002            !bare.iter().any(|label| label == "contact-shadows"),
19003            "a frame that did not ask must record no march at all: {bare:#?}"
19004        );
19005        let at = |labels: &[String], wanted: &str| {
19006            labels
19007                .iter()
19008                .position(|label| label == wanted)
19009                .unwrap_or_else(|| panic!("no `{wanted}` pass in {labels:#?}"))
19010        };
19011        let march = at(&marched, "contact-shadows");
19012        assert!(
19013            march > at(&marched, "depth-prepass"),
19014            "the march reads the prepass's depth, so it cannot precede it: {marched:#?}"
19015        );
19016        assert!(
19017            march < at(&marched, "forward"),
19018            "and the forward pass binds what it wrote, so it cannot follow it: {marched:#?}"
19019        );
19020
19021        assert_eq!(
19022            marched_reads,
19023            bare_reads + 1,
19024            "the forward pass has to take one more image into `ShaderRead` on the frame that \
19025             marched — the mask. Equal counts mean the pass wrote a transient the shading \
19026             never reads."
19027        );
19028
19029        renderer.destroy(device);
19030        pool.destroy(device);
19031        device.destroy_image_view(imported.view);
19032        device.destroy_image(imported.image);
19033        recorder.assert_valid();
19034    }
19035
19036    /// **The ground grid is off until a caller asks, and then it is the last
19037    /// pass of the frame — after the tonemap.**
19038    ///
19039    /// Three claims and each is a separate way to get this wrong. Off by default
19040    /// is what keeps every sample and every golden image where they were. *After
19041    /// the tonemap* is the placement decision: added a line earlier it would
19042    /// draw into the HDR scene colour and be tonemapped like geometry, which
19043    /// compiles, draws a grid, and gives it a colour that moves with the
19044    /// exposure. And switching it off again has to remove the pass, not merely
19045    /// stop reporting it.
19046    ///
19047    /// The whole list is compared rather than its length, for the reason the
19048    /// effect-toggle test gives: one more pass is satisfied by gaining the wrong
19049    /// one.
19050    #[test]
19051    fn the_ground_grid_is_opt_in_and_lands_after_the_tonemap() {
19052        let _blurs = ssao_blur_switch();
19053        let (recorder, device, queue) = open();
19054        let device = device.as_ref();
19055        let mut renderer =
19056            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19057        let imported = swapchain_image(device);
19058        let mut pool = crate::TransientPool::new();
19059
19060        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19061        assert!(
19062            renderer.ground_grid().is_none(),
19063            "a renderer nobody asked has no grid"
19064        );
19065        assert!(
19066            !off.contains(&"grid".to_string()),
19067            "the grid must not be in a frame nobody asked for it in: {off:#?}"
19068        );
19069
19070        renderer
19071            .set_ground_grid(device, Some(GridStyle::default()))
19072            .expect("the null backend builds every pipeline");
19073        assert_eq!(renderer.ground_grid(), Some(&GridStyle::default()));
19074        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19075
19076        let mut expected = off.clone();
19077        // The statistics copy is added after every render pass and stays last —
19078        // see `add_passes`. So the grid goes in front of it, which is directly
19079        // after the tonemap.
19080        let tonemap = expected
19081            .iter()
19082            .position(|label| label == "tonemap")
19083            .expect("a frame has to reach the swapchain");
19084        expected.insert(tonemap + 1, "grid".to_string());
19085        assert_eq!(
19086            on, expected,
19087            "the grid must be the one pass gained, and it must sit after the tonemap"
19088        );
19089
19090        renderer
19091            .set_ground_grid(device, None)
19092            .expect("switching off builds nothing");
19093        assert!(renderer.ground_grid().is_none());
19094        assert_eq!(
19095            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
19096            off,
19097            "switching the grid off has to remove its pass, not just stop reporting it"
19098        );
19099
19100        renderer.destroy(device);
19101        pool.destroy(device);
19102        device.destroy_image_view(imported.view);
19103        device.destroy_image(imported.image);
19104        recorder.assert_valid();
19105    }
19106
19107    /// **A second occlusion blur is a pass the frame records, an image it takes
19108    /// out of the pool, and a triangle its counter reports** — or it is a switch
19109    /// that does nothing.
19110    ///
19111    /// `crcbl`'s `forward_e2e::occlusion` measures what the second blur is worth
19112    /// by driving the pipelines itself, so nothing there would notice that a
19113    /// real frame never records it. The three things below are what a frame has
19114    /// to do differently, and each of them fails silently on its own: a missing
19115    /// pass draws a slightly rougher picture, a missing image is a bind of the
19116    /// wrong one, and a counter short by one is a number nobody reads until it
19117    /// is quoted.
19118    ///
19119    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19120    /// [`ssao_blur_switch`] and for [`debug_draw_switch`]'s reason.
19121    /// The id [`Ssao::add_passes`] hands back is the reconstruction's target,
19122    /// whichever blur ran into it.
19123    ///
19124    /// **The one thing about that chain no other check can see.** The pass list
19125    /// is identical either way, the graph accepts a written-and-never-read
19126    /// transient without complaint, and every golden is at one blur where the
19127    /// two blur answers coincide — so a frame bound to the wrong image draws
19128    /// something nobody would question, which is exactly what the function's
19129    /// own doc warns about. Verified 2026-08-31 by returning `blurred` from the
19130    /// two-blur arm: `crcbl-render`'s unit tests, the forward and mesh e2e
19131    /// suites and lantern's golden all stayed green.
19132    ///
19133    /// **Since the halving it is a second silent failure and a louder one.**
19134    /// Every working image is [`crate::ssao::half_extent`] of the frame, so a
19135    /// returned working id is not merely a rougher channel — it is an image a
19136    /// quarter of the size bound where `mesh.slang` reads at `SV_Position`,
19137    /// which its clamp turns into occlusion smeared over the top-left quarter of
19138    /// the frame rather than into an error.
19139    #[test]
19140    fn the_occlusion_id_handed_back_is_the_reconstruction_target() {
19141        let (_recorder, device, queue) = open();
19142        let device = device.as_ref();
19143        let mut ssao = Ssao::new(device, 1, ForwardRenderer::build_fullscreen).expect("built");
19144        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19145
19146        let one = {
19147            let mut graph = crate::RenderGraph::new(queue);
19148            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19149            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19150            let blurred =
19151                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19152            let upsampled = graph.create_image(
19153                "ssao-upsampled",
19154                crate::targets::ambient_occlusion(TEST_EXTENT),
19155            );
19156            let got = ssao.add_passes(
19157                &mut graph,
19158                0,
19159                TEST_EXTENT,
19160                depth,
19161                crate::ssao::OcclusionImages {
19162                    raw,
19163                    blurred,
19164                    again: None,
19165                    upsampled,
19166                },
19167            );
19168            (got == upsampled, got == blurred || got == raw)
19169        };
19170        assert!(one.0, "one blur finishes in the reconstruction's image");
19171        assert!(
19172            !one.1,
19173            "and never in one of the half-extent images the chain worked in"
19174        );
19175
19176        let two = {
19177            let mut graph = crate::RenderGraph::new(queue);
19178            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19179            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19180            let blurred =
19181                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19182            let again = graph.create_image(
19183                "ssao-blurred-2",
19184                crate::targets::ambient_occlusion(gathered),
19185            );
19186            let upsampled = graph.create_image(
19187                "ssao-upsampled",
19188                crate::targets::ambient_occlusion(TEST_EXTENT),
19189            );
19190            let got = ssao.add_passes(
19191                &mut graph,
19192                0,
19193                TEST_EXTENT,
19194                depth,
19195                crate::ssao::OcclusionImages {
19196                    raw,
19197                    blurred,
19198                    again: Some(again),
19199                    upsampled,
19200                },
19201            );
19202            (got == upsampled, got == again || got == blurred)
19203        };
19204        assert!(
19205            two.0,
19206            "two blurs finish in the reconstruction's image as well, which is the id the forward \
19207             pass binds"
19208        );
19209        assert!(
19210            !two.1,
19211            "and not in a blur's own image -- a frame bound to one of those is a frame nobody \
19212             would question"
19213        );
19214    }
19215
19216    /// **The gather runs at half the frame and the reconstruction runs at all
19217    /// of it** — or the halving is a description nobody rendered into.
19218    ///
19219    /// The pass list cannot see this: three passes with the right labels in the
19220    /// right order is exactly what a chain that halved nothing would record. The
19221    /// **render area** is where the halving is observable, and the graph derives
19222    /// it from each pass's colour attachment — so this is the check that the
19223    /// transients [`ForwardRenderer::add_passes`] created are the ones
19224    /// [`crate::ssao::half_extent`] sized, and that the reconstruction was given
19225    /// the frame-sized one.
19226    ///
19227    /// Neither mistake is an error anywhere else. Working images at the frame's
19228    /// extent are four times the march and a reconstruction reading the corner
19229    /// of its input; a frame-sized image handed to the march and a half-sized
19230    /// one to the forward pass is occlusion smeared over a quarter of the
19231    /// picture by `mesh.slang`'s clamp. Both are pictures.
19232    ///
19233    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19234    /// [`ssao_blur_switch`] and for that function's second reason: it looks the
19235    /// occlusion chain's passes up by name, and a second blur arriving from
19236    /// another thread's switch is a pass this frame did not ask for.
19237    #[test]
19238    fn the_occlusion_chain_gathers_at_half_the_frame_and_reconstructs_at_all_of_it() {
19239        let _switch = ssao_blur_switch();
19240
19241        let (recorder, device, queue) = open();
19242        let device = device.as_ref();
19243        let mut renderer =
19244            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19245        let imported = swapchain_image(device);
19246        let mut pool = crate::TransientPool::new();
19247        renderer
19248            .begin_frame(
19249                device,
19250                &Camera::default(),
19251                &DirectionalLight::default(),
19252                TEST_EXTENT,
19253            )
19254            .expect("write");
19255        let mut graph = crate::RenderGraph::new(queue);
19256        let target = graph.import_image("target", imported);
19257        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19258        let compiled = graph.compile(&pool).expect("a legal frame");
19259        let area_of = |label: &str| {
19260            let pass = compiled
19261                .passes()
19262                .iter()
19263                .find(|pass| pass.label() == label)
19264                .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
19265            let area = pass.render_area();
19266            (area.width, area.height)
19267        };
19268
19269        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19270        assert_ne!(
19271            gathered, TEST_EXTENT,
19272            "the fixture extent has to halve to something else, or every assertion below holds \
19273             of a chain that halved nothing"
19274        );
19275        assert_eq!(
19276            area_of("ssao"),
19277            gathered,
19278            "the march has to run over the gather extent"
19279        );
19280        assert_eq!(
19281            area_of("ssao-blur"),
19282            gathered,
19283            "and so does the blur over what the march wrote"
19284        );
19285        assert_eq!(
19286            area_of("ssao-upsample"),
19287            TEST_EXTENT,
19288            "the reconstruction writes the channel `mesh.slang` reads at `SV_Position`, so it \
19289             runs at the frame's own extent"
19290        );
19291
19292        drop(compiled);
19293        renderer.destroy(device);
19294        pool.destroy(device);
19295        device.destroy_image_view(imported.view);
19296        device.destroy_image(imported.image);
19297        recorder.assert_valid();
19298    }
19299
19300    /// **The comparison seam records a second march, scissored to the columns
19301    /// the first one was kept off.**
19302    ///
19303    /// `crate::split`'s geometry, read off the encoder rather than off the code
19304    /// that drove it: two passes, and two `SetScissor` rectangles that tile the
19305    /// gather extent between them.
19306    ///
19307    /// **What this cannot see is which block each march bound.** The reference
19308    /// backend records a bind group as a handle and a layout, not as the
19309    /// resources behind it, so pointing both marches at one buffer leaves this
19310    /// test green — measured, by doing exactly that. The group inequality below
19311    /// is kept because it is free and would catch the two marches sharing a
19312    /// cache, which is a different fault; what covers the blocks is
19313    /// `crate::ssao`'s `the_seams_other_side_is_what_the_chain_ships`, and what
19314    /// is not covered at all is the wiring between them. `docs/backlog.md`
19315    /// carries that gap.
19316    ///
19317    /// **The control is the same frame without a seam**, and it is what makes
19318    /// the assertions mean anything: a chain that scissored unconditionally
19319    /// would satisfy every claim below and change every golden in the workspace,
19320    /// so the frame nobody asked to compare has to record one march and set no
19321    /// rectangle at all.
19322    ///
19323    /// Holds [`ssao_split_switch`] for [`ssao_blur_switch`]'s reason: the seam
19324    /// is process-wide state and a frame that picked one up from another
19325    /// thread's test is a frame with a pass this one did not ask for.
19326    #[test]
19327    fn the_comparison_seam_marches_twice_over_columns_that_tile_the_gather() {
19328        use crcbl_hal::null::Command;
19329
19330        let _blurs = ssao_blur_switch();
19331        let split = ssao_split_switch();
19332        // Third, after the two above: the only other test that takes this one
19333        // takes it alone, so this is the whole order and there is no cycle in
19334        // it. Moved below, because two blocks holding the same scalars are
19335        // equal whatever the seam did.
19336        let slices = ssao_slice_switch();
19337        // The count the seam's far side reads, and one that is not it. Read off
19338        // the variable rather than written down: which end of the range ships
19339        // has changed once already, and a test naming the wrong end would be
19340        // comparing the shipped configuration against itself.
19341        let ships = match crate::ssao::r_ssao_slices.default() {
19342            crcbl_console::Value::Int(count) => *count,
19343            other => panic!("`r_ssao_slices` defaults to {other:?}, which is not a count"),
19344        };
19345        let moved = if ships == i64::from(ssao::SLICE_COUNT_MAX) {
19346            i64::from(ssao::SLICE_COUNT_DEFAULT)
19347        } else {
19348            i64::from(ssao::SLICE_COUNT_MAX)
19349        };
19350        assert_ne!(
19351            ships, moved,
19352            "the two slice counts this compares are one count, so the blocks below would differ \
19353             by nothing whatever the seam did"
19354        );
19355        slices.set(ships);
19356
19357        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19358        // One entry per march the frame recorded: the last rectangle that pass
19359        // left the scissor at, and the group it bound.
19360        //
19361        // **The last and not the only one.** The graph opens every pass with a
19362        // scissor over the whole render area, so a march that sets none of its
19363        // own still records one — which is why "did it scissor at all" is not
19364        // the question and "what did it end up cropped to" is.
19365        let marches = |recorder: &Recorder, from: usize| {
19366            let mut inside = false;
19367            let mut found: Vec<(crcbl_hal::Rect2d, crcbl_hal::BindGroupHandle)> = Vec::new();
19368            let mut rect = None;
19369            let mut group = None;
19370            for command in &recorder.commands()[from..] {
19371                if let Some((_, label)) = command.opens_pass() {
19372                    inside = matches!(label, Some("ssao" | "ssao-shipped"));
19373                    (rect, group) = (None, None);
19374                    continue;
19375                }
19376                if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19377                    if let (true, Some(rect), Some(group)) = (inside, rect, group) {
19378                        found.push((rect, group));
19379                    }
19380                    inside = false;
19381                    continue;
19382                }
19383                if !inside {
19384                    continue;
19385                }
19386                match command {
19387                    Command::SetScissor(at) => rect = Some(*at),
19388                    Command::BindGroup { group: bound, .. } => group = Some(*bound),
19389                    _ => {}
19390                }
19391            }
19392            found
19393        };
19394
19395        let (recorder, device, queue) = open();
19396        let device = device.as_ref();
19397        let mut renderer =
19398            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19399
19400        split.set(0.0);
19401        let alone = frame_seen_from(
19402            device,
19403            &mut renderer,
19404            queue,
19405            &Camera::default(),
19406            &DirectionalLight::default(),
19407        );
19408        let plain = marches(&recorder, 0);
19409        let after = recorder.commands().len();
19410        let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
19411        let (uncompared_console, uncompared_shipped) = (
19412            recorder.buffer_bytes(console).expect("the console's block"),
19413            recorder.buffer_bytes(shipped).expect("the seam's block"),
19414        );
19415        alone.release(device);
19416
19417        split.set(0.5);
19418        slices.set(moved);
19419        let frame = frame_seen_from(
19420            device,
19421            &mut renderer,
19422            queue,
19423            &Camera::default(),
19424            &DirectionalLight::default(),
19425        );
19426        let compared = marches(&recorder, after);
19427        let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
19428        let (compared_console, compared_shipped) = (
19429            recorder.buffer_bytes(console).expect("the console's block"),
19430            recorder.buffer_bytes(shipped).expect("the seam's block"),
19431        );
19432        frame.finish(device, renderer);
19433
19434        assert_eq!(
19435            plain.len(),
19436            1,
19437            "a frame comparing nothing recorded {} march(es); the seam is off, so there is one",
19438            plain.len()
19439        );
19440        assert_eq!(
19441            (
19442                plain[0].0.x,
19443                plain[0].0.y,
19444                plain[0].0.width,
19445                plain[0].0.height
19446            ),
19447            (0, 0, gathered.0, gathered.1),
19448            "a frame comparing nothing left its march cropped to something other than the whole \
19449             gather extent {gathered:?} — so the chain crops whether or not anybody asked it to, \
19450             and every golden in this workspace was blessed on a frame that does not"
19451        );
19452
19453        assert_eq!(
19454            compared.len(),
19455            2,
19456            "a frame comparing two configurations recorded {} march(es)",
19457            compared.len()
19458        );
19459        let (left, right) = (compared[0].0, compared[1].0);
19460        assert_eq!(
19461            (left.x, left.y, right.y),
19462            (0, 0, 0),
19463            "both halves start at the top and the left one at the edge"
19464        );
19465        assert_eq!(
19466            i64::from(right.x),
19467            i64::from(left.width),
19468            "the second march starts where the first one ended, or a column is drawn twice"
19469        );
19470        assert_eq!(
19471            (left.width + right.width, left.height, right.height),
19472            (gathered.0, gathered.1, gathered.1),
19473            "the two rectangles have to cover the gather extent {gathered:?} exactly"
19474        );
19475        assert!(
19476            left.width < gathered.0 && right.width < gathered.0,
19477            "one half covers the whole extent, so the other draws over it and the seam is a \
19478             rectangle that crops nothing"
19479        );
19480        assert_ne!(
19481            compared[0].1, compared[1].1,
19482            "the two marches bound one group, so they cannot be reading two blocks"
19483        );
19484
19485        // How far the reference backend can follow the far side. It will say
19486        // what bytes a buffer holds and it will not say which buffer a group
19487        // names, so the two together are "there are two blocks, and they differ
19488        // by the knob that was moved" — not "the right march read the right
19489        // one". Pointing both marches at one buffer still passes; see this
19490        // module's entry in `docs/backlog.md`.
19491        assert_eq!(
19492            uncompared_console, uncompared_shipped,
19493            "the console sat at its defaults and the two blocks still differ, so the seam's far \
19494             side is not this frame with the shipped scalars — it is another frame"
19495        );
19496        assert_ne!(
19497            compared_console, compared_shipped,
19498            "one slice count was moved off the shipped one and both blocks still hold the same \
19499             bytes, so a comparison shows the same picture twice"
19500        );
19501
19502        recorder.assert_valid();
19503    }
19504
19505    /// Every gather pipeline the frame bound, in the order the marches ran.
19506    ///
19507    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
19508    /// `marches` closure asking the other question of the same stream: that one
19509    /// reads the scissor and the group, and this one reads the pipeline. Only
19510    /// the `ssao` and `ssao-shipped` passes are looked at, because every other
19511    /// pass in the chain binds a pipeline too and a filter over the whole stream
19512    /// would be counting blurs.
19513    ///
19514    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
19515    fn gathers_bound(recorder: &Recorder, from: usize) -> Vec<crcbl_hal::GraphicsPipelineHandle> {
19516        use crcbl_hal::null::Command;
19517
19518        let mut inside = false;
19519        let mut found = Vec::new();
19520        for command in &recorder.commands()[from..] {
19521            if let Some((_, label)) = command.opens_pass() {
19522                inside = matches!(label, Some("ssao" | "ssao-shipped"));
19523                continue;
19524            }
19525            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19526                inside = false;
19527                continue;
19528            }
19529            if let (true, Command::BindGraphicsPipeline(pipeline)) = (inside, command) {
19530                found.push(*pipeline);
19531            }
19532        }
19533        found
19534    }
19535
19536    /// **`r_ssao_technique` decides which shader the gather runs**, read off the
19537    /// pipeline the `ssao` pass bound.
19538    ///
19539    /// The observable `docs/backlog.md` says the uniform block cannot have. The
19540    /// reference backend records a bind group as a handle and a layout rather
19541    /// than as the resources behind it, so nothing can ask which *block* a march
19542    /// read — but a pipeline is recorded as itself, so which *technique* a march
19543    /// ran is a question this backend answers. `Ssao::gathers` is what names the
19544    /// two, so this is an equality against the pipeline built from each shader
19545    /// rather than an inequality that any two handles would satisfy.
19546    ///
19547    /// **The default arm is the load-bearing half.** A selector that read the
19548    /// wrong variable, or a `pipeline_for` whose arms were swapped, would still
19549    /// change the frame when the console moved; what would go with it is every
19550    /// golden in this workspace, which is blessed on the technique that ships.
19551    ///
19552    /// Holds [`ssao_blur_switch`] for its own reason and
19553    /// [`ssao_technique_switch`] third, after it and [`ssao_split_switch`] —
19554    /// see `crate::ssao::TECHNIQUE_SWITCH` on the order.
19555    #[test]
19556    fn the_occlusion_technique_picks_the_gathers_pipeline() {
19557        let _blurs = ssao_blur_switch();
19558        let _seam = ssao_split_switch();
19559        let technique = ssao_technique_switch();
19560        // The name to move to, taken out of the variable's own set — see
19561        // `other_technique_name`.
19562        let other = other_technique_name();
19563
19564        let (recorder, device, queue) = open();
19565        let device = device.as_ref();
19566        let mut renderer =
19567            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19568        let (ships, cheap) = renderer.primary.ssao.gathers();
19569        assert_ne!(
19570            ships, cheap,
19571            "the renderer built one gather pipeline for both techniques, so nothing below can \
19572             tell them apart"
19573        );
19574
19575        let shipped = frame_seen_from(
19576            device,
19577            &mut renderer,
19578            queue,
19579            &Camera::default(),
19580            &DirectionalLight::default(),
19581        );
19582        let by_default = gathers_bound(&recorder, 0);
19583        let after = recorder.commands().len();
19584        shipped.release(device);
19585
19586        technique.set(other);
19587        let moved_frame = frame_seen_from(
19588            device,
19589            &mut renderer,
19590            queue,
19591            &Camera::default(),
19592            &DirectionalLight::default(),
19593        );
19594        let moved = gathers_bound(&recorder, after);
19595        moved_frame.finish(device, renderer);
19596
19597        assert_eq!(
19598            by_default,
19599            vec![ships],
19600            "a frame nobody has touched the console on gathered through something other than \
19601             `ssao.slang`'s pipeline, which is what every golden in this workspace was blessed on"
19602        );
19603        assert_eq!(
19604            moved,
19605            vec![cheap],
19606            "`r_ssao_technique {other}` left the frame gathering through the pipeline \
19607             it gathered through before, so the selector reaches nothing"
19608        );
19609        recorder.assert_valid();
19610    }
19611
19612    /// **The comparison seam's two marches run two techniques**, which is what
19613    /// the seam was built for.
19614    ///
19615    /// Alcove's second milestone is SSAO and GTAO in
19616    /// one frame, and this is that claim as a pair of pipeline handles: with the
19617    /// technique moved the near side runs the cheap tier and the far side the
19618    /// one that ships, and with it at its default both marches run the same
19619    /// shader and the seam separates nothing.
19620    ///
19621    /// **The control is the frame at the default**, and it is what makes the
19622    /// first half mean anything: a far side that always ran `ssao.slang` would
19623    /// satisfy the inequality below whatever `shipped_technique` did, and a
19624    /// chain that had simply forgotten to pass the far side a pipeline of its
19625    /// own would too.
19626    #[test]
19627    fn the_comparison_seam_marches_through_two_techniques() {
19628        let _blurs = ssao_blur_switch();
19629        let seam = ssao_split_switch();
19630        let technique = ssao_technique_switch();
19631        let other = other_technique_name();
19632
19633        let (recorder, device, queue) = open();
19634        let device = device.as_ref();
19635        let mut renderer =
19636            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19637        let (ships, cheap) = renderer.primary.ssao.gathers();
19638
19639        seam.set(0.5);
19640        let compared = frame_seen_from(
19641            device,
19642            &mut renderer,
19643            queue,
19644            &Camera::default(),
19645            &DirectionalLight::default(),
19646        );
19647        let one_technique = gathers_bound(&recorder, 0);
19648        let after = recorder.commands().len();
19649        compared.release(device);
19650
19651        technique.set(other);
19652        let frame = frame_seen_from(
19653            device,
19654            &mut renderer,
19655            queue,
19656            &Camera::default(),
19657            &DirectionalLight::default(),
19658        );
19659        let two_techniques = gathers_bound(&recorder, after);
19660        frame.finish(device, renderer);
19661
19662        assert_eq!(
19663            one_technique,
19664            vec![ships, ships],
19665            "a seam with the technique at its default has to march the shipped gather twice — \
19666             both sides read `shipped`'s configuration, and the picture is one technique either \
19667             side of a line"
19668        );
19669        assert_eq!(
19670            two_techniques,
19671            vec![cheap, ships],
19672            "with `r_ssao_technique {other}` the near side has to run the cheap tier \
19673             and the far side what ships; the far side follows the variable's *default*, exactly \
19674             as the four scalars do"
19675        );
19676        recorder.assert_valid();
19677    }
19678
19679    /// **The frame block carries the console's shadow filter on the near side
19680    /// of the seam, the shipped one on the far side, and the column
19681    /// [`crate::split::halves`] counted.**
19682    ///
19683    /// [`the_comparison_seam_marches_through_two_techniques`]'s claim for the
19684    /// other seam, and it has to be a claim about *bytes* rather than about
19685    /// pass handles: the occlusion chain compares two pipelines and this
19686    /// compares two arms of one, so there is nothing in the pass list to look
19687    /// at. What a person sees is decided entirely by the row this asserts.
19688    ///
19689    /// **The frame at the default is the control**, and it is what makes the
19690    /// rest mean anything: a block that always wrote the shipped filter into
19691    /// both lanes would satisfy the third case's far side whatever
19692    /// `shipped_filter` did, and one that copied the near lane into the far one
19693    /// would satisfy the first two.
19694    ///
19695    /// The column is compared against `halves`' own answer rather than against
19696    /// a number written here, which is the seam module's whole point: a test
19697    /// that multiplied the fraction by the width itself would be a second
19698    /// opinion about the rounding, and the floor is exactly what that module's
19699    /// `the_seam_takes_the_floor_of_the_column_it_asks_for` exists to pin.
19700    ///
19701    /// [`the_comparison_seam_marches_through_two_techniques`]: fn@the_comparison_seam_marches_through_two_techniques
19702    #[test]
19703    fn the_frame_block_carries_a_shadow_filter_for_each_side_of_the_seam() {
19704        let switch = shadow_filter_switch();
19705
19706        let (recorder, device, queue) = open();
19707        let device = device.as_ref();
19708        let mut renderer =
19709            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19710
19711        // The seam is counted over the extent the scene is *drawn* at, which is
19712        // what `SV_Position.x` is denominated in — not the caller's window.
19713        let internal = renderer.internal_extent(TEST_EXTENT);
19714        let (left, _) = crate::split::halves(internal, 0.5).expect("a seam down the middle");
19715        assert!(
19716            left.width > 0,
19717            "a seam with no columns on one side would make every assertion below hold of a \
19718             frame that compares nothing"
19719        );
19720
19721        let ships = shadow::shipped_filter();
19722        let other = shadow::Filter::Box;
19723        assert_ne!(
19724            other.mode(),
19725            ships.mode(),
19726            "the filter this test moves the console to is the one that ships, so the seam it \
19727             asks for compares one kernel against itself"
19728        );
19729
19730        let draw = |renderer: &mut ForwardRenderer| {
19731            renderer
19732                .begin_frame(
19733                    device,
19734                    &Camera::default(),
19735                    &DirectionalLight::default(),
19736                    TEST_EXTENT,
19737                )
19738                .expect("write");
19739            let bytes = recorder
19740                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
19741                .expect("this frame's uniform block is live");
19742            let at = mesh::FRAME_UNIFORMS_SIZE - 16;
19743            core::array::from_fn(|lane| {
19744                u32::from_le_bytes(
19745                    bytes[at + lane * 4..at + lane * 4 + 4]
19746                        .try_into()
19747                        .expect("four bytes"),
19748                )
19749            })
19750        };
19751
19752        let shipped: [u32; 4] = draw(&mut renderer);
19753        assert_eq!(
19754            shipped,
19755            [ships.mode(), ships.mode(), 0, 0],
19756            "a frame nobody has touched the console on must carry the shipped filter in both \
19757             lanes and no column, which is the row every golden in this workspace was blessed \
19758             under"
19759        );
19760
19761        switch.filter(other);
19762        let unsplit: [u32; 4] = draw(&mut renderer);
19763        assert_eq!(
19764            unsplit,
19765            [other.mode(), other.mode(), 0, 0],
19766            "`r_shadow_filter {}` with no seam has to reach every pixel, so both lanes carry it",
19767            other.label()
19768        );
19769
19770        switch.seam(0.5);
19771        let compared: [u32; 4] = draw(&mut renderer);
19772        assert_eq!(
19773            compared,
19774            [other.mode(), ships.mode(), left.width, 0],
19775            "a seam at 0.5 has to put the console's filter left of `halves`' column and the \
19776             shipped one right of it; the far side follows the variable's *default*, exactly \
19777             as the occlusion chain's does"
19778        );
19779
19780        renderer.destroy(device);
19781        recorder.assert_valid();
19782    }
19783
19784    #[test]
19785    fn a_second_occlusion_blur_is_a_pass_the_frame_records() {
19786        let switch = ssao_blur_switch();
19787
19788        let (recorder, device, queue) = open();
19789        let device = device.as_ref();
19790        let mut renderer =
19791            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19792        let imported = swapchain_image(device);
19793        let pool = crate::TransientPool::new();
19794
19795        let once = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19796        let counted_once = renderer.counters().instances;
19797        assert!(
19798            once.contains(&"ssao-blur".to_string()),
19799            "the shipping frame has to blur once, or the arm below is about a frame with no \
19800             occlusion in it at all: {once:#?}"
19801        );
19802        assert!(
19803            !once.contains(&"ssao-blur-2".to_string()),
19804            "a frame nobody moved the switch for must record one blur: {once:#?}"
19805        );
19806
19807        switch.set(2);
19808        let twice = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19809        let counted_twice = renderer.counters().instances;
19810        assert!(
19811            twice.contains(&"ssao-blur-2".to_string()),
19812            "`r_ssao_blur_passes 2` must put a second blur in the frame: {twice:#?}"
19813        );
19814        assert_eq!(
19815            twice.len(),
19816            once.len() + 1,
19817            "the second blur is the only pass that may join the frame: {twice:#?}"
19818        );
19819        assert_eq!(
19820            counted_twice,
19821            counted_once + FULLSCREEN_DRAWS,
19822            "the frame recorded a full-screen triangle its counter did not report"
19823        );
19824
19825        // The pass has to write somewhere the forward pass then reads, and the
19826        // graph is what would refuse a frame that bound an image nothing wrote.
19827        // `passes_in_a_frame` compiles rather than executes, so this is the
19828        // check that the third transient was requested at all.
19829        assert!(
19830            twice.iter().any(|pass| pass == "forward"),
19831            "the frame still has to reach its forward pass: {twice:#?}"
19832        );
19833        recorder.assert_valid();
19834    }
19835
19836    /// Every host-written buffer at the end of a whole ring of frames, keyed by
19837    /// the handle written and holding what that handle last held.
19838    ///
19839    /// A whole ring rather than one frame, because the blocks a frame writes are
19840    /// themselves rings — a buffer per frame in flight, [`Ssao`]'s among them —
19841    /// so one frame touches one slot of each and two single-frame batches would
19842    /// be comparing different buffers. A ring writes every slot, so two batches'
19843    /// keys line up and a difference between them is a difference in *bytes*.
19844    ///
19845    /// Only the events this call appends are read, so a caller can take one
19846    /// batch after another off the same recorder.
19847    fn host_buffers_over_a_ring(
19848        recorder: &Recorder,
19849        device: &dyn Device,
19850        renderer: &mut ForwardRenderer,
19851        queue: QueueHandle,
19852    ) -> std::collections::BTreeMap<u64, Vec<u8>> {
19853        let from = recorder.events().len();
19854        for _ in 0..FRAMES_IN_FLIGHT {
19855            frame(device, renderer, queue).release(device);
19856        }
19857        recorder.events()[from..]
19858            .iter()
19859            .filter_map(|event| match event {
19860                Event::BufferWritten { buffer, .. } => Some(*buffer),
19861                _ => None,
19862            })
19863            .map(|buffer| {
19864                let bytes = recorder
19865                    .buffer_bytes(buffer)
19866                    .expect("the stream only names buffers this recorder created");
19867                (buffer.to_bits(), bytes)
19868            })
19869            .collect()
19870    }
19871
19872    /// **`r_ssao_slices` reaches the block `ssao.slang` reads, on every frame of
19873    /// the ring, and moves nothing else in the frame.**
19874    ///
19875    /// The device test drives the two occlusion pipelines directly and
19876    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] moves the *blur*
19877    /// count, so until this the slice count was a variable with a `get_i64` and
19878    /// no evidence that a rendered frame ever carried it: `slice_count` could
19879    /// have returned its default unconditionally and every check in this
19880    /// workspace would still be green.
19881    ///
19882    /// So the observable is the bytes, taken off the null recorder's write log
19883    /// after a whole ring of frames at each setting and compared **by handle**.
19884    /// Two claims come out of that comparison and both are load-bearing:
19885    ///
19886    /// * **Some block moved** — every ring slot, in fact, which is what says the
19887    ///   count reaches the frame at all rather than only the slot the last frame
19888    ///   happened to land in.
19889    /// * **Every block that moved, moved only there.** A frame is a few dozen
19890    ///   host writes and the slice count has business with exactly one word of
19891    ///   one of them; a setting that perturbed a matrix, an instance or a shadow
19892    ///   view would be drawing a different frame for a reason nobody asked for,
19893    ///   and the "at least one differs" half alone would pass on it happily.
19894    ///
19895    /// **Holds every switch whose row is in a block it compares**, in the lock
19896    /// order: the two batches are compared byte for byte over every host
19897    /// buffer the frame writes, so any console row another test moves between
19898    /// them — the blur count, the seam, the technique, the shadow filter, or
19899    /// `crate::ssao`'s own mover of the params block — reads here as "some
19900    /// other write moving". [`ssao_technique_switch`] is the one that
19901    /// serialises against that mover.
19902    #[test]
19903    fn four_slices_reach_the_frame_the_shader_reads() {
19904        let _blurs = ssao_blur_switch();
19905        let _seam = ssao_split_switch();
19906        let switch = ssao_slice_switch();
19907        let _technique = ssao_technique_switch();
19908        let _filter = shadow_filter_switch();
19909
19910        let (recorder, device, queue) = open();
19911        let device = device.as_ref();
19912        let mut renderer =
19913            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19914
19915        // A ring rendered before either batch is taken, because the two below
19916        // are compared by handle and the renderer's opening frame writes blocks
19917        // no later frame writes again: it fills a cold shadow atlas, so the
19918        // shadow views' uniform blocks and the draw-generation blocks of the
19919        // cascades that were drawn are written once and never again while the
19920        // cache holds. Those would be in the first batch and missing from the
19921        // second, and a key that is only in one of them is a difference this
19922        // test cannot say anything about.
19923        for _ in 0..FRAMES_IN_FLIGHT {
19924            frame(device, &mut renderer, queue).release(device);
19925        }
19926        let shipping = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
19927        switch.set(i64::from(ssao::SLICE_COUNT_MAX));
19928        let asked = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
19929        assert_eq!(
19930            shipping.keys().collect::<Vec<_>>(),
19931            asked.keys().collect::<Vec<_>>(),
19932            "the two batches must write the same buffers, or they are not comparable",
19933        );
19934
19935        // Which bytes moving the count alone is allowed to move, asked of
19936        // `SsaoParams::to_bytes` rather than written here as an offset: the
19937        // block's layout is `crcbl_shaders::ssao`'s, and a field inserted ahead
19938        // of the count would leave a number spelled here pointing at the radius.
19939        let block_of = |slices| {
19940            ssao::SsaoParams {
19941                inv_proj: [0.0; 16],
19942                proj: [0.0; 16],
19943                inv_view: [0.0; 16],
19944                radius: 0.0,
19945                slices,
19946                intensity: ssao::INTENSITY_DEFAULT,
19947                bent_normals: crate::ssao::bent_normals(),
19948            }
19949            .to_bytes()
19950        };
19951        let at_shipping = block_of(ssao::SLICE_COUNT_DEFAULT);
19952        let at_max = block_of(ssao::SLICE_COUNT_MAX);
19953        let count_word: Vec<usize> = (0..ssao::PARAMS_SIZE)
19954            .filter(|at| at_shipping[*at] != at_max[*at])
19955            .collect();
19956
19957        let mut moved = 0;
19958        for (handle, before) in &shipping {
19959            let after = &asked[handle];
19960            if before == after {
19961                continue;
19962            }
19963            moved += 1;
19964            let mut only_the_count = before.clone();
19965            for at in &count_word {
19966                assert_eq!(
19967                    before[*at], at_shipping[*at],
19968                    "buffer {handle} differs between the batches but did not go in holding the \
19969                     shipping slice count, so this is some other write moving",
19970                );
19971                only_the_count[*at] = at_max[*at];
19972            }
19973            assert_eq!(
19974                after, &only_the_count,
19975                "buffer {handle} moved somewhere other than the slice count's word: the setting \
19976                 is perturbing a block it has no business in",
19977            );
19978        }
19979        assert_eq!(
19980            moved, FRAMES_IN_FLIGHT,
19981            "`r_ssao_slices 4` must reach every slot of the occlusion ring; a count that moved \
19982             none of them is a console variable no rendered frame reads",
19983        );
19984
19985        renderer.destroy(device);
19986        recorder.assert_valid();
19987    }
19988
19989    /// **The debug draw layer costs a frame nothing until something is appended
19990    /// *and* the console switch is on, and then it is the pass immediately
19991    /// before the tonemap.**
19992    ///
19993    /// Four claims, and each is a separate way to get this wrong.
19994    ///
19995    /// * **Off by default** is what keeps every golden image in the workspace
19996    ///   where it was blessed.
19997    /// * **A segment appended while the switch is off records nothing**, so a
19998    ///   system may append unconditionally.
19999    /// * **The switch on with an empty buffer records nothing either** — this is
20000    ///   the "costs nothing when empty" claim as a check rather than a sentence:
20001    ///   the compiled pass list is compared whole against the frame drawn before
20002    ///   the layer was switched on, so a pass that clears, blits or barriers
20003    ///   anything would show up here.
20004    /// * **Before the tonemap**, which is
20005    ///   `docs/plan/18-render-features.md`'s interaction rule and the opposite of
20006    ///   the ground grid above. Recorded a line later it would draw into the
20007    ///   display-space target and be free of the exposure, which compiles and
20008    ///   draws lines and is the wrong picture.
20009    ///
20010    /// And the fifth, which is what "immediate mode" means: the frame *after*
20011    /// the one that appended records nothing again, because
20012    /// [`ForwardRenderer::begin_frame`] cleared the buffer.
20013    ///
20014    /// The whole list is compared rather than its length, for the ground grid
20015    /// test's reason: one more pass is satisfied by gaining the wrong one.
20016    ///
20017    /// **This test owns `r_debug_draw` for its duration**, through
20018    /// [`debug_draw_switch`]: a plain `cargo test` run shares one process
20019    /// between tests, so the two checks here that move it have to take turns.
20020    /// `cargo nextest`, which CI runs, gives each a process of its own and needs
20021    /// none of it.
20022    #[test]
20023    fn the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap() {
20024        let switch = debug_draw_switch();
20025        let _blurs = ssao_blur_switch();
20026
20027        let (recorder, device, queue) = open();
20028        let device = device.as_ref();
20029        let mut renderer =
20030            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20031        let imported = swapchain_image(device);
20032        let mut pool = crate::TransientPool::new();
20033
20034        assert!(
20035            !crate::DebugDraw::enabled(),
20036            "the layer must be off before anything switches it on, or every claim below is \
20037             about a different default"
20038        );
20039        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20040        assert!(
20041            !off.contains(&"debug-draw".to_string()),
20042            "the layer must not be in a frame nobody switched it on for: {off:#?}"
20043        );
20044
20045        renderer
20046            .debug_draw()
20047            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20048        assert_eq!(
20049            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20050            off,
20051            "a segment appended while the switch is off must record no pass"
20052        );
20053
20054        switch.set(true);
20055        assert_eq!(
20056            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20057            off,
20058            "the switch on with an empty buffer must record the frame the layer's absence would"
20059        );
20060
20061        renderer
20062            .debug_draw()
20063            .aabb(-Vec3::ONE, Vec3::ONE, [0.0, 1.0, 0.0, 1.0]);
20064        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20065        let mut expected = off.clone();
20066        let tonemap = expected
20067            .iter()
20068            .position(|label| label == "tonemap")
20069            .expect("a frame has to reach the swapchain");
20070        expected.insert(tonemap, "debug-draw".to_string());
20071        assert_eq!(
20072            on, expected,
20073            "the layer must be the one pass gained, and it must sit before the tonemap"
20074        );
20075
20076        assert_eq!(
20077            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20078            off,
20079            "the buffer is immediate mode: the frame after the one that appended must record \
20080             nothing"
20081        );
20082
20083        switch.set(false);
20084        renderer.destroy(device);
20085        pool.destroy(device);
20086        device.destroy_image_view(imported.view);
20087        device.destroy_image(imported.image);
20088        recorder.assert_valid();
20089    }
20090
20091    /// **The debug draw layer's own call is counted in the frame's draws.**
20092    ///
20093    /// [`ForwardRenderer::counters`]' draw count is compared against the
20094    /// commands the null backend actually recorded, which is the same instrument
20095    /// `the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know`
20096    /// uses — so a layer whose line list was recorded and not counted fails here
20097    /// rather than quietly making every panel's draw row one short.
20098    ///
20099    /// Both directions are asserted: the frame that drew a segment records one
20100    /// more draw than the frame before it, *and* the counter moved by the same
20101    /// one. A count wired to a constant satisfies neither.
20102    ///
20103    /// It owns `r_debug_draw` for its duration, on
20104    /// `the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap`'s
20105    /// terms.
20106    #[test]
20107    fn the_debug_draw_layers_call_is_counted_in_the_frames_draws() {
20108        let switch = debug_draw_switch();
20109        let _blurs = ssao_blur_switch();
20110
20111        let (recorder, device, queue) = open();
20112        let device = device.as_ref();
20113        let mut renderer =
20114            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20115
20116        // A different sun in each of the two frames, so both of them redraw the
20117        // shadow atlas: the claim below is that the layer's own call is the one
20118        // draw the second frame gained, and a second frame that cached its
20119        // atlas would have lost the atlas's draws at the same time. See
20120        // [`moving_sun`].
20121        let quiet = frame_moving_the_sun(device, &mut renderer, queue, 0);
20122        let without = renderer.counters().draws;
20123        assert_eq!(
20124            without,
20125            recorded_draws(&recorder) as u64,
20126            "the counter and the frame's recorded draws disagree before the layer draws at all"
20127        );
20128        quiet.release(device);
20129
20130        switch.set(true);
20131        renderer
20132            .debug_draw()
20133            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20134        let drawn = frame_moving_the_sun(device, &mut renderer, queue, 1);
20135        let with = renderer.counters().draws;
20136        assert_eq!(
20137            with,
20138            without + 1,
20139            "the layer records one draw, so the count has to move by one"
20140        );
20141        assert_eq!(
20142            recorded_draws(&recorder) as u64,
20143            without + with,
20144            "the two frames' recorded draws and the two counts disagree, so the layer's call is \
20145             counted somewhere it was not recorded or recorded somewhere it was not counted"
20146        );
20147
20148        switch.set(false);
20149        drawn.finish(device, renderer);
20150        recorder.assert_valid();
20151    }
20152
20153    /// **The depth-only passes run the depth-only entry point, and the colour
20154    /// pass does not.**
20155    ///
20156    /// Topic 43 §2 split the vertex pool so a pass
20157    /// that wants a clip position and no more could fetch stream 0 alone, and
20158    /// [`MeshModules::depth_pipeline`] naming `mesh.slang`'s `depthVertexMain`
20159    /// is the whole of how that split is spent. **Nothing else in the tree sees
20160    /// it.** `crcbl_shaders::mesh`'s
20161    /// `the_depth_entry_point_fetches_the_position_stream_alone` reads the
20162    /// compiled artifact and would pass with the entry point built and unused;
20163    /// no golden moves, because the two stages compute the same clip position on
20164    /// purpose; the render graph records a legal frame either way; and the
20165    /// measured price says nothing — pointing this pipeline back at `vertexMain`
20166    /// cost the depth prepass about a tenth more on lavapipe and nothing to
20167    /// three figures on an RX 7900 XTX, measured 2026-08-31. So the wiring is
20168    /// asserted here, against the reference backend, which records the entry
20169    /// point a pipeline names precisely so this question has an answer.
20170    ///
20171    /// **Both halves, so the check is shown to discriminate.** A lookup that
20172    /// answered `depthVertexMain` for every pipeline would satisfy the first
20173    /// assertion alone, and the colour pipeline is the one that must *not* have
20174    /// moved. The labels are the descriptors' own and are what the two are told
20175    /// apart by, so a renamed pipeline fails at the `expect` rather than
20176    /// silently matching nothing.
20177    #[test]
20178    fn the_depth_pipeline_names_the_depth_only_vertex_stage_and_the_colour_one_does_not() {
20179        let (recorder, device, queue) = open();
20180        let device = device.as_ref();
20181        let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20182        // A mesh stage has no vertex entry point to name, and this whole rung is
20183        // about the raster arm — see [`MeshModules::depth_pipeline`]. The null
20184        // preset reports no `Features::MESH_SHADER`, so this is what it built;
20185        // asserted rather than assumed, because a preset that grew the feature
20186        // would leave every assertion below looking for pipelines that do not
20187        // exist.
20188        assert_ne!(
20189            renderer.geometry_path(),
20190            crcbl_hal::GeometryPath::MeshShader,
20191            "this device built a mesh-shader path, whose geometry stage names no vertex \
20192             entry point at all"
20193        );
20194
20195        let pipelines = recorder.graphics_pipeline_vertex_entries();
20196        let entry_of = |label: &str| -> String {
20197            let found: Vec<&str> = pipelines
20198                .iter()
20199                .filter(|(name, _)| name.as_deref() == Some(label))
20200                .map(|(_, entry)| entry.as_str())
20201                .collect();
20202            assert_eq!(
20203                found.len(),
20204                1,
20205                "the renderer built {} pipeline(s) labelled `{label}`, out of {pipelines:?}",
20206                found.len()
20207            );
20208            found[0].to_owned()
20209        };
20210
20211        assert_eq!(
20212            entry_of("shadow cascade"),
20213            "depthVertexMain",
20214            "the shadow atlas and the depth prepass share this pipeline, and it is the one \
20215             that reads the position stream alone"
20216        );
20217        assert_eq!(
20218            entry_of("forward mesh"),
20219            "vertexMain",
20220            "the colour pass needs every attribute the depth pass skips, so it is the entry \
20221             point that reads a whole vertex"
20222        );
20223        assert_eq!(
20224            entry_of("shadow cascade masked"),
20225            "vertexMain",
20226            "the cutout twin has to read a whole vertex: the UV it samples the mask from lives \
20227             in the attribute region `depthVertexMain` exists not to read"
20228        );
20229
20230        renderer.destroy(device);
20231        recorder.assert_valid();
20232    }
20233
20234    /// **A masked material moves that mesh's depth draws onto the cutout
20235    /// pipeline, and moves nothing else.**
20236    ///
20237    /// The mechanism is which pipeline handle the recorded stream binds and
20238    /// which buckets' indirect calls follow each bind — the wireframe test's
20239    /// observable, for the same reason: a field saying a mode was read would
20240    /// prove the flag was read, not that the frame changed.
20241    ///
20242    /// Four claims, and each rules out a different way of passing wrongly:
20243    ///
20244    /// * a scene with nothing masked binds the vertex-only pipeline and
20245    ///   **never** the cutout one, which is the "an opaque frame costs what it
20246    ///   always did" claim at the level a null device can see it;
20247    /// * a scene with one masked row binds **both** in the depth prepass and
20248    ///   both in the shadow atlas — a per-frame choice binds one or the other,
20249    ///   never the pair;
20250    /// * the calls following each bind are exactly that mode's buckets, in
20251    ///   bucket order, read off the argument offsets the draws name. A split
20252    ///   that bound both pipelines and drew every bucket under each would
20253    ///   satisfy the claim above and double the frame's draws;
20254    /// * and folding the two handles together — then collapsing the runs of
20255    ///   equal binds the fold creates — leaves the two frames' bind streams
20256    ///   **equal**, so the colour pass, the tile clears and the reflective
20257    ///   shadow map are all where they were. A change that had also moved the
20258    ///   colour pass would satisfy the first three and fail this.
20259    ///
20260    /// The two scenes differ in one flags word and nothing else.
20261    #[test]
20262    fn a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline() {
20263        use crcbl_hal::null::Command;
20264
20265        // The occlusion blur count is a process-global console variable and a
20266        // frame binds one pipeline per blur, so a concurrent test moving it
20267        // would put a bind in one of these frames and not the other — the
20268        // wireframe test's hazard exactly.
20269        let _blurs = ssao_blur_switch();
20270
20271        let masked_scene = {
20272            let mut scene = crate::scene::demo();
20273            scene.materials[DEMO_UNTINTED].flags =
20274                crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
20275            scene
20276        };
20277
20278        /// What one scene's frame reveals: the bucket count and each bucket's
20279        /// mode, how often each depth pipeline was bound, the (pipeline, bucket)
20280        /// pairs the depth prepass and the shadow atlas recorded, and the whole
20281        /// bind stream with the two depth handles folded into one.
20282        struct Recorded {
20283            modes: Vec<u32>,
20284            cutouts: usize,
20285            plains: usize,
20286            prepass: Vec<(bool, u32)>,
20287            atlas: Vec<(bool, u32)>,
20288            folded: Vec<GraphicsPipelineHandle>,
20289        }
20290
20291        // One frame each, from two renderers rather than two frames from one:
20292        // a bucket table is fixed at build, and two builds keep the frames'
20293        // shadow-atlas state identical — both are a first frame.
20294        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20295            let (recorder, device, queue) = open();
20296            let device = device.as_ref();
20297            let mut renderer =
20298                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20299                    .expect("the null backend accepts the demo description");
20300            place_cube(&mut renderer, Mat4::IDENTITY);
20301            let imported = swapchain_image(device);
20302            let mut pool = crate::TransientPool::new();
20303            renderer
20304                .begin_frame(
20305                    device,
20306                    &Camera::default(),
20307                    &DirectionalLight::default(),
20308                    (64, 48),
20309                )
20310                .expect("write");
20311            let mut graph = crate::RenderGraph::new(queue);
20312            let target = graph.import_image("target", imported);
20313            renderer.add_passes(&mut graph, &pool, target, (64, 48));
20314            let compiled = graph.compile(&pool).expect("a legal frame");
20315            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20316                label: Some("alpha mask lap"),
20317                queue,
20318            });
20319            compiled
20320                .execute(device, &mut pool, encoder.as_mut(), None)
20321                .expect("the graph executed");
20322            encoder.finish().expect("recording succeeded");
20323            let plain = renderer.shadow_pipeline.single;
20324            let cutout = renderer.depth_masked_pipeline.single;
20325            assert_ne!(
20326                plain, cutout,
20327                "the two depth pipelines have to be two objects, or nothing below discriminates"
20328            );
20329            // Which bucket a draw is, recovered from the argument offset it
20330            // names — the offsets are the renderer's own accessor, so a call
20331            // pointing at the wrong bucket has no entry here at all.
20332            let bucket_of = |args_offset: u64| -> u32 {
20333                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
20334                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
20335                    .unwrap_or_else(|| {
20336                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
20337                    })
20338            };
20339            // Per depth pass: the pipeline in force at each indirect call and
20340            // the bucket that call drew, in the order they were recorded.
20341            let pass_calls = |label: &str| -> Vec<(bool, u32)> {
20342                let mut current = None;
20343                let mut out = Vec::new();
20344                for command in commands_in_pass(&recorder, label) {
20345                    match command {
20346                        Command::BindGraphicsPipeline(handle) => current = Some(handle),
20347                        Command::DrawIndexedIndirectCount(draw) => {
20348                            let handle = current.expect("a draw follows a pipeline bind");
20349                            assert!(
20350                                handle == plain || handle == cutout,
20351                                "a depth pass drew under a pipeline that is neither depth one"
20352                            );
20353                            out.push((handle == cutout, bucket_of(draw.args_offset)));
20354                        }
20355                        _ => {}
20356                    }
20357                }
20358                out
20359            };
20360            let prepass = pass_calls("depth-prepass");
20361            let atlas = pass_calls("shadow");
20362            let binds: Vec<GraphicsPipelineHandle> = recorder
20363                .commands()
20364                .iter()
20365                .filter_map(|command| match command {
20366                    Command::BindGraphicsPipeline(handle) => Some(*handle),
20367                    _ => None,
20368                })
20369                .collect();
20370            let cutouts = binds.iter().filter(|handle| **handle == cutout).count();
20371            let plains = binds.iter().filter(|handle| **handle == plain).count();
20372            let mut folded: Vec<GraphicsPipelineHandle> = Vec::with_capacity(binds.len());
20373            for handle in binds {
20374                let handle = if handle == cutout { plain } else { handle };
20375                // The fold turns the masked frame's `plain, cutout` pair into
20376                // `plain, plain`; collapsing a run of equal binds is what makes
20377                // the two streams comparable without hiding a bind of anything
20378                // else, since no pass in either frame binds two *different*
20379                // pipelines that the fold could bring together.
20380                if folded.last() != Some(&handle) {
20381                    folded.push(handle);
20382                }
20383            }
20384            let modes = renderer.bucket_modes.clone();
20385            renderer.destroy(device);
20386            recorder.assert_valid();
20387            Recorded {
20388                modes,
20389                cutouts,
20390                plains,
20391                prepass,
20392                atlas,
20393                folded,
20394            }
20395        };
20396
20397        let opaque = bound(&crate::scene::demo());
20398        let masked = bound(&masked_scene);
20399
20400        assert_eq!(
20401            opaque.cutouts, 0,
20402            "a scene with nothing masked must never bind the cutout pipeline"
20403        );
20404        assert!(
20405            opaque.plains > 0,
20406            "a scene with nothing masked must bind the vertex-only pipeline, or the assertion \
20407             above is about a frame with no depth pass in it"
20408        );
20409        assert!(
20410            opaque.modes.iter().all(|mode| *mode == 0),
20411            "and every one of its buckets is opaque: {:?}",
20412            opaque.modes
20413        );
20414        assert_eq!(
20415            opaque.prepass.iter().filter(|(cutout, _)| *cutout).count(),
20416            0,
20417            "so no opaque draw is recorded under the cutout pipeline"
20418        );
20419
20420        assert!(
20421            masked.cutouts > 0 && masked.plains > 0,
20422            "a masked scene must bind **both** depth pipelines — {} cutout and {} plain — or \
20423             the choice is still per frame",
20424            masked.cutouts,
20425            masked.plains
20426        );
20427        // What each depth pass should have recorded: every opaque bucket under
20428        // the plain pipeline in bucket order, then every masked one under the
20429        // cutout, which is the partition order `depth_partitions` lays down.
20430        let want: Vec<(bool, u32)> = [false, true]
20431            .into_iter()
20432            .flat_map(|cutout| {
20433                masked
20434                    .modes
20435                    .iter()
20436                    .enumerate()
20437                    .filter(move |(_, mode)| {
20438                        (**mode == crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK) == cutout
20439                    })
20440                    .map(move |(bucket, _)| (cutout, u32::try_from(bucket).expect("a few buckets")))
20441            })
20442            .collect();
20443        assert!(
20444            want.iter().any(|(cutout, _)| *cutout) && want.iter().any(|(cutout, _)| !*cutout),
20445            "the masked demo has to hold buckets of both modes, or this compares one partition \
20446             against itself: {:?}",
20447            masked.modes
20448        );
20449        assert_eq!(
20450            masked.prepass, want,
20451            "the depth prepass must record each bucket once, under the pipeline its own mode \
20452             asked for"
20453        );
20454        // The atlas draws every bucket once per occupied view, and the
20455        // partition is **outside** the view loop — one pipeline bind covers
20456        // every view of that mode — so its stream is each partition's bucket
20457        // list repeated once per view.
20458        let views = masked.atlas.len() / want.len();
20459        assert!(
20460            views > 0 && masked.atlas.len() % want.len() == 0,
20461            "the shadow atlas recorded {} calls over {} buckets, which is not a whole number \
20462             of views",
20463            masked.atlas.len(),
20464            want.len()
20465        );
20466        let mut atlas_want: Vec<(bool, u32)> = Vec::with_capacity(masked.atlas.len());
20467        for cutout in [false, true] {
20468            let partition: Vec<(bool, u32)> = want
20469                .iter()
20470                .copied()
20471                .filter(|(mode, _)| *mode == cutout)
20472                .collect();
20473            for _ in 0..views {
20474                atlas_want.extend_from_slice(&partition);
20475            }
20476        }
20477        assert_eq!(
20478            masked.atlas, atlas_want,
20479            "and every shadow view draws both partitions, each under its own pipeline"
20480        );
20481
20482        assert_eq!(
20483            masked.folded, opaque.folded,
20484            "the frame gained or lost a pipeline bind beyond the cutout twin beside a plain one"
20485        );
20486    }
20487
20488    /// **A double-sided material moves every pass's draws for its own buckets
20489    /// onto the `CullMode::None` twins, and moves nothing else.**
20490    ///
20491    /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]'s
20492    /// claim for glTF's other mode, and it is wider by construction: an alpha
20493    /// mask is cut inside a fragment stage, so only the two depth-only passes
20494    /// route around it, while a cull mode is a pipeline state and **every** pass
20495    /// that draws the surface has to route around it — the colour pass, both
20496    /// depth passes and the two reflective shadow maps.
20497    ///
20498    /// So this walks the whole recorded stream rather than two named passes:
20499    /// every render pass that recorded an indirect draw is read back as the
20500    /// (side, bucket) pairs it recorded, and each of the four claims below is
20501    /// about all of them at once.
20502    ///
20503    /// * a scene with nothing double-sided binds **no** cull-none twin
20504    ///   anywhere, which is the "an all-single-sided frame costs what it always
20505    ///   did" claim at the level a null device can see it;
20506    /// * a scene with one double-sided row binds a twin in every pass that
20507    ///   draws — a frame that had only routed the colour pass would satisfy
20508    ///   nothing below, and one that had only routed the depth passes would
20509    ///   draw a surface the prepass wrote no depth for;
20510    /// * the calls following each bind are exactly that side's buckets, in
20511    ///   bucket order. A split that bound both pipelines and drew every bucket
20512    ///   under each would satisfy the claim above and double the frame's draws;
20513    /// * and folding each twin onto the pipeline it is a twin of — then
20514    ///   collapsing the runs of equal binds the fold creates — leaves the two
20515    ///   frames' bind streams **equal**, so nothing else in the frame moved.
20516    ///
20517    /// The two scenes differ in one flags word and nothing else.
20518    ///
20519    /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]: fn@a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline
20520    #[test]
20521    fn a_double_sided_material_moves_every_passs_draws_onto_the_cull_none_twins() {
20522        use crcbl_hal::null::Command;
20523
20524        // The occlusion blur count is a process-global console variable and a
20525        // frame binds one pipeline per blur — the masked test's hazard exactly.
20526        let _blurs = ssao_blur_switch();
20527
20528        // **A scene whose probes ask to be updated**, because the reflective
20529        // shadow maps are recorded by a volume rather than by an effect bit —
20530        // and they are two of the five passes this claim is about. The demo's
20531        // empty grid records neither, which would leave the widest half of the
20532        // routing unchecked.
20533        let scene_with_probes = || {
20534            let mut scene = crate::scene::demo();
20535            scene.capacities.probes = 1;
20536            scene.probes = crate::scene::ProbeGrid {
20537                volume: crcbl_shaders::probe::ProbeVolume {
20538                    origin: [0.0; 3],
20539                    inv_spacing: [1.0; 3],
20540                    counts: [1, 1, 1],
20541                    levels: 1,
20542                    steps: crcbl_shaders::probe::ProbeSteps::default(),
20543                },
20544                probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
20545                update: ProbeUpdate::EveryFrame,
20546            };
20547            scene
20548        };
20549        let single_scene = scene_with_probes();
20550        let double_scene = {
20551            let mut scene = scene_with_probes();
20552            scene.materials[DEMO_UNTINTED].flags = crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED;
20553            scene
20554        };
20555
20556        /// What one scene's frame reveals: each bucket's mode, how often a
20557        /// cull-none twin was bound at all, every drawing pass's (side, bucket)
20558        /// pairs in record order, and the whole bind stream with each twin
20559        /// folded onto the pipeline it twins.
20560        struct Recorded {
20561            modes: Vec<u32>,
20562            twins_bound: usize,
20563            passes: Vec<(String, Vec<(bool, u32)>)>,
20564            folded: Vec<GraphicsPipelineHandle>,
20565        }
20566
20567        // One frame each, from two renderers rather than two frames from one, on
20568        // the masked test's terms: a bucket table is fixed at build, and two
20569        // builds keep both frames a first frame.
20570        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20571            let (recorder, device, queue) = open();
20572            let device = device.as_ref();
20573            let mut renderer =
20574                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20575                    .expect("the null backend accepts the demo description");
20576            assert!(
20577                !renderer.emit.is_mesh(),
20578                "this preset built a mesh-shader path, whose draws carry no argument offset to \
20579                 recover a bucket from"
20580            );
20581            place_cube(&mut renderer, Mat4::IDENTITY);
20582            // **One shadowed spot**, so the punctual reflective shadow map has a
20583            // face to draw into: the pass is recorded on every frame but its
20584            // view loop is empty without one, and an empty loop records no draw
20585            // for the claim below to be about.
20586            renderer.set_lights(&[crate::Light::Spot(crate::SpotLight {
20587                position: Vec3::new(0.0, 2.0, 0.0),
20588                radius: 8.0,
20589                color: Vec3::splat(4.0),
20590                direction: Vec3::NEG_Y,
20591                inner_angle: 0.3,
20592                outer_angle: 0.6,
20593                fill: false,
20594            })]);
20595            let imported = swapchain_image(device);
20596            let mut pool = crate::TransientPool::new();
20597            renderer
20598                .begin_frame(
20599                    device,
20600                    &Camera::default(),
20601                    &DirectionalLight::default(),
20602                    (64, 48),
20603                )
20604                .expect("write");
20605            let mut graph = crate::RenderGraph::new(queue);
20606            let target = graph.import_image("target", imported);
20607            renderer.add_passes(&mut graph, &pool, target, (64, 48));
20608            let compiled = graph.compile(&pool).expect("a legal frame");
20609            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20610                label: Some("double sided lap"),
20611                queue,
20612            });
20613            compiled
20614                .execute(device, &mut pool, encoder.as_mut(), None)
20615                .expect("the graph executed");
20616            encoder.finish().expect("recording succeeded");
20617
20618            // Every twin and the pipeline it twins, so a bind can be reported as
20619            // a side and folded back. Asserted distinct, or nothing here
20620            // discriminates.
20621            let sided = [
20622                renderer.mesh_pipeline,
20623                renderer.shadow_pipeline,
20624                renderer.depth_masked_pipeline,
20625                renderer.rsm_pipeline,
20626            ];
20627            for pair in sided {
20628                assert_ne!(
20629                    pair.single, pair.double,
20630                    "a pipeline and its cull-none twin have to be two objects"
20631                );
20632            }
20633            let twin_of = |handle: GraphicsPipelineHandle| -> Option<GraphicsPipelineHandle> {
20634                sided
20635                    .iter()
20636                    .find(|pair| pair.double == handle)
20637                    .map(|pair| pair.single)
20638            };
20639            let bucket_of = |args_offset: u64| -> u32 {
20640                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
20641                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
20642                    .unwrap_or_else(|| {
20643                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
20644                    })
20645            };
20646
20647            let mut passes: Vec<(String, Vec<(bool, u32)>)> = Vec::new();
20648            let mut folded: Vec<GraphicsPipelineHandle> = Vec::new();
20649            let mut twins_bound = 0usize;
20650            let mut current: Option<GraphicsPipelineHandle> = None;
20651            let mut label: Option<String> = None;
20652            let mut calls: Vec<(bool, u32)> = Vec::new();
20653            let commands = recorder.commands();
20654            for command in &commands {
20655                match command {
20656                    Command::BeginRenderPass { label: name, .. } => {
20657                        label = name.clone();
20658                        calls = Vec::new();
20659                    }
20660                    Command::EndRenderPass => {
20661                        if !calls.is_empty() {
20662                            passes.push((
20663                                label.clone().expect("every pass here is labelled"),
20664                                std::mem::take(&mut calls),
20665                            ));
20666                        }
20667                    }
20668                    Command::BindGraphicsPipeline(handle) => {
20669                        current = Some(*handle);
20670                        if twin_of(*handle).is_some() {
20671                            twins_bound += 1;
20672                        }
20673                        // The fold turns a `single, double` pair into
20674                        // `single, single`; collapsing a run of equal binds is
20675                        // what makes the two streams comparable without hiding
20676                        // a bind of anything else.
20677                        let folded_handle = twin_of(*handle).unwrap_or(*handle);
20678                        if folded.last() != Some(&folded_handle) {
20679                            folded.push(folded_handle);
20680                        }
20681                    }
20682                    Command::DrawIndexedIndirectCount(draw) => {
20683                        let handle = current.expect("a draw follows a pipeline bind");
20684                        calls.push((twin_of(handle).is_some(), bucket_of(draw.args_offset)));
20685                    }
20686                    Command::DrawIndexedIndirect(draw) => {
20687                        let handle = current.expect("a draw follows a pipeline bind");
20688                        calls.push((twin_of(handle).is_some(), bucket_of(draw.offset)));
20689                    }
20690                    _ => {}
20691                }
20692            }
20693            let modes = renderer.bucket_modes.clone();
20694            renderer.destroy(device);
20695            pool.destroy(device);
20696            device.destroy_image_view(imported.view);
20697            device.destroy_image(imported.image);
20698            recorder.assert_valid();
20699            Recorded {
20700                modes,
20701                twins_bound,
20702                passes,
20703                folded,
20704            }
20705        };
20706
20707        let single = bound(&single_scene);
20708        let double = bound(&double_scene);
20709
20710        assert_eq!(
20711            single.twins_bound, 0,
20712            "a scene with nothing double-sided must never bind a cull-none twin"
20713        );
20714        // Named rather than counted, because the claim is that **every** pass
20715        // that draws the surface routes: a frame that had quietly stopped
20716        // recording one of them would satisfy a count and leave that pass's
20717        // routing unchecked for ever.
20718        let drawing: Vec<&str> = single
20719            .passes
20720            .iter()
20721            .map(|(name, _)| name.as_str())
20722            .collect();
20723        for pass in ["shadow", "depth-prepass", "forward", "rsm", "rsm-punctual"] {
20724            assert!(
20725                drawing.contains(&pass),
20726                "`{pass}` drew nothing in this frame, so its routing is unchecked: {drawing:?}"
20727            );
20728        }
20729        assert!(
20730            double.twins_bound > 0,
20731            "a double-sided scene must bind the cull-none twins"
20732        );
20733        assert_eq!(
20734            double
20735                .passes
20736                .iter()
20737                .map(|(name, _)| name)
20738                .collect::<Vec<_>>(),
20739            single
20740                .passes
20741                .iter()
20742                .map(|(name, _)| name)
20743                .collect::<Vec<_>>(),
20744            "the two frames must draw in the same passes, or they are not comparable"
20745        );
20746
20747        // What each drawing pass should have recorded: every single-sided bucket
20748        // under the plain pipeline in bucket order, then every double-sided one
20749        // under the twin — the partition order `sided_partitions` lays down —
20750        // repeated once per view for a pass that draws several.
20751        let want: Vec<(bool, u32)> = [false, true]
20752            .into_iter()
20753            .flat_map(|twin| {
20754                double
20755                    .modes
20756                    .iter()
20757                    .enumerate()
20758                    .filter(move |(_, mode)| {
20759                        (**mode & crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED != 0) == twin
20760                    })
20761                    .map(move |(bucket, _)| (twin, u32::try_from(bucket).expect("a few buckets")))
20762            })
20763            .collect();
20764        assert!(
20765            want.iter().any(|(twin, _)| *twin) && want.iter().any(|(twin, _)| !*twin),
20766            "the double-sided demo has to hold buckets of both sides, or this compares one \
20767             partition against itself: {:?}",
20768            double.modes
20769        );
20770        for (name, calls) in &double.passes {
20771            let views = calls.len() / want.len();
20772            assert!(
20773                views > 0 && calls.len() % want.len() == 0,
20774                "`{name}` recorded {} call(s) over {} bucket(s), which is not a whole number of \
20775                 views",
20776                calls.len(),
20777                want.len()
20778            );
20779            // The partition is **outside** any view loop — one pipeline bind
20780            // covers every view of that side — so the stream is each partition's
20781            // bucket list repeated once per view.
20782            let mut expected: Vec<(bool, u32)> = Vec::with_capacity(calls.len());
20783            for twin in [false, true] {
20784                let partition: Vec<(bool, u32)> = want
20785                    .iter()
20786                    .copied()
20787                    .filter(|(side, _)| *side == twin)
20788                    .collect();
20789                for _ in 0..views {
20790                    expected.extend_from_slice(&partition);
20791                }
20792            }
20793            assert_eq!(
20794                *calls, expected,
20795                "`{name}` must record each bucket once per view, under the pipeline its own \
20796                 side asked for"
20797            );
20798        }
20799
20800        assert_eq!(
20801            double.folded, single.folded,
20802            "the frame gained or lost a pipeline bind beyond a cull-none twin beside the \
20803             pipeline it twins"
20804        );
20805    }
20806
20807    /// **The wireframe view swaps the colour pass's pipeline and nothing else.**
20808    ///
20809    /// The mechanism, at the level a null device can observe it: which pipeline
20810    /// handle each pass of the recorded stream binds. A field on the renderer
20811    /// would say only that a flag moved — this says the *frame* moved, and says
20812    /// which part of it did.
20813    ///
20814    /// Four claims, and each rules out a different way of passing wrongly:
20815    ///
20816    /// * the filled pipeline is bound on a frame nobody asked, and the wireframe
20817    ///   one does not exist;
20818    /// * switching on **removes** the filled pipeline from the stream — a second
20819    ///   pipeline that was built and never bound would still leave it there;
20820    /// * every other pipeline the frame binds is unchanged, so the depth prepass
20821    ///   and the shadow cascades are still filling triangles;
20822    /// * and switching off puts the stream back exactly, so the view is a toggle
20823    ///   rather than a one-way door.
20824    #[test]
20825    fn the_wireframe_view_swaps_the_colour_passs_pipeline_and_no_other() {
20826        use crcbl_hal::null::Command;
20827
20828        // The pipelines a frame binds include one per occlusion blur, and the
20829        // blur count is a process-global console variable — so a concurrent
20830        // test holding `r_ssao_blur_passes` at two adds a bind to one of the
20831        // frames below and not to the others. It reddened this assertion on
20832        // 2026-08-31 under a workspace `cargo test`.
20833        let _blurs = ssao_blur_switch();
20834        let (recorder, device, queue) =
20835            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
20836        let device = device.as_ref();
20837        assert!(
20838            ForwardRenderer::supports_wireframe(device),
20839            "this test needs the line fill mode, and asked the device for it",
20840        );
20841        let mut renderer =
20842            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20843        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
20844        let imported = swapchain_image(device);
20845        let mut pool = crate::TransientPool::new();
20846
20847        // The pipelines one frame binds, in record order. Cumulative recorder,
20848        // so each call takes the tail its own frame added.
20849        let mut seen = 0usize;
20850        // A different sun each lap, so the shadow atlas is redrawn in every one
20851        // of them: the comparison below is "which pipelines did this frame
20852        // bind", and a lap that cached its atlas would bind the depth-only
20853        // pipeline one fewer time for a reason that has nothing to do with the
20854        // wireframe. See [`moving_sun`].
20855        let mut lap = 0u32;
20856        let mut pipelines_in_a_frame = |renderer: &mut ForwardRenderer, pool: &mut _| {
20857            lap += 1;
20858            renderer
20859                .begin_frame(device, &Camera::default(), &moving_sun(lap), (64, 48))
20860                .expect("write");
20861            let mut graph = crate::RenderGraph::new(queue);
20862            let target = graph.import_image("target", imported);
20863            renderer.add_passes(&mut graph, pool, target, (64, 48));
20864            let compiled = graph.compile(pool).expect("a legal frame");
20865            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20866                label: Some("wireframe lap"),
20867                queue,
20868            });
20869            compiled
20870                .execute(device, pool, encoder.as_mut(), None)
20871                .expect("the graph executed");
20872            encoder.finish().expect("recording succeeded");
20873            let commands = recorder.commands();
20874            let bound: Vec<GraphicsPipelineHandle> = commands[seen..]
20875                .iter()
20876                .filter_map(|command| match command {
20877                    Command::BindGraphicsPipeline(handle) => Some(*handle),
20878                    _ => None,
20879                })
20880                .collect();
20881            seen = commands.len();
20882            bound
20883        };
20884
20885        let filled = renderer.mesh_pipeline.single;
20886        let off = pipelines_in_a_frame(&mut renderer, &mut pool);
20887        assert!(
20888            off.contains(&filled),
20889            "a frame nobody asked has to bind the filled pipeline: {off:?}",
20890        );
20891        assert!(!renderer.wireframe());
20892        assert!(
20893            renderer.wireframe_pipeline.is_none(),
20894            "the wireframe pipeline must not be built until it is asked for",
20895        );
20896
20897        renderer
20898            .set_wireframe(device, true)
20899            .expect("a device with the line fill mode builds it");
20900        assert!(renderer.wireframe());
20901        let lines = renderer
20902            .wireframe_pipeline
20903            .expect("switching on is what builds it")
20904            .single;
20905        let on = pipelines_in_a_frame(&mut renderer, &mut pool);
20906        assert!(
20907            !on.contains(&filled),
20908            "the colour pass still bound the filled pipeline: {on:?}",
20909        );
20910        assert_eq!(
20911            on.iter().filter(|handle| **handle == lines).count(),
20912            1,
20913            "the wireframe pipeline has to be bound exactly once — by the colour pass: {on:?}",
20914        );
20915        let substituted: Vec<GraphicsPipelineHandle> = on
20916            .iter()
20917            .map(|handle| if *handle == lines { filled } else { *handle })
20918            .collect();
20919        assert_eq!(
20920            substituted, off,
20921            "the frame gained or lost a pipeline bind beyond the colour pass's: {on:?} against \
20922             {off:?}",
20923        );
20924
20925        renderer
20926            .set_wireframe(device, false)
20927            .expect("switching off builds nothing");
20928        assert!(!renderer.wireframe());
20929        assert_eq!(
20930            pipelines_in_a_frame(&mut renderer, &mut pool),
20931            off,
20932            "switching the view off has to put the filled pipeline back, not just stop reporting \
20933             it",
20934        );
20935
20936        renderer.destroy(device);
20937        pool.destroy(device);
20938        device.destroy_image_view(imported.view);
20939        device.destroy_image(imported.image);
20940        recorder.assert_valid();
20941    }
20942
20943    /// **The colour pass tests against the prepass's depth instead of clearing
20944    /// and rewriting it, so each pixel is shaded once** — and a wireframe frame
20945    /// does the opposite, because lines do not reproduce a filled prepass.
20946    ///
20947    /// Both halves have to hold together or the frame is wrong in one of two
20948    /// ways, so both are asserted here. The attachment alone read-only while the
20949    /// pipeline still wrote would be a pipeline writing to a read-only
20950    /// attachment; the pipeline alone on `GreaterOrEqual` against an attachment
20951    /// this pass had just *cleared* would reject every fragment and draw a black
20952    /// frame. Neither shows up as an error — the first is a validation message
20953    /// on one backend and undefined behaviour on the rest, the second is a
20954    /// picture — which is why the observable is read off the compiled graph and
20955    /// off the pipeline state rather than off a screenshot.
20956    #[test]
20957    fn the_colour_pass_shades_once_per_pixel_against_the_prepasss_depth() {
20958        let (recorder, device, queue) =
20959            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
20960        let device = device.as_ref();
20961        let mut renderer =
20962            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20963        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
20964        let imported = swapchain_image(device);
20965        let mut pool = crate::TransientPool::new();
20966
20967        // Each pass's depth attachment, off the graph's own dump: the label it
20968        // was declared under, and the `load`/`store`/`write` triple the backend
20969        // is handed. A pass with no depth attachment contributes nothing, which
20970        // is what makes the lookup below a search rather than an index.
20971        let depth_of = |renderer: &mut ForwardRenderer, pool: &mut _, label: &str| {
20972            renderer
20973                .begin_frame(
20974                    device,
20975                    &Camera::default(),
20976                    &DirectionalLight::default(),
20977                    (64, 48),
20978                )
20979                .expect("write");
20980            let mut graph = crate::RenderGraph::new(queue);
20981            let target = graph.import_image("target", imported);
20982            renderer.add_passes(&mut graph, pool, target, (64, 48));
20983            let dump = graph.compile(pool).expect("a legal frame").dump();
20984            let mut pass = String::new();
20985            let mut found = None;
20986            for line in dump.lines() {
20987                if let Some(rest) = line.split(" pass \"").nth(1) {
20988                    pass = rest.trim_end_matches('"').to_string();
20989                    if let Some((name, _)) = pass.split_once('"') {
20990                        pass = name.to_string();
20991                    }
20992                }
20993                if pass == label
20994                    && let Some(at) = line.find("depth load=")
20995                {
20996                    // Without the slot note the dump appends: which physical
20997                    // image the transient landed on is aliasing's business, not
20998                    // this assertion's.
20999                    let role = &line[at..];
21000                    let role = role.split_once(" [").map_or(role, |(head, _)| head);
21001                    found = Some(role.trim().to_string());
21002                }
21003            }
21004            found.unwrap_or_else(|| panic!("no depth attachment on `{label}`:\n{dump}"))
21005        };
21006
21007        assert_eq!(
21008            depth_of(&mut renderer, &mut pool, "depth-prepass"),
21009            "depth load=Clear store=Store write=yes",
21010            "the prepass is what puts the depth there, so it clears, writes and keeps it",
21011        );
21012        assert_eq!(
21013            depth_of(&mut renderer, &mut pool, "forward"),
21014            "depth load=Load store=Store write=no",
21015            "and the colour pass reads it: a clear here would throw away the prepass and \
21016             pay for the overdraw again, and a write would be a second pass writing the \
21017             same values",
21018        );
21019        assert_eq!(
21020            MeshModules::color_depth_stencil(PolygonMode::Fill),
21021            Some(DepthStencilState {
21022                format: Format::D32Float,
21023                depth_write: false,
21024                depth_compare: CompareOp::GreaterOrEqual,
21025                stencil: None,
21026                bias: DepthBias::default(),
21027            }),
21028            "and the pipeline agrees with the attachment: equality against the prepass, \
21029             reachable only through the `OrEqual` under reversed-Z",
21030        );
21031
21032        renderer
21033            .set_wireframe(device, true)
21034            .expect("this device was asked for the line fill mode");
21035        assert_eq!(
21036            depth_of(&mut renderer, &mut pool, "forward"),
21037            "depth load=Clear store=Store write=yes",
21038            "a wireframe frame keeps the old shape: `PolygonMode::Line` interpolates depth \
21039             along the edge rather than across the face, so testing it against a filled \
21040             prepass rejects most of the wireframe — and *loading* that depth under the \
21041             writing default's `Greater` would reject all of it",
21042        );
21043        assert_eq!(
21044            MeshModules::color_depth_stencil(PolygonMode::Line),
21045            MeshModules::depth_stencil(),
21046            "which is the writing default, the same state the depth-only twin uses",
21047        );
21048
21049        renderer.destroy(device);
21050        pool.destroy(device);
21051        device.destroy_image_view(imported.view);
21052        device.destroy_image(imported.image);
21053        recorder.assert_valid();
21054    }
21055
21056    /// **A device with no line fill mode is refused, not quietly filled.**
21057    ///
21058    /// The failure this rules out is the silent one: a caller who binds a key to
21059    /// this, presses it, and gets the solid frame back with nothing anywhere
21060    /// saying why — which on a model whose silhouette hides its interior is
21061    /// indistinguishable from a wireframe that worked. WebGPU is the real device
21062    /// this happens on; `open`'s null device stands in for it, because
21063    /// [`DeviceDesc::for_adapter`] asks for
21064    /// [`Features::GPU_DRIVEN`] and nothing else.
21065    #[test]
21066    fn a_device_without_the_line_fill_mode_refuses_the_wireframe_rather_than_filling_it() {
21067        let (recorder, device, queue) = open();
21068        let device = device.as_ref();
21069        assert!(
21070            !ForwardRenderer::supports_wireframe(device),
21071            "this device was not asked for the line fill mode, so it must not report it",
21072        );
21073        let mut renderer =
21074            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21075
21076        let refused = renderer
21077            .set_wireframe(device, true)
21078            .expect_err("a device without the feature has to say so");
21079        assert!(
21080            matches!(
21081                refused,
21082                HalError::UnsupportedFeatures { missing } if missing == Features::POLYGON_MODE_LINE
21083            ),
21084            "the refusal has to name the feature to go and look up, and is {refused:?}",
21085        );
21086        assert!(
21087            !renderer.wireframe(),
21088            "a refused request must leave the view off rather than half on",
21089        );
21090        assert!(
21091            renderer.wireframe_pipeline.is_none(),
21092            "nothing may be left behind by a refusal",
21093        );
21094        // And switching *off* is still fine on such a device: it builds nothing.
21095        renderer
21096            .set_wireframe(device, false)
21097            .expect("switching off asks the device for nothing");
21098
21099        renderer.destroy(device);
21100        recorder.assert_valid();
21101    }
21102
21103    /// The grid's own full-screen triangle is counted as submitted, and only
21104    /// while it is on.
21105    ///
21106    /// [`FrameCounters::instances`] is the "submitted" half of the debug panel's
21107    /// row, and every full-screen pass in the frame contributes one — so a grid
21108    /// that drew and was not counted makes that row disagree with the frame by
21109    /// exactly one triangle, silently.
21110    #[test]
21111    fn the_grids_triangle_is_counted_only_while_it_is_on() {
21112        let _blurs = ssao_blur_switch();
21113        let (recorder, device, queue) = open();
21114        let device = device.as_ref();
21115        let mut renderer =
21116            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21117        let imported = swapchain_image(device);
21118        let mut pool = crate::TransientPool::new();
21119
21120        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21121        let off = renderer.counters();
21122
21123        renderer
21124            .set_ground_grid(device, Some(GridStyle::default()))
21125            .expect("the null backend builds every pipeline");
21126        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21127        let on = renderer.counters();
21128
21129        assert_eq!(
21130            on.draws - off.draws,
21131            FULLSCREEN_DRAWS,
21132            "the grid records exactly one draw"
21133        );
21134        assert_eq!(
21135            on.instances - off.instances,
21136            FULLSCREEN_DRAWS,
21137            "and exactly one submitted instance"
21138        );
21139
21140        renderer.destroy(device);
21141        pool.destroy(device);
21142        device.destroy_image_view(imported.view);
21143        device.destroy_image(imported.image);
21144        recorder.assert_valid();
21145    }
21146
21147    /// One frame on a device of its own, under an override switching `off`.
21148    ///
21149    /// **A device of its own per arm**, because a [`Recorder`] accumulates for a
21150    /// device's whole life: asking "did the atlas pass draw" of a recorder that
21151    /// has seen two frames answers about both of them, and the arm that matters
21152    /// most here is the one whose answer must be zero.
21153    ///
21154    /// Returns what the frame reported and what its atlas pass actually drew.
21155    fn frame_switching_off(off: RenderEffects) -> (FrameCounters, u64, usize) {
21156        use crcbl_hal::null::Command;
21157
21158        let recorder = Recorder::new();
21159        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21160        let adapter = instance.adapters().remove(0);
21161        let opened = instance
21162            .create_device(&DeviceDesc::for_adapter(adapter.id))
21163            .expect("the null backend always opens");
21164        let device = opened.as_ref();
21165        let queue = opened.queue(QueueKind::Graphics).expect("always present");
21166        let mut renderer =
21167            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21168        // A shadowed light beside the cascades, so the atlas pass has draws to
21169        // lose rather than being empty either way.
21170        renderer.set_lights(&[shadowable_spot(-1.0)]);
21171        // **[`OUTSIDE_THE_DEFAULT`] forced on, then `off` forced off.** The default
21172        // camera stack leaves both of them out — see
21173        // [`RenderEffects::DEFAULT_STACK`] — so a control frame built on the
21174        // default alone would be measuring three effects and calling it five,
21175        // and their arms below would be switching off something already off.
21176        // `force` clears the other side, so an arm whose `off` is one of them
21177        // still resolves to off.
21178        renderer.set_effect_request(EffectRequest {
21179            programmatic: EffectOverride::none()
21180                .force(OUTSIDE_THE_DEFAULT, Some(true))
21181                .force(off, Some(false)),
21182            ..EffectRequest::default()
21183        });
21184
21185        let recorded = frame(device, &mut renderer, queue);
21186        assert_eq!(
21187            renderer.effects(),
21188            RenderEffects::all().difference(off),
21189            "the frame must have resolved to the set the request asked for"
21190        );
21191        let counters = renderer.counters();
21192        let instances = renderer.instances.len() as u64;
21193        let atlas_draws = commands_in_pass(&recorder, "shadow")
21194            .into_iter()
21195            .filter(|command| {
21196                matches!(
21197                    command,
21198                    Command::DrawIndexedIndirect(_)
21199                        | Command::DrawIndexedIndirectCount(_)
21200                        | Command::DrawMeshTasksIndirect(_)
21201                )
21202            })
21203            .count();
21204        assert_eq!(
21205            counters.draws,
21206            recorded_draws(&recorder) as u64,
21207            "the counter and the frame's own recorded stream must agree, whatever is switched off"
21208        );
21209        recorded.finish(device, renderer);
21210        recorder.assert_valid();
21211        (counters, instances, atlas_draws)
21212    }
21213
21214    /// **A switched-off effect is work the frame did not record**, and a frame
21215    /// that still executes with the placeholder bound in place of what it lost.
21216    ///
21217    /// The other half of the pass-list test above, and the half a pass list
21218    /// cannot make: the `shadow` pass is still *there* with shadows off, so the
21219    /// question is whether it drew. That answer comes off the recorded command
21220    /// stream, which is a different instrument from `recorded_draws` — the number
21221    /// under test.
21222    ///
21223    /// Executed rather than only compiled, because the occlusion switch changes
21224    /// which image the forward pass has bound. A frame that declared a read of a
21225    /// transient it never created, or bound a view the graph never realised,
21226    /// fails here and compiles perfectly.
21227    #[test]
21228    fn a_switched_off_effect_is_work_the_frame_did_not_record() {
21229        let _blurs = ssao_blur_switch();
21230        let (control, instances, atlas_draws) = frame_switching_off(RenderEffects::empty());
21231        assert!(
21232            atlas_draws > 0,
21233            "with shadows on the atlas pass has to draw something, or turning it off means \
21234             nothing"
21235        );
21236        assert_eq!(
21237            control.instances,
21238            instances
21239                + fullscreen_passes(
21240                    RenderEffects::all(),
21241                    TEST_EXTENT,
21242                    false,
21243                    crate::ssao::blur_passes(),
21244                ) * FULLSCREEN_DRAWS,
21245            "the control frame submits one triangle per full-screen pass"
21246        );
21247
21248        // Each pair is one full-screen triangle per pass, and the atlas is
21249        // untouched by either.
21250        for (off, fewer) in [
21251            (
21252                RenderEffects::AMBIENT_OCCLUSION,
21253                u64::from(Ssao::passes(crate::ssao::blur_passes())),
21254            ),
21255            // The contact march's one pass, and a constant rather than a
21256            // function of anything: it has no blur behind it and no chain.
21257            (
21258                RenderEffects::CONTACT_SHADOWS,
21259                u64::from(ContactShadows::PASSES),
21260            ),
21261            // The march's two passes and the reductions that feed them, which
21262            // is what makes this arm's number a function of the extent the way
21263            // the chain's below is.
21264            (
21265                RenderEffects::REFLECTIONS,
21266                u64::from(Ssr::PASSES) + u64::from(crate::hiz::levels_for(TEST_EXTENT)),
21267            ),
21268            // Not a constant, unlike the occlusion pair above: the chain's
21269            // length is a function of the extent, and this is what it is at
21270            // `TEST_EXTENT`.
21271            (
21272                RenderEffects::BLOOM,
21273                u64::from(Bloom::passes_for(TEST_EXTENT)),
21274            ),
21275        ] {
21276            let (counters, instances, atlas) = frame_switching_off(off);
21277            assert_eq!(
21278                counters.draws,
21279                control.draws - fewer * FULLSCREEN_DRAWS,
21280                "{off:?}: the frame must record one draw fewer per pass it did not add"
21281            );
21282            assert_eq!(
21283                counters.instances,
21284                instances
21285                    + fullscreen_passes(
21286                        RenderEffects::all().difference(off),
21287                        TEST_EXTENT,
21288                        false,
21289                        crate::ssao::blur_passes(),
21290                    ) * FULLSCREEN_DRAWS,
21291                "{off:?}: and must not report as submitted a triangle it never submitted"
21292            );
21293            assert_eq!(
21294                atlas, atlas_draws,
21295                "{off:?}: a screen-space effect must not touch the shadow atlas"
21296            );
21297        }
21298
21299        // Shadows: the atlas pass survives and draws nothing at all, which is
21300        // the mechanism — a cleared reversed-Z atlas reads as fully lit.
21301        let (counters, _, atlas) = frame_switching_off(RenderEffects::SHADOWS);
21302        assert_eq!(
21303            atlas, 0,
21304            "with shadows off the atlas pass must record its clear and no draw"
21305        );
21306        assert_eq!(
21307            counters.draws,
21308            control.draws - atlas_draws as u64,
21309            "and the frame must record exactly the atlas pass's draws fewer"
21310        );
21311    }
21312
21313    /// **Every pass the frame records gets a row in the report, except the ones
21314    /// that open no scope.**
21315    ///
21316    /// The observable the bound exists for: the samples' hand-picked capacity
21317    /// timed the first eight passes of a fourteen-pass frame and reported eight
21318    /// rows, which reads exactly like a frame that has eight passes. Sized from
21319    /// [`MAX_TIMED_PASSES`](crate::MAX_TIMED_PASSES), the report names every
21320    /// pass the graph compiled, in order — so a bound one short of the frame
21321    /// makes this list short too.
21322    ///
21323    /// A [`PassKind::Copy`](crate::graph::PassKind::Copy) is filtered out of the
21324    /// expectation rather than expected to be missing by accident. The seam
21325    /// takes a timestamp only where a pass opens and closes and a copy opens
21326    /// nothing, so `PassTimers` gives it no query pair and no row — a row
21327    /// reading 0.000 ms would be a measurement nobody made.
21328    #[test]
21329    fn every_pass_of_the_frame_gets_a_timing_row() {
21330        let _blurs = ssao_blur_switch();
21331        // And the comparison seam, so the frame this checks carries the
21332        // occlusion chain's second march: `docs/plan/ROADMAP.md`'s S4D row asks
21333        // for a *per-technique* cost, and what makes that true is this test's
21334        // own claim — every pass that opens a scope gets a row — applied to a
21335        // frame that compares. See `crate::ssao`'s `r_ssao_split`.
21336        let split = ssao_split_switch();
21337        split.set(0.5);
21338        let recorder = Recorder::new();
21339        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21340        let adapter = instance.adapters().remove(0);
21341        // `TIMESTAMP_QUERY` is not part of `GPU_DRIVEN` — topic 10's browsers
21342        // may lack it — so a device that wants timers has to ask for it, and
21343        // `open` above, which uses `DeviceDesc::for_adapter`, does not.
21344        let opened = instance
21345            .create_device(&DeviceDesc {
21346                label: Some("timed frame"),
21347                adapter: adapter.id,
21348                required_features: Features::GPU_DRIVEN,
21349                optional_features: Features::TIMESTAMP_QUERY,
21350                compatible_surface: None,
21351            })
21352            .expect("the null backend always opens");
21353        let queue = opened.queue(QueueKind::Graphics).expect("always present");
21354        let device = opened.as_ref();
21355        let mut renderer =
21356            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21357        renderer.set_lights(&[shadowable_spot(-1.0), shadowable_spot(1.0)]);
21358        let mut timers = crate::PassTimers::new(device, FRAMES_IN_FLIGHT, crate::MAX_TIMED_PASSES)
21359            .expect("the tier A null adapter has timestamp queries");
21360        let imported = swapchain_image(device);
21361        let mut pool = crate::TransientPool::new();
21362        let mut recorded = Vec::new();
21363        let mut compiled_labels = Vec::new();
21364
21365        // The ring is one slot longer than the frames in flight and resolves a
21366        // slot only when it comes round again, so the first frame's report is
21367        // that many frames behind it — see the [`timing`](crate::timing) docs.
21368        for _ in 0..FRAMES_IN_FLIGHT + 2 {
21369            renderer
21370                .begin_frame(
21371                    device,
21372                    &Camera::default(),
21373                    &DirectionalLight::default(),
21374                    (64, 48),
21375                )
21376                .expect("write");
21377            let mut graph = crate::RenderGraph::new(queue);
21378            let target = graph.import_image("target", imported);
21379            renderer.add_passes(&mut graph, &pool, target, (64, 48));
21380            let compiled = graph.compile(&pool).expect("a legal frame");
21381            if compiled_labels.is_empty() {
21382                compiled_labels = compiled
21383                    .passes()
21384                    .iter()
21385                    .filter(|pass| pass.kind() != crate::graph::PassKind::Copy)
21386                    .map(|pass| pass.label().to_string())
21387                    .collect();
21388            }
21389            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21390                label: Some("timed frame"),
21391                queue,
21392            });
21393            compiled
21394                .execute(device, &mut pool, encoder.as_mut(), Some(&mut timers))
21395                .expect("the graph executed");
21396            recorded.push(encoder.finish().expect("recording succeeded"));
21397        }
21398
21399        let reported: Vec<&str> = timers
21400            .latest()
21401            .passes
21402            .iter()
21403            .map(|timing| timing.label.as_str())
21404            .collect();
21405        // Anti-vacuity for the seam held above: a frame that did not compare
21406        // would satisfy the equality below and say nothing about a
21407        // per-technique cost, because there would be one technique in it.
21408        for label in ["ssao", "ssao-shipped"] {
21409            assert!(
21410                compiled_labels.iter().any(|pass| pass == label),
21411                "the frame compiled no `{label}` pass, so the seam did not reach it and this \
21412                 test says nothing about a comparison having a cost per side. Its passes: \
21413                 {compiled_labels:?}"
21414            );
21415        }
21416        assert_eq!(
21417            reported,
21418            compiled_labels,
21419            "the report must name every pass the frame compiled that opens a scope, in order \
21420             — {} of {} timed with a capacity of {}",
21421            reported.len(),
21422            compiled_labels.len(),
21423            timers.capacity()
21424        );
21425
21426        timers.destroy(device);
21427        renderer.destroy(device);
21428        for commands in recorded {
21429            device.destroy_command_buffer(commands);
21430        }
21431        pool.destroy(device);
21432        device.destroy_image_view(imported.view);
21433        device.destroy_image(imported.image);
21434        recorder.assert_valid();
21435    }
21436
21437    /// One mesh-table entry, decoded from the bytes that reached the device.
21438    fn mesh_entry(
21439        recorder: &Recorder,
21440        renderer: &ForwardRenderer,
21441        id: u32,
21442    ) -> crcbl_shaders::mesh::GpuMesh {
21443        let table = recorder
21444            .buffer_bytes(renderer.pool.table_buffer())
21445            .expect("the table is live");
21446        let at = id as usize * crcbl_shaders::mesh::MESH_ENTRY_STRIDE;
21447        crcbl_shaders::mesh::GpuMesh::from_bytes(
21448            table[at..at + crcbl_shaders::mesh::MESH_ENTRY_STRIDE]
21449                .try_into()
21450                .expect("one whole entry"),
21451        )
21452    }
21453
21454    // --- skinning: the seam a caller draws a skinned mesh through -----------
21455
21456    /// A renderer with [`scene::demo`]'s cube reserved for skinning, and a
21457    /// [`Skinning`] built against that renderer's own vertex pool.
21458    struct SkinnedFixture {
21459        renderer: ForwardRenderer,
21460        skinning: Skinning,
21461        skinned: SkinnedMesh,
21462        palette: Vec<Mat4>,
21463        bindings: Vec<crcbl_shaders::skinning::SkinBinding>,
21464    }
21465
21466    impl SkinnedFixture {
21467        fn build(device: &dyn Device, queue: QueueHandle) -> Self {
21468            let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
21469                .expect("the null backend accepts every descriptor");
21470            let skinned = renderer
21471                .reserve_skinned(DEMO_CUBE)
21472                .expect("a default pool has room for two halves of a cube");
21473            let skinning = Skinning::new(
21474                device,
21475                &crate::skinning::SkinningDesc {
21476                    label: Some("skinned fixture"),
21477                    frames: FRAMES_IN_FLIGHT,
21478                    ranges: 1,
21479                    joints: 1,
21480                    bindings: skinned.vertex_count(),
21481                    // The renderer's own pool, which is the whole of what makes
21482                    // the dispatch's output reachable by its draws.
21483                    vertices: renderer.vertex_buffer(),
21484                    attribute_base: renderer.attribute_base(),
21485                },
21486            )
21487            .expect("the null backend accepts every descriptor");
21488            let bindings = vec![
21489                crcbl_shaders::skinning::SkinBinding {
21490                    joints: [0; crcbl_shaders::skinning::JOINTS_PER_VERTEX],
21491                    weights: [1.0, 0.0, 0.0, 0.0],
21492                };
21493                skinned.vertex_count() as usize
21494            ];
21495            Self {
21496                renderer,
21497                skinning,
21498                skinned,
21499                palette: vec![Mat4::IDENTITY],
21500                bindings,
21501            }
21502        }
21503
21504        /// One skinned frame's `begin_skinned_frame`, with this fixture's single
21505        /// range.
21506        fn begin(&mut self, device: &dyn Device) {
21507            let range = self.skinned.skin_range(&self.palette, &self.bindings);
21508            self.renderer
21509                .begin_skinned_frame(
21510                    device,
21511                    &mut self.skinning,
21512                    &[range],
21513                    &Camera::default(),
21514                    &DirectionalLight::default(),
21515                    TEST_EXTENT,
21516                )
21517                .expect("a legal skinning plan");
21518        }
21519
21520        fn destroy(mut self, device: &dyn Device) {
21521            self.renderer.release_skinned(self.skinned);
21522            self.skinning.destroy(device);
21523            self.renderer.destroy(device);
21524        }
21525    }
21526
21527    /// How many times the host wrote the mesh-table entry `id` names.
21528    fn table_writes(recorder: &Recorder, renderer: &ForwardRenderer, id: u32) -> usize {
21529        let table = renderer.pool.table_buffer();
21530        let at = u64::from(id) * crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u64;
21531        recorder
21532            .events()
21533            .into_iter()
21534            .filter(|event| {
21535                matches!(
21536                    event,
21537                    crcbl_hal::null::Event::BufferWritten { buffer, offset, .. }
21538                        if *buffer == table && *offset == at
21539                )
21540            })
21541            .count()
21542    }
21543
21544    /// The record `handle` names, out of the ring buffer **this frame draws
21545    /// from** rather than out of the pool's host mirror.
21546    ///
21547    /// A mirror and a buffer that disagree is exactly the defect a re-pointing
21548    /// design can have, so every claim about a skinned instance's bases is read
21549    /// off the bytes a shader would.
21550    fn instance_record(
21551        recorder: &Recorder,
21552        renderer: &ForwardRenderer,
21553        handle: InstanceHandle,
21554    ) -> mesh::GpuInstance {
21555        let buffer = renderer.instances.buffers()[renderer.frame()];
21556        let bytes = recorder.buffer_bytes(buffer).expect("the ring is live");
21557        let index = renderer
21558            .instances
21559            .index(handle)
21560            .expect("the object is live") as usize;
21561        let at = index * mesh::INSTANCE_STRIDE;
21562        mesh::GpuInstance::from_bytes(
21563            bytes[at..at + mesh::INSTANCE_STRIDE]
21564                .try_into()
21565                .expect("one whole instance"),
21566        )
21567    }
21568
21569    /// **A skinned primitive takes no mesh-table entry of its own, and nothing
21570    /// rewrites the one it draws through.**
21571    ///
21572    /// [`crate::mesh_pool`]'s table is one host-visible buffer rather than a ring
21573    /// precisely because nothing rewrites an entry between frames, so a design
21574    /// that re-pointed an entry at the half a frame writes would be wrong only
21575    /// on the frames that overlap — which is to say invisibly. What alternates
21576    /// instead is a field of the *instance*, and instances go through a ring.
21577    ///
21578    /// So a skinned object draws through the source mesh's own entry: the same
21579    /// id [`add_instance`](ForwardRenderer::add_instance) would give it, still
21580    /// carrying the bind pose's base vertex, still written exactly once after
21581    /// four skinned frames. That shared entry is also what lets one mesh be
21582    /// drawn skinned and unskinned in the same frame.
21583    #[test]
21584    fn a_skinned_mesh_takes_no_table_entry_and_rewrites_none() {
21585        let (recorder, device, queue) = open();
21586        let device = device.as_ref();
21587        let mut fixture = SkinnedFixture::build(device, queue);
21588
21589        let bind_pose_id = fixture.renderer.mesh_ids[DEMO_CUBE];
21590        assert_eq!(
21591            fixture.skinned.mesh_id(),
21592            bind_pose_id,
21593            "a skinned instance names the mesh it was deformed from, so the bucket, the level \
21594             tables and the bounding box all resolve as the bind pose's"
21595        );
21596
21597        let bind_pose = mesh_entry(&recorder, &fixture.renderer, bind_pose_id);
21598        assert_eq!(
21599            bind_pose.base_vertex,
21600            fixture.skinned.input_base(),
21601            "the entry goes on naming the bind pose the dispatch reads, not either half it \
21602             writes"
21603        );
21604        for parity in 0..2 {
21605            assert_ne!(
21606                fixture.skinned.region().base(parity),
21607                bind_pose.base_vertex,
21608                "half {parity} must not be the bind pose, which the kernel reads while it \
21609                 writes them"
21610            );
21611        }
21612        assert_ne!(
21613            fixture.skinned.region().base(0),
21614            fixture.skinned.region().base(1),
21615            "the two halves are separate reservations, or the ping-pong is one buffer"
21616        );
21617
21618        // Counted before the frames rather than compared against a literal:
21619        // `MeshPool::new` clears the whole table with one write at offset zero,
21620        // which lands on this entry too, so the number here is the pool's
21621        // start-up and not this test's business. What the loop below has to
21622        // leave alone is whatever it is.
21623        let writes_before = table_writes(&recorder, &fixture.renderer, bind_pose_id);
21624        assert!(
21625            writes_before > 0,
21626            "the entry was written at least once before any frame ran, or the counter below \
21627             is counting nothing and the comparison after the frames is vacuous"
21628        );
21629
21630        // Four frames, which is two of each parity: enough that a design
21631        // rewriting an entry per frame would have written four more times.
21632        let imported = swapchain_image_at(device, TEST_EXTENT);
21633        let mut pool = crate::TransientPool::new();
21634        for _ in 0..4 {
21635            fixture.begin(device);
21636            let mut graph = crate::RenderGraph::new(queue);
21637            let target = graph.import_image("target", imported);
21638            fixture.renderer.add_skinned_passes(
21639                &mut graph,
21640                &pool,
21641                target,
21642                TEST_EXTENT,
21643                &fixture.skinning,
21644            );
21645            graph.compile(&pool).expect("a legal frame");
21646        }
21647
21648        assert_eq!(
21649            table_writes(&recorder, &fixture.renderer, bind_pose_id),
21650            writes_before,
21651            "entry {bind_pose_id} was written again by a skinned frame; the whole reason this \
21652             table is one buffer rather than a ring is that nothing rewrites an entry between \
21653             frames"
21654        );
21655
21656        fixture.destroy(device);
21657        pool.destroy(device);
21658        device.destroy_image_view(imported.view);
21659        device.destroy_image(imported.image);
21660        recorder.assert_valid();
21661    }
21662
21663    /// **A skinned object's recorded base vertex follows the parity of the frame
21664    /// it is drawn in**, and it carries the bit that makes a shader read it.
21665    ///
21666    /// The other half of the design: the table entry never moves, so what has to
21667    /// alternate is a field of the *instance* — and it has to alternate in the
21668    /// buffer the frame actually draws from, which is why this reads the
21669    /// instance ring's bytes rather than the host's mirror.
21670    ///
21671    /// Three claims, and the last two are what stop the first being vacuous. The
21672    /// base must be the one this frame's parity names; the record must carry
21673    /// [`GpuInstance::BASE_VERTEX_OVERRIDE`](mesh::GpuInstance::BASE_VERTEX_OVERRIDE),
21674    /// without which the raster stages read the mesh entry and the field is
21675    /// decoration; and two consecutive frames must have named **different**
21676    /// halves, without which a renderer ignoring the parity entirely would pass.
21677    #[test]
21678    fn a_skinned_draw_carries_the_base_the_frames_dispatch_filled() {
21679        let (recorder, device, queue) = open();
21680        let device = device.as_ref();
21681        let mut fixture = SkinnedFixture::build(device, queue);
21682        let handle = fixture
21683            .renderer
21684            .add_skinned_instance(&SkinnedInstanceDesc {
21685                mesh: &fixture.skinned,
21686                material: DEMO_UNTINTED,
21687                transform: Mat4::IDENTITY,
21688            })
21689            .expect("a pool of thousands has room for one object");
21690
21691        let mut carried = Vec::new();
21692        for _ in 0..2 {
21693            fixture.begin(device);
21694            let parity = fixture.skinning.parity();
21695            let instance = instance_record(&recorder, &fixture.renderer, handle);
21696            assert_eq!(
21697                instance.base_vertex,
21698                fixture.skinned.region().base(parity),
21699                "the buffer this frame draws from must carry the base parity {parity} writes"
21700            );
21701            assert_eq!(
21702                instance.flags & mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
21703                mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
21704                "without the bit the raster stages resolve the mesh entry's base and this \
21705                 field is never read"
21706            );
21707            assert_eq!(
21708                instance.mesh, fixture.renderer.mesh_ids[DEMO_CUBE],
21709                "and the record still names the source mesh, which is what its bucket, its \
21710                 levels and its bounding box resolve through"
21711            );
21712            carried.push(instance.base_vertex);
21713        }
21714        assert_ne!(
21715            carried[0], carried[1],
21716            "two consecutive frames must have drawn different halves, or a renderer that \
21717             ignored the parity entirely would pass this"
21718        );
21719
21720        fixture.destroy(device);
21721        recorder.assert_valid();
21722    }
21723
21724    /// **A skinned object's record names the half the frame before it filled**,
21725    /// and it starts at rest.
21726    ///
21727    /// The other half of a skinned motion vector. The base above is where a
21728    /// fragment *is*; this is where it *was*, and without it the geometry stages
21729    /// put the previous transform through this frame's deformed vertex — so a
21730    /// limb that swung reports the motion of the body it hangs off. See
21731    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
21732    ///
21733    /// Four claims, and the first and last are what stop the middle two being a
21734    /// restatement of the parity:
21735    ///
21736    /// * the **first** frame of a fresh object writes the base it draws out of,
21737    ///   because the other half holds whatever its reservation came with and a
21738    ///   motion vector against undefined vertices is worse than no motion;
21739    /// * the frames after it write
21740    ///   [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base),
21741    ///   which must also **differ** from the base they draw out of — a renderer
21742    ///   that wrote the current base into both lanes would satisfy every "it is
21743    ///   a legal base" reading of this and leave every skinned instance at rest;
21744    /// * and moving the object onto a **different region** puts it back at rest
21745    ///   for one frame, because the halves it now names are two runs it has
21746    ///   never been drawn out of.
21747    #[test]
21748    fn a_skinned_draw_carries_the_previous_half_and_starts_at_rest() {
21749        let (recorder, device, queue) = open();
21750        let device = device.as_ref();
21751        let mut fixture = SkinnedFixture::build(device, queue);
21752        let handle = fixture
21753            .renderer
21754            .add_skinned_instance(&SkinnedInstanceDesc {
21755                mesh: &fixture.skinned,
21756                material: DEMO_UNTINTED,
21757                transform: Mat4::IDENTITY,
21758            })
21759            .expect("a pool of thousands has room for one object");
21760
21761        for frame in 1..=3u32 {
21762            fixture.begin(device);
21763            let parity = fixture.skinning.parity();
21764            let instance = instance_record(&recorder, &fixture.renderer, handle);
21765            assert_eq!(
21766                instance.base_vertex,
21767                fixture.skinned.region().base(parity),
21768                "frame {frame} must draw out of the half parity {parity} fills"
21769            );
21770            if frame == 1 {
21771                assert_eq!(
21772                    instance.previous_base_vertex, instance.base_vertex,
21773                    "a fresh object has no previous deformation, so its first frame owes rest \
21774                     rather than a half no dispatch has written"
21775                );
21776            } else {
21777                assert_eq!(
21778                    instance.previous_base_vertex,
21779                    fixture.skinned.region().previous_base(parity),
21780                    "frame {frame} must subtract against the half the frame before it filled"
21781                );
21782                assert_ne!(
21783                    instance.previous_base_vertex, instance.base_vertex,
21784                    "frame {frame} named one half twice, which is every skinned fragment at \
21785                     rest however far its surface moved"
21786                );
21787            }
21788        }
21789
21790        // The same object, moved onto a region it has never been drawn out of:
21791        // both halves are runs no dispatch of this object's has filled, so the
21792        // rule that put the first frame at rest applies again.
21793        let second = fixture
21794            .renderer
21795            .reserve_skinned(DEMO_CUBE)
21796            .expect("a default pool has room for two more halves of a cube");
21797        assert_ne!(
21798            second.region().base(0),
21799            fixture.skinned.region().base(0),
21800            "the second reservation is the same two runs as the first, so nothing below is \
21801             about a change of region at all"
21802        );
21803        fixture.renderer.set_skinned_instance(
21804            handle,
21805            &SkinnedInstanceDesc {
21806                mesh: &second,
21807                material: DEMO_UNTINTED,
21808                transform: Mat4::IDENTITY,
21809            },
21810        );
21811
21812        for frame in 1..=2u32 {
21813            fixture.begin(device);
21814            let parity = fixture.skinning.parity();
21815            let instance = instance_record(&recorder, &fixture.renderer, handle);
21816            assert_eq!(
21817                instance.base_vertex,
21818                second.region().base(parity),
21819                "frame {frame} after the move must draw out of the new region"
21820            );
21821            if frame == 1 {
21822                assert_eq!(
21823                    instance.previous_base_vertex, instance.base_vertex,
21824                    "the first frame on a new region owes rest, exactly as a fresh object does"
21825                );
21826            } else {
21827                assert_eq!(
21828                    instance.previous_base_vertex,
21829                    second.region().previous_base(parity),
21830                    "and the frame after it is subtracting against the new region's other half"
21831                );
21832            }
21833        }
21834
21835        fixture.renderer.release_skinned(second);
21836        fixture.destroy(device);
21837        recorder.assert_valid();
21838    }
21839
21840    /// **A skinned object that moves carries the transform it moved from**, and
21841    /// the frame after it is back at rest.
21842    ///
21843    /// The transform half of a skinned motion vector, and the half the
21844    /// per-frame re-point used to erase: it rewrote the record through
21845    /// [`InstancePool::set`], which fills the previous transform out of the
21846    /// record it overwrites — and that record already held this frame's
21847    /// transform, because
21848    /// [`set_skinned_instance`](ForwardRenderer::set_skinned_instance) had put
21849    /// it there. Every skinned instance then read `previous_transform ==
21850    /// transform` on every frame, so a character that walked contributed
21851    /// nothing to the motion target from the walk, only from its deformation.
21852    /// [`InstancePool::set_bases`] is what the re-point goes through instead.
21853    ///
21854    /// Both frames are the claim. Without the second, a re-point that wrote
21855    /// some *other* stale transform into the field would pass; and the second
21856    /// is the pool's own rest rule reaching a skinned object at all, which a
21857    /// re-point that kept enrolling the element every frame would suppress
21858    /// for ever.
21859    ///
21860    /// Read out of the ring buffer the frame draws from, on
21861    /// [`instance_record`]'s terms.
21862    #[test]
21863    fn a_skinned_instance_that_moves_carries_the_transform_it_moved_from() {
21864        let (recorder, device, queue) = open();
21865        let device = device.as_ref();
21866        let mut fixture = SkinnedFixture::build(device, queue);
21867        let handle = fixture
21868            .renderer
21869            .add_skinned_instance(&SkinnedInstanceDesc {
21870                mesh: &fixture.skinned,
21871                material: DEMO_UNTINTED,
21872                transform: Mat4::IDENTITY,
21873            })
21874            .expect("a pool of thousands has room for one object");
21875
21876        // Two frames standing still, so the history the move is measured
21877        // against is a settled record rather than a fresh one.
21878        fixture.begin(device);
21879        fixture.begin(device);
21880
21881        let moved = Mat4::from_translation(Vec3::new(5.0, 0.0, 0.0));
21882        fixture.renderer.set_skinned_instance(
21883            handle,
21884            &SkinnedInstanceDesc {
21885                mesh: &fixture.skinned,
21886                material: DEMO_UNTINTED,
21887                transform: moved,
21888            },
21889        );
21890        fixture.begin(device);
21891        let instance = instance_record(&recorder, &fixture.renderer, handle);
21892        assert_eq!(
21893            instance.transform,
21894            moved.to_cols_array(),
21895            "the frame that moved the object must draw it where it arrived"
21896        );
21897        assert_eq!(
21898            instance.previous_transform,
21899            Mat4::IDENTITY.to_cols_array(),
21900            "and it must say where from — a previous transform equal to the current one is \
21901             the re-point having overwritten the move"
21902        );
21903
21904        fixture.begin(device);
21905        let settled = instance_record(&recorder, &fixture.renderer, handle);
21906        assert_eq!(
21907            settled.transform,
21908            moved.to_cols_array(),
21909            "nothing moved it again"
21910        );
21911        assert_eq!(
21912            settled.previous_transform, settled.transform,
21913            "so the frame after the move owes rest; a re-point that enrolled the element \
21914             every frame would keep it reporting the move for ever"
21915        );
21916
21917        fixture.destroy(device);
21918        recorder.assert_valid();
21919    }
21920
21921    /// **The graph barriers the skinning dispatch's write before every pass that
21922    /// pulls vertices**, and it does so because `add_skinned_passes` added the
21923    /// dispatch itself rather than trusting a caller to.
21924    ///
21925    /// Pass order alone would not settle it — a dispatch that ran first and was
21926    /// never barriered is the exact defect, and it produces a correct-looking
21927    /// frame on a desktop driver. So the transition out of
21928    /// [`ResourceState::ShaderReadWrite`] is named: there must be exactly one,
21929    /// it must sit after the dispatch, and it must sit at or before the first of
21930    /// the three passes that draw.
21931    #[test]
21932    fn the_skinning_dispatch_is_barriered_before_every_pass_that_draws() {
21933        let (recorder, device, queue) = open();
21934        let device = device.as_ref();
21935        let mut fixture = SkinnedFixture::build(device, queue);
21936        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
21937        fixture
21938            .renderer
21939            .add_skinned_instance(&SkinnedInstanceDesc {
21940                mesh: &fixture.skinned,
21941                material: DEMO_UNTINTED,
21942                transform: Mat4::IDENTITY,
21943            })
21944            .expect("room for one object");
21945        fixture.begin(device);
21946
21947        let imported = swapchain_image_at(device, TEST_EXTENT);
21948        let mut pool = crate::TransientPool::new();
21949        let mut graph = crate::RenderGraph::new(queue);
21950        let target = graph.import_image("target", imported);
21951        // The same node `Skinning::add_pass` imports — one handle is one node —
21952        // so the barriers below can be named rather than guessed at.
21953        let vertices = graph.import_buffer(
21954            "vertex-pool",
21955            ImportedBuffer {
21956                buffer: fixture.renderer.vertex_buffer(),
21957                initial: ResourceState::ShaderRead,
21958                final_state: ResourceState::ShaderRead,
21959            },
21960        );
21961        fixture.renderer.add_skinned_passes(
21962            &mut graph,
21963            &pool,
21964            target,
21965            TEST_EXTENT,
21966            &fixture.skinning,
21967        );
21968        let compiled = graph.compile(&pool).expect("a legal frame");
21969        let labels: Vec<&str> = compiled
21970            .passes()
21971            .iter()
21972            .map(crate::graph::CompiledPass::label)
21973            .collect();
21974
21975        let dispatch = labels
21976            .iter()
21977            .position(|label| *label == "skinning")
21978            .expect("add_skinned_passes adds the dispatch itself");
21979        let drawing: Vec<usize> = ["shadow", "depth-prepass", "forward"]
21980            .into_iter()
21981            .map(|wanted| {
21982                labels
21983                    .iter()
21984                    .position(|label| *label == wanted)
21985                    .unwrap_or_else(|| panic!("the frame draws through {wanted}: {labels:?}"))
21986            })
21987            .collect();
21988        for (label, at) in ["shadow", "depth-prepass", "forward"]
21989            .into_iter()
21990            .zip(&drawing)
21991        {
21992            assert!(
21993                dispatch < *at,
21994                "the dispatch is at {dispatch} and {label} at {at}: {labels:?}"
21995            );
21996        }
21997
21998        // Each drawing pass declares the read for itself, and this is asserted
21999        // per pass rather than left to the single barrier below. The graph
22000        // transitions the region once, before the first reader, and a later
22001        // pass that never declared the read finds it already in the state it
22002        // wanted — so dropping the declaration from `forward` alone changes no
22003        // barrier and moves no label, and every assertion in this test still
22004        // passes. What it does drop is that pass's *dependency* on the
22005        // dispatch, which is the only thing keeping the two in this order.
22006        for (label, at) in ["shadow", "depth-prepass", "forward"]
22007            .into_iter()
22008            .zip(&drawing)
22009        {
22010            assert!(
22011                compiled.passes()[*at].reads_buffer(vertices),
22012                "{label} draws skinned vertices and must declare that it reads them, or \
22013                 nothing but declaration order keeps it after the dispatch"
22014            );
22015        }
22016
22017        let released: Vec<usize> = compiled
22018            .passes()
22019            .iter()
22020            .enumerate()
22021            .filter(|(_, pass)| {
22022                pass.barriers().buffers.iter().any(|barrier| {
22023                    barrier.buffer == vertices
22024                        && barrier.from == ResourceState::ShaderReadWrite
22025                        && barrier.to == ResourceState::ShaderRead
22026                })
22027            })
22028            .map(|(at, _)| at)
22029            .collect();
22030        assert_eq!(
22031            released.len(),
22032            1,
22033            "exactly one transition out of the dispatch's write: {released:?} in {labels:?}"
22034        );
22035        let barrier = released[0];
22036        let first_draw = *drawing.iter().min().expect("three passes");
22037        assert!(
22038            dispatch < barrier && barrier <= first_draw,
22039            "the barrier is at {barrier}, the dispatch at {dispatch} and the first pass that \
22040             draws at {first_draw} — a draw that reads the region before the write is made \
22041             visible is the whole defect this seam exists to prevent"
22042        );
22043
22044        drop(compiled);
22045        fixture.destroy(device);
22046        pool.destroy(device);
22047        device.destroy_image_view(imported.view);
22048        device.destroy_image(imported.image);
22049        recorder.assert_valid();
22050    }
22051
22052    /// A frame with nothing to skin adds no dispatch and declares no read, and
22053    /// is the frame [`ForwardRenderer::add_passes`] would have built.
22054    #[test]
22055    fn a_frame_with_no_skinned_range_is_the_frame_add_passes_builds() {
22056        let _blurs = ssao_blur_switch();
22057        let (recorder, device, queue) = open();
22058        let device = device.as_ref();
22059        let mut fixture = SkinnedFixture::build(device, queue);
22060        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
22061
22062        let imported = swapchain_image_at(device, TEST_EXTENT);
22063        let pool = crate::TransientPool::new();
22064        let mut skinned_labels = Vec::new();
22065        for _ in 0..1 {
22066            fixture
22067                .renderer
22068                .begin_skinned_frame(
22069                    device,
22070                    &mut fixture.skinning,
22071                    &[],
22072                    &Camera::default(),
22073                    &DirectionalLight::default(),
22074                    TEST_EXTENT,
22075                )
22076                .expect("an empty plan is a legal one");
22077            let mut graph = crate::RenderGraph::new(queue);
22078            let target = graph.import_image("target", imported);
22079            fixture.renderer.add_skinned_passes(
22080                &mut graph,
22081                &pool,
22082                target,
22083                TEST_EXTENT,
22084                &fixture.skinning,
22085            );
22086            skinned_labels = graph
22087                .compile(&pool)
22088                .expect("a legal frame")
22089                .passes()
22090                .iter()
22091                .map(|pass| pass.label().to_string())
22092                .collect();
22093        }
22094        let plain = passes_in_a_frame(
22095            device,
22096            queue,
22097            &mut fixture.renderer,
22098            imported,
22099            &pool,
22100            TEST_EXTENT,
22101        );
22102        assert_eq!(
22103            skinned_labels, plain,
22104            "a frame with nothing to skin must cost the vertex pool no barrier at all"
22105        );
22106
22107        fixture.destroy(device);
22108        let mut pool = pool;
22109        pool.destroy(device);
22110        device.destroy_image_view(imported.view);
22111        device.destroy_image(imported.image);
22112        recorder.assert_valid();
22113    }
22114
22115    /// One frame recorded end to end: `begin_frame`, the graph, and an encoder
22116    /// the commands land in.
22117    ///
22118    /// Returned rather than cleaned up here because the caller reads the
22119    /// recorder afterwards, and everything below must outlive that.
22120    struct Frame {
22121        imported: ImportedImage,
22122        pool: crate::TransientPool,
22123        commands: crcbl_hal::CommandBufferHandle,
22124    }
22125
22126    impl Frame {
22127        /// Releases the frame and the image it drew into, leaving the renderer
22128        /// alive for another one.
22129        fn release(self, device: &dyn Device) {
22130            device.destroy_command_buffer(self.commands);
22131            let mut pool = self.pool;
22132            pool.destroy(device);
22133            device.destroy_image_view(self.imported.view);
22134            device.destroy_image(self.imported.image);
22135        }
22136
22137        /// Releases the frame, the renderer and the image it drew into.
22138        fn finish(self, device: &dyn Device, renderer: ForwardRenderer) {
22139            self.release(device);
22140            renderer.destroy(device);
22141        }
22142    }
22143
22144    /// Everything one labelled pass recorded, and nothing any other pass did.
22145    ///
22146    /// **Every draw assertion below is scoped through this**, and the reason is
22147    /// topic 18: the frame now records the same indirect call the colour pass
22148    /// records once per shadow cascade as well, out of that cascade's own
22149    /// arguments. A test filtering the whole stream for `DrawIndexedIndirect`
22150    /// would see one per cascade as well as the colour pass's, and could not
22151    /// say which pass any of them belonged to — so "the forward pass records one
22152    /// call per bucket" would become a claim about a total, which a shadow pass
22153    /// recording the wrong thing could satisfy.
22154    /// The compute dispatches a default frame's **resolve** records, which
22155    /// every dispatch count in this module sees and none of them is about.
22156    ///
22157    /// `RenderEffects::DEFAULT_STACK` carries `CMAA2`, whose edge detect and
22158    /// shape classification are dispatches; its apply is a draw and does not
22159    /// count here. `each_effect_toggle_removes_exactly_the_passes_it_owns` is
22160    /// what pins the resolve's pass list itself, so a tier that grew a dispatch
22161    /// fails there first and arrives here as a second red rather than as a
22162    /// silent skew.
22163    const RESOLVE_DISPATCHES: usize = 2;
22164
22165    fn commands_in_pass(
22166        recorder: &crcbl_hal::null::Recorder,
22167        label: &str,
22168    ) -> Vec<crcbl_hal::null::Command> {
22169        use crcbl_hal::null::Command;
22170
22171        let mut inside = false;
22172        let mut out = Vec::new();
22173        for command in recorder.commands() {
22174            if let Some((_, recorded)) = command.opens_pass() {
22175                inside = recorded == Some(label);
22176                continue;
22177            }
22178            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
22179                inside = false;
22180                continue;
22181            }
22182            if inside {
22183                out.push(command);
22184            }
22185        }
22186        assert!(!out.is_empty(), "no pass labelled `{label}` recorded work");
22187        out
22188    }
22189
22190    /// The extent every helper frame in this module is drawn at.
22191    ///
22192    /// Named since the bloom chain, whose length is a function of it — see
22193    /// [`crate::bloom`] — so a test comparing a pass count against
22194    /// [`fullscreen_passes`] has to ask about the same size the frame was drawn
22195    /// at. Small on purpose: two chain levels is enough for every arm here, and
22196    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`] is the one
22197    /// test that needs a frame large enough for six.
22198    ///
22199    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
22200    const TEST_EXTENT: (u32, u32) = (64, 48);
22201
22202    /// The effects a caller has to ask for, because the default stack leaves
22203    /// them out — see [`RenderEffects::DEFAULT_STACK`].
22204    ///
22205    /// Named rather than written out at each of the three sites that force them
22206    /// on, because the point of those sites is "every effect there is" and the
22207    /// bug they exist to catch is a new effect joining the set and one site
22208    /// still measuring the old one while calling it the whole stack. They are
22209    /// held out of the default for different reasons — [`crate::effects`] gives
22210    /// each, and [`RenderEffects::CONTACT_SHADOWS`]'s is the only one that is a
22211    /// pending re-bless rather than a decision — and share only that a test
22212    /// wanting the widest frame must ask.
22213    ///
22214    /// **Named for what it is rather than for what most of it is**: the set held
22215    /// four post passes and a resolve when it was `POST_EFFECTS`, and the contact
22216    /// march is neither.
22217    const OUTSIDE_THE_DEFAULT: RenderEffects = RenderEffects::BLOOM
22218        .union(RenderEffects::ANTIALIASING)
22219        .union(RenderEffects::VOLUMETRIC_FOG)
22220        .union(RenderEffects::AUTO_EXPOSURE)
22221        .union(RenderEffects::CMAA2)
22222        .union(RenderEffects::CONTACT_SHADOWS);
22223
22224    /// Every effect this renderer draws is either in the default stack or in
22225    /// [`OUTSIDE_THE_DEFAULT`].
22226    ///
22227    /// The guard on the three sites above: they force [`OUTSIDE_THE_DEFAULT`] on and
22228    /// call the result "every effect", which is only true while nothing else is
22229    /// held out. An effect added outside the default stack and not added
22230    /// here makes this red before it makes a pass-list assertion red — which is
22231    /// the useful order, since a pass list going red says a label moved and this
22232    /// says what actually happened.
22233    #[test]
22234    fn forcing_the_post_effects_on_reaches_every_effect_there_is() {
22235        assert_eq!(
22236            RenderEffects::DEFAULT_STACK.union(OUTSIDE_THE_DEFAULT),
22237            RenderEffects::all(),
22238            "an effect outside the default stack that no test forces on is an effect \
22239             the every-effect frames below have never drawn"
22240        );
22241    }
22242
22243    /// The default sun, turned a little further round for each `lap`.
22244    ///
22245    /// Topic 45's static-caching rung means a second frame over
22246    /// a scene nothing moved in records **no shadow pass at all** — see
22247    /// [`ForwardRenderer::shadow_atlas_cached`]. That is the feature, and it is
22248    /// a difference that every A/B drawing two frames from one renderer would
22249    /// otherwise be measuring on top of the one it is about. Turning the sun is
22250    /// the smallest input the atlas depends on: the cascades are refitted, so
22251    /// the atlas is redrawn, and no pass, pipeline or draw of the frame moves
22252    /// with it.
22253    ///
22254    /// Lap zero is [`DirectionalLight::default`] exactly, so a test whose first
22255    /// frame is the ordinary one keeps the frame every other test draws.
22256    fn moving_sun(lap: u32) -> DirectionalLight {
22257        let sun = DirectionalLight::default();
22258        // A degree a lap, about the axis the default direction is not parallel
22259        // to. Small enough that every cascade still sees the scene, and large
22260        // enough that the snapped cascade origin actually moves.
22261        let turn = Mat4::from_rotation_y(
22262            f32::from(u16::try_from(lap).expect("a handful of laps")) * std::f32::consts::PI
22263                / 180.0,
22264        );
22265        DirectionalLight {
22266            direction: turn.transform_vector3(sun.direction).normalize(),
22267            ..sun
22268        }
22269    }
22270
22271    /// [`frame`] drawn under [`moving_sun`], so this frame's shadow atlas is
22272    /// not the one the lap before it left in the image.
22273    fn frame_moving_the_sun(
22274        device: &dyn Device,
22275        renderer: &mut ForwardRenderer,
22276        queue: QueueHandle,
22277        lap: u32,
22278    ) -> Frame {
22279        frame_lit_by(device, renderer, queue, &moving_sun(lap))
22280    }
22281
22282    fn frame(device: &dyn Device, renderer: &mut ForwardRenderer, queue: QueueHandle) -> Frame {
22283        frame_lit_by(device, renderer, queue, &DirectionalLight::default())
22284    }
22285
22286    fn frame_lit_by(
22287        device: &dyn Device,
22288        renderer: &mut ForwardRenderer,
22289        queue: QueueHandle,
22290        sun: &DirectionalLight,
22291    ) -> Frame {
22292        frame_seen_from(device, renderer, queue, &Camera::default(), sun)
22293    }
22294
22295    fn frame_seen_from(
22296        device: &dyn Device,
22297        renderer: &mut ForwardRenderer,
22298        queue: QueueHandle,
22299        camera: &Camera,
22300        sun: &DirectionalLight,
22301    ) -> Frame {
22302        renderer
22303            .begin_frame(device, camera, sun, TEST_EXTENT)
22304            .expect("write");
22305        let imported = swapchain_image(device);
22306        let mut graph = crate::RenderGraph::new(queue);
22307        let target = graph.import_image("target", imported);
22308        let mut pool = crate::TransientPool::new();
22309        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
22310        let compiled = graph.compile(&pool).expect("a legal frame");
22311        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
22312            label: Some("forward frame"),
22313            queue,
22314        });
22315        compiled
22316            .execute(device, &mut pool, encoder.as_mut(), None)
22317            .expect("the graph executed");
22318        let commands = encoder.finish().expect("recording succeeded");
22319        Frame {
22320            imported,
22321            pool,
22322            commands,
22323        }
22324    }
22325
22326    /// A stand-in for the acquired swapchain image the frame normally ends in,
22327    /// at [`TEST_EXTENT`].
22328    fn swapchain_image(device: &dyn Device) -> ImportedImage {
22329        swapchain_image_at(device, TEST_EXTENT)
22330    }
22331
22332    /// The same, at an extent of the caller's choosing.
22333    ///
22334    /// A frame's attachments must all be one size — the graph refuses a pass
22335    /// whose colour target and depth disagree — so a test drawing at anything
22336    /// but [`TEST_EXTENT`] has to import a target of that size too.
22337    pub(super) fn swapchain_image_at(device: &dyn Device, extent: (u32, u32)) -> ImportedImage {
22338        let format = Format::Rgba8UnormSrgb;
22339        let image = device
22340            .create_image(&crcbl_hal::ImageDesc {
22341                label: Some("fake swapchain image"),
22342                image_type: crcbl_hal::ImageType::D2,
22343                extent: crcbl_hal::Extent3d::d2(extent.0, extent.1),
22344                format,
22345                mip_levels: 1,
22346                samples: 1,
22347                usage: crcbl_hal::ImageUsage::COLOR_ATTACHMENT | crcbl_hal::ImageUsage::PRESENT,
22348            })
22349            .expect("an image");
22350        let view = device
22351            .create_image_view(&crcbl_hal::ImageViewDesc {
22352                label: Some("fake swapchain view"),
22353                image,
22354                view_type: crcbl_hal::ImageViewType::D2,
22355                format,
22356                range: crcbl_hal::ImageSubresourceRange::all(format),
22357            })
22358            .expect("a view");
22359        ForwardRenderer::present_target(image, view, format, extent)
22360    }
22361
22362    /// The spin is a rotation: no scale, no shear, so the cube neither grows
22363    /// nor mirrors as it turns, and every mesh golden blessed at a `spin` is a
22364    /// picture of one cube.
22365    ///
22366    /// That is also what keeps those goldens insensitive to `mesh.slang`'s
22367    /// `normal_basis`. A matrix with orthonormal rows and a positive
22368    /// determinant is its own cofactor matrix, to within a rounding step, so
22369    /// the vertex stage writes the normals it wrote when it multiplied by the
22370    /// bare 3×3 — see [`crcbl_shaders::mesh::GpuInstance::transform`], which no
22371    /// longer requires a caller to be rigid at all.
22372    #[test]
22373    fn the_spin_matrix_stays_rigid() {
22374        for seconds in [0.0f32, 0.5, 3.25, 100.0] {
22375            let model = ForwardRenderer::spin(seconds);
22376            let basis = glam::Mat3::from_mat4(model);
22377            let product = basis * basis.transpose();
22378            for (row, expected) in [
22379                (product.x_axis, Vec3::X),
22380                (product.y_axis, Vec3::Y),
22381                (product.z_axis, Vec3::Z),
22382            ] {
22383                assert!(
22384                    (row - expected).length() < 1e-5,
22385                    "the spin at {seconds}s is not orthonormal: {product:?}"
22386                );
22387            }
22388            assert!((model.determinant() - 1.0).abs() < 1e-5, "at {seconds}s");
22389        }
22390        // And it actually moves.
22391        assert_ne!(ForwardRenderer::spin(0.0), ForwardRenderer::spin(1.0));
22392    }
22393
22394    /// The swapchain import says what a swapchain image actually needs, which is
22395    /// the knowledge the hand-written barriers used to carry.
22396    #[test]
22397    fn the_present_target_starts_undefined_and_ends_presentable() {
22398        let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
22399        let image = pool.insert(0).cast();
22400        let view = pool.insert(0).cast();
22401        let imported =
22402            ForwardRenderer::present_target(image, view, Format::Bgra8UnormSrgb, (1280, 720));
22403        assert_eq!(imported.initial, ResourceState::Undefined);
22404        assert_eq!(imported.final_state, ResourceState::Present);
22405        assert_eq!(imported.extent, (1280, 720));
22406    }
22407
22408    /// The scene target is `Rgba16Float`, and the depth target is the
22409    /// reversed-Z format. Both are locked decisions and both are cheap to pin.
22410    #[test]
22411    fn the_scene_targets_are_hdr_and_reversed_z() {
22412        let color = crate::targets::scene_color((64, 48));
22413        assert_eq!(color.format, Format::Rgba16Float);
22414        assert!(color.format.is_hdr_capable());
22415        assert!(color.usage.contains(crcbl_hal::ImageUsage::SAMPLED));
22416
22417        let depth = crate::targets::scene_depth((64, 48));
22418        assert_eq!(depth.format, Format::D32Float);
22419        assert_eq!(
22420            DepthStencilState::default().depth_compare,
22421            crcbl_hal::CompareOp::Greater
22422        );
22423    }
22424
22425    /// A sun ten degrees or so above the horizon, and one further round: two
22426    /// atmospheres whose LUTs are nowhere near each other, so a comparison
22427    /// between them cannot pass by the two skies being alike.
22428    ///
22429    /// Spelled as directions rather than as angles for
22430    /// `crcbl_shaders::atmosphere`'s reason — nothing here takes a `sin` of its
22431    /// own — and normalised by `Atmosphere::parameters` on the way in.
22432    const MOVED_SUN: Atmosphere = Atmosphere {
22433        sun_direction: Vec3::new(1.0, 0.2, 0.0),
22434        ..Atmosphere::NOON
22435    };
22436
22437    /// [`MOVED_SUN`] again, further round and lower.
22438    const MOVED_AGAIN: Atmosphere = Atmosphere {
22439        sun_direction: Vec3::new(1.0, 0.05, 0.5),
22440        ..Atmosphere::NOON
22441    };
22442
22443    /// Frames the striped march takes to cross the LUT.
22444    const MARCH_FRAMES: usize = crcbl_shaders::atmosphere::SKY_VIEW_HEIGHT / SKY_VIEW_BUILD_ROWS;
22445
22446    /// The bytes the most recent sky-view LUT upload put on the device.
22447    ///
22448    /// `crate::sky_pass` writes the whole buffer at offset zero on every frame
22449    /// that has an atmosphere, into the slot that frame is using — so the last
22450    /// write to any of the ring's buffers is the LUT the frame just recorded
22451    /// would draw. That is the only place the presented LUT is observable: the
22452    /// renderer's own copy is what a test could assert about instead, and it
22453    /// would then be asserting about the thing rather than about what reached
22454    /// the device.
22455    fn presented_lut(recorder: &Recorder, luts: &[BufferHandle]) -> Vec<u8> {
22456        recorder
22457            .events()
22458            .into_iter()
22459            .rev()
22460            .find_map(|event| match event {
22461                crcbl_hal::null::Event::BufferWritten { buffer, .. } if luts.contains(&buffer) => {
22462                    recorder.buffer_bytes(buffer)
22463                }
22464                _ => None,
22465            })
22466            .expect("a frame with an atmosphere uploads a sky-view LUT")
22467    }
22468
22469    /// A renderer with an atmosphere set and its first LUT marched, and the
22470    /// buffers that LUT reaches the device through.
22471    ///
22472    /// The three tests below all start here: the first march is synchronous, so
22473    /// one frame is what it takes to have a sky to be stale about.
22474    fn with_marched_atmosphere(
22475        device: &dyn Device,
22476        queue: QueueHandle,
22477        atmosphere: Atmosphere,
22478    ) -> (ForwardRenderer, Vec<BufferHandle>) {
22479        let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
22480            .expect("the null backend builds a renderer");
22481        let luts = renderer.primary.sky_pass.luts().to_vec();
22482        renderer.set_atmosphere(Some(atmosphere));
22483        atmosphere_frame(&mut renderer, device);
22484        (renderer, luts)
22485    }
22486
22487    /// One frame of the atmosphere tests: nothing is drawn, and `begin_frame`
22488    /// is what writes the blocks and steps the march.
22489    fn atmosphere_frame(renderer: &mut ForwardRenderer, device: &dyn Device) {
22490        renderer
22491            .begin_frame(
22492                device,
22493                &Camera::default(),
22494                &DirectionalLight::default(),
22495                (64, 48),
22496            )
22497            .expect("the frame's blocks are written");
22498    }
22499
22500    /// A sun that moved is marched a stripe per frame, and every frame until it
22501    /// is finished still uploads the LUT of the sun before it.
22502    ///
22503    /// **The amortisation, from the device's side.** Before this, one
22504    /// `begin_frame` marched the whole LUT, so a scene that swept its sun paid
22505    /// tens of milliseconds of CPU in every frame. The claim now is three
22506    /// things at once, and only the middle one is about performance: the march
22507    /// advances by `SKY_VIEW_BUILD_ROWS` per frame, the bytes reaching the
22508    /// device meanwhile are the *previous* sun's rather than a half-marched
22509    /// sky, and the new sun's LUT arrives whole on the frame the march ends.
22510    ///
22511    /// **And the aerial-perspective LUT keeps the same pace**: it rides the
22512    /// same stripes, so it too uploads the previous sun's air on every frame
22513    /// of the march and the new sun's on the frame that ends it — the lag
22514    /// behind a moving sun is [`MARCH_FRAMES`] for both, and the two never
22515    /// reach the device a sun apart.
22516    #[test]
22517    fn a_moving_sun_is_marched_a_stripe_per_frame() {
22518        let (recorder, device, queue) = open();
22519        let (mut renderer, luts) =
22520            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22521        let aerials = renderer.primary.sky_pass.aerials().to_vec();
22522
22523        let before_view = SkyView::build(&Atmosphere::NOON.parameters());
22524        let after_view = SkyView::build(&MOVED_SUN.parameters());
22525        let before = before_view.rows();
22526        let after = after_view.rows();
22527        let (air_before, air_after) = (before_view.aerial().rows(), after_view.aerial().rows());
22528        assert_ne!(
22529            before, after,
22530            "the two suns march to the same LUT, so nothing below distinguishes them"
22531        );
22532        assert_ne!(
22533            air_before, air_after,
22534            "the two suns march to the same air, so nothing below distinguishes them"
22535        );
22536        assert!(
22537            renderer.sky_view_build.is_none(),
22538            "the first march is synchronous, so no build is left in flight"
22539        );
22540        assert_eq!(
22541            presented_lut(&recorder, &luts),
22542            before,
22543            "the frame after `set_atmosphere` did not upload that sun's LUT"
22544        );
22545        assert_eq!(
22546            presented_lut(&recorder, &aerials),
22547            air_before,
22548            "the frame after `set_atmosphere` did not upload that sun's air"
22549        );
22550
22551        renderer.set_atmosphere(Some(MOVED_SUN));
22552        for step in 1..MARCH_FRAMES {
22553            atmosphere_frame(&mut renderer, device.as_ref());
22554            assert_eq!(
22555                renderer
22556                    .sky_view_build
22557                    .as_ref()
22558                    .map(SkyViewBuild::rows_done),
22559                Some(step * SKY_VIEW_BUILD_ROWS),
22560                "frame {step} of the march is not a stripe further along than frame {} was",
22561                step - 1
22562            );
22563            assert_eq!(
22564                presented_lut(&recorder, &luts),
22565                before,
22566                "frame {step} of the march uploaded something other than the sky it is still \
22567                 drawing"
22568            );
22569            assert_eq!(
22570                presented_lut(&recorder, &aerials),
22571                air_before,
22572                "frame {step} of the march uploaded air other than the sky it is still drawing's"
22573            );
22574        }
22575
22576        atmosphere_frame(&mut renderer, device.as_ref());
22577        assert!(
22578            renderer.sky_view_build.is_none(),
22579            "the march did not finish in the frames its own stripe says it takes"
22580        );
22581        assert_eq!(
22582            presented_lut(&recorder, &luts),
22583            after,
22584            "the frame that finished the march did not upload the new sun's LUT"
22585        );
22586        assert_eq!(
22587            presented_lut(&recorder, &aerials),
22588            air_after,
22589            "the frame that finished the march did not upload the new sun's air"
22590        );
22591    }
22592
22593    /// An atmosphere adds the composite for its air whether or not the fog
22594    /// effect is on, and the block tells the composite which halves to read.
22595    ///
22596    /// **The seam between the two volumes, on the renderer's side.** Three
22597    /// frames of one renderer: no atmosphere and the default stack, which has
22598    /// no fog effect in it — no composite at all, the frame drawn before the
22599    /// air existed; an atmosphere and the same stack — the composite and
22600    /// nothing of the column, and a block saying so; and an atmosphere with
22601    /// the fog effect forced on — all three passes, and a block saying both.
22602    /// The counters are held to the frame on the second: the composite is a
22603    /// full-screen triangle, and a frame that drew it and did not count it
22604    /// makes the debug panel's row disagree with the frame by one.
22605    #[test]
22606    fn an_atmosphere_composites_its_air_with_or_without_the_fog_effect() {
22607        let _blurs = ssao_blur_switch();
22608        let (recorder, device, queue) = open();
22609        let device = device.as_ref();
22610        let mut renderer =
22611            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
22612        let blocks: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
22613            .map(|frame| renderer.primary.volumetric.buffers(frame).params)
22614            .collect();
22615        let imported = swapchain_image(device);
22616        let mut pool = crate::TransientPool::new();
22617        let block = |recorder: &Recorder| {
22618            let bytes: [u8; crcbl_shaders::volumetric::PARAMS_SIZE] =
22619                presented_lut(recorder, &blocks)
22620                    .try_into()
22621                    .expect("the block is its own size");
22622            crcbl_shaders::volumetric::VolumetricParams::from_bytes(&bytes)
22623        };
22624        let column = ["volumetric-scatter", "volumetric-integrate"];
22625
22626        let bare = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22627        let before = renderer.counters();
22628        assert!(
22629            !bare.iter().any(|pass| pass.starts_with("volumetric")),
22630            "a frame with neither fog nor an atmosphere records {bare:?}"
22631        );
22632        let off = block(&recorder);
22633        assert_eq!(
22634            off.aerial_params,
22635            [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
22636            "a frame with no atmosphere writes something into the aerial row"
22637        );
22638
22639        renderer.set_atmosphere(Some(Atmosphere::NOON));
22640        let air = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22641        assert!(
22642            air.iter().any(|pass| pass == "volumetric-composite")
22643                && !air.iter().any(|pass| column.contains(&pass.as_str())),
22644            "an atmosphere with the fog effect off records {air:?}, where it should composite its \
22645             air and run nothing of the column"
22646        );
22647        let after = renderer.counters();
22648        assert_eq!(
22649            after.draws - before.draws,
22650            (SkyPass::PASSES + u64::from(Volumetric::COMPOSITE_PASSES)) * FULLSCREEN_DRAWS,
22651            "the atmosphere's two full-screen passes — the sky and the air — are not both counted"
22652        );
22653        let aerial_only = block(&recorder);
22654        let sun = Atmosphere::NOON.parameters().sun_direction;
22655        assert_eq!(
22656            aerial_only.aerial_params,
22657            [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON],
22658            "the aerial row does not carry the atmosphere's sun and its switch"
22659        );
22660        assert_eq!(
22661            aerial_only.fog_params[3],
22662            crcbl_shaders::volumetric::LOCAL_COLUMN_OFF,
22663            "the block tells the composite to read a column no pass filled"
22664        );
22665
22666        renderer.set_effect_request(EffectRequest {
22667            programmatic: EffectOverride::none().force(RenderEffects::VOLUMETRIC_FOG, Some(true)),
22668            ..EffectRequest::default()
22669        });
22670        let both = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22671        assert!(
22672            column
22673                .iter()
22674                .chain(&["volumetric-composite"])
22675                .all(|name| both.iter().any(|pass| pass == name)),
22676            "an atmosphere with the fog effect on records {both:?}"
22677        );
22678        assert_eq!(
22679            block(&recorder).fog_params[3],
22680            crcbl_shaders::volumetric::LOCAL_COLUMN_ON,
22681            "the block tells the composite to skip a column the frame filled"
22682        );
22683
22684        renderer.destroy(device);
22685        pool.destroy(device);
22686        device.destroy_image_view(imported.view);
22687        device.destroy_image(imported.image);
22688        recorder.assert_valid();
22689    }
22690
22691    /// A sun that moves while a march is in flight restarts it from row zero.
22692    ///
22693    /// **The decision `refresh_sky_view` writes down**, and the reason a sun
22694    /// that moves every frame shows a frozen sky rather than a stuttering one:
22695    /// finishing a march for a sun that has already moved would swap in a LUT
22696    /// that is wrong on arrival. What is observable is the progress counter —
22697    /// a build that kept its rows would be two stripes along here rather than
22698    /// one — and the sun the build in flight names.
22699    #[test]
22700    fn a_sun_that_moves_mid_march_restarts_it() {
22701        let (recorder, device, queue) = open();
22702        let (mut renderer, luts) =
22703            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22704        let before = SkyView::build(&Atmosphere::NOON.parameters()).rows();
22705
22706        renderer.set_atmosphere(Some(MOVED_SUN));
22707        atmosphere_frame(&mut renderer, device.as_ref());
22708        atmosphere_frame(&mut renderer, device.as_ref());
22709        assert_eq!(
22710            renderer
22711                .sky_view_build
22712                .as_ref()
22713                .map(SkyViewBuild::rows_done),
22714            Some(2 * SKY_VIEW_BUILD_ROWS),
22715            "two frames of marching did not leave two stripes marched"
22716        );
22717
22718        renderer.set_atmosphere(Some(MOVED_AGAIN));
22719        atmosphere_frame(&mut renderer, device.as_ref());
22720        assert_eq!(
22721            renderer
22722                .sky_view_build
22723                .as_ref()
22724                .map(SkyViewBuild::rows_done),
22725            Some(SKY_VIEW_BUILD_ROWS),
22726            "the march kept the rows it had marched for a sun that has since moved"
22727        );
22728        assert_eq!(
22729            renderer
22730                .sky_view_build
22731                .as_ref()
22732                .map(SkyViewBuild::atmosphere),
22733            Some(MOVED_AGAIN.parameters()),
22734            "the build in flight is marching a sun the caller has moved away from"
22735        );
22736        assert_eq!(
22737            presented_lut(&recorder, &luts),
22738            before,
22739            "a restart uploaded something other than the last LUT that finished"
22740        );
22741    }
22742
22743    /// A frame whose sun has not moved marches nothing and re-takes neither
22744    /// projection.
22745    ///
22746    /// **What `PresentedSky` is for.** `gradient_fit` and `irradiance` used to
22747    /// be taken from the LUT in every `begin_frame`, which is host work a still
22748    /// sun has no reason to pay. Both are now taken once, where the march
22749    /// finishes — so a sentinel written over the cached gradient survives a
22750    /// frame if and only if that frame took neither the march nor the
22751    /// projection again, and the same sentinel's bytes turn up in what the
22752    /// frame wrote, which is what says the cache is the thing being read.
22753    #[test]
22754    fn a_still_sun_marches_nothing_and_reprojects_nothing() {
22755        let (recorder, device, queue) = open();
22756        let (mut renderer, _luts) =
22757            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22758
22759        let sentinel = crcbl_shaders::sky::SkyGradient {
22760            zenith: [0.125, 0.25, 0.375],
22761            horizon: [0.5, 0.625, 0.75],
22762            ground: [0.875, 1.125, 1.375],
22763        };
22764        let presented = renderer
22765            .sky_view
22766            .as_mut()
22767            .expect("the first frame marched a LUT");
22768        assert_ne!(
22769            presented.gradient, sentinel,
22770            "the sentinel is what the real projection already returns, so it proves nothing"
22771        );
22772        presented.gradient = sentinel;
22773
22774        let before = recorder.events().len();
22775        atmosphere_frame(&mut renderer, device.as_ref());
22776        assert_eq!(
22777            renderer
22778                .sky_view
22779                .as_ref()
22780                .map(|presented| presented.gradient),
22781            Some(sentinel),
22782            "a frame under a sun that has not moved re-took the projections"
22783        );
22784        assert!(
22785            renderer.sky_view_build.is_none(),
22786            "a frame under a sun that has not moved started a march"
22787        );
22788
22789        let wanted: Vec<u8> = sentinel
22790            .rows()
22791            .iter()
22792            .flatten()
22793            .flat_map(|value| value.to_le_bytes())
22794            .collect();
22795        let used = recorder
22796            .events()
22797            .into_iter()
22798            .skip(before)
22799            .filter_map(|event| match event {
22800                crcbl_hal::null::Event::BufferWritten { buffer, .. } => {
22801                    recorder.buffer_bytes(buffer)
22802                }
22803                _ => None,
22804            })
22805            .any(|bytes| {
22806                bytes
22807                    .windows(wanted.len())
22808                    .any(|window| window == wanted.as_slice())
22809            });
22810        assert!(
22811            used,
22812            "the cached gradient reached no block this frame wrote, so the frame is not reading \
22813             the cache at all"
22814        );
22815    }
22816
22817    /// **The frame block's ambient rows carry the marched LUT's own L1
22818    /// projection**, and not the three-band fit's.
22819    ///
22820    /// `begin_frame` writes [`PresentedSky::irradiance`] into
22821    /// [`FrameUniforms::sky_sh_r`] and the two rows beside it, and until this
22822    /// test nothing read them back. The only reader of those rows is arithmetic
22823    /// in `mesh.slang`'s fragment stage, and no frame in the tree draws a
22824    /// surface under an atmosphere — `crcbl`'s
22825    /// `an_atmosphere_frame_is_the_host_lut` puts no geometry in its scene at
22826    /// all — so `PresentedSky::new` handed `view.gradient_fit().irradiance()`
22827    /// instead, the three-band fit's projection rather than the LUT's, was a
22828    /// swap `docs/backlog.md` recorded passing every suite in the tree on
22829    /// 2026-09-06.
22830    ///
22831    /// **Both halves are needed and the second is the sabotage's.** The rows
22832    /// equalling the LUT's projection is the wiring; the rows *differing* from
22833    /// the fit's is what makes the equality a claim about which projection
22834    /// arrived rather than about two numbers that happen to agree. The
22835    /// `assert_ne` above them is the anti-vacuity: a sun for which the two
22836    /// projections coincide would make this test pass under the swap.
22837    ///
22838    /// [`FrameUniforms::sky_sh_r`]: crcbl_shaders::mesh::FrameUniforms::sky_sh_r
22839    #[test]
22840    fn an_atmosphere_writes_the_luts_own_ambient_term() {
22841        /// The three rows, as the little-endian bytes `FrameUniforms::to_bytes`
22842        /// puts in the block.
22843        fn rows(probe: &crcbl_shaders::probe::GpuProbe) -> Vec<u8> {
22844            [probe.sh_r, probe.sh_g, probe.sh_b]
22845                .iter()
22846                .flatten()
22847                .flat_map(|value| value.to_le_bytes())
22848                .collect()
22849        }
22850
22851        let (recorder, device, queue) = open();
22852        let (renderer, _luts) = with_marched_atmosphere(device.as_ref(), queue, MOVED_SUN);
22853
22854        let view = SkyView::build(&MOVED_SUN.parameters());
22855        let marched = rows(&view.irradiance());
22856        let fitted = rows(&view.gradient_fit().irradiance());
22857        assert_ne!(
22858            marched, fitted,
22859            "this sun's LUT and its three-band fit project to the same rows, so a block \
22860             carrying either would satisfy the check below and the swap it exists for would \
22861             pass"
22862        );
22863
22864        let block = recorder
22865            .buffer_bytes(renderer.primary.uniforms[renderer.frame])
22866            .expect("a frame with an atmosphere writes its uniform block");
22867        let at = mesh::SKY_SH_R_OFFSET;
22868        assert_eq!(
22869            &block[at..at + marched.len()],
22870            marched.as_slice(),
22871            "the frame block's sky rows are not `SkyView::irradiance` of the LUT this frame \
22872             marched, so the ambient term the fragment stage evaluates comes from somewhere \
22873             else"
22874        );
22875        assert_ne!(
22876            &block[at..at + fitted.len()],
22877            fitted.as_slice(),
22878            "the frame block's sky rows are the gradient fit's projection — the LUT was \
22879             marched and then thrown away for the three-band approximation of it"
22880        );
22881
22882        renderer.destroy(device.as_ref());
22883    }
22884}