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, DrawGenPipelines, 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::pipeline_batch;
192use crate::probe::{ProbeTable, ProbeTableDesc};
193use crate::probe_gather::{ProbeGather, ProbeGatherDesc, RsmImages, RsmTargets};
194use crate::rsm;
195use crate::scene::{self, Geometry, InstanceDesc, PageKind, ProbeUpdate, SceneDesc};
196use crate::shadow::{self, Cascades};
197use crate::skinning::{SkinRange, SkinnedMesh, Skinning, SkinningError};
198use crate::sky_pass::SkyPass;
199use crate::ssao::{Ssao, cached_group};
200use crate::ssr::{Ssr, SsrEnvironment, SsrImages};
201use crate::stack::CameraStack;
202use crate::texture::{PendingUpload, UploadBatch, UploadedTexture, upload_texture_mip_layers};
203use crate::transient::TransientPool;
204use crate::upscale::Upscale;
205use crate::volumetric::{FroxelBuffers, Medium, Volumetric, VolumetricImages, VolumetricReads};
206use crate::water::{Water, WaterBodies, WaterFrame, WaterImages, WaterInputs};
207use crcbl_shaders::atmosphere::{SKY_VIEW_BUILD_ROWS, SkyView, SkyViewBuild};
208
209mod bucket_draws;
210mod frame_prepare;
211mod pages;
212mod shadow_inputs;
213mod view;
214
215use pages::{PageBindings, RetiredPage, upload_page};
216
217pub use shadow_inputs::{FRAME_UNIFORMS_READERS, UniformsField, UniformsReader};
218
219use bucket_draws::{BucketDraws, EmitTail, RegionStep};
220
221use view::{FramePasses, Overlays, TonemapPipeline, View, ViewInputs, ViewOutput};
222pub use view::{
223    FrameTargets, MAX_VIEWS, ViewBackground, ViewDesc, ViewId, ViewLighting, ViewMask, ViewTarget,
224};
225
226/// The clear behind the mesh, in **linear** light.
227///
228/// The scene target is `Rgba16Float`, so this is a linear value and the tonemap
229/// pass plus the swapchain's sRGB encode are what turn it into pixels. Writing a
230/// display-referred colour here would come out visibly paler, which is the
231/// classic HDR-pipeline mistake and worth a sentence rather than a surprise.
232pub const SCENE_CLEAR: [f32; 4] = [0.012, 0.016, 0.030, 1.0];
233
234/// How many frames of uniform buffers to keep. Matches the frame loop's
235/// frames-in-flight.
236pub const FRAMES_IN_FLIGHT: usize = 2;
237
238// The UI pass this renderer draws its HUD through keeps a ring of its own,
239// built at `crcbl_frame`'s default depth; held equal here, where both are in
240// scope, so the HUD cannot fall a frame behind the ring it shares a submit with.
241const _: () = assert!(crcbl_frame::ui_pass::FRAMES_IN_FLIGHT == FRAMES_IN_FLIGHT);
242
243/// The darkest exposure [`ForwardRenderer::set_exposure`] will accept: **five
244/// stops below** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`].
245///
246/// The floor exists so that the control cannot be driven somewhere it cannot be
247/// driven back from. The operator clamps its own *output* to `[0, 1]`, so an
248/// unclamped input has two dead ends: far enough down and every pixel rounds to
249/// the same black byte, far enough up and every pixel saturates to white — and
250/// in both the picture stops carrying the information a user would need to see
251/// which way to go. Five stops is well inside either: it is a sixteenth of the
252/// scene's brightness, dark but plainly still a picture, and it is the range a
253/// camera's exposure-compensation dial covers.
254pub const EXPOSURE_MIN: f32 = 1.0 / 32.0;
255
256/// The brightest exposure [`ForwardRenderer::set_exposure`] will accept: **five
257/// stops above** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`], for
258/// [`EXPOSURE_MIN`]'s reason.
259pub const EXPOSURE_MAX: f32 = 32.0;
260
261/// The default has to be reachable from both ends of the range, or a control
262/// that steps by a ratio starts somewhere it can only leave in one direction.
263const _: () = assert!(
264    EXPOSURE_MIN > 0.0
265        && EXPOSURE_MIN < crcbl_shaders::tonemap::DEFAULT_EXPOSURE
266        && EXPOSURE_MAX > crcbl_shaders::tonemap::DEFAULT_EXPOSURE
267);
268
269/// The format the frame's depth buffer is created with, taken from the
270/// description that creates it rather than written down a second time.
271///
272/// Read by [`ForwardRenderer::set_ground_grid`], whose pipeline is built for a
273/// depth attachment before there is a frame to ask. The extent is irrelevant to
274/// a format, which is why any is passed.
275pub(crate) const SCENE_DEPTH_FORMAT: Format = crate::targets::scene_depth((1, 1)).format;
276
277/// The format the frame's HDR scene target is created with, taken from the
278/// description that creates it rather than written down a second time.
279///
280/// Read by [`crate::debug_draw`], whose pipeline blends into whichever image the
281/// chain of HDR passes ended with — every one of them is a
282/// [`crate::targets::scene_color`]. The extent is irrelevant to a format,
283/// which is why any is passed.
284pub(crate) const SCENE_COLOR_FORMAT: Format = crate::targets::scene_color((1, 1)).format;
285
286/// The format §3.2's base-colour page is created with.
287///
288/// **`Rgba8UnormSrgb`, and that is the colour-space decision** — the argument
289/// for it is at the `upload_texture_mip_layers` call inside
290/// [`ForwardRenderer::with_scene`]. Named rather than spelled twice because
291/// [`ForwardRenderer::base_color_page_import`] has to declare the same format
292/// the image was created with, and a barrier naming a format the image is not in
293/// picks the wrong aspects.
294const BASE_COLOR_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
295
296/// The format topic 43 §2's **normal** page is
297/// created with.
298///
299/// **`Rgba8Unorm`, and the missing `Srgb` is the whole decision.**
300/// Topic 44's rung 2 argues it: a base-colour texel is a
301/// colour and glTF defines it as sRGB-encoded, so the format above is what makes
302/// the sampler decode it; a normal texel is a *number* — three components of a
303/// direction, stored as `n * 0.5 + 0.5` — and pushing it through the sRGB
304/// transfer curve is wrong by a gamma. What that looks like is not an error but
305/// a surface that leans further off vertical than the author drew, which is why
306/// the mistake survives review everywhere it is made.
307///
308/// `the_page_formats_split_colour_from_number` is the whole guard, and it is
309/// worth having because the four constants sit a few lines apart and the wrong
310/// one compiles.
311const NORMAL_PAGE_FORMAT: Format = Format::Rgba8Unorm;
312
313/// The format topic 43 §2's **metallic-roughness-
314/// occlusion** page is created with.
315///
316/// **`Rgba8Unorm`, and the missing `Srgb` is the same decision
317/// [`NORMAL_PAGE_FORMAT`] argues.** An occlusion, a roughness and a metalness
318/// are numbers rather than colours — glTF 2.0 §3.9.2 and §3.9.5 define them as
319/// linear factors — and a surface shaded through an sRGB decode of them is
320/// smoother and shinier than the author drew, which is a failure that survives
321/// review because it looks like a choice.
322///
323/// A separate constant from [`NORMAL_PAGE_FORMAT`] rather than a reuse of it,
324/// for [`LTC_SIZE_U32`]'s reason: the two stand for different facts, and a day
325/// one of them wanted a different format should be an edit here rather than a
326/// search for which callers of a shared name meant which page.
327const MRO_PAGE_FORMAT: Format = Format::Rgba8Unorm;
328
329/// The format topic 43 §2's **emissive** page is
330/// created with.
331///
332/// **`Rgba8UnormSrgb`, and it is the base-colour page's decision rather than
333/// the normal page's.** An emissive texel is a colour: glTF 2.0 §3.9.4 defines
334/// `emissiveTexture` as sRGB-encoded exactly as it defines `baseColorTexture`,
335/// and `GpuMaterial::emissive` beside it is a linear radiance, so the format is
336/// what puts the two in one space before they are multiplied.
337///
338/// A separate constant from [`BASE_COLOR_PAGE_FORMAT`] for the reason above it,
339/// and `the_page_formats_split_colour_from_number` is the guard that the four
340/// do not drift into one another.
341const EMISSIVE_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
342
343/// What the renderer needs of a [`PageKind`] to create and fill its image.
344///
345/// Written here rather than in [`crate::scene`] because the two answers are the
346/// device's: the format is the one [`base_color_page_import`] and
347/// [`normal_page_import`] have to declare, and the filter is the one
348/// [`crate::mip`] builds the chain with. A kind added by
349/// topic 43 §2's rung 3 is a new arm in each.
350///
351/// [`base_color_page_import`]: ForwardRenderer::base_color_page_import
352/// [`normal_page_import`]: ForwardRenderer::normal_page_import
353impl PageKind {
354    /// The format this kind's image is created with.
355    ///
356    /// The sRGB in one and its absence in the other is the whole colour-space
357    /// decision — see [`BASE_COLOR_PAGE_FORMAT`] and [`NORMAL_PAGE_FORMAT`],
358    /// which is where each is argued.
359    const fn format(self) -> Format {
360        match self {
361            Self::BaseColor => BASE_COLOR_PAGE_FORMAT,
362            Self::Normal => NORMAL_PAGE_FORMAT,
363            Self::MetallicRoughnessOcclusion => MRO_PAGE_FORMAT,
364            Self::Emissive => EMISSIVE_PAGE_FORMAT,
365        }
366    }
367
368    /// Every mip level below `level0`, built on the host with this kind's own
369    /// filter.
370    ///
371    /// [`crate::mip::normal_chain`] averages the decoded vectors plainly and
372    /// renormalises, where [`crate::mip::chain`] decodes an sRGB curve and
373    /// weights by alpha. A normal map mipped through the colour filter leans
374    /// further off vertical at every level than the map it was built from, and
375    /// nothing in a frame reports it.
376    fn chain(self, level0: &[u8], extent: u32) -> Vec<Vec<u8>> {
377        match self {
378            Self::BaseColor | Self::Emissive => crate::mip::chain(level0, extent),
379            Self::Normal => crate::mip::normal_chain(level0, extent),
380            Self::MetallicRoughnessOcclusion => crate::mip::linear_chain(level0, extent),
381        }
382    }
383
384    /// The device label this kind's image is created under.
385    const fn upload_label(self) -> &'static str {
386        match self {
387            Self::BaseColor => "material base colour",
388            Self::Normal => "material normals",
389            Self::MetallicRoughnessOcclusion => "material metallic-roughness-occlusion",
390            Self::Emissive => "material emissive",
391        }
392    }
393}
394
395/// The one texel a page **nothing names** is created with.
396///
397/// [`crate::texture::upload_texture_mip_layers`] refuses a zero-layer image, and
398/// every bind group of the mesh layout has to fill both page bindings whether or
399/// not the description carried either page — so a [`PageKind`] with no layers
400/// gets a 1×1 single-layer image in its own format instead of an `extent²` one
401/// nobody samples. That is the whole of what row (d) bought back:
402/// `apps/alcove`, `apps/sundial` and `apps/quarry` name no page at all, and
403/// every scene in the tree that has no normal map used to carry a full neutral
404/// layer and a third again for its chain.
405///
406/// **Magenta, and it is never sampled for its value.** A material naming no page
407/// carries [`GpuMaterial::NO_PAGE`](mesh::GpuMaterial::NO_PAGE):
408/// `mesh.slang`'s `base_color_texel` discards the fetch with a select and
409/// returns the literal `1.0`, and `shading_normal_of` returns before it fetches
410/// at all. So nothing should ever read this — and the value is chosen so that if
411/// something does, the frame says so in a colour no lit surface in this engine
412/// produces. White would blend into every untextured surface and black would
413/// read as a shadow; both are failures a golden could pass.
414const PAGE_PLACEHOLDER_TEXEL: [u8; 4] = [0xFF, 0x00, 0xFF, 0xFF];
415
416/// The format the motion-vector target is created with: two channels of half
417/// float, topic 43 §9's third colour attachment.
418///
419/// **Named here rather than in [`crate::targets::motion`]**, on
420/// [`crate::graph`]'s other format-owning descriptions' terms: the description
421/// and
422/// [`MeshModules::COLOR_TARGETS`] have to agree, and the pass that builds the
423/// pipeline is the one that owns the answer.
424///
425/// # The convention the target holds, so a consumer never has to guess it
426///
427/// **Current minus previous, in texture coordinates, `+y` down.** A pass
428/// holding the previous frame reads its history at `uv - motion`, and a surface
429/// travelling right and down the screen has both components positive.
430/// `mesh.slang`'s `motion_vector` is where the mapping is written out and this
431/// is the same sentence on the host side, because the first consumer will read
432/// one of the two and not both.
433///
434/// # Two channels and half float
435///
436/// A motion vector is a screen-space offset and has no third component. Half
437/// float rather than a normalised integer because the value is signed and
438/// unbounded — an object crossing the frame in one frame is a motion past `1.0`
439/// — and because the interesting magnitudes are small: a surface moving a
440/// tenth of a pixel is the case a temporal filter is most sensitive to, and
441/// eight or even sixteen unsigned bits over a `-1..1` range would quantise it
442/// into rest. It is also the format `crcbl_hal::Format::Rg16Float`'s own doc
443/// names motion vectors as the use for.
444pub(crate) const MOTION_FORMAT: Format = Format::Rg16Float;
445
446/// Which picture the colour pass draws instead of the shaded one.
447///
448/// The engine's debug views, as one value rather than as independent booleans,
449/// because they are not independent: every one of them rides in a single lane of
450/// the frame's uniform block and the shaders test the thresholds outermost
451/// first, so a renderer with two of them set draws exactly one.
452/// [`ForwardRenderer::debug_view`] is where that order lives, and this is what it
453/// answers with — so a menu row, a debug panel and the picture cannot disagree
454/// about which view is on.
455///
456/// **The declaration order is not the precedence** — each view was appended as
457/// it arrived, and [`ForwardRenderer::debug_view`] is the one place the order is
458/// decided. The sentinels in
459/// [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) ascend with it, though:
460/// see its `HEATMAP_VIEW_ON`, and the shaders test the outermost threshold
461/// first.
462#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
463pub enum DebugView {
464    /// The lit picture. What every frame draws unless a caller asked otherwise.
465    #[default]
466    Shaded,
467    /// Each cluster shaded by the projected screen-space error the LOD
468    /// selection judged it on — [`ForwardRenderer::set_heatmap`].
469    Heatmap,
470    /// Each cluster tinted by the DAG level it was decimated to —
471    /// [`ForwardRenderer::set_lod_view`].
472    LodTint,
473    /// World-space surface normals — [`ForwardRenderer::set_normals_view`].
474    Normals,
475    /// The ambient-occlusion channel alone, as grey —
476    /// [`ForwardRenderer::set_occlusion_view`].
477    AmbientOcclusion,
478    /// The motion vector each fragment wrote, stretched and centred on grey —
479    /// [`ForwardRenderer::set_motion_view`].
480    Motion,
481    /// The bent direction the occlusion channel carries beside its scalar, as
482    /// `n * 0.5 + 0.5` — [`ForwardRenderer::set_bent_normal_view`]. **Wins over
483    /// every other view.**
484    BentNormal,
485    /// The sun's cascades and the lit tiles beside them — the `D32Float` shadow
486    /// atlas itself, letterboxed over the finished frame with a border round
487    /// every occupied slot — [`ForwardRenderer::set_atlas_view`].
488    ///
489    /// **The one view that is a pass rather than a branch in `mesh.slang`**, and
490    /// therefore the one whose lane is the off sentinel: the colour pass draws
491    /// the shaded picture exactly as it always did and `crate::atlas_view`
492    /// replaces it afterwards. That module's header is where the placement is
493    /// argued.
494    ///
495    /// It resolves **below every view above and above [`Self::Cascades`]** — see
496    /// [`ForwardRenderer::debug_view`].
497    ShadowAtlas,
498    /// The shaded picture tinted by the cascade each sun-lit fragment's shadow
499    /// was sampled from, with the cross-fade band drawn as the blend of the two
500    /// — [`ForwardRenderer::set_cascade_view`].
501    ///
502    /// **Loses to every other view**, and it is the only one that does. The views
503    /// above draw something *instead of* the shaded picture; this one draws the
504    /// shaded picture and multiplies it, so there is nothing left for it to
505    /// modulate as soon as one of them is on. See
506    /// [`ForwardRenderer::debug_view`].
507    Cascades,
508}
509
510impl DebugView {
511    /// What a panel row or a summary line calls it.
512    #[must_use]
513    pub const fn label(self) -> &'static str {
514        match self {
515            Self::Shaded => "shaded",
516            Self::Heatmap => "heatmap",
517            Self::LodTint => "lod tint",
518            Self::Normals => "normals",
519            Self::AmbientOcclusion => "ambient occlusion",
520            Self::Motion => "motion",
521            Self::BentNormal => "bent normal",
522            Self::ShadowAtlas => "shadow atlas",
523            Self::Cascades => "cascades",
524        }
525    }
526}
527
528// Mesh-only resources follow the complete common fragment binding range.
529// Metal assigns dense native indices by resource-table order, so inserting a
530// mesh-only buffer before lights/probes would shift the layout away from the
531// independently compiled fragment stage. Sparse logical bindings cost no slots.
532const CLUSTERS_BINDING: u32 = 32;
533const CLUSTER_VERTICES_BINDING: u32 = 33;
534const CLUSTER_CORNERS_BINDING: u32 = 34;
535const CLUSTER_DRAW_ARGS_BINDING: u32 = 35;
536const CLUSTER_CULL_BINDING: u32 = 36;
537const CLUSTER_CULL_STATS_BINDING: u32 = 37;
538const CLUSTER_SELECT_BINDING: u32 = 38;
539const CLUSTER_SELECTION_BINDING: u32 = 39;
540const CLUSTER_GROUP_STATE_BINDING: u32 = 40;
541
542/// The shared fragment shader's shadow atlas slot. Historical logical gaps
543/// remain reserved so the raster shader bindings stay unchanged.
544const SHADOW_ATLAS_BINDING: u32 = 15;
545
546/// The bind-group slot the shadow atlas's **comparison** sampler is bound to.
547const SHADOW_SAMPLER_BINDING: u32 = 16;
548
549/// The bind-group slot the base-colour page is bound to.
550///
551/// Named because [`ForwardRenderer::replace_page`] rewrites it in every group
552/// of the mesh layout, as it does each page's binding — see
553/// `pages::page_binding`.
554const BASE_COLOR_PAGE_BINDING: u32 = 7;
555
556/// The bind-group slot the base-colour page's sampler is bound to.
557///
558/// Named because it is an entry [`ForwardRenderer::set_anisotropy`] rewrites
559/// in every group of the mesh layout: a sampler is a resource a group holds by
560/// handle, so a new sampler is a new group, and the rebuild finds the entry by
561/// this number.
562const PAGE_SAMPLER_BINDING: u32 = 8;
563
564/// The shared fragment shader's light list. Both shader modules declare it
565/// before mesh-only buffers so native buffer index 7 is common to both stages.
566const LIGHT_LIST_BINDING: u32 = 20;
567
568/// The bind-group slot the froxel grid is read through.
569const LIGHT_GRID_BINDING: u32 = 21;
570
571/// The fragment shader's screen-space occlusion texture. Mesh-only additions
572/// are buffers, so this resource does not shift their native argument table.
573const AMBIENT_OCCLUSION_BINDING: u32 = 22;
574
575/// The shared irradiance probe table, native buffer 9 in both shader modules.
576/// `mesh_cluster.slang` mirrors it before its own buffers to preserve the prefix.
577const PROBE_TABLE_BINDING: u32 = 23;
578
579/// The mesh path's packed `DrawGen` table, read for the screen-error heatmap.
580/// Its logical binding stays 24; after the shared fragment buffer prefix it is
581/// native buffer 10. The raster path does not declare this storage buffer.
582const LEVEL_GROUP_TABLE_BINDING: u32 = 24;
583
584/// The bind-group slot the split-sum `DFG` table is fetched through — how much
585/// of the light arriving at a GGX lobe that lobe hands back.
586///
587/// No mirror is needed in `mesh_cluster.slang`: that module adds only buffers
588/// after the shared prefix. The fragment shader's `specular_dfg` remains at
589/// native texture 3, following `ambient_occlusion` at texture 2.
590///
591/// **An image rather than a storage buffer, and that is forced.** The table is
592/// 4096 pairs and a buffer would carry it exactly; but the raster path's layout
593/// is at the WebGPU storage-buffer ceiling in its *vertex* stage, and Slang's
594/// Metal backend materialises every global into every entry point — so a row
595/// bound to the fragment stage alone would be a global the vertex stage names
596/// and nothing fills. See [`crcbl_hal::check_portable_storage_buffers`] and
597/// binding 7's `geometry` visibility.
598const SPECULAR_DFG_BINDING: u32 = 25;
599
600/// The bind-group slot §2's normal page is sampled through.
601///
602/// **Appended past [`SPECULAR_DFG_BINDING`], never inserted**, for
603/// [`PROBE_TABLE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
604/// next index in its Metal argument table by counting the same-table entries of
605/// this layout, and Slang numbers a stage's arguments by declaration order, so
606/// the two agree only while both ascend. No mirror is needed in
607/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
608///
609/// **No sampler of its own.** The page is read through
610/// [`PAGE_SAMPLER_BINDING`]'s sampler, the same trilinear anisotropic one the
611/// base-colour page uses, because it is sampled at the same UV over an image of
612/// the same extent. A second sampler would be a second layout entry, a second
613/// index in Metal's sampler argument table, and a second thing
614/// [`ForwardRenderer::set_anisotropy`] has to rebuild — for a filter that would
615/// be identical.
616const NORMAL_PAGE_BINDING: u32 = 26;
617
618/// The bind-group slot topic 44's rung 5 reads its linearly
619/// transformed cosine table through.
620///
621/// **Appended past [`NORMAL_PAGE_BINDING`], never inserted**, for that
622/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
623/// Metal argument table by counting the same-table entries of this layout, and
624/// Slang numbers a stage's arguments by declaration order, so the two agree only
625/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
626/// needs no mirror there and no index anything already owns moves.
627///
628/// **No sampler**, like the table two rows below it: four `Load`s and a bilinear
629/// blend written out in the shader, because a hardware filter's weights are
630/// fixed-function arithmetic four rasterisers compute independently and these
631/// goldens are compared across all four.
632const LTC_TABLE_BINDING: u32 = 27;
633
634/// The bind-group slot topic 45's contact-shadow channel is
635/// read through.
636///
637/// **Appended past [`LTC_TABLE_BINDING`], never inserted**, for that constant's
638/// reason exactly: `crcbl-mtl` gives a resource the next index in its Metal
639/// argument table by counting the same-table entries of this layout, and Slang
640/// numbers a stage's arguments by declaration order, so the two agree only while
641/// both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it needs
642/// no mirror there and no index anything already owns moves.
643///
644/// **No sampler**, like the occlusion channel: `mesh.slang`'s `contact_at` is a
645/// clamped `Load` at `SV_Position.xy`, and the channel is exactly the size of
646/// the frame on every pass that computed one.
647const CONTACT_SHADOW_BINDING: u32 = 28;
648
649/// The bind-group slot the irradiance probes' per-probe
650/// visibility maps are read through: one `Rg32Float` layer per probe.
651///
652/// **Appended past [`CONTACT_SHADOW_BINDING`], never inserted**, for that
653/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
654/// Metal argument table by counting the same-table entries of this layout, and
655/// Slang numbers a stage's arguments by declaration order, so the two agree only
656/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
657/// needs no mirror there and no index anything already owns moves —
658/// `msl/mesh.metal` puts it at `texture(7)`, the next free index of that table.
659///
660/// **A texture rather than a storage buffer, and that is forced**: the raster
661/// path's vertex stage is already at every storage buffer a WebGPU device
662/// guarantees, which is the same reason [`SPECULAR_DFG_BINDING`] is an image.
663///
664/// **No sampler**, like the occlusion channel and both cooked tables:
665/// `mesh.slang`'s `probe_moments` is four clamped `Load`s and a blend written
666/// out, because a hardware filter's weights are fixed-function arithmetic four
667/// rasterisers compute independently — and because `Rg32Float` is not a
668/// filterable format on WebGPU without an optional feature.
669const PROBE_VISIBILITY_BINDING: u32 = 29;
670
671/// The bind-group slot topic 43 §2's packed
672/// **metallic-roughness-occlusion** page is sampled through.
673///
674/// **Appended past [`PROBE_VISIBILITY_BINDING`], never inserted**, for
675/// [`NORMAL_PAGE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
676/// next index in its Metal argument table by counting the same-table entries of
677/// this layout, and Slang numbers a stage's arguments by declaration order, so
678/// the two agree only while both ascend. No mirror is needed in
679/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
680///
681/// **No sampler of its own**, for [`NORMAL_PAGE_BINDING`]'s reason: the page is
682/// read at the same UV over an image of the same shape as the base-colour one,
683/// so it goes through [`PAGE_SAMPLER_BINDING`]'s sampler and adds no entry to
684/// Metal's sampler argument table.
685const MRO_PAGE_BINDING: u32 = 30;
686
687/// The bind-group slot topic 43 §2's **emissive**
688/// page is sampled through.
689///
690/// **Appended past [`MRO_PAGE_BINDING`], never inserted**, for that constant's
691/// reason exactly, and it shares [`PAGE_SAMPLER_BINDING`]'s sampler on the same
692/// terms. `mesh_cluster.slang` adds only buffers after these textures, so it needs no
693/// mirror there and no index anything already owns moves.
694const EMISSIVE_PAGE_BINDING: u32 = 31;
695
696/// [`crcbl_shaders::dfg::DFG_SIZE`] as an image extent.
697///
698/// The table is square, and its size is a compile-time constant, so the
699/// conversion belongs here rather than as a fallible one at the upload.
700const DFG_SIZE_U32: u32 = dfg::DFG_SIZE as u32;
701
702/// [`crcbl_shaders::ltc::LTC_SIZE`] as an image extent.
703///
704/// The same number as [`DFG_SIZE_U32`], and a separate constant rather than a
705/// reuse of it: `crcbl_shaders::ltc`'s `the_grid_is_the_dfg_table_s_grid` is
706/// what says the two tables are the same square, and each upload naming its own
707/// module is what would make a day they were not into a compile error here
708/// rather than a stretched image.
709const LTC_SIZE_U32: u32 = ltc::LTC_SIZE as u32;
710
711/// The `Rgba8Unorm` texel that occludes nothing and steers nothing.
712///
713/// What [`ForwardRenderer::ambient_occlusion_placeholder`] holds, and therefore
714/// what `mesh.slang` reads on a frame drawing without
715/// [`RenderEffects::AMBIENT_OCCLUSION`].
716///
717/// **`r` is `0xFF`, which is `1.0`**: the shading multiplies its ambient by
718/// this and the term is untouched. Any other value would be a silent global
719/// ambient scale.
720///
721/// **`gba` are [`ssao::BENT_NORMAL_NONE`], which decodes to a zero-length
722/// direction** — the sentinel the occlusion chain writes wherever it has no
723/// bent direction to report, and which `mesh.slang`'s `bent_normal_at` answers
724/// with the fragment's own shading normal. So "no occlusion pass ran" and "no
725/// direction at this pixel" are one case with one answer, and a frame drawn
726/// with the effect off is the frame this renderer drew before the channel was
727/// widened. Encoding a direction here instead would tilt every ambient term in
728/// such a frame towards one world axis.
729const AMBIENT_OCCLUSION_NONE: [u8; 4] = [
730    0xFF,
731    ssao::BENT_NORMAL_NONE,
732    ssao::BENT_NORMAL_NONE,
733    ssao::BENT_NORMAL_NONE,
734];
735
736/// The `R8Unorm` texel the sun reaches unobstructed: `1.0`, which is `0xFF`.
737///
738/// What [`ForwardRenderer::contact_shadow_placeholder`] holds, and therefore
739/// what `mesh.slang` reads on a frame drawing without
740/// [`RenderEffects::CONTACT_SHADOWS`] — it multiplies `sun_visibility` by this
741/// and the cascades have the last word alone. Any other value would be a silent
742/// global scale on the sun.
743///
744/// The same byte as [`AMBIENT_OCCLUSION_NONE`]'s first and a constant of its
745/// own, for the reason [`LTC_SIZE_U32`] is not [`DFG_SIZE_U32`]: the two
746/// placeholders stand for different facts, and a day one of them wanted a
747/// different value should be an edit here rather than a search for which
748/// callers of a shared name meant which thing.
749const CONTACT_SHADOW_NONE: u8 = 0xFF;
750
751/// The one `Rg32Float` texel that occludes nothing: a mean distance of
752/// [`probe_visibility::FAR`](crcbl_shaders::probe_visibility::FAR) and its
753/// square.
754///
755/// What [`ForwardRenderer::probe_visibility_placeholder`] holds, and therefore
756/// what `mesh.slang` reads on a frame drawn before anything was captured or with
757/// `r_probe_visibility` off. No surface in any scene is further away than that,
758/// so `probe_weight` answers one for every probe and every fragment, and the
759/// grid is the unweighted trilinear blend it was before this rung — which is
760/// what makes the off position bit-identical rather than merely close.
761///
762/// Any *smaller* value would be a silent occluder: every probe in every scene
763/// would read as being behind a wall, and the whole grid would collapse onto
764/// `PROBE_OCCLUDED_WEIGHT`.
765fn probe_visibility_none() -> [u8; crcbl_shaders::probe_visibility::TEXEL_BYTES] {
766    let mut texel = [0u8; crcbl_shaders::probe_visibility::TEXEL_BYTES];
767    let far = crcbl_shaders::probe_visibility::FAR;
768    texel[..4].copy_from_slice(&far.to_le_bytes());
769    texel[4..].copy_from_slice(&(far * far).to_le_bytes());
770    texel
771}
772
773/// The reversed-Z far plane, in the two places that have to agree about it.
774///
775/// `ssao.slang` leaves early at exactly this depth because the unprojection there
776/// divides by a `clip.w` an infinite reversed-Z projection takes to zero. The
777/// shader cannot include the seam and `crcbl-shaders` does not depend on it, so
778/// the mirror is checked here — which is the only place both names are in scope.
779const _: () = assert!(crcbl_hal::depth::CLEAR == crcbl_shaders::ssao::DEPTH_FAR);
780
781/// How many buckets a resident mesh occupies, which is **not the same on every
782/// geometry path** — the one place in this renderer the two differ in shape
783/// rather than in the call they record.
784///
785/// A flat mesh is one bucket either way. A DAG is one bucket on
786/// [`EmitTail::Mesh`]: a bucket is a mesh's run of clusters, and the point of
787/// topic 25's per-cluster selection is that one dispatch covers
788/// several levels at once, so the run is every level's clusters end to end and
789/// the bucket's mesh id is level 0's.
790///
791/// On the two indirect tails a DAG is one bucket **per level**, because there
792/// the same plan takes a uniform cut and a level is drawn as an ordinary index
793/// range: a DAG's levels are separate mesh table entries, `draw_gen.slang`
794/// selects one per instance, and a bucket is what an indexed draw of one index
795/// range *is*. See [`ForwardRenderer::level_buckets`].
796const fn buckets_for(levels: usize, emit: EmitTail) -> usize {
797    if emit.is_mesh() { 1 } else { levels }
798}
799
800/// Every material mode this renderer routes a draw by, and the order the bucket
801/// table lays its per-mode runs of every mesh's levels down in.
802///
803/// [`GpuMaterial::mode`](mesh::GpuMaterial::mode)'s whole range, which is why
804/// the routing is total rather than checked: a row's mode is
805/// `flags & GpuMaterial::MODE_MASK`, that mask is the alpha-mask bit and the
806/// double-sided one, and the four combinations of them are these — so no
807/// material can carry a mode that is not in this list and no instance can
808/// scatter into a bucket that does not exist. Widening the mask means adding the
809/// mode here **and** giving it a depth pipeline in
810/// [`ForwardRenderer::depth_partitions`] in the same change — the two are the
811/// producer and the consumer of one list.
812///
813/// **A scene emits a twin per mode its own materials carry**, not one per
814/// entry here: two materials of two modes are two twins whichever two they are,
815/// and only a scene actually holding all four pays for four. The build below is
816/// where that filter is, and this module's
817/// `an_all_opaque_scene_keeps_one_bucket_per_mesh_level` is what holds it.
818const DEPTH_MODES: [u32; 4] = [
819    0,
820    mesh::GpuMaterial::ALPHA_MODE_MASK,
821    mesh::GpuMaterial::DOUBLE_SIDED,
822    mesh::GpuMaterial::ALPHA_MODE_MASK | mesh::GpuMaterial::DOUBLE_SIDED,
823];
824
825/// A pipeline and its [`CullMode::None`] twin: the two objects a pass binds to
826/// draw single-sided and double-sided buckets of one frame.
827///
828/// **A pipeline rather than a per-draw state, because no backend seam exposes
829/// dynamic cull mode** — and `crcbl_hal::CommandEncoder::set_stencil_reference`
830/// is the precedent for why one would not be added: a raster state a recorded
831/// stream carried per draw is a state every backend has to be able to change
832/// between two indirect calls, and the portable answer to "this draw rasterises
833/// differently" is a second pipeline. Which draws take which is
834/// [`ForwardRenderer::sided_partitions`].
835///
836/// Four passes need the pair — the colour pass, the two depth-only ones and the
837/// reflective shadow map — so it is a type rather than eight fields.
838///
839/// **The twin exists only where the scene can draw with it.** A bucket table is
840/// fixed at build, from the modes the description's materials carry (see
841/// [`ForwardRenderer::bucket_modes`]), and nothing adds a material afterwards;
842/// so `build` knows then whether any bucket will ever be double-sided, and
843/// compiles the twin for that scene alone. Each twin is a cold compile as long
844/// as the pipeline it twins.
845///
846/// [`ForwardRenderer::partitions`] is what makes an unbuilt twin unbindable:
847/// it takes each pipeline as an [`Option`], so there is no handle to record
848/// for one that was never compiled, and a partition with draws in it and no
849/// pipeline is a panic rather than a bind.
850#[derive(Clone, Copy, Debug, PartialEq, Eq)]
851struct SidedPipelines {
852    /// [`CullMode::Back`]: every bucket whose material is single-sided, which is
853    /// every bucket of every scene that does not use `doubleSided`.
854    single: GraphicsPipelineHandle,
855    /// [`CullMode::None`]: the buckets whose material carries
856    /// [`GpuMaterial::DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED), and
857    /// [`None`] for a scene with no such bucket.
858    double: Option<GraphicsPipelineHandle>,
859}
860
861impl SidedPipelines {
862    /// Both halves, single-sided first, for a pass to hand
863    /// [`ForwardRenderer::partitions`] — keyed by the
864    /// [`DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED) bit.
865    fn by_side(self) -> [(u32, Option<GraphicsPipelineHandle>); 2] {
866        [
867            (0, Some(self.single)),
868            (mesh::GpuMaterial::DOUBLE_SIDED, self.double),
869        ]
870    }
871
872    /// Every pipeline this holds, for a release.
873    fn handles(self) -> impl Iterator<Item = GraphicsPipelineHandle> {
874        std::iter::once(self.single).chain(self.double)
875    }
876}
877
878/// The pixel budget topic 25's descent compares a group's projected
879/// error against, unless a caller sets another with
880/// [`ForwardRenderer::set_lod_error_budget`].
881///
882/// One pixel, because that is what the metric is *for*: a level's error is how
883/// far its simplification may have moved the surface, so a budget of a pixel is
884/// the point at which a level change stops being something a viewer can see.
885/// The plan's "correct thresholds make pops sub-pixel by definition" is this
886/// number.
887const LOD_ERROR_BUDGET: f32 = 1.0;
888
889/// Bytes one bucket's draw-constant block occupies, whichever of the two blocks
890/// it holds.
891///
892/// The larger of [`mesh::DRAW_CONSTANTS_SIZE`] and
893/// [`CLUSTER_DRAW_CONSTANTS_SIZE`](crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE),
894/// because which one a bucket holds is the geometry path's decision and the
895/// buffer, its dynamic stride and the range the bind group names are all fixed
896/// before that decision reaches them.
897///
898/// **The bound range is the half that bites.** A range sized for the smaller
899/// block leaves the larger one's tail outside it, and a uniform read past the
900/// bound range is not a fault — it is a zero. Sized at sixteen bytes, the mesh
901/// path's `group_stride` read back as zero and every instance descended against
902/// instance zero's LOD state.
903const DRAW_CONSTANTS_BLOCK: u64 =
904    if mesh::DRAW_CONSTANTS_SIZE > crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE {
905        mesh::DRAW_CONSTANTS_SIZE as u64
906    } else {
907        crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE as u64
908    };
909
910/// How far below the budget an already-expanded group is held before it
911/// collapses again — topic 25's "switch-up and switch-down differ",
912/// as a fraction of [`LOD_ERROR_BUDGET`].
913///
914/// A ratio and not an offset because the band has to scale with the budget: a
915/// fixed number of pixels is most of a one-pixel budget and none of a fifty-pixel
916/// one. A fifth of the budget is a deadband a camera has to move decisively out
917/// of, and one a camera drifting along a boundary never leaves — which is the
918/// flicker the plan is about. `crcbl_shaders::cluster_select::LodBudgets` is the
919/// pair this produces, and a ratio of one is that type's `sharp`: no band, and
920/// the setting that shows the band is what stops the flicker.
921const LOD_HOLD_RATIO: f32 = 0.8;
922
923/// How much larger than the camera's the pixel budget a shadow cascade selects
924/// under is — topic 25's "**Shadow LOD bias**: shadow-pass culling
925/// selects +1/+2 coarser levels — casters are cheap where it never shows".
926///
927/// # A budget factor, because a level is not a parameter of the rule
928///
929/// The descent compares a group's projected error to a pixel budget; it never
930/// names a level. So "one or two levels coarser" is an *intent*, and the budget
931/// that produces it is the setting — and the two do not convert, because how far
932/// apart two levels' errors are is a property of the mesh. The committed dunes
933/// DAG is the demonstration: the step from one level's error to the next is
934/// several times larger in the middle of that hierarchy than at its base, and
935/// across its top levels there is no step at all — they report one error and are
936/// never separately selected by any budget. A bias expressed in levels would
937/// mean something different at each of those. `cook-clusters` prints the per
938/// level errors it built.
939///
940/// Four, then, is two doublings of the budget: enough that a caster is drawn
941/// coarser than the same object is in the colour pass, and small enough to stay
942/// inside what a shadow hides. What hides it is that a shadow edge is filtered —
943/// the atlas is read through a comparison sampler with linear filtering, so an
944/// edge arrives already spread over neighbouring texels — and that the atlas
945/// quantises every caster to [`shadow::TILE`] texels per cascade before anything
946/// samples it.
947///
948/// # Why one number, applied to the whole pass
949///
950/// **A cut is a cover only while expansion is monotone up the DAG**, and this
951/// scaling is what keeps it so. Multiplying both budgets by one positive
952/// constant leaves the rule in
953/// [`crcbl_shaders::cluster_select`]'s form with different constants in it, and
954/// that module's induction turns on the projected error being monotone up the
955/// DAG rather than on what the constants are — so the shadow pass's cut is a
956/// cover for exactly the reason the camera's is. A bias that varied by cluster,
957/// by group, by level or by cascade would not be: two groups on one branch would
958/// be judged against different budgets, and a child expanding under an
959/// unexpanded parent is a hole.
960///
961/// Being larger than one also makes the shadow pass's expanded set a **subset**
962/// of the colour pass's, since the two now select from one eye at one scale: a
963/// group over `k` times the budget is over the budget. So the shadow cut is
964/// never finer than the camera's anywhere, which is the property
965/// `crcbl-vk`'s `the_shadow_cascades_select_coarser_than_the_camera` reads back
966/// and asserts.
967pub const SHADOW_LOD_BIAS: f32 = 4.0;
968
969/// How many culls the shadow atlas needs: one per cascade and **one per shadowed
970/// light**, whatever kind of light it is.
971///
972/// Topic 18's fourth decision, as a number. A point light's six faces share the
973/// light's sphere — which is what a cull tests against — so they share one
974/// [`DrawGen`] and its visible set, and the six draws differ in a matrix and a
975/// viewport. Six generators per light would be six copies of
976/// [`TileBuffers::group_state`], which is where the cost of one is written down.
977const SHADOW_CULLS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS;
978
979/// How many shadow *views* there are: one per cascade, and one per face of every
980/// light slot.
981///
982/// A view is what has a matrix, so it is what has a frame-block copy, a bind
983/// group and a cut of its own — while a *tile* is where a view lands in the
984/// atlas and a *cull* is which visible set it draws. The three were one number
985/// until a light could own six tiles.
986///
987/// Every slot carries [`shadow::POINT_FACES`] views whether the light in it is a
988/// point or a spot, because a bind group names its buffers when it is created
989/// and the kind of light holding a slot changes per frame. A spot uses face 0's
990/// view and the other five are never recorded — they cost a uniform buffer and a
991/// descriptor each, which is nothing beside the [`DrawGen`] a second *cull*
992/// would cost.
993const SHADOW_VIEWS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS * shadow::POINT_FACES;
994
995/// Cascade 0's view, which is the one the irradiance probes'
996/// reflective shadow map is drawn through.
997///
998/// **A cascade is its own view index**, which is what `add_shadow_pass`'s view
999/// list pushes; [`shadow_view`] numbers a *light slot's* faces and starts past
1000/// [`shadow::CASCADES`], so it is not the function to reach for here.
1001const CASCADE_ZERO_VIEW: usize = 0;
1002
1003const _: () = assert!(
1004    CASCADE_ZERO_VIEW < shadow::CASCADES,
1005    "cascade 0's view has to be one of the cascades' own, not a light slot's"
1006);
1007
1008/// Which view is face `face` of light slot `slot`.
1009const fn shadow_view(slot: usize, face: usize) -> usize {
1010    shadow::CASCADES + slot * shadow::POINT_FACES + face
1011}
1012
1013/// Which cull light slot `slot` draws from.
1014const fn shadow_cull(slot: usize) -> usize {
1015    shadow::CASCADES + slot
1016}
1017
1018/// One punctual shadow face this frame draws into the punctual reflective
1019/// shadow map, and everything both halves of the updater need of it.
1020///
1021/// The irradiance probes' punctual producer. It carries no
1022/// matrix and no visible set: a face's transform is already in the uniform block
1023/// [`ForwardRenderer::shadow_groups`] binds, and its draws are the ones its
1024/// slot's cull generated for the atlas — which is what makes this rung cost no
1025/// second cull and no second matrix.
1026#[derive(Clone, Copy, Debug)]
1027struct PunctualFace {
1028    /// Which shadow view this face is — [`shadow_view`]'s answer, and the index
1029    /// of the bind group whose block holds that face's own `view_proj`.
1030    view: usize,
1031    /// Which of the frame's shadow culls generated its draws — [`shadow_cull`]'s
1032    /// answer for the slot this face belongs to.
1033    cull: usize,
1034    /// Which face of its light this is, and so — where the light's cull tagged
1035    /// its casters by face — which draw region it draws.
1036    face: usize,
1037    /// Where it lands in the punctual map — [`rsm::punctual_tile`], which is the
1038    /// rectangle the pass sets its viewport to *and* the one the gather reads
1039    /// this face's texels out of.
1040    tile: shadow::TileRect,
1041    /// The light this is a face of, as the gather weighs its texels.
1042    producer: PunctualProducer,
1043}
1044
1045/// The draw region face `face` of a light draws: its own region where the
1046/// light's cull tagged casters by face, and region 0 — every survivor — where it
1047/// did not. See [`crcbl_shaders::draw_gen::FACE_REGION_BASE`].
1048fn face_region(by_face: bool, face: usize) -> u32 {
1049    if by_face {
1050        crcbl_shaders::draw_gen::FACE_REGION_BASE
1051            + u32::try_from(face).unwrap_or_else(|_| unreachable!("a light has six faces"))
1052    } else {
1053        0
1054    }
1055}
1056
1057/// One light's row in the gather's producer table, for the face standing at
1058/// `tile`.
1059///
1060/// **Built out of the light's own row**, which is the one place a light becomes
1061/// numbers — so the falloff, the cone and the colour the bounce is weighed by
1062/// are the very ones `mesh.slang` weighs the same light's direct term by, rather
1063/// than a second reading of the same fields that could round or widen
1064/// differently. [`Light::row`](crate::light::Light::row) is handed [`None`]
1065/// because a producer occludes through nothing: the gather gates a texel with
1066/// the probe's own visibility map, not with the light's.
1067fn producer_row(light: &Light, tile: shadow::TileRect) -> PunctualProducer {
1068    let row = light.row(None);
1069    PunctualProducer {
1070        position: [row.position[0], row.position[1], row.position[2]],
1071        radius: row.position[3],
1072        color: [row.color[0], row.color[1], row.color[2]],
1073        cos_outer: row.direction[3],
1074        axis: [row.direction[0], row.direction[1], row.direction[2]],
1075        cos_inner: row.cos_inner,
1076        origin: [tile.x, tile.y],
1077        side: tile.side,
1078        kind: row.kind,
1079    }
1080}
1081
1082const _: () = assert!(
1083    SHADOW_CULLS == shadow::GROUPS,
1084    "a cull is a cadence group: `shadow::Cadence` schedules what this file \
1085     dispatches, and two different counts would schedule a group nothing draws"
1086);
1087
1088/// Vertices in the over-sized triangle `mesh.slang`'s `depthClearVertexMain`
1089/// generates from `SV_VertexID`. No geometry is bound.
1090const TILE_CLEAR_VERTICES: u32 = 3;
1091
1092const _: () = assert!(
1093    crcbl_shaders::mesh::SHADOW_ATLAS_CLEAR_DEPTH == crcbl_hal::depth::CLEAR,
1094    "the stage that resets one tile writes a depth the attachment's own clear \
1095     does not, so a held tile and a cleared one would answer differently where \
1096     nothing was drawn"
1097);
1098
1099/// Narrows the shadow pass's viewport and scissor to one tile of the atlas.
1100///
1101/// The rectangle the allocator handed out — the same one the fragment stage
1102/// samples through, out of [`shadow::Selection`]. The graph set a viewport over
1103/// the whole atlas before the pass body ran, and this is what narrows it: the
1104/// same clip-space matrix mapped into a different part of the image, and for a
1105/// point light six different matrices into six of them off one visible set.
1106///
1107/// A function rather than the two calls inline, because the tile clear and the
1108/// draws that follow it walk the same tiles and a viewport set one way for one
1109/// of them would clear a rectangle nothing draws into.
1110fn set_shadow_tile(encoder: &mut dyn crcbl_hal::CommandEncoder, tile: shadow::TileRect) {
1111    let rect = Rect2d {
1112        x: i32::try_from(tile.x).unwrap_or(i32::MAX),
1113        y: i32::try_from(tile.y).unwrap_or(i32::MAX),
1114        width: tile.side,
1115        height: tile.side,
1116    };
1117    encoder.set_viewport(&Viewport {
1118        x: rect.x as f32,
1119        y: rect.y as f32,
1120        width: rect.width as f32,
1121        height: rect.height as f32,
1122        ..Viewport::from_size(rect.width, rect.height)
1123    });
1124    encoder.set_scissor(&rect);
1125}
1126
1127/// What the last executed graph left the renderer-owned import `image` in, as an
1128/// [`ImportedImage::initial`].
1129///
1130/// **[`ResourceState::Undefined`] is the answer to an empty ledger, not a
1131/// fallback around one.** The ledger records what a graph *executed*, so nothing
1132/// recorded means nothing has run against this image on this pool — a freshly
1133/// created image before its first frame, and an image whose pool has been
1134/// through [`TransientPool::destroy`] — and `Undefined` is what an image no
1135/// barrier has moved is in. It is also the only declaration that lets the
1136/// incoming barrier hand the image a layout at all: every other state names an
1137/// old layout the image is not in.
1138///
1139/// The reason this is a lookup and not a field the renderer advances: a graph is
1140/// built, then compiled, and [`RenderGraph::compile`] can refuse it. A field
1141/// stepped forward while the passes were declared would have moved for a frame
1142/// that never reached the GPU, and the next frame's declaration — now wrong —
1143/// has no ledger entry to contradict it, so [`InitialClaim::Tracked`] would pass
1144/// it through. One source of truth is what removes that gap rather than
1145/// narrowing it.
1146fn imported_state(pool: &TransientPool, image: ImageHandle) -> ResourceState {
1147    pool.imported_image_use(image)
1148        .unwrap_or(ResourceState::Undefined)
1149}
1150
1151/// The passes [`ForwardRenderer::add_passes`] records itself: the shadow
1152/// atlas's, the two reflective shadow maps, the depth prepass, the forward pass,
1153/// the debug draw layer, the tonemap, the ground grid and the
1154/// culling-statistics copy — plus [`Ssao::MAX_PASSES`], [`Ssr::PASSES`],
1155/// [`ProbeGather::PASSES`], [`Bloom::MAX_PASSES`], [`Exposure::PASSES`],
1156/// [`POST_TONEMAP_PASSES`] and [`Upscale::PASSES`] beside them.
1157///
1158/// [`AtlasView::PASSES`] has no term of its own and is inside
1159/// [`POST_TONEMAP_PASSES`] instead, which is where that is argued: the atlas
1160/// viewer and the resolve are never both recorded.
1161///
1162/// The reflective shadow maps and [`ProbeGather::PASSES`] are counted on the
1163/// ground grid's terms: all three are off unless a scene's
1164/// [`ProbeUpdate`] asks for them, and a bound short
1165/// of the frame that does ask would silently stop timing its last pass. The
1166/// punctual map is a pass whether or not the frame has a punctual light to draw
1167/// into it — see `ForwardRenderer::add_shadow_pass`, where the clear is what the
1168/// gather reads on a frame that lights none.
1169///
1170/// Every other pass in the frame belongs to a [`DrawGen`] or to the
1171/// [`LightGrid`], which is why this is the only count written here rather than
1172/// derived — see [`ForwardRenderer::MAX_PASSES`]. The copy is counted even
1173/// though a device that refused the readback records one fewer: this is a
1174/// ceiling, and one that came up short would silently stop timing the last pass
1175/// of every frame. It is the **all-effects-on** count for the same reason: a
1176/// frame that switched one off records fewer, and a bound that tracked the
1177/// toggles would have to be re-sized whenever they moved.
1178///
1179/// The ground grid is counted on the same terms, even though it is off by
1180/// default and is not a [`RenderEffects`] bit: a caller that switches it on
1181/// records one more pass, and a bound short of that would silently stop timing
1182/// the last pass of every frame it drew. The render-scale upscale is the second
1183/// of those — see [`ForwardRenderer::set_render_scale`], which is `1.0` and
1184/// therefore absent until a caller moves it. The debug draw layer is the third,
1185/// and [`DebugDraw::MAX_PASSES`] is its own ceiling.
1186///
1187/// **The bloom, Hi-Z and occlusion terms are ceilings where the others are
1188/// counts**: a chain's length is a function of the target's extent — see
1189/// [`crate::bloom`] and [`crate::hiz`] — and the occlusion pair's is a function
1190/// of [`crate::ssao::r_ssao_blur_passes`], while this constant is read before
1191/// either an extent or a console is known. The frame that lands on
1192/// it is a large one with bloom switched on; every smaller frame records fewer,
1193/// exactly as a frame with a free shadow slot does.
1194const RENDER_PASSES: u32 = 8
1195    // The occlusion cull's late depth prepass and its farthest pyramid, on the
1196    // ground grid's terms: off unless a caller switches the cull on.
1197    + 1
1198    + OcclusionPyramid::PASSES
1199    + DebugDraw::MAX_PASSES
1200    + ProbeGather::PASSES
1201    + Ssao::MAX_PASSES
1202    + ContactShadows::PASSES
1203    + Hiz::PASSES
1204    + Ssr::PASSES
1205    + Volumetric::PASSES
1206    + Water::PASSES
1207    + Grass::PASSES
1208    + Exposure::PASSES
1209    + Bloom::MAX_PASSES
1210    + POST_TONEMAP_PASSES
1211    + Upscale::PASSES;
1212
1213/// What the frame's one resolve slot costs at its widest: the larger of the two
1214/// antialiasing tiers.
1215///
1216/// **The larger and not the sum**, because the two are never both recorded —
1217/// [`RenderEffects::CMAA2`] carries that in writing and
1218/// [`ForwardRenderer::add_passes`] is where the choice is made. So this is the
1219/// all-effects-on count as well as the ceiling, which is the property
1220/// [`RENDER_PASSES`] needs from every term it adds up.
1221///
1222/// [`ForwardRenderer::add_passes`]: ForwardRenderer::add_passes
1223const RESOLVE_PASSES: u32 = if Fxaa::PASSES > Cmaa2::PASSES {
1224    Fxaa::PASSES
1225} else {
1226    Cmaa2::PASSES
1227};
1228
1229/// What the frame's one **post-tonemap** slot costs at its widest: the resolve
1230/// above, or [`crate::atlas_view`]'s pass, which replaces the picture instead of
1231/// filtering it.
1232///
1233/// **The larger and not the sum**, on [`RESOLVE_PASSES`]' terms and for a
1234/// reason of the same shape: [`ForwardRenderer::resolved_effects`] takes *both*
1235/// antialiasing tiers off for every debug view, and the atlas viewer records
1236/// only on the frame [`ForwardRenderer::debug_view`] resolved to
1237/// [`DebugView::ShadowAtlas`] — which is a debug view. So a frame that draws the
1238/// atlas resolves nothing, a frame that resolves is not drawing the atlas, and
1239/// neither can be short of this. `the_pass_bound_is_the_widest_frame_the_renderer_records`
1240/// is what holds the arithmetic to a frame that was actually recorded.
1241const POST_TONEMAP_PASSES: u32 = if RESOLVE_PASSES > AtlasView::PASSES {
1242    RESOLVE_PASSES
1243} else {
1244    AtlasView::PASSES
1245};
1246
1247/// Draws a full-screen pass records: the over-sized triangle, drawn once.
1248///
1249/// The smallest fraction of the target extent a frame may be drawn at.
1250///
1251/// A quarter in each dimension, which is a sixteenth of the pixels — below that
1252/// the internal frame is small enough that a Catmull-Rom reconstruction of it
1253/// stops being a picture of the scene and starts being a picture of the filter,
1254/// and the Hi-Z pyramid and the bloom chain both run out of levels. Every
1255/// engine's resolution slider bottoms out somewhere; this is where this one
1256/// does, and [`ForwardRenderer::set_render_scale`] clamps to it rather than
1257/// refusing, so a settings slider cannot hand the renderer a frame it cannot
1258/// draw.
1259pub const MIN_RENDER_SCALE: f32 = 0.25;
1260
1261/// The anisotropy the base-colour page is sampled with where the device grants
1262/// [`Features::SAMPLER_ANISOTROPY`].
1263///
1264/// Eight, which is topic 43's filtering rung's
1265/// default and the figure current engines default their own slider to: past it
1266/// the footprint's long axis is already sampled finely enough that sixteen is
1267/// invisible at a grazing angle and costs the same again in fetches. A device
1268/// whose [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) is lower gets
1269/// that limit instead — [`ForwardRenderer::anisotropy_for`] is the clamp — and a
1270/// device without the feature gets one, which is the value that turns it off.
1271pub const DEFAULT_ANISOTROPY: f32 = 8.0;
1272
1273/// Named rather than written into [`ForwardRenderer::counters`]'s arithmetic,
1274/// because these are the only draws in this file whose instance and triangle
1275/// counts the CPU knows exactly — everything else here goes through an indirect
1276/// call.
1277const FULLSCREEN_DRAWS: u64 = 1;
1278
1279/// How many full-screen passes a frame drawing `effects` at `extent` records:
1280/// the tonemap, always, and each switched-on effect's passes beside it.
1281///
1282/// **A function of the frame rather than a constant**, since
1283/// topic 48's toggles: it was the tonemap alone, then
1284/// five, and either written down is a number that stops matching the frame. The
1285/// tonemap is the one that is not conditional — a frame has to reach the
1286/// swapchain.
1287///
1288/// **`extent` is here because the bloom chain's length depends on it** — see
1289/// [`crate::bloom`] — where the two pairs above are the same two passes at every
1290/// size. A frame too small for even one chain level records none of them, which
1291/// is the same arithmetic as the toggle being off. It is the **internal** render
1292/// extent for the same reason: that is the extent every one of these passes runs
1293/// at.
1294///
1295/// `upscaling` is not a [`RenderEffects`] bit and could not be one — it is a
1296/// resolution, not an effect — so it arrives as its own argument, on the ground
1297/// grid's terms. It is false on every frame at full render scale, which is the
1298/// frame this function counted before the knob existed.
1299///
1300/// `ssao_blurs` arrives the same way and for the same reason: it is a console
1301/// variable rather than an effect bit, and it is the caller's job to read it
1302/// **once** for the frame. Reading it here as well would be a second read that
1303/// a command landing between the two could disagree with, and the disagreement
1304/// would be a counter describing a frame that was not recorded.
1305fn fullscreen_passes(
1306    effects: RenderEffects,
1307    extent: (u32, u32),
1308    upscaling: bool,
1309    ssao_blurs: u32,
1310) -> u64 {
1311    let mut passes = 1;
1312    if upscaling {
1313        passes += Upscale::PASSES as u64;
1314    }
1315    if effects.contains(RenderEffects::AMBIENT_OCCLUSION) {
1316        passes += u64::from(Ssao::passes(ssao_blurs));
1317    }
1318    if effects.contains(RenderEffects::CONTACT_SHADOWS) {
1319        passes += u64::from(ContactShadows::PASSES);
1320    }
1321    if effects.contains(RenderEffects::REFLECTIONS) {
1322        // The march's pair, and the pyramid it climbs — which is as long as the
1323        // extent allows and is zero on a frame too small to halve once, so this
1324        // term is the only one here that is not a constant per effect.
1325        passes += Ssr::PASSES as u64 + u64::from(crate::hiz::levels_for(extent));
1326    }
1327    if effects.contains(RenderEffects::BLOOM) {
1328        passes += u64::from(Bloom::passes_for(extent));
1329    }
1330    // **One resolve slot, and the higher tier takes it.** Both bits set is a
1331    // frame with CMAA2's passes and no FXAA pass at all, which is what
1332    // [`RenderEffects::CMAA2`] means by the two never both running — so this is
1333    // an `else if` rather than two independent terms.
1334    //
1335    // **[`Cmaa2::FULLSCREEN_PASSES`] and not [`Cmaa2::PASSES`]**: what this
1336    // function counts is full-screen *draws*, and two of that tier's three
1337    // passes are compute dispatches. [`crate::exposure`]'s three are left out
1338    // of this arithmetic for the same reason.
1339    if effects.contains(RenderEffects::CMAA2) {
1340        passes += Cmaa2::FULLSCREEN_PASSES;
1341    } else if effects.contains(RenderEffects::ANTIALIASING) {
1342        passes += Fxaa::PASSES as u64;
1343    }
1344    if effects.contains(RenderEffects::VOLUMETRIC_FOG) {
1345        // **[`Volumetric::COMPOSITE_PASSES`], not [`Volumetric::PASSES`].** The
1346        // scatter and the column scan are compute dispatches; what this
1347        // function counts is full-screen *draws*, and only the composite is
1348        // one. An atmosphere runs the composite without the effect, and the
1349        // caller adds that one — it is not an effect bit.
1350        passes += u64::from(Volumetric::COMPOSITE_PASSES);
1351    }
1352    // [`RenderEffects::AUTO_EXPOSURE`] adds none, and that is the whole of its
1353    // entry here: all three of its passes are compute dispatches, and the
1354    // exposure they measure reaches the picture through the tonemap's own draw.
1355    passes
1356}
1357
1358/// The budget an **orthographic** camera selects under: one no group satisfies,
1359/// so every group expands and the base level is drawn whole.
1360///
1361/// The metric divides a projected error by the distance to the group's sphere,
1362/// and an orthographic projection has no such falloff — see
1363/// [`Projection::pixels_per_unit`], which is where the trade is written down.
1364/// Drawing the finest level is the conservative answer and the honest one; a
1365/// distance term invented for a projection that has none would be neither.
1366///
1367/// [`Projection::pixels_per_unit`]: crate::camera::Projection::pixels_per_unit
1368const LOD_BUDGET_NONE: f32 = f32::NEG_INFINITY;
1369
1370/// Where a skinned object is, and what it draws: [`InstanceDesc`] with a
1371/// [`SkinnedMesh`] where the description's mesh index would be.
1372///
1373/// The mesh is a reservation rather than an index because a skinned draw is not
1374/// only a mesh — it also names a *run of the vertex pool* the skinning dispatch
1375/// fills, and which of the reservation's two runs that is changes every frame.
1376/// [`ForwardRenderer::begin_skinned_frame`] is what keeps it current, so nothing
1377/// here carries a parity.
1378#[derive(Clone, Copy, Debug)]
1379pub struct SkinnedInstanceDesc<'a> {
1380    /// The region this object is drawn out of, from
1381    /// [`ForwardRenderer::reserve_skinned`].
1382    pub mesh: &'a SkinnedMesh,
1383    /// Which [`SceneDesc::materials`] row it shades through, exactly as
1384    /// [`InstanceDesc::material`].
1385    pub material: usize,
1386    /// Where it is: a model matrix, on [`InstanceDesc::transform`]'s terms.
1387    ///
1388    /// The joints are **not** in it — a palette carries each joint's global
1389    /// transform times its inverse bind matrix, and this is what puts the
1390    /// deformed mesh in the world. See
1391    /// [`SkinRange::palette`](crate::skinning::SkinRange::palette).
1392    pub transform: Mat4,
1393}
1394
1395/// The sky-view LUT a frame is drawn from, and everything taken out of it.
1396///
1397/// **The two projections are cached beside the LUT rather than taken per
1398/// frame**, which is what makes a frame under a sun that has not moved do no
1399/// host LUT work at all: both are functions of the LUT alone, and the LUT only
1400/// changes when [`ForwardRenderer::refresh_sky_view`] swaps a finished build
1401/// in. [`crate::sky_pass`] still encodes [`SkyView::rows`] and its aerial LUT's
1402/// rows per frame, because those are writes into the frame's own ring slots
1403/// rather than projections.
1404#[derive(Clone, Debug)]
1405struct PresentedSky {
1406    /// The normalised sun and viewpoint the LUT was marched for, which is what
1407    /// [`ForwardRenderer::refresh_sky_view`] compares this frame's atmosphere
1408    /// against.
1409    parameters: crcbl_shaders::atmosphere::Atmosphere,
1410    /// The marched LUT: what [`crate::sky_pass`] uploads and the background
1411    /// samples.
1412    view: SkyView,
1413    /// [`SkyView::gradient_fit`], which `ssr.slang` reflects with and the sky
1414    /// pass's block carries.
1415    gradient: crcbl_shaders::sky::SkyGradient,
1416    /// [`SkyView::irradiance`], which is the frame block's L1 ambient term.
1417    irradiance: crcbl_shaders::probe::GpuProbe,
1418}
1419
1420impl PresentedSky {
1421    /// Takes both projections from a LUT that has just been marched.
1422    fn new(parameters: crcbl_shaders::atmosphere::Atmosphere, view: SkyView) -> Self {
1423        Self {
1424            parameters,
1425            gradient: view.gradient_fit(),
1426            irradiance: view.irradiance(),
1427            view,
1428        }
1429    }
1430}
1431
1432/// What [`ForwardRenderer::begin_frame`] fitted for the whole frame, kept so a
1433/// secondary view begun after it writes its blocks against the same sun, light
1434/// rows and shadow matrices the primary camera's were written against.
1435///
1436/// Everything here is decided by the primary camera and drawn once: the rows
1437/// carry the shadow tiles the primary camera's selection handed out, and the
1438/// cascades are fitted to its frustum. A secondary view samples the maps those
1439/// passes drew — `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
1440#[derive(Clone, Debug)]
1441struct FrameScene {
1442    light: DirectionalLight,
1443    rows: Vec<crcbl_shaders::light::GpuLight>,
1444    cascades: Cascades,
1445    shadow_view_proj: [[f32; 16]; shadow::CASCADES],
1446    light_view_proj: [[f32; 16]; shadow::LIGHT_TILES],
1447    atlas_rects: [[f32; 4]; shadow::TILES],
1448}
1449
1450/// The bucket and level tables a scene's generators are all built from, kept
1451/// so [`ForwardRenderer::create_view`] can build one more after `build` has
1452/// returned.
1453#[derive(Debug)]
1454struct DrawTables {
1455    bucket_meshes: Vec<u32>,
1456    bucket_clusters: Vec<u32>,
1457    bucket_cluster_bases: Vec<u32>,
1458    mesh_levels: Vec<level_select::MeshLevels>,
1459    level_groups: Vec<level_select::LevelGroup>,
1460    level_meshes: Vec<u32>,
1461    instance_capacity: u32,
1462    light_capacity: u32,
1463}
1464
1465/// The primary frame attachments an overlay may use before antialiasing and
1466/// render-scale reconstruction.
1467///
1468/// `display` is the display-space image the tonemap and post-tonemap overlays
1469/// have written. `depth` is the matching internal scene depth image, retained
1470/// as a read-only attachment for depth-tested overlays. Both have
1471/// `internal_extent` dimensions.
1472#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1473pub struct ForwardOverlayTargets {
1474    pub display: ImageId,
1475    pub depth: ImageId,
1476    pub internal_extent: (u32, u32),
1477}
1478
1479/// Everything the forward frame owns, created once.
1480#[derive(Debug)]
1481pub struct ForwardRenderer {
1482    // Geometry: the global pools, and the meshes resident in them. Each
1483    // range is resolved once, at build, and `MeshPool::mesh` only hands one out
1484    // for a mesh whose upload has completed — so there is no way to reach a
1485    // draw below with a mesh the GPU has not received.
1486    pool: MeshPool,
1487    /// The dynamic offset of each bucket's [`mesh::DrawConstants`] block, in
1488    /// [`SceneDesc::meshes`] order. Its length is the bucket count, which
1489    /// [`buckets_for`] says is a property of the path as well as of the scene.
1490    ///
1491    /// **The whole of what the CPU still says per draw.** Everything else a
1492    /// draw needs — how many instances, which indices, which vertices — is in
1493    /// the arguments the GPU wrote or in a table it resolves them through.
1494    bucket_constants: Vec<u32>,
1495    /// What one draw region adds to a bucket's offsets — the same for every
1496    /// generator this renderer built, because they share one bucket table.
1497    region_step: RegionStep,
1498    /// The material mode of each bucket, in the same order — the copy the
1499    /// **passes** read, where `DrawGen`'s copy is the one the GPU scatters
1500    /// against.
1501    ///
1502    /// What it is for: the depth prepass and the shadow atlas partition their
1503    /// call list on it and bind a pipeline per partition, so an opaque mesh in a
1504    /// scene with a cutout in it keeps the vertex-only stage. See
1505    /// [`ForwardRenderer::depth_partitions`].
1506    ///
1507    /// All zeroes for a scene whose materials are all opaque — every demo and
1508    /// every golden in this tree — which is exactly one bucket per mesh and one
1509    /// partition, byte for byte the stream they recorded before modes existed.
1510    bucket_modes: Vec<u32>,
1511
1512    // The instance array, and the objects' places in it. Nothing here is
1513    // rewritten per frame: the pool uploads what a caller changed and nothing
1514    // else, so a scene nobody moved costs no transfer at all.
1515    instances: InstancePool,
1516    /// The mesh table id of each description mesh's **level 0**, in
1517    /// [`SceneDesc::meshes`] order — what an [`InstanceDesc::mesh`] index
1518    /// resolves through.
1519    ///
1520    /// Level 0's and not the whole run, because that is the entry an instance
1521    /// carries: `cull.slang` reads a bounding box out of it and a DAG's coarser
1522    /// levels approximate the same surface inside the same box. The coarser
1523    /// entries are resident and no instance names one — a cluster reaches its
1524    /// own level's vertices through
1525    /// [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`], and the
1526    /// uniform cut reaches them through the bucket table.
1527    ///
1528    /// Kept rather than resolved per call because every write of an instance
1529    /// writes the whole record, and an instance that lost its mesh id would
1530    /// resolve to entry 0 — which is a mesh, and the wrong one.
1531    mesh_ids: Vec<u32>,
1532    /// Level 0's pool handle for each description mesh that can be skinned, in
1533    /// [`SceneDesc::meshes`] order, and [`None`] for the ones that cannot — see
1534    /// [`ResidentMesh::skinnable`].
1535    ///
1536    /// What [`ForwardRenderer::reserve_skinned`] resolves an
1537    /// [`InstanceDesc::mesh`] index through. Kept rather than looked up, because
1538    /// there is no way back from a table id to the handle that owns it: an id is
1539    /// a bare index and a [`MeshHandle`] is generational.
1540    skinnable_meshes: Vec<Option<MeshHandle>>,
1541    /// Every object [`ForwardRenderer::add_skinned_instance`] placed, with the
1542    /// two base vertices it alternates between.
1543    ///
1544    /// The list [`ForwardRenderer::begin_skinned_frame`] walks to point each one
1545    /// at the half of its region *this* frame's dispatch fills. Entries whose
1546    /// instance has gone stale are dropped as it walks, so
1547    /// [`ForwardRenderer::remove_instance`] needs to know nothing about
1548    /// skinning.
1549    skinned_instances: Vec<SkinnedInstance>,
1550
1551    /// §3.2's material table, and the rows in it.
1552    ///
1553    /// One buffer shared by every frame's bind group, not a ring — see
1554    /// [`crate::material_table`], which is where that decision lives.
1555    materials: MaterialTable,
1556    /// The table row of each description material, in [`SceneDesc::materials`]
1557    /// order — what an [`InstanceDesc::material`] index resolves through.
1558    ///
1559    /// Kept for the reason [`ForwardRenderer::mesh_ids`] is: a `set` writes the
1560    /// whole record, and an instance that lost its material id would name row 0
1561    /// by accident, which is a material and only *happens* to be the untinted
1562    /// one.
1563    material_ids: Vec<u32>,
1564    /// Topic 50's irradiance grid, row by row.
1565    ///
1566    /// One buffer shared by every frame's bind group, like the material table
1567    /// and for a stronger version of its reason: a probe is written when the
1568    /// scene is made resident and there is no call that rewrites one. See
1569    /// [`crate::probe`].
1570    probes: ProbeTable,
1571    /// Where those rows are, which rides in the frame block rather than in a
1572    /// buffer of its own — a fragment needs it before it knows which row to
1573    /// fetch.
1574    ///
1575    /// Kept rather than re-derived because [`SceneDesc`] is read once, at build.
1576    /// [`ProbeVolume::default`](crcbl_shaders::probe::ProbeVolume::default) is a
1577    /// grid of nothing, which is what a description with no probes leaves here
1578    /// and what makes the whole feature add zero.
1579    probe_volume: crcbl_shaders::probe::ProbeVolume,
1580    /// §3.2's texture side: one `D2Array` image whose layers the material rows
1581    /// index. One page, bound once, for every material — see the module docs on
1582    /// why this is [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) and not
1583    /// a bindless descriptor array.
1584    base_color_page: UploadedTexture,
1585    /// §2's second page: one `D2Array` image of tangent-space normals, whose
1586    /// layers [`GpuMaterial::normal_texture`](mesh::GpuMaterial::normal_texture)
1587    /// indexes.
1588    ///
1589    /// The base-colour page's own shape at [`NORMAL_PAGE_BINDING`], sampled
1590    /// through the same UV and the same sampler, and **created linear** — see
1591    /// [`NORMAL_PAGE_FORMAT`]. Its extent is its own: a description sizes each
1592    /// [`PageKind`] separately, so a 512² normal page beside a 2048²
1593    /// base-colour one is what the caller wrote and what this holds.
1594    normal_page: UploadedTexture,
1595    /// §2's third page: one `D2Array` image of glTF's packed occlusion,
1596    /// roughness and metallic, whose layers
1597    /// [`metallic_roughness_occlusion_texture`](mesh::GpuMaterial::metallic_roughness_occlusion_texture)
1598    /// indexes.
1599    ///
1600    /// The normal page's own shape at [`MRO_PAGE_BINDING`], sampled through the
1601    /// same UV and the same sampler, and **created linear** — see
1602    /// [`MRO_PAGE_FORMAT`].
1603    mro_page: UploadedTexture,
1604    /// §2's fourth page: one `D2Array` image of emitted radiance, whose layers
1605    /// [`emissive_texture`](mesh::GpuMaterial::emissive_texture) indexes.
1606    ///
1607    /// The base-colour page's own shape at [`EMISSIVE_PAGE_BINDING`], and
1608    /// **created sRGB** rather than linear, because an emissive texel is a
1609    /// colour — see [`EMISSIVE_PAGE_FORMAT`].
1610    emissive_page: UploadedTexture,
1611    /// Each [`PageKind`]'s image size in texels, as a width and a height,
1612    /// indexed by [`PageKind::index`].
1613    ///
1614    /// Square, because [`PageDesc`](crate::scene::PageDesc) carries one extent
1615    /// per kind rather than a rectangle. `(1, 1)` for a kind the description
1616    /// named no layer of, which is the placeholder's extent and not the
1617    /// description's — see [`PAGE_PLACEHOLDER_TEXEL`]. Kept rather than
1618    /// re-derived because [`add_passes`](Self::add_passes) declares both pages
1619    /// to the graph and an [`ImportedImage`] names an extent, and the
1620    /// description they came from is the caller's, read once at build.
1621    page_extents: [(u32, u32); PageKind::ALL.len()],
1622    /// The sampler the page is read through.
1623    base_color_sampler: SamplerHandle,
1624    /// The anisotropy [`ForwardRenderer::base_color_sampler`] was created
1625    /// with, after [`set_anisotropy`](ForwardRenderer::set_anisotropy)'s clamp.
1626    anisotropy: f32,
1627    /// How many layers each [`PageKind`]'s page holds, indexed by
1628    /// [`PageKind::index`] — zero for a kind the description named none of.
1629    ///
1630    /// What [`replace_page`](ForwardRenderer::replace_page) holds a
1631    /// replacement to, so every material row's layer number goes on naming the
1632    /// same texture.
1633    page_layers: [usize; PageKind::ALL.len()],
1634    /// `[frame]`: the page sampler and the four page views that slot's
1635    /// mesh-layout groups name.
1636    ///
1637    /// A slot moves onto [`ForwardRenderer::page_bindings`] at its own
1638    /// `begin_frame` and not before — see [`ForwardRenderer::adopt_pages`] —
1639    /// so this is what says which slots still name a sampler
1640    /// [`set_anisotropy`](ForwardRenderer::set_anisotropy) replaced or a page
1641    /// [`replace_page`](ForwardRenderer::replace_page) did.
1642    slot_pages: Vec<PageBindings>,
1643    /// Page samplers and pages replaced while some slot may still name them.
1644    /// Each is destroyed as the last slot naming it moves off, or at
1645    /// [`destroy`](ForwardRenderer::destroy).
1646    retired_pages: Vec<RetiredPage>,
1647
1648    /// Draw calls the last [`ForwardRenderer::add_passes`] recorded — see
1649    /// [`ForwardRenderer::counters`], which is the only thing that reads it.
1650    ///
1651    /// Kept rather than recomputed because the shadow pass's share is the number
1652    /// of **occupied** tiles, which [`ForwardRenderer::add_shadow_pass`] works
1653    /// out from topic 45's tile allocation and nothing outside
1654    /// it can restate without becoming the second copy that drifts.
1655    recorded_draws: u64,
1656    /// Which call the forward pass records — the device's [`GeometryPath`],
1657    /// resolved once.
1658    emit: EmitTail,
1659    /// The most buckets one call of the geometry passes draws, or `None` where
1660    /// they record a call per bucket — [`EmitTail::range_limit`], resolved at
1661    /// build with [`emit`](Self::emit) and for its reason.
1662    range_limit: Option<u32>,
1663    /// §3.5's clusters, and **only on [`EmitTail::Mesh`]**: the two indirect
1664    /// tails draw the same geometry out of the index pool and read none of
1665    /// this. `None` is therefore the ordinary state on most devices rather than
1666    /// a failure, and it is also what makes a fall-through impossible — see
1667    /// [`ForwardRenderer::geometry_path`].
1668    clusters: Option<ClusterPool>,
1669    /// Whether the mesh pipeline was built with §3.5's amplification stage in
1670    /// front of it — see [`ForwardRenderer::culls_clusters`], which is where
1671    /// what it means is written down.
1672    culls_clusters: bool,
1673    /// Where each description mesh's clusters are in
1674    /// [`ForwardRenderer::clusters`] — every level of it, as one run, in
1675    /// [`SceneDesc::meshes`] order. Empty off the mesh path, where there is no
1676    /// cluster pool at all. See [`ForwardRenderer::cluster_range`].
1677    mesh_clusters: Vec<ClusterRange>,
1678    /// The bucket each level of each description mesh draws through, finest
1679    /// first, in [`SceneDesc::meshes`] order — and empty on the mesh path. See
1680    /// [`ForwardRenderer::level_buckets`].
1681    ///
1682    /// **The run for the scene's first material mode**, which is `OPAQUE`
1683    /// wherever the scene has an opaque material at all: the table is every
1684    /// mesh's levels once per mode the scene holds, mode by mode, and this
1685    /// names a mesh's levels in the first of those runs. See
1686    /// [`ForwardRenderer::bucket_modes`].
1687    mesh_level_buckets: Vec<Vec<u32>>,
1688    /// The pixel budget topic 25's descent compares a group's
1689    /// projected error against. [`LOD_ERROR_BUDGET`] until
1690    /// [`ForwardRenderer::set_lod_error_budget`] says otherwise.
1691    lod_error_budget: f32,
1692    /// How far below that an expanded group is held before it collapses again.
1693    /// [`LOD_HOLD_RATIO`] until
1694    /// [`ForwardRenderer::set_lod_hold_ratio`] says otherwise.
1695    lod_hold_ratio: f32,
1696    /// The same three numbers the shadow cascades selected under, which is
1697    /// [`ForwardRenderer::lod_params`] with both budgets scaled by
1698    /// [`SHADOW_LOD_BIAS`] and the same pixels-per-unit.
1699    ///
1700    /// Kept beside the camera's for its reason: a reader comparing the two cuts
1701    /// takes both pairs from here rather than re-deriving the bias, which would
1702    /// be comparing two copies of one arithmetic instead of two selections.
1703    shadow_lod_params: [f32; 3],
1704
1705    /// The lights a caller set beside the sun, as
1706    /// [`ForwardRenderer::set_lights`] was handed them.
1707    ///
1708    /// Kept rather than converted on the way in, because a row is the *frame's*
1709    /// artefact: the sun arrives per frame at
1710    /// [`begin_frame`](ForwardRenderer::begin_frame) and is row 0, so the list a
1711    /// frame uploads cannot be assembled until then.
1712    extra_lights: Vec<Light>,
1713
1714    /// One [`mesh::DrawConstants`] block per draw, a device dynamic-offset
1715    /// alignment apart. Shared by every frame's bind group rather than ringed,
1716    /// because nothing rewrites it after `build`: a mesh's base vertex and an
1717    /// object's instance index are decided when the pools allocate them.
1718    draw_constants: BufferHandle,
1719    /// The camera's resources and history — see [`view`], which is where the
1720    /// line between a camera's state and the scene's is drawn.
1721    primary: View,
1722    /// Every secondary view [`ForwardRenderer::create_view`] built, indexed by
1723    /// [`ViewId::index`] less one — a free id is `None`.
1724    views: Vec<Option<View>>,
1725    /// The tables a view's generator is built from — see [`DrawTables`].
1726    draw_tables: DrawTables,
1727    /// Counts every [`begin_frame`](ForwardRenderer::begin_frame), so a view can
1728    /// say which frame it was last begun for — see [`View::begun`].
1729    frame_serial: u64,
1730    /// The frame the last `begin_frame` opened, for
1731    /// [`begin_view`](ForwardRenderer::begin_view). `None` before the first.
1732    frame_scene: Option<FrameScene>,
1733    /// Which frame-in-flight slot is current. Set from
1734    /// [`InstancePool::begin_frame`]'s return rather than counted here, so the
1735    /// uniform ring and the instance ring cannot drift apart.
1736    frame: usize,
1737
1738    mesh_layout: BindGroupLayoutHandle,
1739    mesh_pipeline_layout: PipelineLayoutHandle,
1740    mesh_pipeline: SidedPipelines,
1741    /// [`ForwardRenderer::mesh_pipeline`] again in
1742    /// [`PolygonMode::Line`], for
1743    /// [`set_wireframe`](ForwardRenderer::set_wireframe).
1744    ///
1745    /// [`None`] until a caller first switches the view on — the ground grid's
1746    /// arrangement exactly, and for its reason: a second pipeline compiled at
1747    /// build would be paid for by every sample, golden and headless run that
1748    /// never asks for a wireframe, which is all of them. Once built it is kept,
1749    /// because switching the view off is
1750    /// [`ForwardRenderer::wireframe_on`] and not a release.
1751    ///
1752    /// **A pair, like the pipeline it replaces**, because [`PolygonMode::Line`]
1753    /// does not disable culling: a single-sided wireframe drawn over a
1754    /// double-sided bucket would leave a surface out of the debug view that the
1755    /// shaded frame beside it draws, which is a view of the document that
1756    /// disagrees with the document.
1757    wireframe_pipeline: Option<SidedPipelines>,
1758    /// Whether [`add_passes`](ForwardRenderer::add_passes) drives the forward
1759    /// pass through [`ForwardRenderer::wireframe_pipeline`]. **`false` by
1760    /// default**: a wireframe is a tool's view of a document, and every sample
1761    /// and every golden image predates it.
1762    wireframe_on: bool,
1763    /// The occlusion and small-feature culls a caller asked for — see
1764    /// [`set_occlusion_culling`](ForwardRenderer::set_occlusion_culling).
1765    occlusion_culling: OcclusionCulling,
1766    /// Whether a point light's six faces cull separately — see
1767    /// [`set_point_face_culls`](ForwardRenderer::set_point_face_culls).
1768    point_face_culls: bool,
1769    /// What a test asked every shadow view's uploaded block to be rewritten
1770    /// with — see
1771    /// [`set_shadow_view_tamper`](ForwardRenderer::set_shadow_view_tamper).
1772    /// [`None`] outside a test.
1773    shadow_view_tamper: Option<fn(&mut mesh::FrameUniforms)>,
1774    /// Whether [`begin_frame`](ForwardRenderer::begin_frame) writes
1775    /// [`FrameUniforms::NORMALS_VIEW_ON`] into the frame block, which makes
1776    /// `mesh.slang`'s fragment stage draw world-space normals instead of shading
1777    /// — see [`set_normals_view`](ForwardRenderer::set_normals_view).
1778    ///
1779    /// **`false` by default**, on [`ForwardRenderer::wireframe_on`]'s terms
1780    /// exactly: it is a tool's view of a document, and every sample and every
1781    /// golden image predates it.
1782    ///
1783    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
1784    normals_view: bool,
1785
1786    /// The exponential height fog the colour pass composites over its
1787    /// radiance — see [`set_fog`](ForwardRenderer::set_fog).
1788    ///
1789    /// **[`Fog::NONE`] by default**, on [`normals_view`](Self::normals_view)'s
1790    /// terms: a caller who never asks for fog draws the frame this renderer
1791    /// drew before the feature existed, and exactly that frame — the shader's
1792    /// composite is an identity at zero density rather than an interpolation
1793    /// that nearly is.
1794    fog: Fog,
1795
1796    /// The gradient sky whose irradiance the colour pass adds to the ambient
1797    /// term — see [`set_sky`](ForwardRenderer::set_sky).
1798    ///
1799    /// **[`Sky::NONE`] by default**, on [`fog`](Self::fog)'s terms: a black
1800    /// gradient projects to coefficients that are all zero, so the three dot
1801    /// products the fragment stage adds are zero and no frame drawn before a
1802    /// sky existed moves.
1803    sky: Sky,
1804    /// The atmosphere that **replaces** [`Self::sky`] when a caller sets one —
1805    /// see [`set_atmosphere`](ForwardRenderer::set_atmosphere).
1806    ///
1807    /// `None` by default, so a renderer nobody calls that on is the renderer it
1808    /// was.
1809    atmosphere: Option<Atmosphere>,
1810    /// The marched sky-view LUT this renderer is drawing, with the parameters
1811    /// it was marched for and the projections taken from it.
1812    ///
1813    /// **Cached against the parameters rather than rebuilt per frame**, because
1814    /// the march is tens of milliseconds of CPU and the sun in most frames has
1815    /// not moved. The stored parameters are the *normalised* ones the shader
1816    /// crate takes, so a caller handing over the same sun spelled two lengths
1817    /// does not force a rebuild.
1818    ///
1819    /// This is the LUT a frame is **drawn from**, which is not the one being
1820    /// marched: see [`Self::sky_view_build`].
1821    sky_view: Option<PresentedSky>,
1822    /// The march in flight, when the sun has moved away from
1823    /// [`Self::sky_view`]'s.
1824    ///
1825    /// [`ForwardRenderer::refresh_sky_view`] steps it
1826    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame and swaps it into
1827    /// [`Self::sky_view`] when it finishes.
1828    ///
1829    /// **The host side is where the double buffer is**: the LUT being drawn and
1830    /// the LUT being marched are these two fields, and [`crate::sky_pass`]'s
1831    /// device ring is untouched. Putting the stripe on the device instead would
1832    /// mean writing part of a ring slot per frame, and that ring's slots are
1833    /// written whole precisely because each is a frame in flight — a partial
1834    /// write would have to track, per slot, which rows of *which* sun that slot
1835    /// already holds, which is bookkeeping the host copy does not need at all.
1836    sky_view_build: Option<SkyViewBuild>,
1837
1838    /// Whether the colour pass tints each cluster by its DAG level instead of
1839    /// shading — see [`set_lod_view`](ForwardRenderer::set_lod_view).
1840    ///
1841    /// **Wins over [`normals_view`](Self::normals_view) when both are set**,
1842    /// because one uniform lane carries both switches and the fragment stage
1843    /// tests the LOD threshold first. `crcbl_shaders`'
1844    /// `the_lod_view_threshold_lies_above_the_normals_view` is what keeps that
1845    /// order true.
1846    lod_view: bool,
1847
1848    /// Whether the colour pass shades each cluster by the projected error the
1849    /// LOD selection judged it on, instead of shading it or tinting it — see
1850    /// [`set_heatmap`](ForwardRenderer::set_heatmap).
1851    ///
1852    /// **Wins over both [`lod_view`](Self::lod_view) and
1853    /// [`normals_view`](Self::normals_view)**, on the same terms and for the same
1854    /// reason: one uniform lane carries all three switches and the shaders test
1855    /// the outermost threshold first. `crcbl_shaders`'
1856    /// `the_heatmap_view_threshold_lies_above_the_lod_view` is what keeps that
1857    /// order true, and
1858    /// `the_three_debug_views_resolve_in_one_order_however_they_are_set` is what
1859    /// holds this side to it.
1860    heatmap: bool,
1861
1862    /// Whether the colour pass draws the ambient-occlusion channel as grey
1863    /// instead of shading — see
1864    /// [`set_occlusion_view`](ForwardRenderer::set_occlusion_view).
1865    ///
1866    /// **Wins over every other view**, on [`heatmap`](Self::heatmap)'s terms and
1867    /// for its reason: one uniform lane, outermost threshold first.
1868    /// `crcbl_shaders`' `the_occlusion_view_threshold_lies_above_the_heatmap` is
1869    /// what keeps that order true, and
1870    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1871    /// this side to it.
1872    occlusion_view: bool,
1873
1874    /// Whether the colour pass draws the motion vector instead of shading — see
1875    /// [`set_motion_view`](ForwardRenderer::set_motion_view).
1876    ///
1877    /// **Wins over every other view**, on [`occlusion_view`](Self::occlusion_view)'s
1878    /// terms and for its reason: one uniform lane, outermost threshold first.
1879    /// `crcbl_shaders`' `the_motion_view_threshold_lies_above_the_occlusion_view`
1880    /// is what keeps that order true, and
1881    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1882    /// this side to it.
1883    motion_view: bool,
1884    /// Whether the colour pass draws the occlusion channel's bent direction
1885    /// instead of shading — see
1886    /// [`set_bent_normal_view`](ForwardRenderer::set_bent_normal_view).
1887    ///
1888    /// **Wins over every other view**, on [`motion_view`](Self::motion_view)'s
1889    /// terms: it is the outermost sentinel in the lane, and
1890    /// `crcbl_shaders`' `the_bent_normal_view_threshold_lies_above_the_motion_view`
1891    /// is what holds the shader's branch order to it.
1892    bent_normal_view: bool,
1893
1894    /// Whether the colour pass tints the shaded picture by the cascade each
1895    /// sun-lit fragment's shadow was sampled from — see
1896    /// [`set_cascade_view`](ForwardRenderer::set_cascade_view).
1897    ///
1898    /// **Loses to every other view**, which is the opposite of every field
1899    /// above and for the reason [`DebugView::Cascades`] carries: every one of them
1900    /// replaces the shaded picture and this one multiplies it, so a frame drawing
1901    /// any of them has nothing for this tint to reach. `crcbl_shaders`'
1902    /// `the_cascade_view_threshold_lies_below_every_replacing_view` is what
1903    /// holds the shader to the same order, from the other end of the lane.
1904    cascade_view: bool,
1905
1906    /// Whether the frame draws the shadow atlas over the finished picture — see
1907    /// [`set_atlas_view`](ForwardRenderer::set_atlas_view).
1908    ///
1909    /// **Not a lane of the frame block**, unlike every field above: this view is
1910    /// a pass rather than a branch in `mesh.slang`, so what reads this is
1911    /// [`ForwardRenderer::add_passes`] deciding whether to record
1912    /// [`crate::atlas_view`]'s. It resolves below every replacing view and above
1913    /// [`cascade_view`](Self::cascade_view) — see
1914    /// [`ForwardRenderer::debug_view`].
1915    atlas_view: bool,
1916
1917    /// Where [`begin_frame`](ForwardRenderer::begin_frame) projects
1918    /// topic 25's selection from, when that is not the camera's own
1919    /// eye — see
1920    /// [`set_frozen_selection_eye`](ForwardRenderer::set_frozen_selection_eye).
1921    ///
1922    /// **[`None`] is not a position, it is "follow the camera"**, and it is what
1923    /// every frame the engine has drawn so far did: the eye handed to
1924    /// [`DrawGen::begin_frame`] is `camera.eye`, byte for byte, so a caller that
1925    /// never sets this writes the parameter block it wrote before this field
1926    /// existed.
1927    ///
1928    /// **Not a [`DebugView`]**, and deliberately: the three views are one
1929    /// picture chosen between, while this is a change to what the *selection*
1930    /// answers and leaves the picture's choice alone. A reviewer freezing the
1931    /// cut and then reading it off the LOD tint is the combination the feature
1932    /// exists for, so the two cannot be alternatives.
1933    frozen_selection_eye: Option<Vec3>,
1934
1935    /// Topic 18's shadow atlas: one `D32Float` image holding
1936    /// [`shadow::TILES`] square tiles in a fixed grid — the sun's cascades
1937    /// first, then one per shadowed light.
1938    ///
1939    /// Owned here rather than created by the graph per frame, because its
1940    /// extent is a **quality setting and not a window size** — nothing about it
1941    /// changes on a resize, so a transient would be re-created for no reason
1942    /// and could not be read back by a test that does not own the graph.
1943    shadow_atlas: ImageHandle,
1944    shadow_atlas_view: ImageViewHandle,
1945    /// A 1×1 depth image that exists so the depth-only pipeline's bind group can
1946    /// fill [`SHADOW_ATLAS_BINDING`] without naming the atlas it is writing.
1947    ///
1948    /// Both halves of that sentence are forced:
1949    ///
1950    /// * **The slot has to be filled.** Slang's Metal backend materialises every
1951    ///   global into every entry point — `msl/mesh.metal`'s `vertexMain` takes
1952    ///   `shadow_atlas [[texture(1)]]` whether it reads it or not — so a
1953    ///   depth-only pipeline sharing this layout still declares the argument. A
1954    ///   layout with the slot removed would break Metal alone, on a runner this
1955    ///   team cannot debug on, which is the trap binding 6's comment already
1956    ///   records.
1957    /// * **It cannot be the atlas.** WebGPU refuses a texture that is a render
1958    ///   attachment and a bind-group resource in the same pass, and the shadow
1959    ///   pass is exactly that pass.
1960    ///
1961    /// Nothing samples it: the shadow pipeline has no fragment stage. It is
1962    /// brought into the graph beside the atlas so its layout transition is the
1963    /// graph's like every other, rather than a hand-written barrier.
1964    shadow_placeholder: ImageHandle,
1965    shadow_placeholder_view: ImageViewHandle,
1966    /// The **comparison** sampler the atlas is read through — hardware PCF.
1967    shadow_sampler: SamplerHandle,
1968    /// The depth-only pipeline every tile is rendered with — and, driven with
1969    /// the camera's own draws, the depth prepass's: `mesh.slang`'s
1970    /// `depthVertexMain` where the geometry comes from a vertex stage, the same
1971    /// geometry stage as [`ForwardRenderer::mesh_pipeline`] where it comes from
1972    /// a mesh one, and no fragment stage in either case.
1973    shadow_pipeline: SidedPipelines,
1974    /// The same two passes' pipeline for the buckets whose material mode cuts
1975    /// an alpha mask: `vertexMain` and `depthMaskedFragmentMain` — see
1976    /// [`MeshModules::depth_masked_pipeline`].
1977    ///
1978    /// [`None`] for a scene whose materials mask nothing, such as the demo
1979    /// scene: the bucket table is fixed at build, so a scene
1980    /// without a masked bucket then never has one — see [`SidedPipelines`] for
1981    /// the twin's same argument. Which buckets are drawn with it is
1982    /// [`ForwardRenderer::depth_partitions`], and it is a **partition of one
1983    /// frame's draws** rather than a choice for the whole frame.
1984    depth_masked_pipeline: Option<SidedPipelines>,
1985    /// The pipeline that resets one tile of the atlas before it is redrawn, on a
1986    /// frame that is keeping some of the others — see
1987    /// [`MeshModules::depth_clear_pipeline`], which is where the whole argument
1988    /// for it lives.
1989    shadow_clear_pipeline: GraphicsPipelineHandle,
1990    /// The irradiance probes' reflective shadow map — see
1991    /// [`MeshModules::rsm_pipeline`]. Built only for a volume that asked for
1992    /// [`ProbeUpdate::EveryFrame`], beside [`ForwardRenderer::probe_gather`] and
1993    /// for its reason, and [`None`] everywhere else; the pass that draws the
1994    /// map is recorded only where this is `Some`.
1995    rsm_pipeline: Option<SidedPipelines>,
1996    /// The compute pass that reads that map into the probe rows, and [`None`]
1997    /// for every scene whose volume is [`ProbeUpdate::Authored`] — which is the
1998    /// whole of what the default costs such a scene: no pipeline, no buffers, no
1999    /// pass and no frame time.
2000    probe_gather: Option<ProbeGather>,
2001    /// Whether cascade 0's view block and cull parameters were written for the
2002    /// frame being recorded, so the reflective shadow map can be drawn from
2003    /// them.
2004    ///
2005    /// Not [`ForwardRenderer::shadow_group_redrawn`], which is a claim about the
2006    /// *atlas*: a frame drawing without
2007    /// [`RenderEffects::SHADOWS`](crate::effects::RenderEffects::SHADOWS) fits
2008    /// cascade 0 for the map and writes no tile, and overloading that flag would
2009    /// report a cascade as redrawn when nothing drew it.
2010    rsm_cull_ready: bool,
2011    /// What the scene said fills the probe rows.
2012    ///
2013    /// Read by [`ForwardRenderer::begin_frame`] — which keeps cascade 0 off the
2014    /// shadow atlas's static-cache hold when the updater is on, because the map
2015    /// is that cascade's own draws — and by the pass recording below.
2016    probe_update: ProbeUpdate,
2017    /// How far cascade 0 reached on the frame being recorded, which is the
2018    /// radius of the sphere it was fitted to — `crate::rsm::texel_area` is what
2019    /// reads it.
2020    ///
2021    /// Written by [`ForwardRenderer::begin_frame`] beside the cascade matrices
2022    /// themselves, rather than recomputed at pass-record time: a frame that
2023    /// scaled its gather by one cascade's footprint while drawing the map
2024    /// through another's would be a bounce that is uniformly wrong, and nothing
2025    /// in the frame could see it.
2026    cascade_reach: f32,
2027    /// The sun's colour premultiplied by its intensity, this frame.
2028    ///
2029    /// The reflective shadow map holds albedo rather than flux — `RsmOutput` in
2030    /// `mesh.slang` argues why — so this is what the gather multiplies by, and it
2031    /// is read off the same [`DirectionalLight`] the cascades were fitted to.
2032    /// The sun's *direction* is not carried beside it: the gather needs none, on
2033    /// `probe_gather.slang`'s own derivation.
2034    sun_color: Vec3,
2035    /// One cull and draw-argument pass **per cascade and per shadowed light**,
2036    /// which is topic 18's "one cull dispatch per cascade against the same
2037    /// instance/geometry pools" with a shadowed light counting as a cascade does.
2038    ///
2039    /// A whole [`DrawGen`] rather than just its cull half: the shadow pass emits
2040    /// the same indirect call the colour pass does, so it needs the same
2041    /// arguments, and there is no "cull only" constructor to reach for. The cost
2042    /// is [`DrawGen`]'s own buffers and per-instance state — see
2043    /// [`TileBuffers::group_state`], which is where that price is written down,
2044    /// and [`SHADOW_CULLS`], which is why a point light has one of these rather
2045    /// than six.
2046    ///
2047    /// **Indexed by cull**: `0..shadow::CASCADES` are the sun's and
2048    /// [`shadow_cull`] is where a light slot's is.
2049    shadow_draws: Vec<DrawGen>,
2050    /// The layouts and pipelines every [`DrawGen`] above and in each view
2051    /// dispatches, compiled once and shared rather than once per generator.
2052    ///
2053    /// This reference is the renderer's own, held so [`create_view`] can hand
2054    /// the set to a view built later; [`destroy`](Self::destroy) gives it back
2055    /// after every generator, and whichever reference goes last destroys it.
2056    ///
2057    /// [`create_view`]: Self::create_view
2058    draw_pipelines: Arc<DrawGenPipelines>,
2059    /// `[frame][view]`: a copy of the frame block whose `view_proj` **is** that
2060    /// view's matrix, so the depth-only pipeline runs the unmodified vertex and
2061    /// mesh stages rather than a second transform path.
2062    shadow_uniforms: Vec<Vec<BufferHandle>>,
2063    /// Empty between frame preparations, with capacity retained for assembly.
2064    shadow_prepare_views: Vec<(usize, usize, mesh::FrameUniforms)>,
2065    /// Empty between frame preparations, with capacity retained for frusta.
2066    shadow_prepare_culls: Vec<(usize, Frustum)>,
2067    /// `[frame][view]`: the mesh layout again, reading that view's uniforms and
2068    /// the survivors of the cull its slot owns.
2069    shadow_groups: Vec<Vec<BindGroupHandle>>,
2070    /// `[frame][view]`: the cut that view's amplification stage chose, one word
2071    /// per resident cluster — and empty where there is no such stage.
2072    ///
2073    /// **A buffer per view rather than the camera's**, unlike every other
2074    /// resource these passes share: the colour pass is recorded last and writes
2075    /// [`ForwardRenderer::cluster_selection`] over whatever a view left in it,
2076    /// so a view writing there leaves nothing behind to read. Without one of
2077    /// these the shadow pass's descent is unobservable — which is the state
2078    /// [`SHADOW_LOD_BIAS`] arrived in, and it is what a bias nothing can measure
2079    /// would have stayed in.
2080    shadow_selection: Vec<Vec<BufferHandle>>,
2081    /// Which of [`ForwardRenderer::extra_lights`] holds each shadow slot, where
2082    /// in the atlas's light region its tiles are, and the memory that keeps that
2083    /// answer from flickering.
2084    ///
2085    /// Re-run every [`ForwardRenderer::begin_frame`] and read by
2086    /// [`ForwardRenderer::add_shadow_pass`], which records a cull for each
2087    /// occupied slot and a viewport per face it has, and nothing at all for the
2088    /// free ones — so an unheld tile keeps the reversed-Z clear, which reads as
2089    /// "nothing stored, fully lit" wherever anything did sample it.
2090    shadow_lights: shadow::Selection,
2091    /// `[group]`: everything that group's maps would be drawn from, as
2092    /// [`ForwardRenderer::shadow_group_record`] spells it.
2093    ///
2094    /// Kept only to tell one frame's answer from the last one's: it is compared
2095    /// and then replaced, and what travels from there is the number below.
2096    ///
2097    /// **Per group rather than per atlas**, since the cadence rung: a group is a
2098    /// cascade or a light slot's whole run of tiles, and holding one map while
2099    /// redrawing another is the whole of what that rung buys.
2100    shadow_group_inputs: Vec<Vec<u8>>,
2101    /// `[group]`: a number that moves whenever that group's entry of
2102    /// [`ForwardRenderer::shadow_group_inputs`] does, and never comes back to a
2103    /// value it has had.
2104    ///
2105    /// So "the image already holds this" is one integer comparison, which is
2106    /// what lets the pass body below carry the answer out of the graph.
2107    shadow_group_id: Vec<u64>,
2108    /// `[group]`: how many instance writes that group's cull could have seen,
2109    /// over the renderer's life — the per-group stand-in for
2110    /// [`InstancePool::revision`] in
2111    /// [`ForwardRenderer::shadow_group_record`], moved by
2112    /// [`ForwardRenderer::note_caster_writes`].
2113    shadow_group_writes: Vec<u64>,
2114    /// `[element]`: where each element of the instance array could draw into a
2115    /// shadow map, as of the last [`ForwardRenderer::note_caster_writes`] —
2116    /// which is what a write's *before* is read from. Grows to the highest
2117    /// element written; an element past its end has never been written and is
2118    /// [`shadow_inputs::CasterFootprint::Nowhere`].
2119    shadow_footprints: Vec<shadow_inputs::CasterFootprint>,
2120    /// The live elements whose mesh has a DAG, and so whose level the selection
2121    /// eye chooses — the ones that put the eye into a light group's record.
2122    shadow_dag_elements: std::collections::BTreeSet<u32>,
2123    /// Scratch for [`InstancePool::take_written`], kept so a frame that moved
2124    /// an instance does not allocate its list.
2125    shadow_written: Vec<u32>,
2126    /// This frame's written elements' footprints, before and after the write,
2127    /// from [`ForwardRenderer::note_caster_writes`] for
2128    /// [`shadow_inputs::shadow_groups_reached`]. Empty on a frame nothing was
2129    /// written in.
2130    shadow_moved: Vec<(
2131        shadow_inputs::CasterFootprint,
2132        shadow_inputs::CasterFootprint,
2133    )>,
2134    /// The number given to the shadow pass this renderer recorded last.
2135    ///
2136    /// Moves once per recorded pass, so the body below can say *which* pass ran
2137    /// with one integer.
2138    shadow_pass_id: u64,
2139    /// The [`ForwardRenderer::shadow_pass_id`] of the last shadow pass that
2140    /// **ran**, written by that pass's own body.
2141    ///
2142    /// By the body rather than by the call that recorded it, and that is the
2143    /// whole of why this is shared state rather than a plain field: a frame
2144    /// whose graph was refused — or built and dropped — recorded a pass that
2145    /// never executed, so the image still holds whatever the frame before it
2146    /// left there. `a_refused_frame_leaves_the_shadow_atlas_where_it_was` is
2147    /// that case, and it is the same boundary [`TransientPool`]'s ledger of
2148    /// imported images uses for the same reason.
2149    ///
2150    /// Zero until a pass has run, and the ids start above it, so the first frame
2151    /// of all draws.
2152    shadow_pass_ran: Arc<AtomicU64>,
2153    /// What the shadow pass recorded last would leave the image holding, if its
2154    /// body ran.
2155    ///
2156    /// Taken and applied by the next [`ForwardRenderer::begin_frame`], which is
2157    /// the only place that can tell whether it did — see
2158    /// [`ForwardRenderer::shadow_pass_ran`].
2159    shadow_pending: Option<ShadowCommit>,
2160    /// `[group]`: the id, the centre that group's maps were projected from and
2161    /// how far they reach, as the record the **image** holds describes them.
2162    ///
2163    /// The id is what says a map is out of date. The centre and reach are what
2164    /// say it is about somewhere else: a map whose own centre has moved further
2165    /// than its own reach covers ground it was never drawn for, and holding
2166    /// that is worse than a shadow that lags — see
2167    /// [`ForwardRenderer::shadow_cadence_reset`].
2168    shadow_group_held: Vec<(u64, Vec3, f32)>,
2169    /// `[group]`: whether this frame redraws that group's maps.
2170    ///
2171    /// Frozen by [`ForwardRenderer::begin_frame`] for
2172    /// [`ForwardRenderer::frame_effects`]' reason: this call decides it and
2173    /// `add_passes` acts on it, and a value that moved between them would skip
2174    /// a cull whose draws were recorded, or the other way about.
2175    shadow_group_redrawn: Vec<bool>,
2176    /// Where every atlas slot's map was laid out on the frame the **image** was
2177    /// drawn from, so a frame can tell whether the texels it is keeping still
2178    /// describe the layout it is about to sample through.
2179    ///
2180    /// A layout that has moved is what makes a frame clear the whole attachment
2181    /// and redraw every group: a tile left over from a different layout is
2182    /// texels nothing this frame can account for. Promoted beside
2183    /// [`ForwardRenderer::shadow_group_held`].
2184    ///
2185    /// [`None`] until a pass has drawn, which is **not** the layout a frame
2186    /// with shadows off produces: an image no pass has touched holds undefined
2187    /// memory rather than a clear, so the first frame of all has to write one
2188    /// whatever it is asked for.
2189    shadow_atlas_layout: Option<Vec<shadow::TileRect>>,
2190    /// Whether any map this frame samples is one an earlier frame drew, rather
2191    /// than one this frame did.
2192    ///
2193    /// The cadence's own readback — see
2194    /// [`ForwardRenderer::shadow_atlas_cached`], which is this for the whole
2195    /// atlas.
2196    shadow_atlas_cached: bool,
2197    /// Whether this frame ignored the cadence because some map's region moved
2198    /// out from under it — see [`ForwardRenderer::shadow_cadence_reset`].
2199    shadow_cadence_reset: bool,
2200    /// How many tiles this frame redraws — see
2201    /// [`ForwardRenderer::shadow_faces_redrawn`].
2202    shadow_faces_redrawn: u32,
2203    /// A shadow cadence the caller pinned, or [`None`] to take the console's.
2204    ///
2205    /// [`ForwardRenderer::set_effect_request`]'s shape at this knob and for its
2206    /// reason: `shadow::r_shadow_cadence` and `shadow::r_shadow_faces` are
2207    /// process-global, and an application that wants a tier's own pair — or a
2208    /// test that wants a frame nothing else in the process can move — needs one
2209    /// that is not.
2210    shadow_cadence_request: Option<shadow::Cadence>,
2211    /// Whether this frame's shadow pass clears the whole attachment, rather
2212    /// than loading it and resetting only the tiles it redraws.
2213    ///
2214    /// Frozen beside [`ForwardRenderer::shadow_group_redrawn`] and for its
2215    /// reason: the decision is `begin_frame`'s and the recording is
2216    /// `add_shadow_pass`'s, and a value that moved between them would load an
2217    /// attachment whose tiles nothing had reset.
2218    shadow_atlas_clears: bool,
2219    /// How many frames have been opened, which is what the cadence is keyed to.
2220    ///
2221    /// **Monotonic, unlike [`ForwardRenderer::frame`]**, which is the index of
2222    /// the frame in flight and wraps every [`FRAMES_IN_FLIGHT`]. A schedule
2223    /// keyed to that would repeat every few frames and bound nothing.
2224    shadow_frame: u64,
2225    /// Whether this frame dispatches skinning, and so rewrites part of the
2226    /// vertex pool the shadow pass draws from.
2227    ///
2228    /// The atlas's one **always redraw**: a skinned caster's vertices are
2229    /// produced by a compute pass into the pool, so there is nothing on the
2230    /// host to compare a frame's geometry against — the palette a caller hands
2231    /// over is not the vertices, and the vertices are never read back. Set by
2232    /// [`ForwardRenderer::begin_skinned_frame`], which is the only call that
2233    /// can make it true, and cleared by [`ForwardRenderer::begin_frame`], which
2234    /// dispatches none.
2235    frame_skins: bool,
2236
2237    /// Topic 03 §3.6's one permitted readback: the camera cull's statistics, on
2238    /// a delayed ring — see [`crate::cull_stats`], which is where the shape and
2239    /// the latency are argued.
2240    ///
2241    /// **The camera's cull only.** [`ForwardRenderer::shadow_draws`] each have a
2242    /// statistics buffer of their own and none of them is read: a cascade's
2243    /// survivor count is a different question about a different frustum, and
2244    /// added into this one it would produce a number larger than the pool holds.
2245    ///
2246    /// [`None`] on a device that would not give out the buffers, which is what
2247    /// makes the counters row degrade to `indirect` rather than fail.
2248    cull_stats: Option<CullStatsRing>,
2249
2250    tonemap_layout: BindGroupLayoutHandle,
2251    tonemap_pipeline_layout: PipelineLayoutHandle,
2252    tonemap_pipeline: GraphicsPipelineHandle,
2253    sampler: SamplerHandle,
2254    /// The multiplier the tonemap pass applies before its clamp — see
2255    /// [`set_exposure`](ForwardRenderer::set_exposure).
2256    ///
2257    /// Always within [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`], because the setter is
2258    /// the only thing that writes it and it clamps.
2259    exposure: f32,
2260    /// How far auto-exposure may move in one frame — see
2261    /// [`set_exposure_adaptation`](ForwardRenderer::set_exposure_adaptation).
2262    ///
2263    /// [`None`] until a caller says otherwise, and that is the whole distance in
2264    /// one frame: the picture the pass drew before adaptation existed.
2265    exposure_adaptation: Option<ExposureAdaptation>,
2266    /// Which operator the tonemap pass runs — see
2267    /// [`set_tonemap_curve`](ForwardRenderer::set_tonemap_curve).
2268    ///
2269    /// [`TonemapCurve::Aces`](crcbl_shaders::tonemap::TonemapCurve::Aces) until
2270    /// a caller says otherwise: this renderer shades in linear HDR, so the
2271    /// filmic roll-off is what a view that has said nothing wants. A
2272    /// display-referred view — a 2D sample, or a fixture whose assertions
2273    /// predict a code value — asks for
2274    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp),
2275    /// which is the identity on `0..=1`.
2276    tonemap_curve: tonemap::TonemapCurve,
2277
2278    /// The format the tonemap pipeline was built for. A swapchain format change
2279    /// needs a new pipeline, which is why it is remembered rather than assumed.
2280    target_format: Format,
2281
2282    /// A 1×1 `R8Unorm` image holding [`AMBIENT_OCCLUSION_NONE`], so a group of
2283    /// the mesh layout can fill [`AMBIENT_OCCLUSION_BINDING`] without naming an
2284    /// occlusion image that does not exist yet.
2285    ///
2286    /// [`ForwardRenderer::shadow_placeholder`]'s argument, one binding along.
2287    /// The shadow pass and the depth prepass name it and never sample it — a
2288    /// depth-only pipeline has no fragment stage — and **the forward pass names
2289    /// it too on a frame drawing without [`RenderEffects::AMBIENT_OCCLUSION`]**,
2290    /// where it is the whole of that effect's off-switch. An AO-on frame binds
2291    /// the occlusion pair's blurred output instead.
2292    ///
2293    /// **It is white because that is the value that occludes nothing**, which is
2294    /// what makes it an honest stand-in for "no occlusion was computed" rather
2295    /// than decoration. That it *reads* as white is `mesh.slang`'s doing: the
2296    /// binding is fetched with a `Load`, and a `Load` past a 1×1 image's one
2297    /// texel is zero on every backend, so the shader clamps the coordinate to the
2298    /// image's extent. See [`add_passes`](ForwardRenderer::add_passes).
2299    ///
2300    /// It is uploaded rather than cleared, so it is in
2301    /// [`ResourceState::ShaderRead`] from the moment it exists and no pass has to
2302    /// declare it to give it a layout.
2303    ambient_occlusion_placeholder: UploadedTexture,
2304    /// A 1×1 `R8Unorm` image holding [`CONTACT_SHADOW_NONE`], so a group of the
2305    /// mesh layout can fill [`CONTACT_SHADOW_BINDING`] without naming a
2306    /// contact-shadow image that does not exist yet.
2307    ///
2308    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, one
2309    /// binding along and with one difference worth stating: an unclamped `Load`
2310    /// past this one's single texel would cost the frame its **sun**, not its
2311    /// ambient. `mesh.slang`'s `contact_at` is what clamps it.
2312    contact_shadow_placeholder: UploadedTexture,
2313    /// A 1×1×1 `Rg32Float` image holding [`probe_visibility_none`], so a group
2314    /// of the mesh layout can fill [`PROBE_VISIBILITY_BINDING`] before anything
2315    /// has been captured — and so the console switch has something to name when
2316    /// the maps are turned off.
2317    ///
2318    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, with the
2319    /// same clamp on the shader's side: `mesh.slang`'s `probe_moments` clamps
2320    /// against `GetDimensions`, so all four of its taps land on this image's one
2321    /// texel and every probe reads as unobstructed.
2322    probe_visibility_placeholder: UploadedTexture,
2323    /// The captured maps, one `Rg32Float` layer per probe — `None` until
2324    /// [`ForwardRenderer::capture_probe_visibility`] has run, which is every
2325    /// frame drawn by a caller that never calls it.
2326    probe_visibility: Option<UploadedTexture>,
2327    /// The scene's static triangles, kept for that capture and for nothing else.
2328    ///
2329    /// Empty for a description that reserved no probes, which is what makes the
2330    /// retention cost of this rung zero for every caller that does not use it —
2331    /// see [`crate::probe_visibility`].
2332    probe_occluders: crate::probe_visibility::Occluders,
2333    /// The split-sum `DFG` table as an `Rgba8Unorm` image — binding
2334    /// [`SPECULAR_DFG_BINDING`], read by multi-scatter energy compensation and
2335    /// by every area light's specular term.
2336    ///
2337    /// Uploaded once from `crcbl_shaders::dfg::pair_texels` and never written
2338    /// again: it is a property of the GGX lobe rather than of a scene, a view or
2339    /// a frame. Unlike [`ForwardRenderer::ambient_occlusion_placeholder`] beside
2340    /// it this is not a stand-in for anything — there is no path on which the
2341    /// table is absent, because there is no path on which the lobe is.
2342    specular_dfg: UploadedTexture,
2343    /// The linearly transformed cosine fit as an `Rgba16Float` image — binding
2344    /// [`LTC_TABLE_BINDING`], and the whole of an area light's specular shape.
2345    ///
2346    /// Uploaded once from `crcbl_shaders::ltc::texels`, on the table above it's
2347    /// terms exactly and for the same reason: it is a property of the lobe, and
2348    /// it is bound on every path because Slang's Metal backend materialises
2349    /// every global into every entry point.
2350    ltc_table: UploadedTexture,
2351    /// `[frame][view]`: the entries [`ForwardRenderer::shadow_groups`] was built
2352    /// from.
2353    ///
2354    /// Kept for one rebuild only: the pages' and their sampler's, which
2355    /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
2356    /// layout a slot holds — [`View::prepass_group_entries`]' reason.
2357    shadow_group_entries: Vec<Vec<Vec<BindGroupEntry>>>,
2358
2359    /// The ground grid's pipeline and uniform ring — see [`crate::grid`].
2360    ///
2361    /// [`None`] until a caller first switches it on with
2362    /// [`set_ground_grid`](ForwardRenderer::set_ground_grid), which is what
2363    /// keeps a sample that never asks for a grid from building a pipeline and a
2364    /// ring of blocks for a pass it does not record. Once built it is kept —
2365    /// switching the grid off is [`ForwardRenderer::ground_grid_on`] and not a
2366    /// release, because releasing a uniform ring the frames in flight may still
2367    /// be reading is exactly what the ring exists to prevent.
2368    ground_grid: Option<GroundGrid>,
2369    /// Whether [`add_passes`](ForwardRenderer::add_passes) records the ground
2370    /// grid's pass. **`false` by default**: the grid is a tool's chrome, and
2371    /// every sample and every golden image predates it.
2372    ground_grid_on: bool,
2373
2374    /// The debug draw layer's immediate-mode buffer and its pass — see
2375    /// [`crate::debug_draw`].
2376    ///
2377    /// Always present and empty by default, because appending to it is what a
2378    /// system does and the buffer is a `Vec`; the pipeline and the rings inside
2379    /// it are what stay unbuilt until a frame has both a segment and
2380    /// [`crate::debug_draw::r_debug_draw`] switched on.
2381    debug_draw: DebugDraw,
2382
2383    /// The shadow atlas viewer — see [`crate::atlas_view`]. It draws on no frame
2384    /// but the one [`debug_view`](Self::debug_view) resolved to
2385    /// [`DebugView::ShadowAtlas`], which is none until a caller calls
2386    /// [`set_atlas_view`](Self::set_atlas_view) — and that frame's
2387    /// [`begin_frame`](Self::begin_frame) is what builds it, so a renderer
2388    /// whose atlas nobody looks at holds no pipeline for it.
2389    atlas_viewer: Option<AtlasView>,
2390    /// Whether the frame [`begin_frame`](Self::begin_frame) opened draws the
2391    /// shadow atlas viewer: [`debug_view`](Self::debug_view) as that call
2392    /// resolved it, frozen on [`frame_effects`](Self::frame_effects)' terms —
2393    /// the viewer's block is written and its pipeline built there, so
2394    /// [`add_passes`](Self::add_passes) has to agree with that call.
2395    frame_atlas_view: bool,
2396    /// How large the internal render target is as a fraction of the extent a
2397    /// caller hands `begin_frame` — see [`set_render_scale`](Self::set_render_scale).
2398    render_scale: f32,
2399    /// [`render_scale`](Self::render_scale) as the frame
2400    /// [`begin_frame`](Self::begin_frame) opened froze it, on
2401    /// [`frame_effects`](Self::frame_effects)' terms: every view's internal
2402    /// extent this frame is taken at it, so a scale moved before
2403    /// [`add_passes`](Self::add_passes) waits for the next frame, as
2404    /// [`set_render_scale`](Self::set_render_scale) says it does.
2405    frame_render_scale: f32,
2406
2407    /// The three layers a caller supplies — see [`crate::effects`].
2408    effect_request: EffectRequest,
2409    /// The fourth layer: what this device can draw, which clamps last and
2410    /// absolutely.
2411    ///
2412    /// **Every effect, and that is a fact about the effects rather than an
2413    /// unfinished clamp.** Topic 18 says so of the occlusion pair in as many
2414    /// words — "there is no device fact to gate on … inventing a capability that
2415    /// is really a performance opinion is what topic 39 exists to prevent" — and
2416    /// the reflection pair's module says it of itself. The shadow atlas is a
2417    /// `D32Float` image and a depth-only pass, which is not something a device
2418    /// that got this far can be missing either: one too small for the atlas
2419    /// fails to *build* this renderer rather than degrading past it.
2420    ///
2421    /// So the clamp is real and its rule set is empty. The first rule arrives
2422    /// with the ray-traced variants of these same three effects, which
2423    /// [`LightingPath`](crcbl_hal::LightingPath) selects and which nothing
2424    /// builds yet.
2425    device_effects: RenderEffects,
2426    /// What the frame [`begin_frame`](ForwardRenderer::begin_frame) opened
2427    /// draws, resolved once there.
2428    ///
2429    /// **Frozen for the frame on purpose.** `begin_frame` skips a shadow cull's
2430    /// parameter write when shadows are off and
2431    /// [`add_passes`](ForwardRenderer::add_passes) skips its dispatch; a request
2432    /// changed between the two would dispatch a cull whose counters nothing
2433    /// zeroed, which is a plausible frame drawn off last frame's numbers.
2434    frame_effects: RenderEffects,
2435    /// How many blur passes the frame [`begin_frame`](ForwardRenderer::begin_frame)
2436    /// opened runs over the raw occlusion channel — [`crate::ssao::blur_passes`],
2437    /// read once there.
2438    ///
2439    /// **Frozen for the frame on [`ForwardRenderer::frame_effects`]'s terms.**
2440    /// [`add_passes`](ForwardRenderer::add_passes) both counts the frame's
2441    /// full-screen triangles and records its passes, and a console command
2442    /// landing between the two reads would leave `counters` describing a frame
2443    /// that was never submitted.
2444    frame_ssao_blurs: u32,
2445    /// Full-screen passes the last [`add_passes`](ForwardRenderer::add_passes)
2446    /// recorded, which is what [`counters`](ForwardRenderer::counters) reports
2447    /// as submitted beside the pool's instances.
2448    ///
2449    /// Stored rather than re-derived from [`ForwardRenderer::frame_effects`]:
2450    /// `counters` describes the frame that *was* recorded, and a request set
2451    /// after it would otherwise change the count of a frame already submitted.
2452    recorded_fullscreen: u64,
2453
2454    /// Whether the last [`add_passes`](ForwardRenderer::add_passes) recorded the
2455    /// debug draw layer's pass, as the one direct draw it costs.
2456    ///
2457    /// Separate from [`ForwardRenderer::recorded_fullscreen`] because it is not
2458    /// a full-screen triangle: it is one line-list draw of every segment this
2459    /// frame appended. Both are direct draws of one instance, which is what
2460    /// [`ForwardRenderer::direct_draws`] adds up.
2461    recorded_debug_draw: u64,
2462    /// How many tiles of the shadow atlas the last
2463    /// [`add_passes`](ForwardRenderer::add_passes) reset with a draw rather
2464    /// than with the attachment's own clear.
2465    ///
2466    /// Zero on every frame that clears the whole attachment, which is every
2467    /// frame until the cadence is switched on — see
2468    /// [`MeshModules::depth_clear_pipeline`]. One over-sized triangle of one
2469    /// instance each, so it joins the full-screen draws rather than the
2470    /// indirect ones.
2471    recorded_tile_clears: u64,
2472    /// `docs/plan/55-water.md`'s bodies of water, meshed, and the ring of
2473    /// buffers every view draws them from — see [`crate::water`]. Empty until
2474    /// [`set_water`](ForwardRenderer::set_water), and an empty set records no
2475    /// pass.
2476    water: WaterBodies,
2477    /// The surface draws the last [`add_passes`](ForwardRenderer::add_passes)
2478    /// recorded for the primary camera: one indexed draw per body, each of one
2479    /// instance, so they join the direct draws on the debug draw layer's terms.
2480    recorded_water_draws: u64,
2481    /// `docs/plan/57-grass.md`'s field, its device resources and the ring of
2482    /// retirements a replaced one leaves — see [`crate::grass`]. Empty until
2483    /// [`set_grass`](ForwardRenderer::set_grass), and an empty field records no
2484    /// pass.
2485    grass: GrassScene,
2486    /// What [`ForwardRenderer::grass`]'s field draws this frame, or [`None`]
2487    /// for a frame with none, frozen by `begin_frame` so that every view's
2488    /// blocks, the grass passes it builds and the passes
2489    /// [`add_passes`](ForwardRenderer::add_passes) records are one field's —
2490    /// a field set between the two is drawn from the next frame on, as a
2491    /// body of water is.
2492    frame_grass: Option<GrassFrame>,
2493    /// The wind block every view writes into its own ring — see
2494    /// [`set_wind`](ForwardRenderer::set_wind). Calm until a caller sets one.
2495    wind: crcbl_shaders::wind::WindParams,
2496    /// The grass draws the last [`add_passes`](ForwardRenderer::add_passes)
2497    /// recorded for the primary camera: one per tile slot per look the field
2498    /// draws.
2499    ///
2500    /// **Not among the direct draws**, unlike the water surface's: every one of
2501    /// them is an indirect call whose instance count lives in a buffer a
2502    /// dispatch wrote, so the CPU knows how many *calls* it submitted and
2503    /// nothing about how many blades came out of them.
2504    recorded_grass_draws: u64,
2505    /// Start-up uploads submitted without a wait — the build's batch, and one
2506    /// for each [`create_view`](ForwardRenderer::create_view) and
2507    /// [`set_wind_layers`](ForwardRenderer::set_wind_layers) since — whose
2508    /// staging the GPU may still be reading.
2509    ///
2510    /// Each is retired by the first `begin_frame` that finds its semaphore
2511    /// signalled, and waited for by [`destroy`](ForwardRenderer::destroy) and
2512    /// [`destroy_view`](ForwardRenderer::destroy_view) before they release
2513    /// anything the copies write. Queue order is what lets a frame read the
2514    /// uploaded resources without waiting first — see [`PendingUpload`] — so
2515    /// every one of them was submitted to the device's graphics queue.
2516    uploads_in_flight: Vec<PendingUpload>,
2517}
2518
2519/// What a partly-built [`ForwardRenderer`] has to give back.
2520///
2521/// `new` creates a dozen objects with `?` between them, and the seam's
2522/// `destroy_*` is explicit — so a failure half way through used to leak
2523/// everything created before it. The recorder's leak assertions cover the happy
2524/// path; this covers the other one.
2525#[derive(Debug, Default)]
2526struct Rollback {
2527    buffers: Vec<BufferHandle>,
2528    bind_groups: Vec<BindGroupHandle>,
2529    bind_group_layouts: Vec<BindGroupLayoutHandle>,
2530    pipeline_layouts: Vec<PipelineLayoutHandle>,
2531    pipelines: Vec<GraphicsPipelineHandle>,
2532    samplers: Vec<SamplerHandle>,
2533    /// The shadow atlas and its placeholder, which are created here rather than
2534    /// uploaded — so unlike [`Rollback::textures`] they are a plain handle each,
2535    /// with their views beside them.
2536    images: Vec<ImageHandle>,
2537    image_views: Vec<ImageViewHandle>,
2538    /// Uploaded images, which own a view each and so cannot be rolled back as
2539    /// one list of handles.
2540    textures: Vec<UploadedTexture>,
2541    /// The geometry pool, which owns two buffers, a semaphore and anything
2542    /// still staged — so it cannot be rolled back as a list of handles.
2543    pool: Option<MeshPool>,
2544    /// The instance pool, which owns one buffer per frame in flight.
2545    instances: Option<InstancePool>,
2546    /// The material table, which owns one buffer.
2547    materials: Option<MaterialTable>,
2548    /// The irradiance probe table, which owns one buffer.
2549    probes: Option<ProbeTable>,
2550    /// The irradiance probes' updater, which owns one pipeline,
2551    /// one layout and a ring of blocks — and only exists for a scene whose
2552    /// volume asked to be updated.
2553    probe_gather: Option<ProbeGather>,
2554    /// A view's cull and draw-argument passes, while [`View::build`] — which
2555    /// keeps a rollback of this type of its own — is still building the rest of
2556    /// that view; the renderer's own rollback never holds one. They
2557    /// own a ring of buffers and dispatch
2558    /// [`draw_pipelines`](Self::draw_pipelines), and clean themselves up on
2559    /// their own failure path, so this only carries one that was built.
2560    draws: Option<DrawGen>,
2561    /// One more of the same per shadow-atlas tile — a `Vec` rather than an
2562    /// `Option`, because a failure part way through the tiles has to release the
2563    /// ones already built.
2564    shadow_draws: Vec<DrawGen>,
2565    /// The draw-generation pipelines every generator shares, released after
2566    /// all of them — see [`ForwardRenderer::draw_pipelines`].
2567    draw_pipelines: Option<Arc<DrawGenPipelines>>,
2568    /// The cluster buffers, which own three buffers and are built on the
2569    /// mesh-shader path alone.
2570    clusters: Option<ClusterPool>,
2571    /// Topic 18's light list and froxel grid, which own a pipeline and a ring of
2572    /// three buffers — and which clean themselves up on their own failure path,
2573    /// so this only carries one that was built.
2574    lights: Option<LightGrid>,
2575    /// Topic 47's depth pyramid, which owns one
2576    /// pipeline, one layout and a ring of blocks per level.
2577    hiz: Option<Hiz>,
2578    /// Topic 03 §3.3's farthest-depth pyramid,
2579    /// which owns one pipeline, one layout and — once a frame culled — a chain
2580    /// of level images.
2581    occlusion_pyramid: Option<OcclusionPyramid>,
2582    /// Topic 47's reflection march, which owns one
2583    /// pipeline, one layout and a ring of blocks.
2584    ssr: Option<Ssr>,
2585    /// The froxel volume, which owns three
2586    /// pipelines, two layouts and two rings of buffers.
2587    volumetric: Option<Volumetric>,
2588    /// Topic 43 §6's auto-exposure, which owns three
2589    /// pipelines, one layout and three rings of buffers.
2590    exposure: Option<Exposure>,
2591    /// The background pass, which owns one pipeline, one layout and a ring of
2592    /// blocks and groups.
2593    sky_pass: Option<SkyPass>,
2594    /// The camera, once [`View::build`] has made it whole — released as one,
2595    /// by [`View::destroy`].
2596    primary: Option<View>,
2597}
2598
2599impl Rollback {
2600    /// Releases everything, in the same dependency order as
2601    /// [`ForwardRenderer::destroy`].
2602    fn run(self, device: &dyn Device) {
2603        if let Some(view) = self.primary {
2604            view.destroy(device);
2605        }
2606        for texture in self.textures {
2607            texture.destroy(device);
2608        }
2609        for handle in self.samplers {
2610            device.destroy_sampler(handle);
2611        }
2612        for handle in self.image_views {
2613            device.destroy_image_view(handle);
2614        }
2615        for handle in self.images {
2616            device.destroy_image(handle);
2617        }
2618        for handle in self.pipelines {
2619            device.destroy_graphics_pipeline(handle);
2620        }
2621        for handle in self.pipeline_layouts {
2622            device.destroy_pipeline_layout(handle);
2623        }
2624        for handle in self.bind_groups {
2625            device.destroy_bind_group(handle);
2626        }
2627        for handle in self.bind_group_layouts {
2628            device.destroy_bind_group_layout(handle);
2629        }
2630        for handle in self.buffers {
2631            device.destroy_buffer(handle);
2632        }
2633        if let Some(clusters) = self.clusters {
2634            clusters.destroy(device);
2635        }
2636        for draws in self.shadow_draws {
2637            draws.destroy(device);
2638        }
2639        if let Some(lights) = self.lights {
2640            lights.destroy(device);
2641        }
2642        if let Some(sky_pass) = self.sky_pass {
2643            sky_pass.destroy(device);
2644        }
2645        if let Some(exposure) = self.exposure {
2646            exposure.destroy(device);
2647        }
2648        if let Some(volumetric) = self.volumetric {
2649            volumetric.destroy(device);
2650        }
2651        if let Some(ssr) = self.ssr {
2652            ssr.destroy(device);
2653        }
2654        if let Some(occlusion_pyramid) = self.occlusion_pyramid {
2655            occlusion_pyramid.destroy(device);
2656        }
2657        if let Some(hiz) = self.hiz {
2658            hiz.destroy(device);
2659        }
2660        if let Some(draws) = self.draws {
2661            draws.destroy(device);
2662        }
2663        // After every generator — the camera's above and each shadow cull's —
2664        // although the reference count would hold it until the last of them
2665        // anyway.
2666        if let Some(pipelines) = self.draw_pipelines {
2667            DrawGenPipelines::release(pipelines, device);
2668        }
2669        // Before the table, because its bind groups name that table's rows.
2670        if let Some(gather) = self.probe_gather {
2671            gather.destroy(device);
2672        }
2673        if let Some(table) = self.probes {
2674            table.destroy(device);
2675        }
2676        if let Some(table) = self.materials {
2677            table.destroy(device);
2678        }
2679        if let Some(pool) = self.instances {
2680            pool.destroy(device);
2681        }
2682        if let Some(pool) = self.pool {
2683            pool.destroy(device);
2684        }
2685    }
2686}
2687
2688/// What every bind group of the mesh layout names identically.
2689///
2690/// Split from [`MeshGroup`] rather than folded into it because the split *is*
2691/// the claim: a resource here cannot differ between the colour pass's group and
2692/// a cascade's, and one there must be looked at.
2693struct SharedBindings<'a> {
2694    vertices: BufferHandle,
2695    draw_constants: BufferHandle,
2696    mesh_table: BufferHandle,
2697    materials: BufferHandle,
2698    /// Bindings [`BASE_COLOR_PAGE_BINDING`], [`NORMAL_PAGE_BINDING`],
2699    /// [`MRO_PAGE_BINDING`] and [`EMISSIVE_PAGE_BINDING`] — the four material
2700    /// pages, every one read through the sampler at [`PAGE_SAMPLER_BINDING`]
2701    /// beside them — as this frame slot names them, which is what
2702    /// [`ForwardRenderer::adopt_pages`] moves one slot at a time.
2703    pages: PageBindings,
2704    /// `Some` on [`GeometryPath::MeshShader`] and on no other path, which is
2705    /// what decides whether the mesh-only bindings exist at all.
2706    clusters: Option<&'a ClusterPool>,
2707    shadow_sampler: SamplerHandle,
2708    /// Bindings [`LIGHT_LIST_BINDING`] and [`LIGHT_GRID_BINDING`], this frame's
2709    /// slots of the light ring.
2710    ///
2711    /// Shared rather than per-group, unlike the instance array beside them, and
2712    /// that is the claim: **a cascade shades nothing**, so it reads the same
2713    /// list and the same grid the colour pass does — the depth-only pipeline
2714    /// simply never looks. Two buffers per pass would be two clustering
2715    /// dispatches for one camera.
2716    lights: BufferHandle,
2717    light_grid: BufferHandle,
2718    /// Binding [`PROBE_TABLE_BINDING`], **this frame's slot** of the irradiance
2719    /// grid's ring.
2720    ///
2721    /// Shared across the *groups of one frame* rather than across frames, which
2722    /// is the light list's arrangement exactly: a cascade shades nothing, so it
2723    /// reads the same rows the colour pass does and the depth-only pipeline
2724    /// simply never looks. What it is not is shared across the ring — see
2725    /// [`crate::probe`] for why the table is per-frame at all.
2726    probes: BufferHandle,
2727    /// Binding [`LEVEL_GROUP_TABLE_BINDING`], `DrawGen`'s packed table buffer.
2728    ///
2729    /// Shared rather than per-group for the probe grid's reason exactly: the
2730    /// regions are written when a mesh becomes resident and never per frame, so
2731    /// a cascade and the colour pass read the same words. What varies between
2732    /// them is the *budget* the mesh stage projects against, and that rides in
2733    /// each pass's own frame block.
2734    tables: BufferHandle,
2735    /// Binding [`SPECULAR_DFG_BINDING`], the split-sum `DFG` pair — see
2736    /// [`ForwardRenderer::specular_dfg`].
2737    ///
2738    /// Shared rather than per-group for the probe grid's reason and more
2739    /// strongly: it is cooked into the binary, uploaded once at build and
2740    /// identical for every view this engine will ever draw. A cascade names it
2741    /// and never looks.
2742    specular_dfg: ImageViewHandle,
2743    /// Binding [`LTC_TABLE_BINDING`], the area lights' fit — see
2744    /// [`ForwardRenderer::ltc_table`]. Shared for the table above it's reason.
2745    ltc_table: ImageViewHandle,
2746}
2747
2748/// The half of a mesh-layout bind group that differs between the colour pass and
2749/// each shadow cascade.
2750///
2751/// One description for both, so the two cannot drift: a cascade's group is the
2752/// colour pass's with six resources swapped, and swapping the wrong five of them
2753/// is a shadow map rendered from the camera — which looks like a shadow map.
2754struct MeshGroup {
2755    /// Binding 0. The colour pass's frame block, or a cascade's copy whose
2756    /// `view_proj` is that cascade's matrix.
2757    uniforms: BufferHandle,
2758    /// Binding 2. This frame's slot of the instance ring.
2759    instances: BufferHandle,
2760    /// Binding 5. Whose survivors this group draws.
2761    runs: BufferHandle,
2762    /// Binding 12, on the mesh path: the same survivors' indirect arguments,
2763    /// read as data.
2764    args: BufferHandle,
2765    /// Binding 13, where there is an amplification stage: the frustum it culls
2766    /// clusters against.
2767    cull_params: BufferHandle,
2768    /// Binding 14, likewise: what it counts survivors into.
2769    cull_stats: BufferHandle,
2770    /// Binding 18, likewise: the cut the descent chose, one word per resident
2771    /// cluster. `None` exactly where there is no amplification stage, which is
2772    /// where the layout has no CLUSTER_SELECTION_BINDING either.
2773    ///
2774    /// **A buffer per pass**, not one shared: the colour pass is recorded last,
2775    /// so a cascade writing the camera's would leave nothing of its own to read.
2776    /// See [`ForwardRenderer::shadow_selection`].
2777    cluster_selection: Option<BufferHandle>,
2778    /// Binding 19, likewise: topic 25's hysteresis state, which the
2779    /// draw-argument pass wrote this frame and this one only reads.
2780    ///
2781    /// **A buffer per pass** as well, because the colour pass and a cascade
2782    /// judge the same groups under different budgets — see
2783    /// [`TileBuffers::group_state`].
2784    group_state: Option<BufferHandle>,
2785    /// Binding [`SHADOW_ATLAS_BINDING`]. The atlas for the pass that reads it,
2786    /// and the placeholder for the pass that writes it — see
2787    /// [`ForwardRenderer::shadow_placeholder`], which is where that is argued.
2788    shadow_map: ImageViewHandle,
2789    /// Binding [`AMBIENT_OCCLUSION_BINDING`]. The blurred occlusion channel for
2790    /// a forward pass that computed one, and the white placeholder everywhere
2791    /// else — see [`ForwardRenderer::ambient_occlusion_placeholder`].
2792    ///
2793    /// **Every group built at `build` names the placeholder**, including the
2794    /// camera's: the occlusion image may be a graph transient whose view exists
2795    /// only at execute time, so the camera's group is rebuilt against whatever
2796    /// the frame bound inside the forward pass and cached — the shape
2797    /// [`View::tonemap_groups`] already has.
2798    ambient_occlusion: ImageViewHandle,
2799    /// Binding [`CONTACT_SHADOW_BINDING`]. The contact-shadow channel for a
2800    /// forward pass that marched one, and the white placeholder everywhere else
2801    /// — see [`ForwardRenderer::contact_shadow_placeholder`].
2802    ///
2803    /// [`MeshGroup::ambient_occlusion`]'s terms exactly, including that every
2804    /// group built at `build` names the placeholder.
2805    contact_shadow: ImageViewHandle,
2806    /// Binding [`PROBE_VISIBILITY_BINDING`]. The captured per-probe visibility
2807    /// maps for the camera's pass, and the one-texel placeholder everywhere
2808    /// else — see [`ForwardRenderer::probe_visibility_placeholder`].
2809    ///
2810    /// [`MeshGroup::ambient_occlusion`]'s terms, with one difference: the image
2811    /// is not a graph transient but an ordinary uploaded texture, so what makes
2812    /// this a per-frame swap is the console switch and whether a capture has
2813    /// happened yet — neither of which is known at `build`.
2814    probe_visibility: ImageViewHandle,
2815}
2816
2817impl MeshGroup {
2818    fn entries(&self, shared: &SharedBindings<'_>) -> Vec<BindGroupEntry> {
2819        let mut entries = vec![
2820            BindGroupEntry {
2821                binding: 0,
2822                array_index: 0,
2823                resource: BindingResource::whole_buffer(self.uniforms),
2824            },
2825            BindGroupEntry {
2826                binding: 1,
2827                array_index: 0,
2828                resource: BindingResource::whole_buffer(shared.vertices),
2829            },
2830            BindGroupEntry {
2831                binding: 2,
2832                array_index: 0,
2833                // **This frame's slot of the instance ring, not a shared
2834                // buffer.** Binding one buffer here for every group would undo
2835                // the ring and reintroduce the cross-submission
2836                // read-after-write hazard it exists to prevent.
2837                resource: BindingResource::whole_buffer(self.instances),
2838            },
2839            BindGroupEntry {
2840                binding: 3,
2841                array_index: 0,
2842                // **One block, not the whole buffer.** The binding is dynamic,
2843                // so the bind's offset is added on top of this one and both
2844                // Vulkan and WebGPU require `offset + dynamic + size` to stay
2845                // inside the buffer — bound whole, the very first non-zero
2846                // dynamic offset would be out of range.
2847                resource: BindingResource::Buffer {
2848                    buffer: shared.draw_constants,
2849                    offset: 0,
2850                    size: DRAW_CONSTANTS_BLOCK,
2851                },
2852            },
2853            BindGroupEntry {
2854                binding: 4,
2855                array_index: 0,
2856                // The same table in every group, unlike the instance array
2857                // above it: the pool writes an entry when a mesh is uploaded or
2858                // freed, neither of which happens between frames here.
2859                resource: BindingResource::whole_buffer(shared.mesh_table),
2860            },
2861            BindGroupEntry {
2862                binding: 5,
2863                array_index: 0,
2864                // Whose cull this group draws from. This is the binding a
2865                // cascade's group differs in most consequentially: it is what
2866                // makes the shadow pass draw what the *light* can see rather
2867                // than what the camera can.
2868                resource: BindingResource::whole_buffer(self.runs),
2869            },
2870            BindGroupEntry {
2871                binding: 6,
2872                array_index: 0,
2873                resource: BindingResource::whole_buffer(shared.materials),
2874            },
2875            BindGroupEntry {
2876                binding: BASE_COLOR_PAGE_BINDING,
2877                array_index: 0,
2878                // **One entry, `array_index: 0`**, because the page is one
2879                // image and the layer is chosen in the shader. A bindless array
2880                // would be one entry per texture at ascending array indices,
2881                // which is the write path `BindGroupEntry`'s own docs describe
2882                // and the one this pass does not take.
2883                resource: BindingResource::ImageView(
2884                    shared.pages.views[PageKind::BaseColor.index()],
2885                ),
2886            },
2887            BindGroupEntry {
2888                binding: PAGE_SAMPLER_BINDING,
2889                array_index: 0,
2890                resource: BindingResource::Sampler(shared.pages.sampler),
2891            },
2892        ];
2893        if let Some(clusters) = shared.clusters {
2894            entries.extend([
2895                BindGroupEntry {
2896                    binding: CLUSTERS_BINDING,
2897                    array_index: 0,
2898                    // The same three buffers in every group, on the mesh table's
2899                    // terms: clusters are written when the pool is built and
2900                    // never again.
2901                    resource: BindingResource::whole_buffer(clusters.clusters()),
2902                },
2903                BindGroupEntry {
2904                    binding: CLUSTER_VERTICES_BINDING,
2905                    array_index: 0,
2906                    resource: BindingResource::whole_buffer(clusters.vertices()),
2907                },
2908                BindGroupEntry {
2909                    binding: CLUSTER_CORNERS_BINDING,
2910                    array_index: 0,
2911                    resource: BindingResource::whole_buffer(clusters.corners()),
2912                },
2913                BindGroupEntry {
2914                    binding: CLUSTER_DRAW_ARGS_BINDING,
2915                    array_index: 0,
2916                    // **Arguments read as data.** The mesh path records no
2917                    // indirect draw at all; what it wants out of this buffer is
2918                    // the one word only the GPU knows — how many instances
2919                    // survived into each bucket.
2920                    resource: BindingResource::whole_buffer(self.args),
2921                },
2922            ]);
2923        }
2924        // Both mesh entry points retain these native buffer arguments even
2925        // when no amplification stage reads them.
2926        if shared.clusters.is_some() {
2927            entries.extend([
2928                BindGroupEntry {
2929                    binding: CLUSTER_CULL_BINDING,
2930                    array_index: 0,
2931                    resource: BindingResource::whole_buffer(self.cull_params),
2932                },
2933                BindGroupEntry {
2934                    binding: CLUSTER_CULL_STATS_BINDING,
2935                    array_index: 0,
2936                    resource: BindingResource::whole_buffer(self.cull_stats),
2937                },
2938            ]);
2939        }
2940        entries.push(BindGroupEntry {
2941            binding: SHADOW_ATLAS_BINDING,
2942            array_index: 0,
2943            resource: BindingResource::ImageView(self.shadow_map),
2944        });
2945        entries.push(BindGroupEntry {
2946            binding: SHADOW_SAMPLER_BINDING,
2947            array_index: 0,
2948            resource: BindingResource::Sampler(shared.shadow_sampler),
2949        });
2950        // Mesh-only buffers are sorted after the common fragment prefix below.
2951        if let Some(clusters) = shared.clusters {
2952            entries.push(BindGroupEntry {
2953                binding: CLUSTER_SELECT_BINDING,
2954                array_index: 0,
2955                // Bound with the geometry rather than with the cull, because
2956                // `vertex_base` *is* geometry: it is which level of a DAG a
2957                // cluster's vertices live in, and both mesh entry points resolve
2958                // a vertex through it.
2959                resource: BindingResource::whole_buffer(clusters.selection()),
2960            });
2961        }
2962        if let Some(selection) = self.cluster_selection {
2963            entries.push(BindGroupEntry {
2964                binding: CLUSTER_SELECTION_BINDING,
2965                array_index: 0,
2966                resource: BindingResource::whole_buffer(selection),
2967            });
2968        }
2969        if let Some(state) = self.group_state {
2970            entries.push(BindGroupEntry {
2971                binding: CLUSTER_GROUP_STATE_BINDING,
2972                array_index: 0,
2973                resource: BindingResource::whole_buffer(state),
2974            });
2975        }
2976        // Topic 18's pair, on every path and in every group — see the layout,
2977        // which has no configuration that omits them either.
2978        entries.push(BindGroupEntry {
2979            binding: LIGHT_LIST_BINDING,
2980            array_index: 0,
2981            resource: BindingResource::whole_buffer(shared.lights),
2982        });
2983        entries.push(BindGroupEntry {
2984            binding: LIGHT_GRID_BINDING,
2985            array_index: 0,
2986            resource: BindingResource::whole_buffer(shared.light_grid),
2987        });
2988        // Shared fragment textures and probes retain their raster bindings.
2989        entries.push(BindGroupEntry {
2990            binding: AMBIENT_OCCLUSION_BINDING,
2991            array_index: 0,
2992            resource: BindingResource::ImageView(self.ambient_occlusion),
2993        });
2994        // And the irradiance grid past it — see [`PROBE_TABLE_BINDING`].
2995        entries.push(BindGroupEntry {
2996            binding: PROBE_TABLE_BINDING,
2997            array_index: 0,
2998            resource: BindingResource::whole_buffer(shared.probes),
2999        });
3000        // Group records are present on both mesh paths, matching the layout.
3001        if shared.clusters.is_some() {
3002            entries.push(BindGroupEntry {
3003                binding: LEVEL_GROUP_TABLE_BINDING,
3004                array_index: 0,
3005                resource: BindingResource::whole_buffer(shared.tables),
3006            });
3007        }
3008        // The DFG texture is read by the fragment stage of every path.
3009        entries.push(BindGroupEntry {
3010            binding: SPECULAR_DFG_BINDING,
3011            array_index: 0,
3012            resource: BindingResource::ImageView(shared.specular_dfg),
3013        });
3014        // And §2's normal page above that, on the same ascending terms — see
3015        // [`NORMAL_PAGE_BINDING`]. Unconditional and `array_index: 0` for
3016        // binding 7's reason: one image, and the layer is chosen in the shader.
3017        entries.push(BindGroupEntry {
3018            binding: NORMAL_PAGE_BINDING,
3019            array_index: 0,
3020            resource: BindingResource::ImageView(shared.pages.views[PageKind::Normal.index()]),
3021        });
3022        // And the area lights' table above that, on the same ascending terms —
3023        // see [`LTC_TABLE_BINDING`].
3024        entries.push(BindGroupEntry {
3025            binding: LTC_TABLE_BINDING,
3026            array_index: 0,
3027            resource: BindingResource::ImageView(shared.ltc_table),
3028        });
3029        // And the contact-shadow channel above that, last of the set and on the
3030        // same ascending terms — see [`CONTACT_SHADOW_BINDING`].
3031        entries.push(BindGroupEntry {
3032            binding: CONTACT_SHADOW_BINDING,
3033            array_index: 0,
3034            resource: BindingResource::ImageView(self.contact_shadow),
3035        });
3036        // And the probe visibility maps above that, on the same ascending terms
3037        // — see [`PROBE_VISIBILITY_BINDING`].
3038        entries.push(BindGroupEntry {
3039            binding: PROBE_VISIBILITY_BINDING,
3040            array_index: 0,
3041            resource: BindingResource::ImageView(self.probe_visibility),
3042        });
3043        // And §2's other two pages above that, last of the set and on the same
3044        // ascending terms — see [`MRO_PAGE_BINDING`] and
3045        // [`EMISSIVE_PAGE_BINDING`]. Unconditional and `array_index: 0` for the
3046        // normal page's reason: one image apiece, and the layer is chosen in
3047        // the shader.
3048        entries.push(BindGroupEntry {
3049            binding: MRO_PAGE_BINDING,
3050            array_index: 0,
3051            resource: BindingResource::ImageView(
3052                shared.pages.views[PageKind::MetallicRoughnessOcclusion.index()],
3053            ),
3054        });
3055        entries.push(BindGroupEntry {
3056            binding: EMISSIVE_PAGE_BINDING,
3057            array_index: 0,
3058            resource: BindingResource::ImageView(shared.pages.views[PageKind::Emissive.index()]),
3059        });
3060        entries.sort_by_key(|entry| entry.binding);
3061        entries
3062    }
3063}
3064
3065/// The two `ArrayPages` images every group of the mesh layout names, as the
3066/// graph knows them.
3067///
3068/// One value rather than two arguments because the two travel together
3069/// everywhere: every pass that declares one declares the other, and a pass
3070/// handed them the wrong way round would order a caller's copy into the wrong
3071/// image — which is a barrier bug, and therefore one that reproduces on one
3072/// backend and not the others.
3073#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3074struct MaterialPages {
3075    /// §3.2's base-colour page — [`ForwardRenderer::base_color_page_import`].
3076    base_color: ImageId,
3077    /// §2's normal page — [`ForwardRenderer::normal_page_import`].
3078    normal: ImageId,
3079    /// §2's metallic-roughness-occlusion page —
3080    /// [`ForwardRenderer::mro_page_import`].
3081    mro: ImageId,
3082    /// §2's emissive page — [`ForwardRenderer::emissive_page_import`].
3083    emissive: ImageId,
3084}
3085
3086/// Everything [`ForwardRenderer::add_shadow_pass`] declares and does not write,
3087/// as the graph knows it.
3088///
3089/// One value rather than an argument apiece for [`MaterialPages`]' reason, and
3090/// the list grew past what an argument list should be the moment the probe rows
3091/// joined it: each of these is in every cascade's bind group and read by no
3092/// cascade, so what the pass does with them is one thing — declare them, so the
3093/// graph can order whoever writes them against these draws.
3094#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3095struct ShadowReads {
3096    /// The occlusion placeholder every cascade's group stands the real channel
3097    /// in for — [`ForwardRenderer::ambient_occlusion_placeholder`].
3098    occlusion_placeholder: ImageId,
3099    /// §3.2's and §2's pages, which the cascades name and never sample.
3100    pages: MaterialPages,
3101    /// The skinned vertex region, where a frame has one — the cascades pull the
3102    /// same geometry the colour pass does.
3103    skinned: Option<BufferId>,
3104    /// This frame's slot of the probe ring — see [`crate::probe`].
3105    probes: BufferId,
3106}
3107
3108/// What the mesh pass's bind-group layout is called.
3109///
3110/// Named rather than written twice because a test asserts on it: the layout's
3111/// *binding numbers* are what `crcbl-mtl` turns into Metal argument-table
3112/// indices by counting, so `the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage`
3113/// has to find this one layout among the recorder's.
3114const MESH_LAYOUT_LABEL: &str = "mesh frame";
3115
3116/// Imports a buffer a pass both reads and writes, carried from one frame on
3117/// its slot to the next: it arrives in the state the previous frame that used
3118/// the slot left it in, and that is the state it is declared to leave in.
3119///
3120/// A record of the cut or a statistics sink, which a pass writes and the next
3121/// frame on the same slot writes again — a barrier naming `Undefined` as its
3122/// source would carry no source scope and order this frame's write against
3123/// nothing.
3124fn import_read_write(graph: &mut RenderGraph<'_>, label: &str, buffer: BufferHandle) -> BufferId {
3125    graph.import_buffer(
3126        label,
3127        ImportedBuffer {
3128            buffer,
3129            initial: ResourceState::ShaderReadWrite,
3130            final_state: ResourceState::ShaderReadWrite,
3131        },
3132    )
3133}
3134
3135/// Declares the buffers a geometry pass reads to find its draws.
3136///
3137/// The other half of [`BucketDraws`]: what the *graph* has to be told, where that
3138/// struct is what the encoder is told. Three passes declare exactly this set, and
3139/// the seam calls the barrier it produces the single most important one in a
3140/// GPU-driven frame — its absence produces "sometimes nothing draws".
3141///
3142/// A caller with a cluster-selection buffer of its own appends it; that is the
3143/// one declaration that differs between the colour pass, a cascade and the depth
3144/// prepass.
3145fn read_draw_sources<'g, 'a>(
3146    pass: PassBuilder<'g, 'a>,
3147    draws: &GeneratedDraws,
3148    emit: EmitTail,
3149) -> PassBuilder<'g, 'a> {
3150    // The buffers the draws come out of. Declaring them is what makes the graph
3151    // transition them out of the compute pass's `ShaderReadWrite`.
3152    let pass = pass.read_buffer(draws.runs_id);
3153    if emit.is_mesh() {
3154        // **The same arguments, read as data rather than executed**, which is
3155        // what the stages use to bound the run of surviving instances they index.
3156        // The per-bucket draw *counts* are not read at all, because nothing here
3157        // is a draw whose count could come from memory.
3158        //
3159        // The dispatch *extents* are a real indirect read — one structure per
3160        // bucket, written by the same pass. They are in a **different buffer**
3161        // from the arguments above and that separation is load-bearing: a
3162        // resource is in exactly one state per pass and these two are in
3163        // different ones. They share a buffer with the counts instead, which
3164        // this path does not read at all — see [`GeneratedDraws::counts`].
3165        let pass = pass
3166            .read_buffer(draws.args_id)
3167            .use_buffer(draws.counts_id, ResourceState::IndirectArgument);
3168        // The amplification stage counts its survivors into the culling
3169        // statistics, which the draw-argument pass read a moment ago — so this
3170        // is a write-after-read the graph has to order, and declaring it is
3171        // the whole of how it learns to.
3172        //
3173        // Topic 25's hysteresis state is read here and written by
3174        // the draw-argument pass a moment ago. Declaring it is what orders the
3175        // two — and what puts it back into `ShaderReadWrite` at the end of the
3176        // graph, which is where the next frame's draw-argument pass expects to
3177        // find it.
3178        //
3179        // **Declared on the whole mesh path, not only where there is an
3180        // amplification stage**, because that is where the bind group now
3181        // names both — see the layout, which is where the Metal argument-table
3182        // arithmetic that forced it is argued. A buffer bound writable and
3183        // never transitioned is a descriptor in the wrong resource state, which
3184        // is what the graph exists to prevent.
3185        pass.use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite)
3186            .read_buffer(draws.group_state_id)
3187    } else {
3188        pass.use_buffer(draws.args_id, ResourceState::IndirectArgument)
3189            .use_buffer(draws.counts_id, ResourceState::IndirectArgument)
3190    }
3191}
3192
3193/// What one [`MeshDesc`](crate::scene::MeshDesc) became once it was resident.
3194///
3195/// One of these per description mesh, in description order — so a mesh's index
3196/// here is its index there, which is what lets the bucket table, the level
3197/// tables and the cluster pool all be filled in by walking one list.
3198struct ResidentMesh {
3199    /// This mesh's table ids, finest first: one entry for a flat mesh, one per
3200    /// level for a DAG. Never empty.
3201    ///
3202    /// Every level is its own vertex range and so its own table entry. Level 0's
3203    /// id is the one the *instance* carries and the one the cull pass reads a
3204    /// bounding box out of; the coarser ones are named by the bucket table on a
3205    /// path that takes a uniform cut, and by nothing at all on the mesh path,
3206    /// where a cluster reaches its own level through
3207    /// [`vertex_bases`](Self::vertex_bases) instead.
3208    levels: Vec<u32>,
3209    /// Per level, how far that level's vertices start past level 0's — so a flat
3210    /// mesh's single entry is zero.
3211    ///
3212    /// What [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`] holds,
3213    /// and the whole of what makes a DAG drawable from one instance: the mesh
3214    /// stage adds this to the instance's own `base_vertex`, so a cut spanning
3215    /// three levels reads three different vertex ranges out of one pool.
3216    vertex_bases: Vec<u32>,
3217    /// Level 0's pool handle, for a mesh that can be **skinned** — and [`None`]
3218    /// for a [`Geometry::Dag`].
3219    ///
3220    /// A DAG is refused because its coarser levels are separate vertex runs no
3221    /// skinning dispatch writes: an instance drawn out of a skinned region
3222    /// resolves every level through [`vertex_bases`](Self::vertex_bases) added
3223    /// to the region's base, which for anything but level 0 is memory the
3224    /// dispatch never touched.
3225    skinnable: Option<MeshHandle>,
3226}
3227
3228impl ResidentMesh {
3229    /// The table id an instance of this mesh carries: **level 0's**, whatever
3230    /// the geometry path, because it is the entry `cull.slang` reads a bounding
3231    /// box out of and the coarser levels approximate the same surface inside the
3232    /// same box.
3233    fn id(&self) -> u32 {
3234        self.levels[0]
3235    }
3236}
3237
3238/// One skinned object the renderer re-points every frame: the instance, and the
3239/// base vertex it draws out of under each parity.
3240///
3241/// The bases are copied out of the [`SkinnedMesh`] rather than borrowed from it,
3242/// so placing an object does not tie the renderer's lifetime to the caller's
3243/// reservation — the renderer never needs the region again, only the two
3244/// numbers.
3245#[derive(Clone, Copy, Debug)]
3246struct SkinnedInstance {
3247    handle: InstanceHandle,
3248    /// Indexed by parity, in [`crate::skinning::SkinnedRegion::base`]'s
3249    /// indexing — so the half a frame of parity `p` draws out of is
3250    /// `bases[p & 1]` and the half the frame before it filled is
3251    /// `bases[(p ^ 1) & 1]`, which is
3252    /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base)'s
3253    /// answer for the same `p`.
3254    bases: [u32; 2],
3255    /// Whether a frame has already pointed this entry at a half of the region
3256    /// it now names.
3257    ///
3258    /// **What makes the previous base meaningful.** The half a frame did not
3259    /// write holds whatever its reservation came with until a dispatch fills
3260    /// it, so an object's first frame out of a region has no previous
3261    /// deformation to point at — naming that half would give it a motion vector
3262    /// against undefined vertices. Such an entry is put at rest instead, which
3263    /// is the rule [`InstancePool::insert`](crate::instance_pool::InstancePool::insert)
3264    /// applies to `previous_transform` for the same reason: a spawn did not
3265    /// travel from anywhere.
3266    pointed: bool,
3267}
3268
3269/// The two base vertices an object drawn out of `mesh` alternates between, in
3270/// [`SkinnedInstance::bases`]' indexing.
3271fn skinned_bases(mesh: &SkinnedMesh) -> [u32; 2] {
3272    [mesh.region().base(0), mesh.region().base(1)]
3273}
3274
3275/// One shadow cull's per-frame buffers, read out of its [`DrawGen`] before that
3276/// generator is handed to the rollback.
3277struct TileBuffers {
3278    runs: Vec<BufferHandle>,
3279    args: Vec<BufferHandle>,
3280    cull_params: Vec<BufferHandle>,
3281    cull_stats: Vec<BufferHandle>,
3282    /// This cull's own hysteresis state, and not the camera's.
3283    ///
3284    /// A shadow view selects from the camera's eye at the camera's scale, like
3285    /// the colour pass, but under budgets [`SHADOW_LOD_BIAS`] times as large — so
3286    /// it reaches a different answer for the same group, and an answer carried
3287    /// between frames needs somewhere of its own to be carried. Sharing the
3288    /// camera's buffer would be two rules writing one history and each undoing
3289    /// the other's band every frame.
3290    ///
3291    /// One per cull rather than one for the shadow pass, even though every one of
3292    /// them selects identically: each cull is its own [`DrawGen`], and one buffer
3293    /// between them would be several dispatches writing one element with nothing
3294    /// ordering them.
3295    ///
3296    /// **This is what a cull costs that is not a dispatch.** It is
3297    /// [`Capacities::instances`](crate::scene::Capacities::instances) × the
3298    /// resident group count words of device-local
3299    /// memory, held for the renderer's whole life whether anything is drawn
3300    /// through it or not, and it is the reason [`shadow::LIGHT_SLOTS`] is a
3301    /// budget rather than "however many lights the scene has" — and the reason a
3302    /// point light's six faces share one of these rather than owning six.
3303    group_state: BufferHandle,
3304}
3305
3306impl ForwardRenderer {
3307    /// Builds both pipelines and makes [`scene::demo`] resident.
3308    ///
3309    /// [`ForwardRenderer::with_scene`] with the engine's own description, and
3310    /// nothing else — so the frame this draws is the one the golden suite has
3311    /// always compared, and every existing caller is untouched.
3312    ///
3313    /// `target_format` must be the format the tonemap pass will render into —
3314    /// dynamic rendering checks pipeline and attachment formats against each
3315    /// other at pass-begin time, not at creation.
3316    ///
3317    /// # Errors
3318    ///
3319    /// [`HalError`], on [`ForwardRenderer::with_scene`]'s terms.
3320    pub fn new(
3321        device: &dyn Device,
3322        queue: QueueHandle,
3323        target_format: Format,
3324    ) -> Result<Self, HalError> {
3325        Self::with_scene(device, queue, target_format, &scene::demo())
3326    }
3327
3328    /// Builds both pipelines and makes `scene` resident.
3329    ///
3330    /// Everything in the description is created here and never grows: the
3331    /// geometry pools, the cluster pool, the material table, the page, the
3332    /// instance array and the bucket table are all sized and filled once. See
3333    /// [`crate::scene`] for why that split is where the seam is, and for the
3334    /// four places a description's *order* decides what the frame looks like.
3335    ///
3336    /// `target_format` must be the format the tonemap pass will render into —
3337    /// dynamic rendering checks pipeline and attachment formats against each
3338    /// other at pass-begin time, not at creation.
3339    ///
3340    /// # No description is too small
3341    ///
3342    /// One mesh and one material row is a scene, and so is
3343    /// [`scene::demo`]'s four and three. Nothing on this type names a
3344    /// description entry by position any more — the five `set_*` demo wrappers
3345    /// that did are gone, and [`ForwardRenderer::add_instance`] takes the mesh
3346    /// and the row a caller wrote its **own** description in.
3347    ///
3348    /// # Errors
3349    ///
3350    /// [`HalError::InvalidDescriptor`] if the description cannot be made
3351    /// resident as written: a page layer that is not its kind's extent's worth of
3352    /// RGBA8, a page kind holding layers at no extent, a material row naming a
3353    /// layer that kind's page has not got, a DAG carrying a vertex array for anything but each of its
3354    /// levels, a cluster array with a read outside itself in it (see
3355    /// [`MeshClusters::check`]), or more vertices, indices, mesh table entries or
3356    /// material rows than [`SceneDesc::capacities`] reserves — that last naming the pool, the
3357    /// capacity and what the description needs, because the answer to it is to
3358    /// raise the number. Every one of those is settled **before the first device
3359    /// object exists**, so a refusal leaks nothing.
3360    ///
3361    /// [`HalError`] otherwise, from any seam call — including the geometry a
3362    /// pool refuses for itself, such as vertex bytes that are not a whole number
3363    /// of vertices. A backend that cannot build a pipeline says so here rather
3364    /// than drawing nothing later, and a failure part-way through releases
3365    /// everything already created, so a caller that retries or exits leaves
3366    /// nothing behind.
3367    pub fn with_scene(
3368        device: &dyn Device,
3369        queue: QueueHandle,
3370        target_format: Format,
3371        scene: &SceneDesc<'_>,
3372    ) -> Result<Self, HalError> {
3373        Self::with_scene_serviced(device, queue, target_format, scene, &mut || {})
3374    }
3375
3376    /// [`ForwardRenderer::with_scene`], calling `service` between the steps of
3377    /// the build so the thread running it can keep its window alive.
3378    ///
3379    /// # What it is for: a build on the thread that owns the window
3380    ///
3381    /// The build needs the device, so it runs on whichever thread holds it —
3382    /// for a game that is the loop thread, which also owns the window, and a
3383    /// desktop marks a window hung when its thread takes no message for a few
3384    /// seconds (see `crcbl_shell::Shell::keep_alive`). A game passes
3385    /// `&mut || shell.keep_alive()` here and the window keeps answering for the
3386    /// whole build.
3387    ///
3388    /// # Where it is called
3389    ///
3390    /// Where the time is, which was measured rather than guessed. With a cold
3391    /// driver shader cache — a player's first launch, or the first after a
3392    /// driver update — **pipeline creation is most of the build**. Measured in
3393    /// 2026-09 on an RX 7900 XTX, release, building one glTF scene: 2.2 to 2.4 s
3394    /// on Vulkan and 1.9 to 2.2 s on D3D12 cold against 0.25 s warm, while the
3395    /// mesh and page uploads took about 0.1 s either way. So `service` runs
3396    /// after every mesh upload (each level of a DAG), after every page layer's
3397    /// mip chain and each page's upload, after each of the camera's
3398    /// post-processing subsystems, before every round of the mesh-pass
3399    /// pipelines, and between the build's other phases. The water and grass
3400    /// passes are not built here: the first frame with a body or a field
3401    /// builds them — see `View::build_content`.
3402    ///
3403    /// **The longest gap left is about one pipeline**, and a pipeline cannot be
3404    /// split: on that scene, cold, it was the forward pass's colour pipeline
3405    /// at 0.31 s on Vulkan and 0.36 s on D3D12, where the build without calls
3406    /// had been one gap of 2 s. Warm, the longest was about 0.04 s. A machine
3407    /// eight times slower under contention still calls back inside the five
3408    /// seconds Windows allows.
3409    ///
3410    /// **One condition on that bound.** The mesh-pass pipelines are compiled
3411    /// as one batch on a device that can take them from several
3412    /// threads, in rounds of a small fixed number of pipelines with `service`
3413    /// on this thread before each — see `crate::pipeline_batch`. A driver that
3414    /// compiles side by side finishes a round in about its slowest compile, so
3415    /// the bound holds. One that serialises its compiles internally takes a
3416    /// whole round's worth between two calls, which is still bounded — the
3417    /// round is capped — but leaves about a quarter of the headroom above: a
3418    /// machine twice as slow rather than eight times. On a device that cannot take
3419    /// pipelines from several threads, `service` runs before each pipeline as
3420    /// it always did.
3421    ///
3422    /// `service` sees nothing of the build and cannot touch the renderer or the
3423    /// scene. Whatever reaches the window meanwhile — input, a resize, a close
3424    /// request — is the caller's to keep for later, as
3425    /// `crcbl_shell::Shell::keep_alive` does.
3426    ///
3427    /// # Errors
3428    ///
3429    /// [`ForwardRenderer::with_scene`]'s, on its terms: a failure part-way
3430    /// through releases everything already created.
3431    pub fn with_scene_serviced(
3432        device: &dyn Device,
3433        queue: QueueHandle,
3434        target_format: Format,
3435        scene: &SceneDesc<'_>,
3436        service: &mut dyn FnMut(),
3437    ) -> Result<Self, HalError> {
3438        Self::build_on_path(
3439            device,
3440            queue,
3441            target_format,
3442            scene,
3443            device.preferred_geometry_path(),
3444            service,
3445        )
3446    }
3447
3448    /// Builds exactly the requested geometry tail, independently of the device's
3449    /// performance preference. Capabilities remain available to other callers.
3450    ///
3451    /// # Errors
3452    ///
3453    /// Returns [`HalError::UnsupportedFeatures`] before creating device objects
3454    /// when the requested tail lacks its required feature. Other failures follow
3455    /// [`Self::with_scene`]'s rollback contract.
3456    pub fn with_scene_on_path(
3457        device: &dyn Device,
3458        queue: QueueHandle,
3459        target_format: Format,
3460        scene: &SceneDesc<'_>,
3461        geometry_path: GeometryPath,
3462    ) -> Result<Self, HalError> {
3463        Self::build_on_path(
3464            device,
3465            queue,
3466            target_format,
3467            scene,
3468            geometry_path,
3469            &mut || {},
3470        )
3471    }
3472
3473    /// The body of [`Self::with_scene_on_path`] and
3474    /// [`Self::with_scene_serviced`], calling `service` where the latter
3475    /// documents.
3476    fn build_on_path(
3477        device: &dyn Device,
3478        queue: QueueHandle,
3479        target_format: Format,
3480        scene: &SceneDesc<'_>,
3481        geometry_path: GeometryPath,
3482        service: &mut dyn FnMut(),
3483    ) -> Result<Self, HalError> {
3484        let required = match geometry_path {
3485            GeometryPath::MeshShader => crcbl_hal::Features::MESH_SHADER,
3486            GeometryPath::IndirectCount => crcbl_hal::Features::DRAW_INDIRECT_COUNT,
3487            GeometryPath::IndirectPerBatch => crcbl_hal::Features::empty(),
3488        };
3489        let missing = required.difference(device.caps().features);
3490        if !missing.is_empty() {
3491            return Err(HalError::UnsupportedFeatures { missing });
3492        }
3493        crcbl_frame::require_frame_queue(device, queue, "a forward renderer")?;
3494        let mut rollback = Rollback::default();
3495        // **One submission and no wait for the build's small uploads**: the
3496        // placeholders, the split-sum and area-light tables, and every view's
3497        // and shadow cull's start-up fills are recorded into this batch as they
3498        // are created, and submitted once the renderer is whole. Each used to
3499        // be its own submit and `wait_idle`, and on Mesa's ANV the first submit
3500        // on a fresh device costs several milliseconds and every later round
3501        // trip about half of one. The geometry pools, the pages and the probe
3502        // table still submit for themselves, all of them before this batch's
3503        // submission, and none of them reads anything it writes.
3504        //
3505        // The batch is submitted without a wait: every reader of what it
3506        // writes is a frame on this same queue, after it, which is all the
3507        // ordering the copies need — see `PendingUpload`. Its staging is
3508        // retired by the first `begin_frame` that finds its semaphore
3509        // signalled, or waited for by `destroy`.
3510        let mut uploads = UploadBatch::new(device, queue, "forward");
3511        match Self::build(
3512            device,
3513            &mut uploads,
3514            target_format,
3515            scene,
3516            geometry_path,
3517            &mut rollback,
3518            service,
3519        ) {
3520            // The submit is the build's last fallible step, so nothing can
3521            // fail between it and the renderer owning the upload: a failed
3522            // submit leaves nothing pending, and `destroy` finds an empty list.
3523            Ok(mut renderer) => match uploads.submit_deferred() {
3524                Ok(pending) => {
3525                    renderer.uploads_in_flight.push(pending);
3526                    Ok(renderer)
3527                }
3528                Err(error) => {
3529                    renderer.destroy(device);
3530                    Err(error)
3531                }
3532            },
3533            Err(error) => {
3534                // The batch first, so nothing it recorded is still pending when
3535                // the rollback destroys what it recorded into.
3536                drop(uploads);
3537                rollback.run(device);
3538                Err(error)
3539            }
3540        }
3541    }
3542
3543    /// Releases every start-up upload the GPU is known to be past, without
3544    /// blocking — the first thing each `begin_frame` does.
3545    ///
3546    /// # Errors
3547    ///
3548    /// [`HalError`] from reading a semaphore — a lost device. What was not
3549    /// released stays in the list.
3550    fn retire_uploads(&mut self, device: &dyn Device) -> Result<(), HalError> {
3551        let mut index = 0;
3552        while index < self.uploads_in_flight.len() {
3553            if self.uploads_in_flight[index].poll(device)? {
3554                // Retired, so dropping it releases nothing and logs nothing.
3555                drop(self.uploads_in_flight.swap_remove(index));
3556            } else {
3557                index += 1;
3558            }
3559        }
3560        Ok(())
3561    }
3562
3563    /// Blocks until every start-up upload has landed and releases them, before
3564    /// `caller` destroys anything their copies write.
3565    ///
3566    /// A failed wait is a lost device. What it would have released is leaked
3567    /// rather than freed under the GPU, and said so in the log; the caller goes
3568    /// on, as a destroy has nothing to hand an error to.
3569    fn wait_for_uploads(&mut self, device: &dyn Device, caller: &str) {
3570        for mut pending in self.uploads_in_flight.drain(..) {
3571            if let Err(error) = pending.wait(device) {
3572                crcbl_core::log::warn!(
3573                    "ForwardRenderer::{caller}: a start-up upload's wait failed ({error}); its \
3574                     staging buffers are leaked rather than freed under the GPU"
3575                );
3576                // Dropping it is the leak, and it logs one of its own.
3577            }
3578        }
3579    }
3580
3581    /// Everything `build` needs to be true of a description, checked **before
3582    /// the first device object exists**.
3583    ///
3584    /// That placement is the whole design of this function. `build` hands the
3585    /// geometry pool and the material table to the rollback and creates a dozen
3586    /// objects with `?` between them; a check that ran part way down that list
3587    /// would be a new early exit on the wrong side of a handover, and a rejected
3588    /// description would leak two device-local buffers. Run from the top of
3589    /// `build`, a refusal costs nothing to unwind because nothing was made.
3590    ///
3591    /// # Errors
3592    ///
3593    /// [`HalError::InvalidDescriptor`] naming the entry that is wrong and what
3594    /// is wrong with it.
3595    fn check_scene(scene: &SceneDesc<'_>) -> Result<(), HalError> {
3596        let refuse = |what: String| Err(HalError::InvalidDescriptor(what));
3597        // A renderer draws meshes, and every table below is sized from them:
3598        // with none, the mesh table's sizing has no level to take a maximum
3599        // of. A scene that draws only the sky is one with meshes and no
3600        // instances.
3601        if scene.meshes.is_empty() {
3602            return refuse(
3603                "a scene description needs at least one mesh; one with meshes and no \
3604                 instances draws only the sky"
3605                    .to_owned(),
3606            );
3607        }
3608        // Every layer's length against its own kind's extent, and layers at no
3609        // extent at all. Checked by the type that owns the page rather than
3610        // here, because that is where a page can be built wrong and where the
3611        // check can be made to fail; see `PageDesc::check`.
3612        scene.page.check()?;
3613        // The probe grid's counts against the rows it carries, which is what
3614        // bounds the shader's fetch. Checked by the type that owns the grid, on
3615        // `PageDesc::check`'s terms exactly — see `ProbeGrid::check`.
3616        scene.probes.check()?;
3617        // A row naming a layer the page does not have is an out-of-range sample,
3618        // which nothing below the seam reports.
3619        //
3620        // **A column carrying `NO_PAGE` is exempt**, and it is the only exempt
3621        // value: it is a sentinel rather than an index — `0xFFFF`, one past
3622        // `mesh::MAX_PAGE_LAYER`, so no page can grow to hold it — and the
3623        // fragment stage never reads a page for it. Exempting it here is what
3624        // lets a material name no texture without the page having to carry a
3625        // layer for it to point at — or, since row (d), having to exist at all.
3626        //
3627        // **Per kind**, because the kinds are separate images with separate
3628        // layer lists and separate extents: a row pointed at a base-colour layer
3629        // number would pass a check that only counted one of them and then
3630        // sample past the end of the other image.
3631        for (row, material) in scene.materials.iter().enumerate() {
3632            for kind in PageKind::ALL {
3633                let names = match kind {
3634                    PageKind::BaseColor => material.base_color_texture,
3635                    PageKind::Normal => material.normal_texture,
3636                    PageKind::MetallicRoughnessOcclusion => {
3637                        material.metallic_roughness_occlusion_texture
3638                    }
3639                    PageKind::Emissive => material.emissive_texture,
3640                };
3641                if names == mesh::GpuMaterial::NO_PAGE {
3642                    continue;
3643                }
3644                let have = scene.page.layers(kind).len();
3645                if names as usize >= have {
3646                    return refuse(format!(
3647                        "material row {row} samples {} page layer {names}, and that page \
3648                         has {have}",
3649                        kind.label()
3650                    ));
3651                }
3652            }
3653        }
3654
3655        for (index, desc) in scene.meshes.iter().enumerate() {
3656            let Geometry::Dag { levels, dag, .. } = &desc.geometry else {
3657                continue;
3658            };
3659            // Zipped together at upload and again at
3660            // `ClusterDag::selection_records`, so a short list would silently
3661            // leave a level's clusters reading the level below's vertices.
3662            if levels.len() != dag.levels.len() {
3663                return refuse(format!(
3664                    "mesh {index} ({}) carries {} vertex array(s) for a DAG of {} level(s)",
3665                    desc.label,
3666                    levels.len(),
3667                    dag.levels.len()
3668                ));
3669            }
3670            for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
3671                let want = level.positions.len() * mesh::VERTEX_STRIDE;
3672                if bytes.len() != want {
3673                    return refuse(format!(
3674                        "mesh {index} ({}) level {depth} carries {} vertex byte(s) for {} \
3675                         position(s), which is {want}",
3676                        desc.label,
3677                        bytes.len(),
3678                        level.positions.len()
3679                    ));
3680                }
3681            }
3682        }
3683
3684        // **Every read the mesh stage makes from a cluster array lands inside
3685        // it.** Checked by the type that owns the arrays, on `PageDesc::check`'s
3686        // terms exactly — see `MeshClusters::check`, which is where the reason
3687        // it cannot be checked below the seam is argued. Both variants carry
3688        // the same type beside a vertex count, so both are checked the same way.
3689        for (index, desc) in scene.meshes.iter().enumerate() {
3690            let levels: Vec<(usize, &MeshClusters)> = match &desc.geometry {
3691                Geometry::Flat {
3692                    vertices, clusters, ..
3693                } => vec![(vertices.len() / mesh::VERTEX_STRIDE, clusters)],
3694                Geometry::Dag { dag, .. } => dag
3695                    .levels
3696                    .iter()
3697                    .map(|level| (level.positions.len(), &level.clusters))
3698                    .collect(),
3699            };
3700            for (depth, (vertices, clusters)) in levels.into_iter().enumerate() {
3701                if let Err(fault) = clusters.check(vertices) {
3702                    return refuse(format!(
3703                        "mesh {index} ({}) level {depth} {fault}",
3704                        desc.label
3705                    ));
3706                }
3707            }
3708        }
3709
3710        // **Capacity, summed over the whole description**, which is the one
3711        // refusal no pool can make for itself. `MeshPool` and `MaterialTable`
3712        // do refuse their own overflow, but they refuse it part way through
3713        // filling something that already exists, and the pair of numbers
3714        // [`MeshPoolError::PoolExhausted`](crate::mesh_pool::MeshPoolError::PoolExhausted)
3715        // carries to tell fragmentation from a full pool says nothing *here*:
3716        // the pool was created empty a few lines below, nothing has been freed
3717        // in it, so its free list is one block and the largest block and the
3718        // total are the same number. At build the answer is always "raise this
3719        // capacity", so it is said by name and before anything is created.
3720        let mut vertices: u64 = 0;
3721        let mut indices: u64 = 0;
3722        for desc in &scene.meshes {
3723            match &desc.geometry {
3724                Geometry::Flat {
3725                    vertices: bytes,
3726                    indices: list,
3727                    ..
3728                } => {
3729                    // Bytes that are not a whole number of vertices are the
3730                    // pool's to refuse, and it refuses before it allocates.
3731                    vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3732                    indices += list.len() as u64;
3733                }
3734                Geometry::Dag { levels, dag, .. } => {
3735                    for bytes in levels {
3736                        vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3737                    }
3738                    for level in &dag.levels {
3739                        // The call the upload itself makes, so the two cannot
3740                        // disagree about what a level costs.
3741                        indices += level.indices().len() as u64;
3742                    }
3743                }
3744            }
3745        }
3746        let entries: u64 = scene
3747            .meshes
3748            .iter()
3749            .map(|desc| desc.geometry.levels() as u64)
3750            .sum();
3751        for (pool, needed, capacity) in [
3752            ("vertex pool", vertices, scene.capacities.vertices),
3753            ("index pool", indices, scene.capacities.indices),
3754            ("mesh table", entries, scene.capacities.meshes),
3755            (
3756                "material table",
3757                scene.materials.len() as u64,
3758                scene.capacities.materials,
3759            ),
3760            (
3761                "probe table",
3762                scene.probes.probes.len() as u64,
3763                scene.capacities.probes,
3764            ),
3765        ] {
3766            if needed > u64::from(capacity) {
3767                return refuse(format!(
3768                    "the {pool} holds {capacity} and the description needs {needed}"
3769                ));
3770            }
3771        }
3772        Ok(())
3773    }
3774
3775    /// The body of [`ForwardRenderer::with_scene`], recording what it has
3776    /// created into `rollback` as it goes and calling `service` where
3777    /// [`ForwardRenderer::with_scene_serviced`] documents.
3778    ///
3779    /// The small start-up uploads go into `uploads`, which the caller submits
3780    /// once this has returned the renderer — nothing here may read them on the
3781    /// GPU first. What still submits for itself takes the batch's queue.
3782    fn build(
3783        device: &dyn Device,
3784        uploads: &mut UploadBatch<'_>,
3785        target_format: Format,
3786        scene: &SceneDesc<'_>,
3787        geometry_path: GeometryPath,
3788        rollback: &mut Rollback,
3789        service: &mut dyn FnMut(),
3790    ) -> Result<Self, HalError> {
3791        // Before anything exists, so a refused description leaks nothing — see
3792        // `check_scene`, which is where that placement is argued.
3793        Self::check_scene(scene)?;
3794        let queue = uploads.queue();
3795
3796        // Resolved before anything is created, because it decides the *shape*
3797        // of what is created — the bind group layout, which pipeline kind the
3798        // pass builds, and what a bucket's constant block says. A device on the
3799        // mesh path never builds the raster pipeline and a device on either
3800        // indirect tail never builds the mesh one, which is what makes "the
3801        // frame came out of the mesh stage" a fact about the object graph
3802        // rather than a claim about a branch.
3803        let emit = EmitTail::from_path(geometry_path);
3804        // And whether that tail draws a range of buckets per call, which only
3805        // changes what the passes record — the constant blocks carry the words
3806        // both shapes read — so it decides nothing about what is created.
3807        let range_limit = emit.range_limit(&device.caps());
3808        // **A second capability, asked separately.** `Features::TASK_SHADER` is
3809        // not implied by `MESH_SHADER`, so §3.5's per-cluster cull is an
3810        // amplification stage this renderer builds where the device has one and
3811        // leaves out where it does not — and a device without it keeps drawing
3812        // through `mesh_cluster.slang`'s un-amplified `meshMain`, which culls
3813        // nothing and emits every cluster. Same picture, more work.
3814        let culls_clusters = emit.is_mesh()
3815            && device
3816                .caps()
3817                .features
3818                .contains(crcbl_hal::Features::TASK_SHADER);
3819
3820        let (pool, residents) = Self::build_geometry(device, queue, scene, service)?;
3821        // What an `InstanceDesc::mesh` index resolves through: one id per
3822        // description mesh, in description order, and each of them that mesh's
3823        // **level 0** whatever the path — because it is the entry the cull pass
3824        // reads a bounding box out of, and a DAG's coarser levels approximate
3825        // the same surface inside the same box.
3826        let mesh_ids: Vec<u32> = residents.iter().map(ResidentMesh::id).collect();
3827        // The scene's own triangles, kept for the probe-visibility capture and
3828        // for nothing else — and kept at all only when the description reserves
3829        // a probe, so a scene without one pays no memory for this rung. Taken
3830        // here because `scene` is the caller's and is read once.
3831        let probe_occluders = crate::probe_visibility::Occluders::from_scene(scene, &mesh_ids);
3832        // The same list one level down: what a caller reserving a skinned region
3833        // names its mesh with. Read here beside the ids rather than from
3834        // `residents` later, because the descriptions this came from are the
3835        // caller's and are read once.
3836        let skinnable_meshes: Vec<Option<MeshHandle>> =
3837            residents.iter().map(|mesh| mesh.skinnable).collect();
3838        // The handles are `Copy`, so they can be read out before the pool
3839        // becomes the rollback's — which it must be before the first `?` below,
3840        // or a failed pipeline would leak two device-local buffers. The index
3841        // pool is not named here at all: it is bound at draw time rather than
3842        // descriptor-written, so only the vertex pool and the mesh table reach a
3843        // bind group.
3844        let vertices = pool.vertex_buffer();
3845        let mesh_table = pool.table_buffer();
3846        rollback.pool = Some(pool);
3847
3848        // §3.2's texture side, before the table that indexes it: a material row
3849        // is written with a layer number, so the layer has to exist to be named.
3850        //
3851        // **One loop over [`PageKind::ALL`]**, because the kinds differ only in
3852        // three answers the kind itself owns — its format, its mip filter and
3853        // its device label — and everything else about creating a page is the
3854        // same code. Two hand-written copies were what let the normal page be
3855        // created through the colour page's filter for as long as nobody
3856        // compared the two, and rung 3 adds two more kinds to get wrong.
3857        //
3858        // **`Rgba8UnormSrgb` on the base-colour page, `Rgba8Unorm` on the
3859        // normal page, and that is the colour-space decision.** A base-colour
3860        // description's texels are sRGB-encoded, which is what glTF defines a
3861        // base-colour texture to be, so the format is what makes the sampler
3862        // decode them — and `mesh.slang` then multiplies a linear texel by a
3863        // linear `base_color` and lights in linear, exactly as it did before
3864        // there was a texture. A normal texel is a *number* and nothing decodes
3865        // it. See `PageKind::format`, and topic 44's rung 2.
3866        //
3867        // Every layer's length against its kind's extent was settled by
3868        // `check_scene` above, before this device object existed.
3869        //
3870        // **Every layer goes up with its mip chain**, built here on the host by
3871        // [`crate::mip`] — topic 43's filtering rung.
3872        // The chain is what a trilinear sampler needs to stop shimmering on a
3873        // minified surface, and it is built at upload rather than by a compute
3874        // pass because the page's format is what decodes it and a host chain is
3875        // the same bytes on every backend.
3876        //
3877        // **A kind with no layers takes one texel.** `upload_texture_mip_layers`
3878        // refuses a zero-layer image and every bind group has to fill both page
3879        // bindings, so a page nothing names is created 1×1 in its own format
3880        // holding [`PAGE_PLACEHOLDER_TEXEL`] — which the shader never reads,
3881        // and which is magenta so that a frame says so if it ever does.
3882        //
3883        // The upload itself is [`upload_page`], shared with
3884        // [`ForwardRenderer::replace_page`] so a page reloaded under a running
3885        // renderer is built exactly as this one was. A layer's chain is host
3886        // work proportional to its texels, so a page of many large layers is
3887        // serviced one layer at a time.
3888        let mut pages: [Option<UploadedTexture>; PageKind::ALL.len()] = [None; PageKind::ALL.len()];
3889        let mut page_extents = [(1, 1); PageKind::ALL.len()];
3890        let mut page_layers = [0; PageKind::ALL.len()];
3891        for kind in PageKind::ALL {
3892            let layers = scene.page.layers(kind);
3893            let (page, extent) = upload_page(
3894                device,
3895                queue,
3896                kind,
3897                scene.page.extent(kind),
3898                layers,
3899                service,
3900            )?;
3901            rollback.textures.push(page);
3902            page_extents[kind.index()] = (extent, extent);
3903            page_layers[kind.index()] = layers.len();
3904            pages[kind.index()] = Some(page);
3905            service();
3906        }
3907        let [
3908            Some(base_color_page),
3909            Some(normal_page),
3910            Some(mro_page),
3911            Some(emissive_page),
3912        ] = pages
3913        else {
3914            unreachable!("the loop above fills a slot for every PageKind::ALL entry");
3915        };
3916
3917        // The page's sampler at the device's default — see `create_page_sampler`
3918        // for what it filters, and `set_anisotropy` for how a caller moves it.
3919        let anisotropy = Self::anisotropy_for(&device.caps());
3920        let base_color_sampler = Self::create_page_sampler(device, anisotropy)?;
3921        rollback.samplers.push(base_color_sampler);
3922        // What every slot's groups are built naming, and what each moves off
3923        // only at its own frame — see `ForwardRenderer::adopt_pages`.
3924        let page_bindings = PageBindings {
3925            sampler: base_color_sampler,
3926            views: [
3927                base_color_page.view,
3928                normal_page.view,
3929                mro_page.view,
3930                emissive_page.view,
3931            ],
3932        };
3933
3934        // The material table, before the instances: an instance is written with
3935        // the material id it carries, so the row has to exist to be named.
3936        let (materials, material_ids) = Self::build_materials(device, scene)?;
3937        let material_buffer = materials.buffer();
3938        rollback.materials = Some(materials);
3939
3940        // Topic 50's irradiance grid: the table is created here once, and
3941        // `crate::probe_gather`'s compute pass rewrites its rows every frame —
3942        // see [`crate::probe`]. **Created even for a description with no probes**, because
3943        // every group of this layout has to fill [`PROBE_TABLE_BINDING`] and the
3944        // honest filler for "no probes were authored" is the zeroed row the
3945        // shader's clamp lands on.
3946        let probe_table = ProbeTable::new(
3947            device,
3948            queue,
3949            &ProbeTableDesc {
3950                label: Some("forward"),
3951                capacity: scene.capacities.probes,
3952                frames: FRAMES_IN_FLIGHT,
3953            },
3954        )?;
3955        // Into the rollback before it is filled, so a copy that fails releases
3956        // the buffers rather than leaking them.
3957        rollback.probes = Some(probe_table);
3958        let probe_table = rollback.probes.as_ref().expect("just stored");
3959        probe_table.fill(device, queue, &scene.probes.probes)?;
3960        // Read out here, like the instance ring's below and for the same
3961        // reason: the handles are `Copy`, and the loop that builds the bind
3962        // groups mutates the rollback the table now lives in.
3963        let probe_buffers: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
3964            .map(|frame| probe_table.buffer(frame))
3965            .collect();
3966        // The irradiance probes' updater, built **only** for a
3967        // description that asked for it. A volume left at
3968        // [`ProbeUpdate::Authored`] gets no pipeline, no buffers and no pass, so
3969        // the default really is the frame every scene drew before this landed.
3970        let probe_gather = match scene.probes.update {
3971            ProbeUpdate::Authored => None,
3972            ProbeUpdate::EveryFrame => Some(ProbeGather::new(
3973                device,
3974                &ProbeGatherDesc {
3975                    label: Some("forward probes"),
3976                    volume: scene.probes.volume,
3977                    probes: &probe_buffers,
3978                },
3979            )?),
3980        };
3981        rollback.probe_gather = probe_gather;
3982        let probe_gather = rollback.probe_gather.take();
3983        service();
3984
3985        // **Empty.** Every object in the scene arrives through
3986        // [`ForwardRenderer::add_instance`], including the demo scene's cube: a
3987        // renderer that inserted one of its description's meshes here would put
3988        // an object in a caller's frame that the caller never asked for.
3989        let instances = InstancePool::new(
3990            device,
3991            &InstancePoolDesc {
3992                label: Some("forward instances"),
3993                capacity: scene.capacities.instances,
3994                frames_in_flight: FRAMES_IN_FLIGHT,
3995            },
3996        )?;
3997        // Same handle-then-hand-over dance as the geometry pool above: the
3998        // buffers are `Copy` and are read out before the pool becomes the
3999        // rollback's, which it must be before the first `?` below — after which
4000        // nothing needs the pool again until `begin_frame`.
4001        let instance_buffers: Vec<BufferHandle> = instances.buffers().to_vec();
4002        rollback.instances = Some(instances);
4003
4004        // The two compute passes, and the buffers the draws come out of. Built
4005        // here rather than beside the pipelines below because the mesh bind
4006        // group names one of its buffers, so it has to exist first.
4007        //
4008        // The bucket table, and the one place its order is decided.
4009        //
4010        // **Built by walking the description**, which is what makes a duplicate
4011        // structurally impossible rather than refused: every bucket's mesh id is
4012        // the id of the description mesh it came from, and two description
4013        // meshes are two uploads with two table entries however alike their
4014        // geometry is. That matters because `draw_gen.slang`'s scatter takes the
4015        // *first* bucket whose mesh id matches, so a second bucket naming one
4016        // mesh would never draw anything at all.
4017        //
4018        // One bucket per mesh, except for two things. A DAG is one bucket where
4019        // an amplification stage picks its cut per cluster and one per level
4020        // where the cull pass picks a uniform one — see [`buckets_for`]. And the
4021        // whole run is repeated once per **material mode** the scene holds, so
4022        // an instance's mode picks a bucket exactly as its mesh does; see
4023        // [`ForwardRenderer::bucket_modes`].
4024        //
4025        // **Mode-major: every mesh's run for one mode, then the next mode's.**
4026        // A mode picks the pipeline a pass binds, so this makes each pipeline's
4027        // partition — [`ForwardRenderer::depth_partitions`] and
4028        // [`ForwardRenderer::sided_partitions`] — one contiguous run of
4029        // buckets, which a device with a draw index records as one ranged call
4030        // rather than a call per bucket — and which the mesh tail behind a
4031        // task stage must have, because it draws each partition as one flat
4032        // call of its run. `DEPTH_MODES` order makes a sided partition one run
4033        // too: opaque sits beside masked, and double-sided beside both.
4034        //
4035        // **Once per mode the scene holds, not once per mode that exists.** A
4036        // scene whose materials are all opaque gets exactly the table it always
4037        // had — same length, same order, same bytes — so the twin costs nothing
4038        // where nothing is masked, which is every demo and every golden here. A
4039        // bucket is not free: every pass records one indirect call per bucket
4040        // per view, and every generator holds its run start.
4041        let scene_modes: Vec<u32> = {
4042            let held: Vec<u32> = DEPTH_MODES
4043                .into_iter()
4044                .filter(|mode| {
4045                    scene
4046                        .materials
4047                        .iter()
4048                        .any(|material| material.mode() == *mode)
4049                })
4050                .collect();
4051            // A description with no materials at all still needs a bucket per
4052            // mesh, or nothing it holds can be drawn.
4053            if held.is_empty() {
4054                vec![DEPTH_MODES[0]]
4055            } else {
4056                held
4057            }
4058        };
4059        // One mode's run: every description mesh's levels, in description
4060        // order. `bucket_bases` is where each mesh starts within it, so the
4061        // tables below can be filled in mesh by mesh rather than by re-deriving
4062        // the arithmetic; mode slot `s` of the mesh is `s` runs further on.
4063        let mut mode_run: Vec<u32> = Vec::new();
4064        let mut bucket_bases: Vec<usize> = Vec::with_capacity(residents.len());
4065        for resident in &residents {
4066            bucket_bases.push(mode_run.len());
4067            mode_run
4068                .extend_from_slice(&resident.levels[..buckets_for(resident.levels.len(), emit)]);
4069        }
4070        let mut bucket_meshes: Vec<u32> = Vec::with_capacity(mode_run.len() * scene_modes.len());
4071        // The mode each of those buckets draws, in step with it.
4072        let mut bucket_modes: Vec<u32> = Vec::with_capacity(bucket_meshes.capacity());
4073        for mode in &scene_modes {
4074            bucket_meshes.extend_from_slice(&mode_run);
4075            bucket_modes.extend(std::iter::repeat_n(*mode, mode_run.len()));
4076        }
4077        let bucket_count = u32::try_from(bucket_meshes.len())
4078            .unwrap_or_else(|_| unreachable!("a table of a few buckets"));
4079
4080        // Topic 25's selection tables, and the one thing that
4081        // decides whether `draw_gen.slang` takes a uniform cut at all.
4082        //
4083        // Every mesh id gets an entry, because the shader indexes this with
4084        // `GpuInstance::mesh` and an instance can name any of them; the default
4085        // is `MeshLevels::FLAT` pointing at a level run that is the mesh itself,
4086        // so a mesh with no hierarchy resolves back to itself with no branch.
4087        // **A DAG keeps that default on the mesh path**, which is how a device
4088        // already descending it per cluster avoids a second, coarser cut on top
4089        // of it — the suppression is data rather than a branch in the shader.
4090        //
4091        // **Sized by the mesh table's capacity, not by the meshes resident in
4092        // it**, because that is the invariant `draw_gen.slang`'s
4093        // `mesh_levels_of` states and indexes on: "every entry an instance can
4094        // name is filled". The read is unbounded and an instance's mesh id is a
4095        // bare table index, so a table sized to the description alone is an
4096        // out-of-range read of whatever the packer laid down next for any id the
4097        // description did not fill. What it finds there decides the frame: zeros
4098        // resolve to mesh 0 and draw another mesh's geometry, and a live
4099        // `group_count` sends `select_level`'s loop over a count no allocation
4100        // backs, which on radv is a hard GPU recovery rather than a wrong
4101        // picture. That is not a hypothetical: it is what a skinned instance
4102        // naming an alias entry did until 2026-08, before it learned to name its
4103        // source mesh instead.
4104        let table_len = usize::try_from(scene.capacities.meshes)
4105            .unwrap_or(usize::MAX)
4106            .max(
4107                usize::try_from(
4108                    residents
4109                        .iter()
4110                        .flat_map(|resident| resident.levels.iter().copied())
4111                        .max()
4112                        .unwrap_or_else(|| {
4113                            unreachable!("check_scene refused an empty description")
4114                        })
4115                        + 1,
4116                )
4117                .unwrap_or_else(|_| unreachable!("a table of a few meshes")),
4118            );
4119        let mut level_meshes: Vec<u32> = (0..table_len)
4120            .map(|id| u32::try_from(id).unwrap_or_else(|_| unreachable!("bounded by table_len")))
4121            .collect();
4122        let mut mesh_levels: Vec<level_select::MeshLevels> = level_meshes
4123            .iter()
4124            .map(|&id| level_select::MeshLevels {
4125                first_level: id,
4126                ..level_select::MeshLevels::FLAT
4127            })
4128            .collect();
4129        // Every DAG's groups end to end, in description order, and where each
4130        // one's run starts. `ClusterSelect` records name a group by its index in
4131        // *this* array — see `ClusterDag::selection_records`' `first_group` — so
4132        // several DAGs concatenate without `crcbl-shaders` knowing they did.
4133        let mut level_groups: Vec<level_select::LevelGroup> = Vec::new();
4134        let mut first_groups: Vec<u32> = Vec::with_capacity(residents.len());
4135        for (index, desc) in scene.meshes.iter().enumerate() {
4136            first_groups.push(
4137                u32::try_from(level_groups.len())
4138                    .unwrap_or_else(|_| unreachable!("a few dozen groups per DAG")),
4139            );
4140            let Geometry::Dag { dag, .. } = &desc.geometry else {
4141                continue;
4142            };
4143            let groups = dag.level_groups();
4144            let id = residents[index].id();
4145            mesh_levels[id as usize] = level_select::MeshLevels {
4146                first_group: first_groups[index],
4147                group_count: u32::try_from(groups.len())
4148                    .unwrap_or_else(|_| unreachable!("a DAG of a few dozen groups")),
4149                // **The mesh path suppresses the uniform cut with a top level of
4150                // zero, not with a group count of zero**, and the difference is
4151                // the hysteresis state: `draw_gen.slang` judges every group it is
4152                // given whatever level it answers, and the amplification stage
4153                // reads those answers. A record naming no groups would leave the
4154                // state untouched and every cluster of the patch collapsed. A
4155                // top level of zero makes the level loop's minimum unreachable,
4156                // so the instance routes to the mesh it already names — which is
4157                // level 0.
4158                first_level: if emit.is_mesh() {
4159                    id
4160                } else {
4161                    u32::try_from(level_meshes.len())
4162                        .unwrap_or_else(|_| unreachable!("a table of a few meshes"))
4163                },
4164                top_level: if emit.is_mesh() {
4165                    0
4166                } else {
4167                    u32::try_from(residents[index].levels.len() - 1)
4168                        .unwrap_or_else(|_| unreachable!("a DAG of a few levels"))
4169                },
4170            };
4171            level_groups.extend(groups);
4172            if !emit.is_mesh() {
4173                level_meshes.extend_from_slice(&residents[index].levels);
4174            }
4175        }
4176
4177        // §3.5's clusters, on the path that reads them and on no other. The
4178        // records are `crcbl-shaders`' — cooked, because the builder is
4179        // `crcbl-scene`'s and the renderer must not depend on that crate — and
4180        // they arrive in bucket-mesh order so a bucket's range is its own
4181        // index. See `crate::cluster_pool`.
4182        //
4183        // Before the draw generation below rather than after it, because the
4184        // per-bucket cluster counts are the x extent of each bucket's mesh
4185        // dispatch and that pass writes the argument structure carrying them.
4186        let mut bucket_clusters = vec![0u32; bucket_meshes.len()];
4187        let mut bucket_cluster_bases = vec![0u32; bucket_meshes.len()];
4188        let mut mesh_clusters: Vec<ClusterRange> = Vec::new();
4189        if emit.is_mesh() {
4190            // A flat mesh is one pool entry and its clusters carry
4191            // `ClusterSelect::ALWAYS`, so the descent draws them from every
4192            // camera; a DAG is **one entry per level**, laid end to end.
4193            let mut cooked: Vec<PooledMesh> = Vec::with_capacity(residents.len());
4194            // Where each description mesh's entries start, on `bucket_bases`'
4195            // terms — the two differ exactly where a DAG's levels are one bucket
4196            // and several entries.
4197            let mut entry_bases: Vec<usize> = Vec::with_capacity(residents.len());
4198            for (index, desc) in scene.meshes.iter().enumerate() {
4199                entry_bases.push(cooked.len());
4200                match &desc.geometry {
4201                    Geometry::Flat { clusters, .. } => {
4202                        cooked.push(PooledMesh::without_lod(clusters.clone()));
4203                    }
4204                    Geometry::Dag { dag, .. } => {
4205                        let selection = dag
4206                            .selection_records(&residents[index].vertex_bases, first_groups[index]);
4207                        for (level, records) in dag.levels.iter().zip(selection) {
4208                            cooked.push(PooledMesh {
4209                                clusters: level.clusters.clone(),
4210                                selection: records,
4211                            });
4212                        }
4213                    }
4214                }
4215            }
4216
4217            let clusters = ClusterPool::new(device, "forward", &cooked)?;
4218            let range = |entry: usize| {
4219                clusters
4220                    .range(entry)
4221                    .unwrap_or_else(|| unreachable!("one range per entry, in order"))
4222            };
4223            // **A DAG's levels are one run, not one per bucket.** `concatenate`
4224            // lays the entries down in the order it was given them, so the
4225            // levels are contiguous: the bucket starts where level 0 does and
4226            // reaches to the end of the last level. That is what lets one
4227            // dispatch cover a cut spanning several of them — and it is why a
4228            // flat mesh, whose one entry is the whole sum, needs no second case.
4229            mesh_clusters.reserve(residents.len());
4230            for (index, resident) in residents.iter().enumerate() {
4231                let entry = entry_bases[index];
4232                let base = range(entry).base;
4233                let count: u32 = (entry..entry + resident.levels.len())
4234                    .map(|entry| range(entry).count)
4235                    .sum();
4236                // **Every one of this mesh's buckets, not only the first.** A
4237                // mode twin draws the same geometry, so it dispatches over the
4238                // same clusters; a twin left at zero launches no workgroup and
4239                // its instances vanish from the frame. One bucket per mode here,
4240                // because the mesh path takes `buckets_for` of one, each a whole
4241                // mode's run past the one before.
4242                for slot in 0..scene_modes.len() {
4243                    let bucket = slot * mode_run.len() + bucket_bases[index];
4244                    bucket_cluster_bases[bucket] = base;
4245                    bucket_clusters[bucket] = count;
4246                }
4247                mesh_clusters.push(ClusterRange { base, count });
4248            }
4249
4250            rollback.clusters = Some(clusters);
4251            service();
4252        }
4253
4254        // One ring per shadow view, indexed `[view][frame]`: topic 25's
4255        // observable, one word per resident cluster holding the cut the descent
4256        // chose — see `ForwardRenderer::shadow_selection` for why a view cannot
4257        // share the camera's, which [`View::build`] allocates beside its cull.
4258        //
4259        // Allocated on the whole mesh path rather than only where there is an
4260        // amplification stage to write them, because the layout declares
4261        // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued.
4262        let mut tile_selection: Vec<Vec<BufferHandle>> = Vec::new();
4263        if emit.is_mesh() {
4264            let count = rollback
4265                .clusters
4266                .as_ref()
4267                .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
4268                .count();
4269            let mut ring = |label: &str| -> Result<Vec<BufferHandle>, HalError> {
4270                let mut buffers = Vec::with_capacity(instance_buffers.len());
4271                for frame in 0..instance_buffers.len() {
4272                    let buffer = device.create_buffer(&BufferDesc {
4273                        label: Some(&format!("{label} {frame}")),
4274                        size: u64::from(count) * 4,
4275                        usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
4276                        memory: MemoryLocation::DeviceLocal,
4277                    })?;
4278                    rollback.buffers.push(buffer);
4279                    buffers.push(buffer);
4280                }
4281                Ok(buffers)
4282            };
4283            for view in 0..SHADOW_VIEWS {
4284                tile_selection.push(ring(&format!("shadow selection {view}"))?);
4285            }
4286        }
4287
4288        // --- the mesh pass ---
4289        //
4290        // No `BindingFlags` anywhere: this layout is legal on **both** tiers,
4291        // because a lit mesh is not a Tier A feature. The bindless shape — a
4292        // trailing `VARIABLE_COUNT | PARTIALLY_BOUND | UPDATE_AFTER_BIND`
4293        // texture array — is topic 03's, at P3.
4294        // **Which stage pulls the geometry**, and the only thing the two shapes
4295        // of this layout disagree about for bindings 0 to 8. `ShaderStages::MESH`
4296        // is outside `GRAPHICS` and `ALL`, so it is named rather than implied,
4297        // and every backend refuses a layout carrying it on a device without
4298        // `Features::MESH_SHADER` — which is exactly the device that never
4299        // reaches this arm.
4300        //
4301        // **`TASK` joins it when there is an amplification stage**, and the
4302        // union is deliberately over every binding rather than the eight
4303        // `taskMain` actually reads. Slang's Metal backend materialises every
4304        // global in every entry point of a module — the argument bindings 6 to
4305        // 8 already carry — so a layout that named only the task stage's own
4306        // reads would be a layout `msl/mesh_cluster.metal` disagrees with, on a
4307        // runner this team cannot debug on.
4308        let geometry = match (emit.is_mesh(), culls_clusters) {
4309            (true, true) => ShaderStages::MESH.union(ShaderStages::TASK),
4310            (true, false) => ShaderStages::MESH,
4311            (false, _) => ShaderStages::VERTEX,
4312        };
4313        let mut mesh_entries = vec![
4314            BindGroupLayoutEntry {
4315                binding: 0,
4316                visibility: geometry.union(ShaderStages::FRAGMENT),
4317                kind: BindingKind::UniformBuffer { dynamic: false },
4318                count: 1,
4319                flags: BindingFlags::empty(),
4320            },
4321            BindGroupLayoutEntry {
4322                binding: 1,
4323                // **Both stages, and here it is the FRAGMENT half that needs
4324                // saying** — binding 6 and 7 are the mirror image, where the
4325                // fragment stage plainly reads the row and the vertex half is
4326                // the one Slang forces. Slang's Metal backend materialises
4327                // every module global into every entry point, so
4328                // `msl/mesh.metal`'s `fragmentMain` takes this buffer whether
4329                // its body dereferences it or not — and Metal's debug layer
4330                // answers a declared-but-unbound fragment argument with
4331                // `missing Buffer binding at index N`, once per draw. Vulkan,
4332                // D3D12 and WebGPU all accept a visibility wider than the
4333                // shader's reads, so naming FRAGMENT costs them nothing but the
4334                // entry itself.
4335                //
4336                // **It does not cost a redundant bind on Metal either**, and
4337                // that is what makes it safe rather than a trade: `crcbl-mtl`
4338                // consults `MTLPipelineOption::BindingInfo` reflection and
4339                // issues the fragment-stage bind only where `MTLBinding::isUsed`
4340                // says the compiled function kept the argument. This entry is
4341                // the permission; the reflection is the decision.
4342                visibility: geometry.union(ShaderStages::FRAGMENT),
4343                kind: BindingKind::StorageBuffer {
4344                    // The shader says `StructuredBuffer`, not
4345                    // `RWStructuredBuffer`, so this is the truth rather than a
4346                    // hint — and it is what lets the graph merge read-after-read.
4347                    read_only: true,
4348                    dynamic: false,
4349                    stride: size_of::<u32>() as u32,
4350                },
4351                count: 1,
4352                flags: BindingFlags::empty(),
4353            },
4354            BindGroupLayoutEntry {
4355                binding: 2,
4356                // Both stages, for binding 1's reason exactly.
4357                visibility: geometry.union(ShaderStages::FRAGMENT),
4358                kind: BindingKind::StorageBuffer {
4359                    // `StructuredBuffer` again: the vertex stage reads its
4360                    // instance and writes nothing. The *host* writes this one
4361                    // every frame, which is a mapped write rather than a shader
4362                    // one and does not make it read-write here.
4363                    read_only: true,
4364                    dynamic: false,
4365                    stride: crcbl_shaders::mesh::INSTANCE_STRIDE as u32,
4366                },
4367                count: 1,
4368                flags: BindingFlags::empty(),
4369            },
4370            BindGroupLayoutEntry {
4371                binding: 3,
4372                // Both stages, for binding 1's reason exactly.
4373                visibility: geometry.union(ShaderStages::FRAGMENT),
4374                // `dynamic: true`, and it is the whole mechanism: it is what
4375                // lets a draw say where its run of instances starts without
4376                // `draw_indexed`'s own base instance, which the module docs and
4377                // `mesh.slang`'s header explain the targets disagree about.
4378                // Same shape, for the same reason, as `crate::sprite_pass`'s.
4379                kind: BindingKind::UniformBuffer { dynamic: true },
4380                count: 1,
4381                flags: BindingFlags::empty(),
4382            },
4383            BindGroupLayoutEntry {
4384                binding: 4,
4385                // Both stages, for binding 1's reason exactly.
4386                visibility: geometry.union(ShaderStages::FRAGMENT),
4387                kind: BindingKind::StorageBuffer {
4388                    // The mesh table. `StructuredBuffer` again — the vertex
4389                    // stage looks its mesh up and writes nothing — and one
4390                    // buffer shared by every frame's group, because unlike the
4391                    // instance array nothing rewrites it between frames.
4392                    read_only: true,
4393                    dynamic: false,
4394                    stride: crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32,
4395                },
4396                count: 1,
4397                flags: BindingFlags::empty(),
4398            },
4399            BindGroupLayoutEntry {
4400                binding: 5,
4401                // Both stages, for binding 1's reason exactly.
4402                visibility: geometry.union(ShaderStages::FRAGMENT),
4403                kind: BindingKind::StorageBuffer {
4404                    // The per-bucket runs of surviving instances. Read-only
4405                    // here and written by the draw-argument pass, which is a
4406                    // different bind group and a different pass — the graph is
4407                    // what orders the two.
4408                    read_only: true,
4409                    dynamic: false,
4410                    stride: size_of::<u32>() as u32,
4411                },
4412                count: 1,
4413                flags: BindingFlags::empty(),
4414            },
4415            BindGroupLayoutEntry {
4416                binding: 6,
4417                // **Both stages, and the union is not belt-and-braces.** The
4418                // fragment stage is where `mesh.slang` now reads the table, so
4419                // it plainly needs it — a pipeline layout that leaves it out is
4420                // refused outright by wgpu and reported as
4421                // `VUID-VkGraphicsPipelineCreateInfo-layout-07988` by Vulkan.
4422                // The vertex half has to stay because Slang's Metal backend
4423                // materialises every global in every entry point: `vertexMain`
4424                // in `msl/mesh.metal` still takes `materials [[buffer(6)]]`
4425                // whether it reads it or not, so dropping VERTEX would break
4426                // Metal alone, on a runner this team cannot debug on.
4427                visibility: geometry.union(ShaderStages::FRAGMENT),
4428                kind: BindingKind::StorageBuffer {
4429                    // The material table. One buffer in every frame's group,
4430                    // like the mesh table above and unlike the instance ring:
4431                    // a material is written when it is created, not per frame.
4432                    read_only: true,
4433                    dynamic: false,
4434                    stride: crcbl_shaders::mesh::MATERIAL_STRIDE as u32,
4435                },
4436                count: 1,
4437                flags: BindingFlags::empty(),
4438            },
4439            BindGroupLayoutEntry {
4440                binding: BASE_COLOR_PAGE_BINDING,
4441                // Both stages, for binding 6's reason exactly: the fragment
4442                // stage samples it, and Slang's Metal backend materialises
4443                // every global in every entry point — `vertexMain` in
4444                // `msl/mesh.metal` takes the texture whether it reads it or
4445                // not, so a layout without VERTEX would break Metal alone.
4446                visibility: geometry.union(ShaderStages::FRAGMENT),
4447                // **`D2Array`, and the layout is where wgpu wants to hear it.**
4448                // The other three backends read the dimension off the bound
4449                // view and never consult this; WebGPU compares the two at
4450                // pipeline creation and refuses the pair, which is what a
4451                // layout claiming `D2` over an array view got — "expects
4452                // dimension = D2, but given a view with dimension = D2Array".
4453                kind: BindingKind::SampledImage {
4454                    view_type: ImageViewType::D2Array,
4455                    sample_type: SampleType::Float,
4456                },
4457                // **`count: 1`, and this is the binding-model decision.** One
4458                // `D2Array` image whose *layers* the material rows index is
4459                // `BindingModel::ArrayPages`; an array of `count` descriptors
4460                // indexed per fragment would be `Bindless` and would need
4461                // `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws.
4462                // So this layout is legal on every device, exactly as the six
4463                // buffers above are, and no `BindingFlags` appear anywhere in
4464                // this file yet.
4465                count: 1,
4466                flags: BindingFlags::empty(),
4467            },
4468            BindGroupLayoutEntry {
4469                binding: PAGE_SAMPLER_BINDING,
4470                visibility: geometry.union(ShaderStages::FRAGMENT),
4471                kind: BindingKind::Sampler { comparison: false },
4472                count: 1,
4473                flags: BindingFlags::empty(),
4474            },
4475        ];
4476        if emit.is_mesh() {
4477            // §3.5's four extra reads, and only on the path that has them.
4478            // Adding them unconditionally would make every device declare four
4479            // buffers `mesh.slang` does not name — and WebGPU, which checks a
4480            // bind group against its layout entry for entry, would then need
4481            // four buffers created for a path that never reads them.
4482            //
4483            // `read_only: true` on all four, which is the truth rather than a
4484            // hint: the mesh stage indexes them and writes nothing, and it is
4485            // what lets the graph merge read-after-read.
4486            //
4487            // Four different element types, so four strides, in binding order:
4488            // the clusters (`Meshlet`), the cluster vertex and corner pools
4489            // (`uint` each), and the per-cluster draw arguments
4490            // (`DrawIndexedArgs`, the indirect layout every API agrees on).
4491            let cluster_strides = [
4492                crcbl_shaders::meshlet::MESHLET_STRIDE as u32,
4493                size_of::<u32>() as u32,
4494                size_of::<u32>() as u32,
4495                crcbl_hal::indirect::DRAW_INDEXED_ARGS_BYTES as u32,
4496            ];
4497            mesh_entries.extend(
4498                (CLUSTERS_BINDING..=CLUSTER_DRAW_ARGS_BINDING)
4499                    .zip(cluster_strides)
4500                    .map(|(binding, stride)| {
4501                        BindGroupLayoutEntry {
4502                            binding,
4503                            // **Not the fragment stage.** These four are the geometry
4504                            // stage's alone, and `mesh_cluster.slang` has no fragment entry
4505                            // point of its own to materialise them into — its fragment
4506                            // stage is `mesh.slang`'s, which does not declare mesh-only
4507                            // buffers.
4508                            visibility: geometry,
4509                            kind: BindingKind::StorageBuffer {
4510                                read_only: true,
4511                                dynamic: false,
4512                                stride,
4513                            },
4514                            count: 1,
4515                            flags: BindingFlags::empty(),
4516                        }
4517                    }),
4518            );
4519        }
4520        // Both mesh entry points retain these declarations. Omitting unused
4521        // task buffers would shift later native buffer indices on the plain
4522        // mesh path, so the layout includes them on both paths.
4523        if emit.is_mesh() {
4524            mesh_entries.push(BindGroupLayoutEntry {
4525                binding: CLUSTER_CULL_BINDING,
4526                visibility: geometry,
4527                // **The same block the instance cull reads**, not a copy: one
4528                // camera, one frustum, and no way for the two rejections to
4529                // disagree about which. `dynamic: false` because there is one
4530                // block per frame rather than one per bucket.
4531                kind: BindingKind::UniformBuffer { dynamic: false },
4532                count: 1,
4533                flags: BindingFlags::empty(),
4534            });
4535            mesh_entries.push(BindGroupLayoutEntry {
4536                binding: CLUSTER_CULL_STATS_BINDING,
4537                visibility: geometry,
4538                kind: BindingKind::StorageBuffer {
4539                    // **The one writable binding this pass has.** The stage adds
4540                    // to a counter, so `read_only: false` is the truth rather
4541                    // than a hint, and it is what makes the graph order this
4542                    // write after the draw-argument pass's read of the same
4543                    // buffer.
4544                    read_only: false,
4545                    dynamic: false,
4546                    stride: size_of::<u32>() as u32,
4547                },
4548                count: 1,
4549                flags: BindingFlags::empty(),
4550            });
4551        }
4552        // Topic 18's cascades, read by the fragment stage and declared last —
4553        // above `mesh_cluster.slang`'s range rather than inside it, for the
4554        // reason `SHADOW_ATLAS_BINDING` gives.
4555        //
4556        // Both carry `geometry` in their visibility beside `FRAGMENT`, for
4557        // binding 7's reason exactly: Slang's Metal backend materialises every
4558        // global into every entry point, and `msl/mesh.metal`'s `vertexMain`
4559        // takes `shadow_atlas [[texture(1)]]` and `shadow_sampler
4560        // [[sampler(1)]]` whether it reads them or not.
4561        mesh_entries.push(BindGroupLayoutEntry {
4562            binding: SHADOW_ATLAS_BINDING,
4563            visibility: geometry.union(ShaderStages::FRAGMENT),
4564            kind: BindingKind::SampledImage {
4565                view_type: ImageViewType::D2,
4566                // **`Depth`, and this is the field the seam grew for this
4567                // pass.** WebGPU will only bind a `D32Float` view through a
4568                // depth sample type, and its shader side agrees — the WGSL
4569                // artifact declares `texture_depth_2d`. The other three
4570                // backends take the interpretation off the view's format and
4571                // never read this.
4572                sample_type: SampleType::Depth,
4573            },
4574            count: 1,
4575            flags: BindingFlags::empty(),
4576        });
4577        mesh_entries.push(BindGroupLayoutEntry {
4578            binding: SHADOW_SAMPLER_BINDING,
4579            visibility: geometry.union(ShaderStages::FRAGMENT),
4580            // The sampler-side twin of the line above: `sampler_comparison` in
4581            // the WGSL, `SamplerComparisonState` in the HLSL, and a
4582            // `compareEnable` on the Vulkan sampler object. The layout has to
4583            // say so on WebGPU and cannot on the other three.
4584            kind: BindingKind::Sampler { comparison: true },
4585            count: 1,
4586            flags: BindingFlags::empty(),
4587        });
4588        // DAG geometry and selection state, in the mesh-only binding range.
4589        if emit.is_mesh() {
4590            mesh_entries.push(BindGroupLayoutEntry {
4591                binding: CLUSTER_SELECT_BINDING,
4592                visibility: geometry,
4593                // Read-only and read by **both** mesh entry points, unlike the
4594                // pair below: a cluster's `vertex_base` is which level of a DAG
4595                // its geometry lives in, which an un-amplified stage needs just
4596                // as much as an amplified one.
4597                kind: BindingKind::StorageBuffer {
4598                    read_only: true,
4599                    dynamic: false,
4600                    stride: crcbl_shaders::cluster_select::CLUSTER_SELECT_STRIDE as u32,
4601                },
4602                count: 1,
4603                flags: BindingFlags::empty(),
4604            });
4605        }
4606        // Both on the whole mesh path, for the two above's reason exactly: the
4607        // amplification stage is the only writer and the only reader, and the
4608        // Metal argument table counts entries rather than reading binding
4609        // numbers.
4610        if emit.is_mesh() {
4611            mesh_entries.push(BindGroupLayoutEntry {
4612                binding: CLUSTER_SELECTION_BINDING,
4613                visibility: geometry,
4614                kind: BindingKind::StorageBuffer {
4615                    // The second writable binding: the amplification stage
4616                    // records the cut it chose, one word per resident cluster.
4617                    read_only: false,
4618                    dynamic: false,
4619                    stride: size_of::<u32>() as u32,
4620                },
4621                count: 1,
4622                flags: BindingFlags::empty(),
4623            });
4624            mesh_entries.push(BindGroupLayoutEntry {
4625                binding: CLUSTER_GROUP_STATE_BINDING,
4626                visibility: geometry,
4627                kind: BindingKind::StorageBuffer {
4628                    // Topic 25's hysteresis state, and read-only
4629                    // here: the draw-argument pass is its only writer, which is
4630                    // what lets a stage with one workgroup per cluster use a
4631                    // decision that has to survive a frame.
4632                    read_only: true,
4633                    dynamic: false,
4634                    stride: size_of::<u32>() as u32,
4635                },
4636                count: 1,
4637                flags: BindingFlags::empty(),
4638            });
4639        }
4640
4641        // The shared fragment light list and froxel grid are bound on every
4642        // path and in every group, unlike the four
4643        // conditional ranges above: `mesh.slang`'s fragment stage reads them
4644        // whatever geometry produced the primitive, so there is no configuration
4645        // in which the layout can omit them.
4646        //
4647        // `geometry` joins `FRAGMENT` in the visibility for binding 7's reason
4648        // exactly: Slang's Metal backend materialises every global into every
4649        // entry point, so the vertex and mesh stages take these buffers whether
4650        // they read them or not.
4651        mesh_entries.push(BindGroupLayoutEntry {
4652            binding: LIGHT_LIST_BINDING,
4653            visibility: geometry.union(ShaderStages::FRAGMENT),
4654            kind: BindingKind::StorageBuffer {
4655                read_only: true,
4656                dynamic: false,
4657                stride: crcbl_shaders::light::LIGHT_STRIDE as u32,
4658            },
4659            count: 1,
4660            flags: BindingFlags::empty(),
4661        });
4662        mesh_entries.push(BindGroupLayoutEntry {
4663            binding: LIGHT_GRID_BINDING,
4664            visibility: geometry.union(ShaderStages::FRAGMENT),
4665            kind: BindingKind::StorageBuffer {
4666                // **Read-only here**, and written by the clustering pass through
4667                // a layout of its own. The graph is what orders the two.
4668                read_only: true,
4669                dynamic: false,
4670                stride: size_of::<u32>() as u32,
4671            },
4672            count: 1,
4673            flags: BindingFlags::empty(),
4674        });
4675        // Topic 46's occlusion channel, last of the set
4676        // — see [`AMBIENT_OCCLUSION_BINDING`] on why last is structural rather
4677        // than tidy.
4678        //
4679        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4680        // `msl/mesh.metal` is the proof rather than the theory: its `vertexMain`
4681        // takes `ambient_occlusion [[texture(2)]]` whether it reads it or not.
4682        mesh_entries.push(BindGroupLayoutEntry {
4683            binding: AMBIENT_OCCLUSION_BINDING,
4684            visibility: geometry.union(ShaderStages::FRAGMENT),
4685            kind: BindingKind::SampledImage {
4686                view_type: ImageViewType::D2,
4687                // **`Float`, unlike the shadow atlas above.** This one is an
4688                // ordinary `R8Unorm` colour image and the WGSL artifact declares
4689                // `texture_2d<f32>` for it; `Depth` here would be a layout
4690                // claiming a depth format the view does not have.
4691                sample_type: SampleType::Float,
4692            },
4693            count: 1,
4694            flags: BindingFlags::empty(),
4695        });
4696        // The irradiance grid, past the occlusion channel — see
4697        // [`PROBE_TABLE_BINDING`] on why the list only ever grows at its top.
4698        //
4699        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4700        // `msl/mesh.metal` is again the proof rather than the theory: its
4701        // `vertexMain` takes `probes [[buffer(9)]]` whether it reads it or not.
4702        mesh_entries.push(BindGroupLayoutEntry {
4703            binding: PROBE_TABLE_BINDING,
4704            visibility: geometry.union(ShaderStages::FRAGMENT),
4705            kind: BindingKind::StorageBuffer {
4706                // **Read-only, and it stays read-only when the updater lands.**
4707                // The rows are device-local now — see [`crate::probe`], which is
4708                // where that is argued — so the seam no longer forces this;
4709                // what forces it is that the shading path does not write a
4710                // probe and this layout has no headroom to pretend otherwise.
4711                // The raster path is at the WebGPU per-stage storage-buffer
4712                // ceiling already, which the check at the end of the layout
4713                // holds it to, so `read_only: false` here would buy a write
4714                // nothing performs at the price of a binding budget there is
4715                // none of. The irradiance probes' gather is a
4716                // compute pass with a layout of its own, and that is where the
4717                // writable binding of these rows belongs.
4718                read_only: true,
4719                dynamic: false,
4720                stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
4721            },
4722            count: 1,
4723            flags: BindingFlags::empty(),
4724        });
4725        if emit.is_mesh() {
4726            // DAG group records follow the common buffer prefix; the
4727            // remaining mesh-only buffers are sorted after them below.
4728            //
4729            // **Conditional like the mesh-only bindings**, and not for tidiness:
4730            // the raster path's layout is at the WebGPU storage-buffer ceiling
4731            // already, so a row bound unconditionally would be a renderer that
4732            // cannot be built in a browser. The mesh path's own reads sit outside
4733            // that count because `ShaderStages::MESH` is not one of the three
4734            // stages it sums.
4735            mesh_entries.push(BindGroupLayoutEntry {
4736                binding: LEVEL_GROUP_TABLE_BINDING,
4737                // Only the geometry stage reads this table: the
4738                // heatmap's colour is chosen where the cluster is known, and
4739                // `mesh.slang`'s fragment stage — which is this pipeline's —
4740                // does not declare this buffer.
4741                visibility: geometry,
4742                kind: BindingKind::StorageBuffer {
4743                    // Read-only and read by **both** mesh entry points, like
4744                    // CLUSTER_SELECT_BINDING: an un-amplified stage draws through the same
4745                    // `emit_cluster`, so a row present for one and absent for the
4746                    // other is a descriptor read out of an empty slot.
4747                    read_only: true,
4748                    dynamic: false,
4749                    stride: size_of::<u32>() as u32,
4750                },
4751                count: 1,
4752                flags: BindingFlags::empty(),
4753            });
4754        }
4755
4756        // The `DFG` table, above everything — see [`SPECULAR_DFG_BINDING`].
4757        //
4758        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4759        // Metal backend materialises every global into every entry point, so
4760        // `msl/mesh.metal`'s `vertexMain` takes `specular_dfg [[texture(3)]]`
4761        // whether it reads it or not.
4762        mesh_entries.push(BindGroupLayoutEntry {
4763            binding: SPECULAR_DFG_BINDING,
4764            visibility: geometry.union(ShaderStages::FRAGMENT),
4765            kind: BindingKind::SampledImage {
4766                view_type: ImageViewType::D2,
4767                // `Float`, as the occlusion channel above: an `Rgba8Unorm`
4768                // colour image, declared `texture_2d<f32>` by the WGSL artifact.
4769                sample_type: SampleType::Float,
4770            },
4771            count: 1,
4772            flags: BindingFlags::empty(),
4773        });
4774
4775        // §2's normal page, above everything — see [`NORMAL_PAGE_BINDING`].
4776        //
4777        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4778        // Metal backend materialises every global into every entry point, so
4779        // `msl/mesh.metal`'s `vertexMain` takes the page whether it samples it
4780        // or not. **A sampled image and not a storage buffer**, which costs this
4781        // layout nothing at the WebGPU ceiling checked below — that limit counts
4782        // storage buffers, and this row is a texture.
4783        mesh_entries.push(BindGroupLayoutEntry {
4784            binding: NORMAL_PAGE_BINDING,
4785            visibility: geometry.union(ShaderStages::FRAGMENT),
4786            kind: BindingKind::SampledImage {
4787                view_type: ImageViewType::D2Array,
4788                // `Float`: an `Rgba8Unorm` image, declared
4789                // `texture_2d_array<f32>` by the WGSL artifact — the same
4790                // sample type the sRGB base-colour page reports, since both
4791                // decode to floats.
4792                sample_type: SampleType::Float,
4793            },
4794            count: 1,
4795            flags: BindingFlags::empty(),
4796        });
4797        // The area lights' table, above the page — see [`LTC_TABLE_BINDING`].
4798        //
4799        // `geometry` beside `FRAGMENT` for the two rows above it's reason.
4800        // `Float` because `Rgba16Float` is a filterable sampled format on every
4801        // target this engine opens, and the WGSL artifact declares it
4802        // `texture_2d<f32>` — the shader only ever `Load`s it, but the layout
4803        // has to say what the module declared.
4804        mesh_entries.push(BindGroupLayoutEntry {
4805            binding: LTC_TABLE_BINDING,
4806            visibility: geometry.union(ShaderStages::FRAGMENT),
4807            kind: BindingKind::SampledImage {
4808                view_type: ImageViewType::D2,
4809                sample_type: SampleType::Float,
4810            },
4811            count: 1,
4812            flags: BindingFlags::empty(),
4813        });
4814        // Topic 45's contact-shadow channel, last of the set —
4815        // see [`CONTACT_SHADOW_BINDING`] on why last is structural rather than
4816        // tidy.
4817        //
4818        // `geometry` beside `FRAGMENT` and `Float` for the occlusion channel's
4819        // reasons exactly: it is the same `R8Unorm` shape, and Slang's Metal
4820        // backend materialises every global into every entry point whether that
4821        // stage reads it or not.
4822        mesh_entries.push(BindGroupLayoutEntry {
4823            binding: CONTACT_SHADOW_BINDING,
4824            visibility: geometry.union(ShaderStages::FRAGMENT),
4825            kind: BindingKind::SampledImage {
4826                view_type: ImageViewType::D2,
4827                sample_type: SampleType::Float,
4828            },
4829            count: 1,
4830            flags: BindingFlags::empty(),
4831        });
4832        // The irradiance probes' per-probe visibility maps, last
4833        // of the set — see [`PROBE_VISIBILITY_BINDING`] on why last is
4834        // structural.
4835        //
4836        // `D2Array` has to be *declared*, not merely bound: WebGPU compares the
4837        // dimension a layout entry claims against the view handed to it at
4838        // pipeline creation, which is the normal page's own note.
4839        // `UnfilterableFloat` for the same reason and measured the same way: the
4840        // image is `Rg32Float`, which is unfilterable without WebGPU's
4841        // `float32-filterable`, and this slot declared `Float` made Chromium
4842        // refuse the whole mesh bind group — "None of the supported sample types
4843        // (UnfilterableFloat) ... match the expected sample types (Float)" —
4844        // which took every 3D demo's frame to black. Reading it only with `Load`
4845        // does not lift that: the check is on the layout against the view's
4846        // format, not on how the shader gets at it.
4847        mesh_entries.push(BindGroupLayoutEntry {
4848            binding: PROBE_VISIBILITY_BINDING,
4849            visibility: geometry.union(ShaderStages::FRAGMENT),
4850            kind: BindingKind::SampledImage {
4851                view_type: ImageViewType::D2Array,
4852                sample_type: SampleType::UnfilterableFloat,
4853            },
4854            count: 1,
4855            flags: BindingFlags::empty(),
4856        });
4857        // §2's other two pages, last of the set — see [`MRO_PAGE_BINDING`] and
4858        // [`EMISSIVE_PAGE_BINDING`] on why last is structural rather than tidy.
4859        //
4860        // `geometry` beside `FRAGMENT`, `D2Array` and `Float` are the normal
4861        // page's three answers exactly, and for its reasons: Slang's Metal
4862        // backend materialises every global into every entry point, WebGPU
4863        // compares the declared dimension against the bound view, and both
4864        // images are `Rgba8Unorm`-family formats that decode to filterable
4865        // floats.
4866        for binding in [MRO_PAGE_BINDING, EMISSIVE_PAGE_BINDING] {
4867            mesh_entries.push(BindGroupLayoutEntry {
4868                binding,
4869                visibility: geometry.union(ShaderStages::FRAGMENT),
4870                kind: BindingKind::SampledImage {
4871                    view_type: ImageViewType::D2Array,
4872                    sample_type: SampleType::Float,
4873                },
4874                count: 1,
4875                flags: BindingFlags::empty(),
4876            });
4877        }
4878        mesh_entries.sort_by_key(|entry| entry.binding);
4879        let mesh_desc = BindGroupLayoutDesc {
4880            label: Some(MESH_LAYOUT_LABEL),
4881            entries: &mesh_entries,
4882        };
4883        // **This layout is at the guaranteed limit with no headroom on the
4884        // raster path, in both raster stages**: the vertex stage takes every
4885        // storage buffer a WebGPU device promises, and since bindings 1 to 5
4886        // gained FRAGMENT visibility for Metal's debug layer the fragment stage
4887        // takes the same number. A ninth in either is a renderer that cannot be
4888        // built in a browser or on SwiftShader, so it fails here rather than at
4889        // somebody else's `createPipelineLayout` — see
4890        // [`crcbl_hal::check_portable_storage_buffers`], which also says why the
4891        // mesh path's extra reads are outside the count.
4892        // `Some("mesh")`, which is the *pipeline* layout's label, not
4893        // `mesh_desc.label` — the error text reads "pipeline layout {label}
4894        // binds …", so naming the bind group layout there sends the reader to
4895        // the wrong object.
4896        check_portable_storage_buffers(Some("mesh"), &[&mesh_desc])?;
4897        let mesh_layout = device.create_bind_group_layout(&mesh_desc)?;
4898        rollback.bind_group_layouts.push(mesh_layout);
4899
4900        // A dynamic offset must be a multiple of the device's alignment, and one
4901        // block has to fit inside one stride. Read from the device rather than
4902        // assumed, exactly as `crate::sprite_pass` does: 256 on WebGPU, 64 on a
4903        // typical desktop Vulkan driver.
4904        //
4905        // One stride for both blocks, sized for the larger — see
4906        // [`DRAW_CONSTANTS_BLOCK`]. Which of the two a bucket's block holds is
4907        // decided below.
4908        let alignment = device.caps().limits.min_uniform_buffer_offset_alignment;
4909        let draw_stride =
4910            u32::try_from(DRAW_CONSTANTS_BLOCK.next_multiple_of(alignment)).map_err(|_| {
4911                HalError::InvalidDescriptor(format!(
4912                    "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic \
4913                         offset can express"
4914                ))
4915            })?;
4916        let draw_constants = device.create_buffer(&BufferDesc {
4917            label: Some("mesh draw constants"),
4918            // A block per bucket per draw region: a region's draws name their
4919            // own run starts, and the mesh path's block names the region's
4920            // argument structure. See `crcbl_shaders::draw_gen::DRAW_REGIONS`.
4921            size: u64::from(draw_stride)
4922                * u64::from(bucket_count)
4923                * u64::from(crcbl_shaders::draw_gen::DRAW_REGIONS),
4924            usage: BufferUsage::UNIFORM,
4925            memory: MemoryLocation::HostUpload,
4926        })?;
4927        rollback.buffers.push(draw_constants);
4928        // --- the shadow map's own resources ---
4929        //
4930        // Before the bind groups, because every one of them names the atlas or
4931        // the placeholder standing in for it.
4932        let (atlas_width, atlas_height) = shadow::atlas_extent();
4933        let shadow_atlas = device.create_image(&ImageDesc {
4934            label: Some("shadow atlas"),
4935            image_type: ImageType::D2,
4936            format: Format::D32Float,
4937            extent: crcbl_hal::Extent3d::d2(atlas_width, atlas_height),
4938            mip_levels: 1,
4939            samples: 1,
4940            // `TRANSFER_SRC` so a test can copy the cascades back and check
4941            // that something was written into them. A shadow map that stayed at
4942            // its clear value produces a frame that looks entirely plausible —
4943            // everything is lit — so the readback is the only thing that can
4944            // tell a working pass from one that drew nothing.
4945            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
4946                .union(ImageUsage::SAMPLED)
4947                .union(ImageUsage::TRANSFER_SRC),
4948        })?;
4949        rollback.images.push(shadow_atlas);
4950        let shadow_atlas_view = device.create_image_view(&ImageViewDesc {
4951            label: Some("shadow atlas"),
4952            image: shadow_atlas,
4953            view_type: ImageViewType::D2,
4954            format: Format::D32Float,
4955            range: ImageSubresourceRange::all(Format::D32Float),
4956        })?;
4957        rollback.image_views.push(shadow_atlas_view);
4958
4959        let shadow_placeholder = device.create_image(&ImageDesc {
4960            label: Some("shadow placeholder"),
4961            image_type: ImageType::D2,
4962            format: Format::D32Float,
4963            extent: crcbl_hal::Extent3d::d2(1, 1),
4964            mip_levels: 1,
4965            samples: 1,
4966            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT.union(ImageUsage::SAMPLED),
4967        })?;
4968        rollback.images.push(shadow_placeholder);
4969        let shadow_placeholder_view = device.create_image_view(&ImageViewDesc {
4970            label: Some("shadow placeholder"),
4971            image: shadow_placeholder,
4972            view_type: ImageViewType::D2,
4973            format: Format::D32Float,
4974            range: ImageSubresourceRange::all(Format::D32Float),
4975        })?;
4976        rollback.image_views.push(shadow_placeholder_view);
4977
4978        // The occlusion placeholder, beside the shadow one and for the same
4979        // reason: every group of this layout has to fill
4980        // [`AMBIENT_OCCLUSION_BINDING`], and most of them are built before the
4981        // graph has an occlusion image to name.
4982        //
4983        // **Uploaded rather than cleared**, unlike the depth placeholder above,
4984        // and the four bytes are the whole point — see
4985        // [`AMBIENT_OCCLUSION_NONE`], which is where each of them is argued.
4986        // Left undefined this would be a random ambient scale *and* a random
4987        // direction to steer it along, on any frame that fell back to it.
4988        let ambient_occlusion_placeholder = uploads.texture(
4989            "ssao placeholder",
4990            Format::Rgba8Unorm,
4991            (1, 1),
4992            &[&[&AMBIENT_OCCLUSION_NONE]],
4993            ImageViewType::D2,
4994        )?;
4995        rollback.textures.push(ambient_occlusion_placeholder);
4996
4997        // The contact-shadow placeholder, beside the occlusion one and on its
4998        // terms exactly: every group of this layout has to fill
4999        // [`CONTACT_SHADOW_BINDING`], and most of them are built before the graph
5000        // has a contact-shadow image to name. `0xFF` is `1.0` through `R8Unorm`,
5001        // so a fragment that reads this one is a fragment the sun reaches
5002        // unobstructed.
5003        let contact_shadow_placeholder = uploads.texture(
5004            "contact shadow placeholder",
5005            Format::R8Unorm,
5006            (1, 1),
5007            &[&[&[CONTACT_SHADOW_NONE]]],
5008            ImageViewType::D2,
5009        )?;
5010        rollback.textures.push(contact_shadow_placeholder);
5011
5012        // The probe-visibility placeholder, on the two above it's terms: every
5013        // group of this layout has to fill [`PROBE_VISIBILITY_BINDING`], and
5014        // nothing has been captured when they are built. One texel of
5015        // [`probe_visibility_none`], which no surface is further away than, so a
5016        // probe read through it keeps all of its weight.
5017        let probe_visibility_placeholder = uploads.texture(
5018            "probe visibility placeholder",
5019            Format::Rg32Float,
5020            (1, 1),
5021            &[&[&probe_visibility_none()]],
5022            ImageViewType::D2Array,
5023        )?;
5024        rollback.textures.push(probe_visibility_placeholder);
5025
5026        // The split-sum `DFG` table, uploaded once and read by every frame this
5027        // renderer will draw — `crcbl_shaders::dfg` is where it is integrated,
5028        // committed and encoded, and `SPECULAR_ALBEDO_BINDING` is where it lands.
5029        //
5030        // **Cooked bytes rather than a computed image**: the integrator
5031        // importance-samples a lobe, which is `sin`, `cos` and a `powf`, and this
5032        // engine's goldens are compared across four backends with no tolerance.
5033        // Baking here would be four slightly different tables.
5034        //
5035        // **Every view's reflection march reads this same image** for its own
5036        // split-sum scale and bias — see `Ssr::dfg` — rather than uploading a
5037        // second copy of the same bytes per view.
5038        let specular_dfg = uploads.texture(
5039            "dfg table",
5040            // Two bytes of fixed point per channel, high byte first — see
5041            // `crcbl_shaders::dfg::PAIR_TEXEL_BYTES`, which argues why this is
5042            // not the `Rg16Float` the format's own doc anticipated.
5043            Format::Rgba8Unorm,
5044            (DFG_SIZE_U32, DFG_SIZE_U32),
5045            &[&[&dfg::pair_texels()]],
5046            ImageViewType::D2,
5047        )?;
5048        rollback.textures.push(specular_dfg);
5049
5050        // The area lights' fit, beside it and on its terms — cooked bytes for
5051        // the same reason, and `Rgba16Float` rather than fixed point because
5052        // these are matrix entries rather than shares of arriving light.
5053        // `crcbl_shaders::ltc::LTC_TEXEL_BYTES` argues the format.
5054        let ltc_table = uploads.texture(
5055            "ltc table",
5056            Format::Rgba16Float,
5057            (LTC_SIZE_U32, LTC_SIZE_U32),
5058            &[&[&ltc::texels()]],
5059            ImageViewType::D2,
5060        )?;
5061        rollback.textures.push(ltc_table);
5062        service();
5063
5064        // **A comparison sampler, and that is the PCF.** Each
5065        // `SampleCmpLevelZero` returns the filtered fraction of four texels that
5066        // passed the test, so the shader's 3×3 kernel is nine hardware-bilinear
5067        // comparisons rather than nine raw fetches it averages itself.
5068        //
5069        // `Greater` for the engine's reversed-Z, exactly as the depth *test*
5070        // is: the receiver survives when it is nearer the light than whatever
5071        // the map stored. `SamplerDesc::compare` carries the same warning.
5072        //
5073        // Clamped on every axis so a receiver just outside a cascade's box
5074        // reads the edge rather than wrapping into the opposite corner — the
5075        // shader's own bounds check is what actually handles that case, and this
5076        // is the second line of defence one texel wide.
5077        let shadow_sampler = device.create_sampler(&SamplerDesc {
5078            label: Some("shadow comparison"),
5079            mag_filter: FilterMode::Linear,
5080            min_filter: FilterMode::Linear,
5081            mip_filter: FilterMode::Nearest,
5082            address_mode: [SamplerAddressMode::ClampToEdge; 3],
5083            compare: Some(crcbl_hal::CompareOp::Greater),
5084            ..SamplerDesc::default()
5085        })?;
5086        rollback.samplers.push(shadow_sampler);
5087
5088        // --- the camera ---
5089        //
5090        // Everything the camera's picture needs of its own, built against the
5091        // scene resources above — see [`view`], which is where the line between
5092        // the two is drawn. Into the rollback whole as soon as it exists, so a
5093        // failure further down releases it with everything else.
5094        let slot_pages = vec![page_bindings; instance_buffers.len()];
5095        // The pipelines every generator dispatches, the camera's and each
5096        // shadow cull's, compiled once here and shared — with the occlusion
5097        // phases, because every camera's generator is built for them.
5098        let draw_pipelines = rollback
5099            .draw_pipelines
5100            .insert(DrawGenPipelines::new(device, true, service)?);
5101        rollback.primary = Some(View::build(
5102            device,
5103            uploads,
5104            &ViewInputs {
5105                id: ViewId::PRIMARY,
5106                effects: RenderEffects::all(),
5107                // What the first frame resolves to unless a caller moves the
5108                // request before it: the default request against the device
5109                // effects this build hands the renderer below.
5110                expected: EffectRequest::default().resolve(RenderEffects::all()),
5111                // A renderer is built at full render scale; a caller that lowers
5112                // it before the first frame — a saved setting — has that
5113                // frame build the upscale.
5114                expected_upscale: false,
5115                background: ViewBackground::Scene,
5116                lighting: ViewLighting::Scene,
5117                target_format,
5118                emit,
5119                instances: &instance_buffers,
5120                mesh_table,
5121                draw_pipelines,
5122                bucket_meshes: &bucket_meshes,
5123                bucket_modes: &bucket_modes,
5124                bucket_clusters: &bucket_clusters,
5125                bucket_cluster_bases: &bucket_cluster_bases,
5126                mesh_levels: &mesh_levels,
5127                level_groups: &level_groups,
5128                level_meshes: &level_meshes,
5129                instance_capacity: scene.capacities.instances,
5130                light_capacity: scene.capacities.lights,
5131                clusters: rollback.clusters.as_ref(),
5132                task_lanes: view::task_lanes(culls_clusters),
5133                mesh_layout,
5134                vertices,
5135                draw_constants,
5136                materials: material_buffer,
5137                pages: &slot_pages,
5138                probes: &probe_buffers,
5139                specular_dfg: specular_dfg.view,
5140                ltc_table: ltc_table.view,
5141                shadow_map: shadow_atlas_view,
5142                shadow_sampler,
5143                ambient_occlusion: ambient_occlusion_placeholder.view,
5144                contact_shadow: contact_shadow_placeholder.view,
5145                probe_visibility: probe_visibility_placeholder.view,
5146            },
5147            service,
5148        )?);
5149        let primary = rollback.primary.as_ref().expect("just stored");
5150
5151        // Written here and never again: **which word holds** a bucket's run
5152        // start is fixed by the bucket table and the capacity, and both are
5153        // fixed at build. What varies per frame is where the run starts and how
5154        // much of it is filled, and the GPU writes both — the start into that
5155        // word, the count into the bucket's indirect arguments. See
5156        // `mesh.slang`'s header for why the block names a word rather than
5157        // carrying the start.
5158        //
5159        // Taken from the camera's generator and bound for every generator's
5160        // draws: the shadow culls and every secondary view are built from the
5161        // same table and the same capacity, so `bucket_start_word` answers the
5162        // same for all of them.
5163        let draws = &primary.draws;
5164        let mut bucket_constants = vec![0u32; bucket_meshes.len()];
5165        // **Every draw region's copy**, region 0's at the offsets
5166        // `bucket_constants` records and each further region a bucket count of
5167        // strides behind the one before: a region's draw reads its own run
5168        // start and — on the mesh path — its own argument structure, and the
5169        // two are the only words a region changes. See
5170        // `crcbl_shaders::draw_gen::DRAW_REGIONS`.
5171        for (region, (bucket, index)) in
5172            (0..crcbl_shaders::draw_gen::DRAW_REGIONS).flat_map(|region| {
5173                (0..bucket_count).map(move |bucket| (region, (bucket, bucket as usize)))
5174            })
5175        {
5176            let offset = (region * bucket_count + bucket) * draw_stride;
5177            if region == 0 {
5178                bucket_constants[index] = offset;
5179            }
5180            let start_at = draws.region_start_word(region, bucket);
5181            // The mesh path's block says three more things — where this
5182            // bucket's mesh's clusters are, how many it has, and which element
5183            // of the indirect arguments holds its instance count — because a
5184            // dispatch carries none of them and a `draw_indexed_indirect` does
5185            // not need them. All three are fixed when the bucket table is,
5186            // exactly like `start_at`.
5187            let block = if emit.is_mesh() {
5188                crcbl_shaders::meshlet::ClusterDrawConstants {
5189                    start_at,
5190                    cluster_base: bucket_cluster_bases[index],
5191                    cluster_count: bucket_clusters[index],
5192                    // The region's argument structure, which is where this
5193                    // region's instance count is.
5194                    bucket: region * bucket_count + bucket,
5195                    // The same number the draw-argument pass indexes the state
5196                    // with, taken from the object that owns the buffer rather
5197                    // than recomputed from the group table — the two indexing it
5198                    // differently is a cluster reading another instance's
5199                    // decision.
5200                    group_stride: draws.group_stride(),
5201                    // Where the group records are in the table buffer, from the
5202                    // object that packed it — the screen-error heatmap's one
5203                    // input that is not already in the frame block. Taken from
5204                    // `DrawGen` rather than recomputed here for `group_stride`'s
5205                    // reason: two spellings of one offset is an overlay reading
5206                    // another region's words as a group.
5207                    level_groups_at: draws.table_offsets().level_groups_at,
5208                    // The same two numbers again as words of that buffer,
5209                    // which is where a draw that is not the first of a ranged
5210                    // call reads them — `mesh_cluster.slang`'s "One call for
5211                    // a range of buckets". This bucket's, not the region's
5212                    // argument structure's: the tables hold one word a bucket.
5213                    cluster_base_at: draws.table_offsets().bucket_cluster_bases_at + bucket,
5214                    cluster_count_at: draws.table_offsets().bucket_clusters_at + bucket,
5215                    // Where this bucket's task chunks start in this region,
5216                    // and where the region's end: what a flat call binding
5217                    // this block searches between — `mesh_cluster.slang`'s
5218                    // `taskMain`.
5219                    chunk_starts_at: draws.chunk_start_word(region, bucket),
5220                    chunk_starts_end: draws.chunk_start_word(region, bucket_count),
5221                }
5222                .to_bytes()
5223                .to_vec()
5224            } else {
5225                // **The bucket's mesh, which is not always the drawn instance's.**
5226                // A uniform cut selects one of a DAG's levels and each level is
5227                // a mesh table entry of its own, so this is what says which
5228                // geometry the draw's index range belongs to; the instance goes
5229                // on naming level 0. See `mesh::DrawConstants::mesh`.
5230                mesh::DrawConstants {
5231                    start_at,
5232                    mesh: bucket_meshes[index],
5233                    mesh_at: draws.bucket_mesh_word(bucket),
5234                }
5235                .to_bytes()
5236                .to_vec()
5237            };
5238            device.write_buffer(draw_constants, u64::from(offset), &block)?;
5239        }
5240
5241        let region_step = RegionStep {
5242            constants: bucket_count * draw_stride,
5243            args: draws.args_region_offset(1),
5244            counts: draws.counts_region_offset(1),
5245        };
5246
5247        // §3.3's cull, once per cascade and once per shadowed light. Each gets
5248        // its own `DrawGen` and therefore its own frustum, survivor list and
5249        // indirect arguments — which is what "one cull dispatch per cascade
5250        // against the same instance/geometry pools" means, and why the instance
5251        // ring and the mesh table below are the same handles the camera's cull
5252        // was given.
5253        //
5254        // **One per light rather than one per tile**, which is topic 18's fourth
5255        // decision and what `SHADOW_CULLS` is: a point light's six faces cull
5256        // against the light's sphere once and draw that one visible set through
5257        // six matrices.
5258        //
5259        // **Built for every slot, including the ones no light may ever hold.** A
5260        // generator's buffers are sized by the instance capacity rather than by
5261        // the scene, so building one on demand would mean allocating device
5262        // memory inside `begin_frame` — and a frame that cannot allocate is a
5263        // frame that cannot draw. The unused ones cost memory and no dispatch:
5264        // `add_shadow_pass` records passes for the occupied slots alone.
5265        for cull in 0..SHADOW_CULLS {
5266            // Into the rollback as each is built, on the same terms as the
5267            // camera's: a failure two culls in has to release the first one,
5268            // and the rollback is the only thing that knows about it.
5269            let label = if cull < shadow::CASCADES {
5270                format!("shadow cascade {cull}")
5271            } else {
5272                format!("shadow light {}", cull - shadow::CASCADES)
5273            };
5274            let draws = DrawGen::new(
5275                device,
5276                uploads,
5277                rollback
5278                    .draw_pipelines
5279                    .as_ref()
5280                    .unwrap_or_else(|| unreachable!("built ahead of the camera")),
5281                &DrawGenDesc {
5282                    label: Some(&label),
5283                    instances: &instance_buffers,
5284                    mesh_table,
5285                    bucket_meshes: &bucket_meshes,
5286                    bucket_modes: &bucket_modes,
5287                    bucket_clusters: &bucket_clusters,
5288                    bucket_cluster_bases: &bucket_cluster_bases,
5289                    mesh_levels: &mesh_levels,
5290                    level_groups: &level_groups,
5291                    level_meshes: &level_meshes,
5292                    instance_capacity: scene.capacities.instances,
5293                    // No view's: a shadow map is drawn from everything resident
5294                    // that casts, so an instance a camera hides still casts its
5295                    // shadow and one `set_instance_casts_shadow` turned off does
5296                    // not — on every geometry path, since this is the cull they
5297                    // all draw from. The reflective shadow maps draw these same
5298                    // survivors, so such an instance bounces no light either.
5299                    hidden_view: mesh::GpuInstance::CASTS_NO_SHADOW,
5300                    // A light slot may hold a point light, whose six faces cull
5301                    // separately into six regions of the one generator; a
5302                    // cascade never does.
5303                    mode: if cull < shadow::CASCADES {
5304                        crcbl_shaders::draw_gen::DrawMode::Plain
5305                    } else {
5306                        crcbl_shaders::draw_gen::DrawMode::Faces
5307                    },
5308                    task_lanes: view::task_lanes(culls_clusters),
5309                },
5310            )?;
5311            rollback.shadow_draws.push(draws);
5312            service();
5313        }
5314        // The handles are `Copy` and are read out here for the same reason the
5315        // camera's are above: the pool they came from is the rollback's now.
5316        let tile_buffers: Vec<TileBuffers> = rollback
5317            .shadow_draws
5318            .iter()
5319            .map(|draws| TileBuffers {
5320                runs: (0..instance_buffers.len())
5321                    .map(|frame| draws.runs(frame))
5322                    .collect(),
5323                args: (0..instance_buffers.len())
5324                    .map(|frame| draws.args(frame))
5325                    .collect(),
5326                cull_params: (0..instance_buffers.len())
5327                    .map(|frame| draws.cull_params(frame))
5328                    .collect(),
5329                cull_stats: (0..instance_buffers.len())
5330                    .map(|frame| draws.visible_count(frame))
5331                    .collect(),
5332                group_state: draws.group_state(),
5333            })
5334            .collect();
5335
5336        let mut shadow_uniforms = Vec::with_capacity(FRAMES_IN_FLIGHT);
5337        let mut shadow_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
5338        let mut shadow_selection = Vec::with_capacity(FRAMES_IN_FLIGHT);
5339        let mut shadow_group_entries = Vec::with_capacity(FRAMES_IN_FLIGHT);
5340        for (frame, &slot_instances) in instance_buffers.iter().enumerate() {
5341            // Everything a group of this layout names that is the same in all of
5342            // this frame's — the camera's list and table buffers included, which
5343            // a shadow view binds because the layout declares them and reads
5344            // nothing of. The per-group half is what `MeshGroup` below varies,
5345            // and the two exist so the colour pass's group and the shadow pass's
5346            // are one description rather than two that agree today.
5347            let shared = SharedBindings {
5348                vertices,
5349                draw_constants,
5350                mesh_table,
5351                materials: material_buffer,
5352                pages: page_bindings,
5353                clusters: rollback.clusters.as_ref(),
5354                shadow_sampler,
5355                lights: primary.lights.lights(frame),
5356                light_grid: primary.lights.grid(frame),
5357                probes: probe_buffers[frame],
5358                tables: primary.draws.tables(),
5359                specular_dfg: specular_dfg.view,
5360                ltc_table: ltc_table.view,
5361            };
5362
5363            // The same layout again, once per shadow view, differing in exactly
5364            // the things a view is: which matrix, and which cull's survivors.
5365            //
5366            // **The view's own uniforms and the cull's shared buffers**, which
5367            // is the whole of what a point light's six faces are: one visible
5368            // set, six matrices. `shadow_cull` is the map from a view to the
5369            // generator behind it, and it is a compile-time one because a bind
5370            // group names its buffers when it is created — where a face's *tile*
5371            // is decided per frame and reaches the device as a viewport.
5372            let mut frame_shadow_uniforms = Vec::with_capacity(SHADOW_VIEWS);
5373            let mut frame_shadow_groups = Vec::with_capacity(SHADOW_VIEWS);
5374            let mut frame_shadow_selection = Vec::with_capacity(SHADOW_VIEWS);
5375            let mut frame_shadow_entries = Vec::with_capacity(SHADOW_VIEWS);
5376            for view in 0..SHADOW_VIEWS {
5377                let buffers = &tile_buffers[if view < shadow::CASCADES {
5378                    view
5379                } else {
5380                    shadow_cull((view - shadow::CASCADES) / shadow::POINT_FACES)
5381                }];
5382                let tile_uniforms = device.create_buffer(&BufferDesc {
5383                    label: Some("shadow view uniforms"),
5384                    size: mesh::FRAME_UNIFORMS_SIZE as u64,
5385                    usage: BufferUsage::UNIFORM,
5386                    memory: MemoryLocation::HostUpload,
5387                })?;
5388                rollback.buffers.push(tile_uniforms);
5389                let entries = MeshGroup {
5390                    uniforms: tile_uniforms,
5391                    instances: slot_instances,
5392                    runs: buffers.runs[frame],
5393                    args: buffers.args[frame],
5394                    // The amplification stage culls clusters against whatever
5395                    // frustum is in this block, and against
5396                    // `frame.camera_position` — which in a view's copy is the
5397                    // *light*. So the per-cluster cull rejects what faces away
5398                    // from the light, which is the right question for a shadow
5399                    // map and the wrong one to have asked with the camera's
5400                    // frustum.
5401                    cull_params: buffers.cull_params[frame],
5402                    cull_stats: buffers.cull_stats[frame],
5403                    // **This view's own**, and not the colour pass's: that pass
5404                    // is recorded last and would write over it. See
5405                    // `ForwardRenderer::shadow_selection`.
5406                    cluster_selection: tile_selection.get(view).map(|ring| ring[frame]),
5407                    // Its cull's — see `TileBuffers::group_state`, which is
5408                    // where that budget is argued.
5409                    group_state: emit.is_mesh().then_some(buffers.group_state),
5410                    shadow_map: shadow_placeholder_view,
5411                    // A cascade shades nothing — the pipeline has no fragment
5412                    // stage — so this slot exists only because Metal
5413                    // materialises every global into every entry point.
5414                    ambient_occlusion: ambient_occlusion_placeholder.view,
5415                    contact_shadow: contact_shadow_placeholder.view,
5416                    probe_visibility: probe_visibility_placeholder.view,
5417                }
5418                .entries(&shared);
5419                let group = device.create_bind_group(&BindGroupDesc {
5420                    label: Some("shadow view"),
5421                    layout: mesh_layout,
5422                    entries: &entries,
5423                    variable_count: None,
5424                })?;
5425                rollback.bind_groups.push(group);
5426                frame_shadow_uniforms.push(tile_uniforms);
5427                frame_shadow_groups.push(group);
5428                frame_shadow_entries.push(entries);
5429                frame_shadow_selection.extend(tile_selection.get(view).map(|ring| ring[frame]));
5430            }
5431            shadow_uniforms.push(frame_shadow_uniforms);
5432            shadow_groups.push(frame_shadow_groups);
5433            shadow_group_entries.push(frame_shadow_entries);
5434            shadow_selection.push(frame_shadow_selection);
5435            service();
5436        }
5437
5438        let mesh_set_layouts = [mesh_layout];
5439        let mesh_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5440            label: Some("mesh"),
5441            bind_group_layouts: &mesh_set_layouts,
5442            // The camera goes in the uniform buffer above rather than here:
5443            // `Features::PUSH_CONSTANTS` is absent on Tier B and the seam is
5444            // explicit that the substitute is a data-layout decision. So this
5445            // file needs no tier branch at all — it has been on Tier B's shape
5446            // since P1, and `crate::ui_pass` is where the split actually bites.
5447            push_constants: None,
5448        })?;
5449        rollback.pipeline_layouts.push(mesh_pipeline_layout);
5450
5451        // The colour pass's pipeline and its depth-only twin, out of one set of
5452        // modules — see [`MeshModules`], which is where the two shapes and the
5453        // reasons for them live. Both are created before either is unwrapped and
5454        // the modules are released between, so a failing creation leaks nothing.
5455        //
5456        // **Each shape has a twin per material side** — see
5457        // [`SidedPipelines`], which is where the cull modes and the reason for a
5458        // pipeline rather than a per-draw state live. The shadow tile clear is
5459        // the one exception: its triangle comes out of `SV_VertexID` and it
5460        // already culls nothing.
5461        //
5462        // Beside them: the cutout twin of the depth shape, which a frame whose
5463        // material table masks alpha is recorded with instead (see
5464        // [`MeshModules::depth_masked_pipeline`]); the one that resets a tile,
5465        // which the cadence rung needs and the attachment's load operation
5466        // cannot express ([`MeshModules::depth_clear_pipeline`]); and the
5467        // irradiance probes' reflective shadow map ([`MeshModules::rsm_pipeline`]).
5468        //
5469        // **Only what this scene can draw with is compiled.** The bucket table
5470        // above is final — nothing adds a material or changes a probe volume's
5471        // update after `build` — so `scene_modes` and the volume are the whole
5472        // of what any frame of this renderer will ask for. The single-sided
5473        // colour and depth shapes and the tile clear are built for every
5474        // scene; each `CullMode::None` twin only where a bucket is
5475        // double-sided, the cutout shape only where one masks, and the
5476        // reflective shadow map only where the probes are updated. An opaque,
5477        // single-sided scene without an updated volume, such as the demo
5478        // scene, compiles only those.
5479        //
5480        // **They are one [`pipeline_batch`], compiled side by side** where
5481        // the device allows it: on a cold driver cache each is a shader
5482        // compilation, and this is the build's longest run of them. `service`
5483        // runs before each round of the batch, or before each pipeline where the
5484        // batch is serial — see [`ForwardRenderer::with_scene_serviced`].
5485        let holds = |mode: u32| scene_modes.contains(&mode);
5486        // The single-sided shapes are built even where `DEPTH_MODES[0]` is not
5487        // held: they are the template the frame's draw lists are partitioned
5488        // from, and the rare scene with no opaque single-sided material pays a
5489        // compile each for them.
5490        let [_, masked, double, masked_double] = DEPTH_MODES;
5491        let any_double = holds(double) || holds(masked_double);
5492        let any_masked = holds(masked) || holds(masked_double);
5493        let updates_probes = scene.probes.update == ProbeUpdate::EveryFrame;
5494        let modules = MeshModules::new(device, emit, culls_clusters)?;
5495        let layout = mesh_pipeline_layout;
5496        let [back, none] = MeshModules::SIDES;
5497        let color =
5498            |cull| modules.color_pipeline(device, layout, PolygonMode::Fill, cull, "forward");
5499        let depth = |cull| modules.depth_pipeline(device, layout, cull);
5500        let depth_masked = |cull| modules.depth_masked_pipeline(device, layout, cull);
5501        let rsm = |cull| modules.rsm_pipeline(device, layout, cull);
5502        // Each member beside whether this scene needs it, in one fixed order the
5503        // results are read back out of below.
5504        let members: [(bool, &pipeline_batch::Job<'_, _>); 9] = [
5505            (true, &|| color(back)),
5506            (any_double, &|| color(none)),
5507            (true, &|| depth(back)),
5508            (holds(double), &|| depth(none)),
5509            (any_masked, &|| depth_masked(back)),
5510            (holds(masked_double), &|| depth_masked(none)),
5511            (true, &|| modules.depth_clear_pipeline(device, layout)),
5512            (updates_probes, &|| rsm(back)),
5513            (updates_probes && any_double, &|| rsm(none)),
5514        ];
5515        let jobs: Vec<&pipeline_batch::Job<'_, _>> = members
5516            .iter()
5517            .filter_map(|(needed, job)| needed.then_some(*job))
5518            .collect();
5519        let mut made = pipeline_batch::create_listed(device, service, &jobs).into_iter();
5520        let results: [Option<Result<GraphicsPipelineHandle, HalError>>; 9] =
5521            members.map(|(needed, _)| {
5522                needed.then(|| {
5523                    made.next()
5524                        .unwrap_or_else(|| unreachable!("one result per job"))
5525                })
5526            });
5527        modules.destroy(device);
5528        // Register every successful creation before propagating any error.
5529        // Results later in this batch may own pipelines even when the first
5530        // result failed; dropping an unvisited Result does not release a HAL
5531        // handle. The outer rollback owns all of them until build succeeds.
5532        for pipeline in results.iter().flatten().flatten() {
5533            rollback.pipelines.push(*pipeline);
5534        }
5535        let [
5536            mesh_single,
5537            mesh_double,
5538            shadow_single,
5539            shadow_double,
5540            depth_masked_single,
5541            depth_masked_double,
5542            shadow_clear_pipeline,
5543            rsm_single,
5544            rsm_double,
5545        ] = results.map(Option::transpose);
5546        let built = |single: Option<GraphicsPipelineHandle>, double| {
5547            single.map(|single| SidedPipelines { single, double })
5548        };
5549        let mesh_pipeline = built(mesh_single?, mesh_double?).unwrap_or_else(|| {
5550            unreachable!("the colour pass's single-sided shape is always built")
5551        });
5552        let shadow_pipeline = built(shadow_single?, shadow_double?)
5553            .unwrap_or_else(|| unreachable!("the depth pass's single-sided shape is always built"));
5554        let depth_masked_pipeline = built(depth_masked_single?, depth_masked_double?);
5555        let shadow_clear_pipeline = shadow_clear_pipeline?
5556            .unwrap_or_else(|| unreachable!("the tile clear is always built"));
5557        let rsm_pipeline = built(rsm_single?, rsm_double?);
5558
5559        // --- the tonemap pass ---
5560        let tonemap_entries = [
5561            BindGroupLayoutEntry {
5562                binding: 0,
5563                visibility: ShaderStages::FRAGMENT,
5564                kind: BindingKind::SampledImage {
5565                    view_type: ImageViewType::D2,
5566                    sample_type: SampleType::Float,
5567                },
5568                count: 1,
5569                flags: BindingFlags::empty(),
5570            },
5571            BindGroupLayoutEntry {
5572                binding: 1,
5573                visibility: ShaderStages::FRAGMENT,
5574                kind: BindingKind::Sampler { comparison: false },
5575                count: 1,
5576                flags: BindingFlags::empty(),
5577            },
5578            // The exposure — see [`set_exposure`](Self::set_exposure). A uniform
5579            // buffer rather than a push constant, which is [`crate::ui_pass`]'s
5580            // decision restated: WebGPU has no push constants at all, so a range
5581            // here would split this pass into a tier A and a tier B form —
5582            // two layouts, two buffers and, because one Slang entry point reads
5583            // either a `[[vk::push_constant]]` block or a `[[vk::binding]]`ed
5584            // one and never both, a second copy of `tonemap.slang`. Four bytes
5585            // once a frame do not buy that.
5586            //
5587            // `FRAGMENT` alone, and the artifact agrees: `spirv/tonemap.spv`
5588            // lists `%params` in the fragment `OpEntryPoint`'s interface and not
5589            // in the vertex one, because the vertex stage generates three
5590            // corners out of `SV_VertexID` and reads nothing.
5591            BindGroupLayoutEntry {
5592                binding: 2,
5593                visibility: ShaderStages::FRAGMENT,
5594                kind: BindingKind::UniformBuffer { dynamic: false },
5595                count: 1,
5596                flags: BindingFlags::empty(),
5597            },
5598            // The measured exposure — see [`crate::exposure`]. **Bound on every
5599            // frame, whether or not anything measured**, because a binding that
5600            // comes and goes is a second pipeline layout and a second group
5601            // cache keyed on which one is live, to save four bytes. The block
5602            // above carries the switch that decides whether the shader reads it.
5603            BindGroupLayoutEntry {
5604                binding: 3,
5605                visibility: ShaderStages::FRAGMENT,
5606                kind: BindingKind::StorageBuffer {
5607                    // Written by `exposure.slang`'s reduce and read here —
5608                    // `StructuredBuffer` in this shader, which is the truth
5609                    // rather than a hint.
5610                    read_only: true,
5611                    dynamic: false,
5612                    stride: size_of::<u32>() as u32,
5613                },
5614                count: 1,
5615                flags: BindingFlags::empty(),
5616            },
5617        ];
5618        let tonemap_desc = BindGroupLayoutDesc {
5619            label: Some("tonemap scene"),
5620            entries: &tonemap_entries,
5621        };
5622        check_portable_storage_buffers(Some("tonemap"), &[&tonemap_desc])?;
5623        let tonemap_layout = device.create_bind_group_layout(&tonemap_desc)?;
5624        rollback.bind_group_layouts.push(tonemap_layout);
5625        let tonemap_set_layouts = [tonemap_layout];
5626        let tonemap_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5627            label: Some("tonemap"),
5628            bind_group_layouts: &tonemap_set_layouts,
5629            push_constants: None,
5630        })?;
5631        rollback.pipeline_layouts.push(tonemap_pipeline_layout);
5632        let tonemap_vertex = entry(&TONEMAP, Stage::Vertex)?;
5633        let tonemap_fragment = entry(&TONEMAP, Stage::Fragment)?;
5634        let tonemap_module = device.create_shader_module(&ShaderModuleDesc {
5635            label: Some("tonemap.slang"),
5636            spirv: TONEMAP.spirv(),
5637            wgsl: TONEMAP.wgsl(),
5638            msl: TONEMAP.msl(),
5639            // A container per entry point, for the reason the mesh module above
5640            // gives.
5641            dxil: &TONEMAP.dxil_containers(),
5642        })?;
5643        let tonemap_targets = [ColorTargetState::opaque(target_format)];
5644        let tonemap_pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5645            label: Some("tonemap"),
5646            layout: tonemap_pipeline_layout,
5647            vertex: ShaderEntry {
5648                module: tonemap_module,
5649                entry_point: tonemap_vertex,
5650            },
5651            fragment: Some(ShaderEntry {
5652                module: tonemap_module,
5653                entry_point: tonemap_fragment,
5654            }),
5655            // The full-screen triangle is deliberately oversized, so two of its
5656            // vertices are outside the viewport and its winding is not worth
5657            // reasoning about. `CullMode::None` is the honest setting.
5658            primitive: PrimitiveState::default(),
5659            depth_stencil: None,
5660            multisample: MultisampleState::default(),
5661            color_targets: &tonemap_targets,
5662        });
5663        device.destroy_shader_module(tonemap_module);
5664        let tonemap_pipeline = tonemap_pipeline?;
5665        rollback.pipelines.push(tonemap_pipeline);
5666        service();
5667
5668        // Nearest, not linear: see `tonemap.slang` on why a 1:1 blit must not
5669        // leave a golden image depending on two rasterisers agreeing about
5670        // texel-centre arithmetic.
5671        let sampler = device.create_sampler(&SamplerDesc {
5672            label: Some("tonemap scene"),
5673            mag_filter: FilterMode::Nearest,
5674            min_filter: FilterMode::Nearest,
5675            mip_filter: FilterMode::Nearest,
5676            address_mode: [SamplerAddressMode::ClampToEdge; 3],
5677            ..SamplerDesc::default()
5678        })?;
5679        rollback.samplers.push(sampler);
5680
5681        // No field, so no pass: the frame every caller of this type drew
5682        // before grass existed. The two calm wind layers are one texel each
5683        // and are what makes a field with no weather set still.
5684        //
5685        // **Before the literal below, not inside it**: the literal moves the
5686        // camera, the shared draw pipelines and the pools out of the rollback,
5687        // so a failure inside it would leak them. `GrassScene::new` releases
5688        // its own half on failure, and the literal then has nothing that can
5689        // fail.
5690        let grass = GrassScene::new(device, uploads, FRAMES_IN_FLIGHT)?;
5691
5692        Ok(Self {
5693            pool: rollback
5694                .pool
5695                .take()
5696                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5697            bucket_constants,
5698            region_step,
5699            bucket_modes,
5700            instances: rollback
5701                .instances
5702                .take()
5703                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5704            mesh_ids,
5705            skinnable_meshes,
5706            skinned_instances: Vec::new(),
5707            materials: rollback
5708                .materials
5709                .take()
5710                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5711            material_ids,
5712            probes: rollback
5713                .probes
5714                .take()
5715                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5716            probe_volume: scene.probes.volume,
5717            base_color_page,
5718            normal_page,
5719            mro_page,
5720            emissive_page,
5721            page_extents,
5722            page_layers,
5723            base_color_sampler,
5724            anisotropy,
5725            // Every slot's groups were just built naming these.
5726            slot_pages: vec![page_bindings; FRAMES_IN_FLIGHT],
5727            retired_pages: Vec::new(),
5728            // No frame has been recorded yet, and the counters say so rather
5729            // than reporting the count a frame *would* have.
5730            recorded_draws: 0,
5731            emit,
5732            range_limit,
5733            clusters: rollback.clusters.take(),
5734            culls_clusters,
5735            draw_constants,
5736            mesh_clusters,
5737            // One entry per description mesh, each holding one bucket per level,
5738            // where the cull pass takes a uniform cut — and nothing at all where
5739            // the amplification stage takes a per-cluster one. Read off the
5740            // bucket table that was actually built rather than re-derived from
5741            // the path.
5742            mesh_level_buckets: if emit.is_mesh() {
5743                Vec::new()
5744            } else {
5745                residents
5746                    .iter()
5747                    .enumerate()
5748                    .map(|(index, resident)| {
5749                        let base = bucket_bases[index];
5750                        (base..base + resident.levels.len())
5751                            .map(|bucket| {
5752                                u32::try_from(bucket)
5753                                    .unwrap_or_else(|_| unreachable!("a table of a few buckets"))
5754                            })
5755                            .collect()
5756                    })
5757                    .collect()
5758            },
5759            lod_error_budget: LOD_ERROR_BUDGET,
5760            lod_hold_ratio: LOD_HOLD_RATIO,
5761            // Overwritten by the first `begin_frame`, which is the only thing
5762            // that can know the viewport.
5763            shadow_lod_params: [0.0, 0.0, 0.0],
5764            extra_lights: Vec::new(),
5765            primary: rollback
5766                .primary
5767                .take()
5768                .unwrap_or_else(|| unreachable!("the camera was placed in the rollback above")),
5769            draw_pipelines: rollback
5770                .draw_pipelines
5771                .take()
5772                .unwrap_or_else(|| unreachable!("built ahead of the camera")),
5773            views: Vec::new(),
5774            draw_tables: DrawTables {
5775                bucket_meshes,
5776                bucket_clusters,
5777                bucket_cluster_bases,
5778                mesh_levels,
5779                level_groups,
5780                level_meshes,
5781                instance_capacity: scene.capacities.instances,
5782                light_capacity: scene.capacities.lights,
5783            },
5784            frame_serial: 0,
5785            frame_scene: None,
5786            frame: 0,
5787            mesh_layout,
5788            mesh_pipeline_layout,
5789            mesh_pipeline,
5790            // Off, and unbuilt, on the ground grid's terms below: the wireframe
5791            // view is opt-in, so a caller that never asks for one draws the
5792            // frame it drew before `set_wireframe` existed.
5793            wireframe_pipeline: None,
5794            wireframe_on: false,
5795            occlusion_culling: OcclusionCulling::OFF,
5796            point_face_culls: true,
5797            shadow_view_tamper: None,
5798            // Off, on the line above's terms: the normals view is opt-in, so a
5799            // caller that never asks for one draws the frame it drew before
5800            // `set_normals_view` existed. It builds nothing, so there is no
5801            // second field here.
5802            normals_view: false,
5803            // Off on the same terms, and "off" here is a density of zero: the
5804            // shader's composite is exactly the identity there, so a caller who
5805            // never calls `set_fog` gets the frame byte for byte.
5806            fog: Fog::NONE,
5807            sky: Sky::NONE,
5808            atmosphere: None,
5809            sky_view: None,
5810            sky_view_build: None,
5811            lod_view: false,
5812            heatmap: false,
5813            occlusion_view: false,
5814            motion_view: false,
5815            bent_normal_view: false,
5816            cascade_view: false,
5817            atlas_view: false,
5818            // Following the camera, on the line above's terms: the selection eye
5819            // is the camera's until a caller pins it, so a renderer nobody calls
5820            // `set_frozen_selection_eye` on hands `begin_frame` exactly what it
5821            // handed before this field existed.
5822            frozen_selection_eye: None,
5823            shadow_atlas,
5824            shadow_atlas_view,
5825            shadow_placeholder,
5826            shadow_placeholder_view,
5827            shadow_sampler,
5828            shadow_pipeline,
5829            depth_masked_pipeline,
5830            shadow_clear_pipeline,
5831            rsm_pipeline,
5832            probe_gather,
5833            probe_update: scene.probes.update,
5834            // Overwritten by the first `begin_frame`, which is the only reader's
5835            // only source. Zero is the honest placeholder: no cascade has been
5836            // fitted yet, and a gather recorded against it would scale by zero
5837            // rather than by a number nobody chose.
5838            cascade_reach: 0.0,
5839            // Nothing has been fitted before the first `begin_frame`.
5840            rsm_cull_ready: false,
5841            sun_color: Vec3::ZERO,
5842            shadow_draws: std::mem::take(&mut rollback.shadow_draws),
5843            shadow_uniforms,
5844            shadow_prepare_views: Vec::new(),
5845            shadow_prepare_culls: Vec::new(),
5846            shadow_groups,
5847            shadow_selection,
5848            shadow_lights: shadow::Selection::default(),
5849            // Nothing has drawn the atlas, so the first frame draws every group
5850            // whatever it is asked for — which is also what gives the image a
5851            // defined content before anything samples it. A record is never
5852            // empty, so the first frame's is a change and takes every id past
5853            // the zero below it.
5854            shadow_group_inputs: vec![Vec::new(); SHADOW_CULLS],
5855            shadow_group_id: vec![0; SHADOW_CULLS],
5856            shadow_group_writes: vec![0; SHADOW_CULLS],
5857            shadow_footprints: Vec::new(),
5858            shadow_dag_elements: std::collections::BTreeSet::new(),
5859            shadow_written: Vec::new(),
5860            shadow_moved: Vec::new(),
5861            shadow_pass_id: 0,
5862            shadow_pass_ran: Arc::new(AtomicU64::new(0)),
5863            shadow_pending: None,
5864            // A reach of zero, so every centre on the first frame is further
5865            // from what the image holds than the nothing it holds reaches —
5866            // which is the reset that frame should be.
5867            shadow_group_held: vec![(0, Vec3::ZERO, 0.0); SHADOW_CULLS],
5868            shadow_group_redrawn: vec![false; SHADOW_CULLS],
5869            shadow_atlas_layout: None,
5870            shadow_atlas_cached: false,
5871            shadow_cadence_reset: false,
5872            shadow_faces_redrawn: 0,
5873            shadow_cadence_request: None,
5874            shadow_atlas_clears: true,
5875            shadow_frame: 0,
5876            frame_skins: false,
5877            // [`FRAMES_IN_FLIGHT`], the number every other ring here is sized
5878            // by, so a slot has been through the whole loop before it is read.
5879            // `culls_clusters` rather than the device's feature bits: what
5880            // decides whether the cluster word is a count is whether *this
5881            // renderer* built an amplification stage.
5882            cull_stats: CullStatsRing::new(device, FRAMES_IN_FLIGHT, culls_clusters),
5883            tonemap_layout,
5884            tonemap_pipeline_layout,
5885            tonemap_pipeline,
5886            sampler,
5887            // The value `tonemap.slang`'s `EXPOSURE` constant held, so a
5888            // renderer nobody has called `set_exposure` on writes the frame it
5889            // wrote before the block existed.
5890            exposure: tonemap::DEFAULT_EXPOSURE,
5891            exposure_adaptation: None,
5892            // And the filmic roll-off over it: this renderer shades in linear
5893            // HDR, so a view that has asked for nothing gets the operator that
5894            // range was shaded for.
5895            tonemap_curve: tonemap::TonemapCurve::Aces,
5896            target_format,
5897            ambient_occlusion_placeholder,
5898            contact_shadow_placeholder,
5899            probe_visibility_placeholder,
5900            // Nothing has been captured, so every frame drawn before
5901            // `capture_probe_visibility` reads the placeholder and weighs every
5902            // probe at one — which is the frame this renderer drew before the
5903            // maps existed.
5904            probe_visibility: None,
5905            probe_occluders,
5906            specular_dfg,
5907            ltc_table,
5908            shadow_group_entries,
5909            // Off, and unbuilt: the grid is opt-in, so a caller that never asks
5910            // for one draws the frame it drew before this module existed.
5911            ground_grid: None,
5912            ground_grid_on: false,
5913            // Empty, and unbuilt: nothing has appended a segment, so this
5914            // renderer records the frame it recorded before the layer existed.
5915            debug_draw: DebugDraw::default(),
5916            // Unbuilt: no frame has shown the atlas — see the field.
5917            atlas_viewer: None,
5918            frame_atlas_view: false,
5919            // Full resolution, which is the frame every caller of this type drew
5920            // before there was a knob — see [`Self::set_render_scale`].
5921            render_scale: 1.0,
5922            frame_render_scale: 1.0,
5923            // The default stack the view wants, no quality clamp and no
5924            // override, which resolves to every effect this device permits but
5925            // the lens one — the frame every caller of this type drew before
5926            // there were toggles. See [`RenderEffects::DEFAULT_STACK`].
5927            effect_request: EffectRequest::default(),
5928            device_effects: RenderEffects::all(),
5929            frame_effects: RenderEffects::DEFAULT_STACK,
5930            // What the switch says today, so a renderer built and never opened
5931            // still describes the frame it would draw. `begin_frame` reads it
5932            // again for the frame it opens.
5933            frame_ssao_blurs: crate::ssao::blur_passes(),
5934            // No frame has been recorded yet, on `recorded_draws`' terms.
5935            recorded_fullscreen: 0,
5936            // No frame has been recorded yet, on `recorded_fullscreen`'s terms.
5937            recorded_debug_draw: 0,
5938            recorded_tile_clears: 0,
5939            // No bodies, so no pass: the frame every caller of this type drew
5940            // before water existed. Nothing is allocated until a body is set.
5941            water: WaterBodies::new(FRAMES_IN_FLIGHT),
5942            recorded_water_draws: 0,
5943            grass,
5944            // No frame has begun.
5945            frame_grass: None,
5946            wind: crcbl_shaders::wind::WindParams::default(),
5947            recorded_grass_draws: 0,
5948            // The build's own batch joins once it is submitted, which is after
5949            // this returns — see `build_on_path`.
5950            uploads_in_flight: Vec::new(),
5951        })
5952    }
5953
5954    /// Builds a full-screen-triangle pipeline out of `shader`'s vertex and
5955    /// fragment entry points.
5956    ///
5957    /// One helper because every post pass in this crate wants the same
5958    /// pipeline — the tonemap's, `ssao`'s, `ssao-blur`'s, `ssr`'s and the rest —
5959    /// differing in the module, the layout and the target format alone. The
5960    /// tonemap's stays written out where it is: it is the one that carries the
5961    /// *why* of the shape, and this is the shape repeated.
5962    ///
5963    /// The module is destroyed before the pipeline result is unwrapped, so a
5964    /// failing creation leaks nothing.
5965    ///
5966    /// # Errors
5967    ///
5968    /// [`HalError`] from the manifest lookup, the module or the pipeline.
5969    fn build_fullscreen(
5970        device: &dyn Device,
5971        label: &str,
5972        shader: &crcbl_shaders::Shader,
5973        layout: PipelineLayoutHandle,
5974        color_targets: &[ColorTargetState],
5975    ) -> Result<GraphicsPipelineHandle, HalError> {
5976        Self::build_fullscreen_with(device, label, shader, layout, color_targets, None)
5977    }
5978
5979    /// [`Self::build_fullscreen`] for a pass that **depth-tests** what it draws
5980    /// against an attachment it does not write.
5981    ///
5982    /// The state is [`DepthStencilState::equal_depth_read_only`], whose
5983    /// [`CompareOp::GreaterOrEqual`] is the reversed-Z pair for "the fragment's
5984    /// depth must equal what is already there". One caller, [`crate::sky_pass`],
5985    /// which emits its triangle at the far plane so that the test selects
5986    /// exactly the pixels no geometry covered — see that module.
5987    ///
5988    /// # Errors
5989    ///
5990    /// [`HalError`] from the manifest lookup, the module or the pipeline.
5991    fn build_tested_fullscreen(
5992        device: &dyn Device,
5993        label: &str,
5994        shader: &crcbl_shaders::Shader,
5995        layout: PipelineLayoutHandle,
5996        color_targets: &[ColorTargetState],
5997        depth_format: Format,
5998    ) -> Result<GraphicsPipelineHandle, HalError> {
5999        Self::build_fullscreen_with(
6000            device,
6001            label,
6002            shader,
6003            layout,
6004            color_targets,
6005            Some(DepthStencilState::equal_depth_read_only(depth_format)),
6006        )
6007    }
6008
6009    /// The body of the two above, which differ in their depth state and in
6010    /// nothing else.
6011    ///
6012    /// # Errors
6013    ///
6014    /// [`HalError`] from the manifest lookup, the module or the pipeline.
6015    fn build_fullscreen_with(
6016        device: &dyn Device,
6017        label: &str,
6018        shader: &crcbl_shaders::Shader,
6019        layout: PipelineLayoutHandle,
6020        color_targets: &[ColorTargetState],
6021        depth_stencil: Option<DepthStencilState>,
6022    ) -> Result<GraphicsPipelineHandle, HalError> {
6023        let vertex = entry(shader, Stage::Vertex)?;
6024        let fragment = entry(shader, Stage::Fragment)?;
6025        let module = device.create_shader_module(&ShaderModuleDesc {
6026            label: Some(shader.source()),
6027            spirv: shader.spirv(),
6028            wgsl: shader.wgsl(),
6029            msl: shader.msl(),
6030            // A container per entry point, for the reason the mesh module gives.
6031            dxil: &shader.dxil_containers(),
6032        })?;
6033        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
6034            label: Some(label),
6035            layout,
6036            vertex: ShaderEntry {
6037                module,
6038                entry_point: vertex,
6039            },
6040            fragment: Some(ShaderEntry {
6041                module,
6042                entry_point: fragment,
6043            }),
6044            // The triangle is deliberately oversized, so two of its vertices are
6045            // outside the viewport and its winding is not worth reasoning about.
6046            primitive: PrimitiveState::default(),
6047            depth_stencil,
6048            multisample: MultisampleState::default(),
6049            color_targets,
6050        });
6051        device.destroy_shader_module(module);
6052        pipeline
6053    }
6054
6055    /// Builds a full-screen-triangle pipeline that writes a **depth**
6056    /// attachment and no colour one.
6057    ///
6058    /// [`Self::build_fullscreen`]'s shape with the two halves of that swapped:
6059    /// no colour target at all, and a depth state whose comparison always
6060    /// passes so every texel of the destination takes the value the fragment
6061    /// computed. The reversed-Z [`CompareOp::Greater`] every geometry pipeline
6062    /// in this file uses would be wrong here — this pass is not depth-testing
6063    /// anything, it is writing a reduction, and a test against the target's
6064    /// undefined contents would drop texels at random.
6065    ///
6066    /// Two callers, [`crate::hiz`] and [`crate::occlusion_cull`], and it stays
6067    /// a method rather than moving there because the module and the
6068    /// destroy-before-unwrap above are this file's, and both take it in exactly
6069    /// as `crate::ssao` takes the sibling.
6070    ///
6071    /// **The entry points are named**, unlike the sibling's: `hiz.slang` has a
6072    /// fragment stage per pyramid, and a stage looked up by kind would be
6073    /// ambiguous.
6074    ///
6075    /// # Errors
6076    ///
6077    /// [`HalError`] from the module or the pipeline.
6078    fn build_depth_fullscreen(
6079        device: &dyn Device,
6080        label: &str,
6081        shader: &crcbl_shaders::Shader,
6082        vertex: &str,
6083        fragment: &str,
6084        layout: PipelineLayoutHandle,
6085        format: Format,
6086    ) -> Result<GraphicsPipelineHandle, HalError> {
6087        let module = device.create_shader_module(&ShaderModuleDesc {
6088            label: Some(shader.source()),
6089            spirv: shader.spirv(),
6090            wgsl: shader.wgsl(),
6091            msl: shader.msl(),
6092            dxil: &shader.dxil_containers(),
6093        })?;
6094        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
6095            label: Some(label),
6096            layout,
6097            vertex: ShaderEntry {
6098                module,
6099                entry_point: vertex,
6100            },
6101            fragment: Some(ShaderEntry {
6102                module,
6103                entry_point: fragment,
6104            }),
6105            primitive: PrimitiveState::default(),
6106            depth_stencil: Some(DepthStencilState {
6107                format,
6108                depth_write: true,
6109                depth_compare: CompareOp::Always,
6110                stencil: None,
6111                bias: DepthBias::default(),
6112            }),
6113            multisample: MultisampleState::default(),
6114            color_targets: &[],
6115        });
6116        device.destroy_shader_module(module);
6117        pipeline
6118    }
6119
6120    /// Creates the geometry pool and makes every mesh of `scene` resident in it.
6121    ///
6122    /// Separate from [`ForwardRenderer::build`] because it is **self-cleaning**:
6123    /// the pool is not the rollback's until this has returned, so a failure
6124    /// between creating it and flushing the last upload releases it here.
6125    fn build_geometry(
6126        device: &dyn Device,
6127        queue: QueueHandle,
6128        scene: &SceneDesc<'_>,
6129        service: &mut dyn FnMut(),
6130    ) -> Result<(MeshPool, Vec<ResidentMesh>), HalError> {
6131        let mut pool = MeshPool::new(
6132            device,
6133            &MeshPoolDesc {
6134                label: Some("forward geometry"),
6135                vertex_capacity: scene.capacities.vertices,
6136                index_capacity: scene.capacities.indices,
6137                mesh_capacity: scene.capacities.meshes,
6138            },
6139        )?;
6140        match Self::residents(device, queue, &mut pool, scene, service) {
6141            Ok(residents) => Ok((pool, residents)),
6142            Err(error) => {
6143                pool.destroy(device);
6144                Err(error)
6145            }
6146        }
6147    }
6148
6149    /// Creates the material table and fills it with `scene`'s rows, returning it
6150    /// and the id of each.
6151    ///
6152    /// Self-cleaning for the same reason [`ForwardRenderer::build_geometry`] is:
6153    /// the table is not the rollback's until this has returned.
6154    fn build_materials(
6155        device: &dyn Device,
6156        scene: &SceneDesc<'_>,
6157    ) -> Result<(MaterialTable, Vec<u32>), HalError> {
6158        let mut materials = MaterialTable::new(
6159            device,
6160            &MaterialTableDesc {
6161                label: Some("forward"),
6162                capacity: scene.capacities.materials,
6163            },
6164        )?;
6165        match Self::material_rows(device, &mut materials, &scene.materials) {
6166            Ok(ids) => Ok((materials, ids)),
6167            Err(error) => {
6168                materials.destroy(device);
6169                Err(error)
6170            }
6171        }
6172    }
6173
6174    /// Inserts `rows` **in order** and returns the id of each.
6175    ///
6176    /// Split out of [`ForwardRenderer::build_materials`] only so the table can
6177    /// be released on a failure without the borrow that filling it takes, which
6178    /// is the same shape [`ForwardRenderer::residents`] has.
6179    ///
6180    /// **In order, because row 0 is not this function's to choose**: it is what
6181    /// [`mesh::GpuInstance::default`] names, so it is what an instance written
6182    /// without a material id shades with. Inserting a description's rows in any
6183    /// other order would move that row under every caller — see
6184    /// [`SceneDesc::materials`], which is where it is a caller's decision.
6185    fn material_rows(
6186        device: &dyn Device,
6187        materials: &mut MaterialTable,
6188        rows: &[mesh::GpuMaterial],
6189    ) -> Result<Vec<u32>, HalError> {
6190        let mut ids = Vec::with_capacity(rows.len());
6191        for row in rows {
6192            let handle = materials.insert(device, row)?;
6193            // The id is asked for rather than assumed, because the number an
6194            // instance carries is this one and nothing else knows it.
6195            ids.push(materials.index(handle).ok_or_else(|| {
6196                HalError::Backend(
6197                    "a material inserted into an empty table did not resolve".to_string(),
6198                )
6199            })?);
6200        }
6201        Ok(ids)
6202    }
6203
6204    /// Uploads every mesh of `scene` and returns their mesh ids — **only** once
6205    /// the transfers have completed.
6206    ///
6207    /// The calls are §3.1's upload path in order: the copies are recorded and
6208    /// submitted against timeline values, [`MeshPool::flush`] is what makes those
6209    /// values pass, and [`MeshPool::mesh`] is what refuses to hand out a range
6210    /// before they have.
6211    ///
6212    /// **In description order**, which is what makes a mesh's table id a
6213    /// property of the description rather than of this loop — the second mesh
6214    /// uploaded is the pool's first resident at a non-zero base vertex, which is
6215    /// what the module docs call the one thing that can tell a working base
6216    /// vertex from a cancelled one.
6217    ///
6218    /// A DAG is **one upload per level**. Every level was decimated separately,
6219    /// so a coarser level's vertices are wherever the collapses put them and
6220    /// belong to no vertex of the level below — a DAG is several vertex ranges,
6221    /// and the pool suballocates in vertices, so several ranges means several
6222    /// uploads. Level 0 goes first, so every other level starts past it and the
6223    /// offsets a cluster carries are non-negative; that is checked rather than
6224    /// assumed, because the pool's free list makes no promise about where a mesh
6225    /// lands.
6226    fn residents(
6227        device: &dyn Device,
6228        queue: QueueHandle,
6229        pool: &mut MeshPool,
6230        scene: &SceneDesc<'_>,
6231        service: &mut dyn FnMut(),
6232    ) -> Result<Vec<ResidentMesh>, HalError> {
6233        let mut uploaded: Vec<Vec<crate::mesh_pool::MeshHandle>> =
6234            Vec::with_capacity(scene.meshes.len());
6235        for desc in &scene.meshes {
6236            match &desc.geometry {
6237                Geometry::Flat {
6238                    vertices,
6239                    indices,
6240                    uv_range,
6241                    flags,
6242                    ..
6243                } => {
6244                    uploaded.push(vec![pool.upload(
6245                        device,
6246                        queue,
6247                        &MeshUpload {
6248                            label: &desc.label,
6249                            vertices,
6250                            indices,
6251                            uv_range: *uv_range,
6252                            flags: *flags,
6253                        },
6254                    )?]);
6255                    service();
6256                }
6257                Geometry::Dag {
6258                    levels,
6259                    dag,
6260                    uv_range,
6261                    flags,
6262                } => {
6263                    let mut handles = Vec::with_capacity(levels.len());
6264                    for (depth, (vertices, level)) in levels.iter().zip(&dag.levels).enumerate() {
6265                        handles.push(pool.upload(
6266                            device,
6267                            queue,
6268                            &MeshUpload {
6269                                label: &format!("{} level {depth}", desc.label),
6270                                vertices,
6271                                indices: &level.indices(),
6272                                // Level 0's range for every level, which is the
6273                                // one the mesh path reads whichever level it
6274                                // draws — see `Geometry::Dag::uv_range`.
6275                                uv_range: *uv_range,
6276                                // And the description's flags for every level,
6277                                // for the same reason: the levels are one
6278                                // surface, so a tangent frame either describes
6279                                // all of them or none.
6280                                flags: *flags,
6281                            },
6282                        )?);
6283                        service();
6284                    }
6285                    uploaded.push(handles);
6286                }
6287            }
6288        }
6289
6290        pool.flush(device)?;
6291        service();
6292        // The table index is the only number that leaves here — where the
6293        // geometry actually is reaches the GPU through the mesh table, and the
6294        // draw arguments are built from that table by a shader. `MeshPool::mesh`
6295        // is still asked, because it is the call that refuses a mesh whose
6296        // upload has not completed, and an id for a mesh that is not there yet
6297        // would be a draw of nothing.
6298        let resolve = |handle| match (pool.mesh(handle), pool.table_index(handle)) {
6299            (Some(_), Some(id)) => Ok(id),
6300            _ => Err(MeshPoolError::NotResident { handle }),
6301        };
6302        let base_vertex = |handle| match pool.mesh(handle) {
6303            Some(range) => Ok(range.base_vertex),
6304            None => Err(MeshPoolError::NotResident { handle }),
6305        };
6306
6307        let mut residents = Vec::with_capacity(uploaded.len());
6308        for (desc, handles) in scene.meshes.iter().zip(&uploaded) {
6309            // **Relative to level 0's base**, because that is the base the
6310            // instance resolves through its mesh id and the one the stage adds
6311            // this on top of. A level that landed *below* level 0 would make the
6312            // sum wrap, so it is refused here rather than drawn as another
6313            // mesh's vertices. A flat mesh is one level and reads zero.
6314            let level_zero = base_vertex(handles[0])?;
6315            let mut vertex_bases = Vec::with_capacity(handles.len());
6316            for (depth, &handle) in handles.iter().enumerate() {
6317                let base = base_vertex(handle)?;
6318                vertex_bases.push(base.checked_sub(level_zero).ok_or_else(|| {
6319                    HalError::InvalidDescriptor(format!(
6320                        "{} level {depth} landed at vertex {base}, below level 0's \
6321                         {level_zero}, so its clusters cannot name their own geometry",
6322                        desc.label
6323                    ))
6324                })?);
6325            }
6326            residents.push(ResidentMesh {
6327                levels: handles
6328                    .iter()
6329                    .map(|&handle| resolve(handle))
6330                    .collect::<Result<_, _>>()?,
6331                vertex_bases,
6332                // Matched on the description rather than counted off `handles`,
6333                // so a DAG decimated to a single level is still refused: what
6334                // makes a mesh skinnable is that every draw of it reads one
6335                // vertex run, and that is a property of the geometry rather than
6336                // of how many levels it happened to arrive with.
6337                skinnable: matches!(desc.geometry, Geometry::Flat { .. }).then(|| handles[0]),
6338            });
6339        }
6340        Ok(residents)
6341    }
6342
6343    /// Rotates to the next frame's uniform buffer and instance buffer, writes
6344    /// this frame's camera and light into the first, and uploads whatever
6345    /// changed into the second.
6346    ///
6347    /// Must be called once per frame, before [`ForwardRenderer::add_passes`].
6348    /// Separate from `add_passes` because the write happens on the CPU and the
6349    /// passes are recorded on the GPU timeline: fusing them would hide the ring
6350    /// rotation inside a function whose name says nothing about it.
6351    ///
6352    /// **It moves nothing.** Every object's transform is the caller's, written
6353    /// through [`ForwardRenderer::set_instance`] whenever it changes, so the
6354    /// transfer this records is [`InstancePool::begin_frame`]'s delta and a
6355    /// frame in which nothing moved uploads no instance bytes at all. The
6356    /// sandbox's spinning cube is one 80-byte write a frame because the sandbox
6357    /// spins it; a still scene is free.
6358    ///
6359    /// It also writes this frame's **cull parameters** — the camera's frustum,
6360    /// extracted from the very same view-projection the uniform block carries,
6361    /// so the pass that decides what is on screen and the pass that draws it
6362    /// cannot be looking at two different cameras — and zeroes the counters the
6363    /// two compute passes only ever add to. See [`crate::draw_gen`] on why those
6364    /// zeroes come from the host.
6365    ///
6366    /// # Errors
6367    ///
6368    /// [`HalError`] if the uniform buffer, the instance buffer or any of the
6369    /// draw-generation buffers could not be written.
6370    pub fn begin_frame(
6371        &mut self,
6372        device: &dyn Device,
6373        camera: &Camera,
6374        light: &DirectionalLight,
6375        extent: (u32, u32),
6376    ) -> Result<(), HalError> {
6377        // First, before anything this frame could release or rewrite.
6378        self.retire_uploads(device)?;
6379        // The instance pool owns the ring, so its slot is the frame index the
6380        // uniform buffer and the bind group below are picked with.
6381        self.frame = self.instances.rotate();
6382        self.frame_skins = false;
6383        self.instances.flush(device)?;
6384        self.begin_frame_body(device, camera, light, extent)
6385    }
6386
6387    /// [`begin_frame`](Self::begin_frame) for a frame that **skins**: the same
6388    /// call with the skinning plan folded into it.
6389    ///
6390    /// It does four things in the one order that is correct, which is why it is
6391    /// a call and not a note in someone's docs:
6392    ///
6393    /// 1. rotates the instance ring, so the frame slot exists;
6394    /// 2. hands that slot and `ranges` to `skinning`, which validates them,
6395    ///    uploads the palettes and **moves the ping-pong** — the only place the
6396    ///    parity ever moves;
6397    /// 3. points every object placed by
6398    ///    [`add_skinned_instance`](Self::add_skinned_instance) at the half of its
6399    ///    region the parity now names;
6400    /// 4. uploads the instance delta, so those bases are the ones this frame
6401    ///    draws.
6402    ///
6403    /// Do those three and four in the other order and the objects carry the
6404    /// previous frame's half — a character posed one frame late, every frame,
6405    /// with nothing to report it. A caller never sees a parity or a table id, and
6406    /// so cannot get that wrong.
6407    ///
6408    /// Build `ranges` with [`SkinnedMesh::skin_range`], one per reserved region
6409    /// this frame animates. A frame with **no** skinned object still calls this
6410    /// with an empty slice — see [`Skinning::begin_frame`], whose slot would
6411    /// otherwise re-dispatch whichever frame last used it.
6412    ///
6413    /// [`add_skinned_passes`](Self::add_skinned_passes) is the other half, and
6414    /// the one that orders the dispatch before the draws.
6415    ///
6416    /// # Errors
6417    ///
6418    /// Whatever [`Skinning::begin_frame`] refuses — a joint index past its
6419    /// palette, a binding count that is not the region's vertex count, more than
6420    /// the pass was built for — and [`SkinningError::Hal`] for anything the seam
6421    /// refused, this renderer's own uniform and instance writes included.
6422    ///
6423    /// # Panics
6424    ///
6425    /// If `skinning` was not built with at least [`FRAMES_IN_FLIGHT`] frames:
6426    /// its rings are indexed by this renderer's frame slot, and
6427    /// [`Skinning::begin_frame`] refuses a slot it has no buffers for.
6428    pub fn begin_skinned_frame(
6429        &mut self,
6430        device: &dyn Device,
6431        skinning: &mut Skinning,
6432        ranges: &[SkinRange<'_>],
6433        camera: &Camera,
6434        light: &DirectionalLight,
6435        extent: (u32, u32),
6436    ) -> Result<(), SkinningError> {
6437        // First, on `begin_frame`'s terms.
6438        self.retire_uploads(device)?;
6439        self.frame = self.instances.rotate();
6440        // An empty plan dispatches nothing — see [`Skinning::begin_frame`] — so
6441        // it leaves the vertex pool where it was, and the shadow atlas with it.
6442        self.frame_skins = !ranges.is_empty();
6443        skinning.begin_frame(device, self.frame, ranges)?;
6444        self.point_skinned_instances(skinning.parity());
6445        self.instances.flush(device)?;
6446        self.begin_frame_body(device, camera, light, extent)?;
6447        Ok(())
6448    }
6449
6450    /// Whether this frame records the irradiance probes' two
6451    /// updater passes.
6452    ///
6453    /// The scene's own answer and the console's together: the volume decides
6454    /// whether the feature applies at all — see [`ProbeUpdate`], which is where
6455    /// the reason it is not an effect bit lives — and `r_probe_bounce` is the
6456    /// on/off pair a pricing run reads the two passes' cost off with everything
6457    /// else held still.
6458    ///
6459    /// **It is not the whole condition.** The map is cascade 0's own draws, so
6460    /// the pass is recorded only where that cascade is being drawn too — see
6461    /// `add_shadow_pass`, which is where the rest of it is.
6462    fn probe_update_runs(&self) -> bool {
6463        self.probe_update == ProbeUpdate::EveryFrame && rsm::enabled()
6464    }
6465
6466    /// The six side-plane sets a point light's face culls test, or `None` for
6467    /// a light that is not a point — or with the face culls switched off, which
6468    /// is one cull against the light's box drawn into all six faces.
6469    ///
6470    /// `faces` are the light's face matrices in face order, the ones its tiles
6471    /// render through.
6472    fn point_face_planes(&self, light: &Light, faces: &[Mat4]) -> Option<crate::cull::FacePlanes> {
6473        if !self.point_face_culls || !matches!(light, Light::Point(_)) {
6474            return None;
6475        }
6476        let matrices: [Mat4; shadow::POINT_FACES] = faces.try_into().ok()?;
6477        Some(crate::cull::face_planes(&matrices))
6478    }
6479
6480    /// Every punctual shadow face this frame draws into the punctual reflective
6481    /// shadow map, in the order the pass draws them and the producer table lists
6482    /// them.
6483    ///
6484    /// **One list for both halves of the updater**, and that is the point:
6485    /// `add_shadow_pass` sets a viewport from a face's
6486    /// [`tile`](PunctualFace::tile) and the gather reads that same rectangle out
6487    /// of the matching producer row, so a face the pass drew and a row the
6488    /// gather walked have to be the same face. Building the two from separate
6489    /// filters is two things that can drift, and the drift would be a light
6490    /// bouncing another light's map.
6491    ///
6492    /// **The occupied slots this frame redraws**, which is the same set
6493    /// `add_shadow_pass` gives the atlas: a face's transform is a shadow view's
6494    /// block and its draws are a shadow cull's, and
6495    /// [`Self::begin_frame_body`](Self::begin_frame) writes neither for a slot
6496    /// it is holding.
6497    ///
6498    /// # Every occupied tile, and no budget of its own
6499    ///
6500    /// The producers are exactly the atlas's occupied faces — up to
6501    /// [`shadow::LIGHT_SLOTS`] lights and [`shadow::LIGHT_TILES`] tiles between
6502    /// them — rather than the highest-ranked light or some smaller count.
6503    ///
6504    /// **Because the budget already exists and is spent.**
6505    /// [`shadow::Selection`] has ranked these lights by projected screen
6506    /// influence and handed out every tile there is; a second budget on top
6507    /// would rank the same lights again, differently, and produce a light that
6508    /// casts a shadow and lends no bounce. That is a difference no picture shows
6509    /// — the same argument [`Self::shadow_lights`] makes about a map's size —
6510    /// and it is the kind of quiet inconsistency the two halves of one light are
6511    /// worst placed to have.
6512    ///
6513    /// It is affordable at the extent that was chosen for it:
6514    /// `apps/lantern` lights seven faces, and
6515    /// [`PUNCTUAL_RSM_SIDE`](crcbl_shaders::probe_gather::PUNCTUAL_RSM_SIDE)
6516    /// carries the sweep that priced them.
6517    ///
6518    /// **Empty where shadows are off**, for that same reason — a punctual face
6519    /// *is* a shadow view. The sun's half is not, which is what
6520    /// `updater_drives_cascade_zero` exists for: switching shadows off keeps the
6521    /// sun's bounce and loses every punctual one, rather than switching the
6522    /// whole updater off with them.
6523    fn punctual_faces(&self) -> Vec<PunctualFace> {
6524        if !self.probe_update_runs() {
6525            return Vec::new();
6526        }
6527        // A frame with the shadows switched off draws no atlas, so no group of
6528        // it is *redrawn* — and `begin_frame_body`'s `updater_drives_cascade_zero`
6529        // branch has still written every one of these views and dispatched every
6530        // one of these culls, for this pass to draw through.
6531        let updater_drives = !self.frame_effects.contains(RenderEffects::SHADOWS);
6532        let mut faces = Vec::new();
6533        for (slot, held) in self.shadow_lights.slots().iter().enumerate() {
6534            let Some(held) = *held else {
6535                continue;
6536            };
6537            if !updater_drives && !self.shadow_group_redrawn[shadow_cull(slot)] {
6538                continue;
6539            }
6540            let Some(light) = self.extra_lights.get(held.light) else {
6541                continue;
6542            };
6543            // A spot draws face 0 alone and a point light all six, each through
6544            // its own matrix into its own tile — `shadow::tile_span` is the same
6545            // function `Selection` allocated the run with, so a face here and a
6546            // tile there cannot disagree about how many there are.
6547            for face in 0..shadow::tile_span(light) {
6548                let tile = rsm::punctual_tile(held.base + face);
6549                faces.push(PunctualFace {
6550                    view: shadow_view(slot, face),
6551                    cull: shadow_cull(slot),
6552                    face,
6553                    tile,
6554                    producer: producer_row(light, tile),
6555                });
6556            }
6557        }
6558        faces
6559    }
6560
6561    /// Puts an object in the scene and returns the handle that names it.
6562    ///
6563    /// An instance in the pool **is** an object in the scene: the frame records
6564    /// a fixed number of draws and the cull pass decides which instances they
6565    /// walk, so adding one costs a slot in an array and not a command. It is
6566    /// drawn from the next [`ForwardRenderer::begin_frame`], which is what
6567    /// uploads it.
6568    ///
6569    /// # The index it lands at is not decoration
6570    ///
6571    /// `draw_gen.slang` keys topic 25's hysteresis state by the
6572    /// instance's **array index**, at `instance_index * group_stride`, and
6573    /// `mesh_cluster.slang`'s amplification stage reads the same address. So the
6574    /// record of which of a DAG's groups an object had expanded belongs to the
6575    /// *slot*, not to the object — and a slot that [`remove_instance`] freed is
6576    /// handed to the next `add_instance`, which inherits it. What that costs is
6577    /// one frame selected against a history that is not this object's, and the
6578    /// next frame's own judgement replaces it; it is never a wrong picture,
6579    /// because every group is judged afresh whatever the state said.
6580    ///
6581    /// That inheritance is inert while the scene holds **one** instance of a DAG
6582    /// mesh, which is every frame the engine has drawn so far — one instance's
6583    /// run has no previous occupant, and a flat mesh's
6584    /// [`MeshLevels`](level_select::MeshLevels) record names no groups at all, so
6585    /// nothing indexes the state for it. It stops being inert the moment an
6586    /// application places a second.
6587    ///
6588    /// [`remove_instance`]: ForwardRenderer::remove_instance
6589    ///
6590    /// # A DAG mesh needs a device that can choose a level
6591    ///
6592    /// One device shape cannot draw a [`Geometry::Dag`] mesh: a mesh stage with
6593    /// **no** amplification stage in front of it emits every cluster of the
6594    /// bucket, which for a DAG is every level at once — several overlapping
6595    /// copies of one surface. This does not refuse it, because it has no
6596    /// vocabulary for that refusal; a caller placing a DAG asks
6597    /// [`ForwardRenderer::selects_levels`] first, and places it only where that
6598    /// says yes. A flat mesh is unaffected on every path.
6599    ///
6600    /// # Errors
6601    ///
6602    /// [`InstancePoolError::PoolFull`] when the instance pool is full. It never
6603    /// grows — [`Capacities::instances`](crate::scene::Capacities::instances) is
6604    /// what a caller sizes it with.
6605    ///
6606    /// # Panics
6607    ///
6608    /// If [`InstanceDesc::mesh`] or [`InstanceDesc::material`] is past the end of
6609    /// the description this renderer was built from. Both are indices a caller
6610    /// wrote against a description it holds, so an out-of-range one is a mistake
6611    /// in the calling code rather than a condition the frame can be in — and the
6612    /// alternative is an object silently drawn as some other mesh, in some other
6613    /// colour.
6614    pub fn add_instance(
6615        &mut self,
6616        desc: &InstanceDesc,
6617    ) -> Result<InstanceHandle, InstancePoolError> {
6618        let instance = self.gpu_instance(desc);
6619        self.instances.insert(&instance)
6620    }
6621
6622    /// Rewrites the object `handle` names — its mesh, its material and its
6623    /// transform, all three.
6624    ///
6625    /// A stale handle — one [`ForwardRenderer::remove_instance`] retired — writes
6626    /// nothing, rather than overwriting whatever took its slot.
6627    ///
6628    /// Takes effect at the next [`ForwardRenderer::begin_frame`], which uploads
6629    /// the element and nothing else: an object that did not move costs no
6630    /// transfer at all.
6631    ///
6632    /// # Panics
6633    ///
6634    /// On [`ForwardRenderer::add_instance`]'s terms, for the same reason.
6635    pub fn set_instance(&mut self, handle: InstanceHandle, desc: &InstanceDesc) {
6636        let mut instance = self.gpu_instance(desc);
6637        instance.flags |= self.kept_flags(handle);
6638        self.instances.set(handle, &instance);
6639    }
6640
6641    /// The bits of `handle`'s record a rewrite of it keeps: its hidden views
6642    /// and whether it casts — see [`ForwardRenderer::set_instance_views`] and
6643    /// [`ForwardRenderer::set_instance_casts_shadow`]. Zero for a stale
6644    /// handle, whose rewrite writes nothing anyway.
6645    fn kept_flags(&self, handle: InstanceHandle) -> u32 {
6646        self.instances.get(handle).map_or(0, |record| {
6647            record.flags
6648                & (mesh::GpuInstance::HIDDEN_VIEWS_MASK | mesh::GpuInstance::CASTS_NO_SHADOW)
6649        })
6650    }
6651
6652    /// Sets whether `handle` casts a shadow. Every instance starts casting.
6653    ///
6654    /// **Every shadow map and nothing else**: an instance that casts none is
6655    /// rejected by the cull of the sun's cascades and of every shadowed light,
6656    /// on every geometry path, so it lands in no tile of the atlas — and in no
6657    /// reflective shadow map, which draws those same culls' survivors, so it
6658    /// bounces no light into the probes either. Every camera still draws it,
6659    /// and it still receives the shadows the rest of the scene casts.
6660    ///
6661    /// What a model drawn for an icon wants, placed where the scene's sun can
6662    /// see it: see [`ViewBackground::Transparent`] and
6663    /// [`set_instance_views`](Self::set_instance_views).
6664    ///
6665    /// A change redraws every shadow map whose cull the instance could be kept
6666    /// by, because it is a write [`InstancePool::take_written`] names. Not a
6667    /// move, on
6668    /// [`set_instance_views`](Self::set_instance_views)' terms, and a stale
6669    /// handle is ignored.
6670    pub fn set_instance_casts_shadow(&mut self, handle: InstanceHandle, casts: bool) {
6671        if let Some(record) = self.instances.get(handle) {
6672            let flags = if casts {
6673                record.flags & !mesh::GpuInstance::CASTS_NO_SHADOW
6674            } else {
6675                record.flags | mesh::GpuInstance::CASTS_NO_SHADOW
6676            };
6677            self.instances.set_flags(handle, flags);
6678        }
6679    }
6680
6681    /// Whether `handle` casts a shadow, or `None` for a stale handle.
6682    #[must_use]
6683    pub fn instance_casts_shadow(&self, handle: InstanceHandle) -> Option<bool> {
6684        self.instances
6685            .get(handle)
6686            .map(|record| record.flags & mesh::GpuInstance::CASTS_NO_SHADOW == 0)
6687    }
6688
6689    /// Takes the object `handle` names back out of the scene, freeing its slot.
6690    ///
6691    /// **A removal is a cleared live bit, not a skipped draw**, because the frame
6692    /// no longer records a draw per object: `cull.slang` asks whether an instance
6693    /// is live before it reads anything else, so removing an object and culling
6694    /// it off screen take the same path out of the frame. An instance left in the
6695    /// pool would be drawn wherever its transform put it.
6696    ///
6697    /// A stale handle removes nothing. Takes effect at the next
6698    /// [`ForwardRenderer::begin_frame`], on
6699    /// [`ForwardRenderer::set_instance`]'s terms.
6700    pub fn remove_instance(&mut self, handle: InstanceHandle) {
6701        self.instances.remove(handle);
6702    }
6703
6704    /// Captures a visibility map for every probe, from the static geometry
6705    /// standing in the scene right now.
6706    ///
6707    /// The probe visibility rung: each probe records how far
6708    /// away the nearest surface is in every direction, and `mesh.slang`'s
6709    /// `probe_irradiance` then weighs each of a fragment's eight probes by
6710    /// whether it can *see* that fragment — so a probe on the far side of a wall
6711    /// contributes nothing and a room stops lighting the room next door.
6712    /// This crate's own `probe_capture` module is the pass, `probe_visibility`
6713    /// is the geometry it draws, and [`crcbl_shaders::probe_visibility`] is the
6714    /// format.
6715    ///
6716    /// # Call it once, after the scene's walls are placed
6717    ///
6718    /// **A description carries no instances** — [`SceneDesc`] is meshes,
6719    /// materials, a page and the probe rows, and the objects arrive afterwards
6720    /// through [`ForwardRenderer::add_instance`] — so there is nothing for a
6721    /// capture inside [`ForwardRenderer::with_scene`] to be about. This is the
6722    /// call that has the room in it, and an application makes it once its static
6723    /// geometry is placed.
6724    ///
6725    /// A caller that never makes it draws exactly the frame this renderer drew
6726    /// before the maps existed: every group names the one-texel placeholder,
6727    /// which no surface is further away than, and every probe keeps all of its
6728    /// weight.
6729    ///
6730    /// **It is a capture of geometry and not a bake of light.** Nothing about
6731    /// the lights is recorded, every one of them still moves, and the rows the
6732    /// probes carry are untouched.
6733    ///
6734    /// # What it sees, and what it does not
6735    ///
6736    /// Every instance live in the pool when it is called, at the transform it
6737    /// then has, rasterised from its mesh's level-0 triangles into six 90°
6738    /// faces per probe. Objects that move
6739    /// afterwards keep the occlusion they had here, which is the accepted limit
6740    /// this technique has everywhere it is used — a probe volume is about the
6741    /// walls. Recapturing after a wall moves is this call again.
6742    ///
6743    /// **The device must be idle.** The previous capture's image is released
6744    /// here, and a frame in flight may still be reading it.
6745    ///
6746    /// # Errors
6747    ///
6748    /// [`HalError`] from the capture. The previous maps are kept on the failing
6749    /// path, so a renderer that has captured once and then failed goes on
6750    /// drawing with what it had.
6751    pub fn capture_probe_visibility(
6752        &mut self,
6753        device: &dyn Device,
6754        queue: QueueHandle,
6755    ) -> Result<(), HalError> {
6756        let placed: Vec<crate::probe_visibility::Occluder> = self
6757            .instances
6758            .live()
6759            .into_iter()
6760            .map(|record| crate::probe_visibility::Occluder {
6761                mesh: record.mesh,
6762                transform: Mat4::from_cols_array(&record.transform),
6763            })
6764            .collect();
6765        let Some(uploaded) = crate::probe_capture::capture(
6766            device,
6767            queue,
6768            &self.probe_volume,
6769            &self.probe_occluders,
6770            &placed,
6771        )?
6772        else {
6773            // No probes, or nothing placed for a map to be about. Leaving the
6774            // placeholder bound is the honest answer, and it is what a scene
6775            // with no probes has always read.
6776            return Ok(());
6777        };
6778        // The cached groups name the view this replaces, so they go before it
6779        // does — a bind group outliving the image it names is a validation
6780        // error on every backend that checks, and a use-after-free on the ones
6781        // that do not.
6782        for slot in &mut self.primary.screen_channel_groups {
6783            if let Some((_, stale)) = slot.take() {
6784                device.destroy_bind_group(stale);
6785            }
6786        }
6787        if let Some(previous) = self.probe_visibility.replace(uploaded) {
6788            previous.destroy(device);
6789        }
6790        Ok(())
6791    }
6792
6793    /// Re-centres the irradiance clipmap on `point` by whole probe steps, and
6794    /// captures the probes the step exposed.
6795    ///
6796    /// The irradiance probes' scrolling: each level moves a whole
6797    /// number of its own probe spacings towards `point`, so the probes that stay
6798    /// inside it stand exactly where they stood and go on being addressed at the
6799    /// rows they already had — and only the slabs the step brought in are
6800    /// captured. Answers how many rows that was, which is **zero for the
6801    /// ordinary frame**: the point has to travel half a probe spacing before the
6802    /// nearest whole step changes at all.
6803    ///
6804    /// [`ProbeVolume::follow`](crcbl_shaders::probe::ProbeVolume::follow) is the
6805    /// rule and `exposed` beside it is the invalidation; this is the two of them
6806    /// plus the device work they imply — the visibility maps of the exposed
6807    /// rows, and the position table the reflective-shadow-map gather reads.
6808    ///
6809    /// # A volume authored to cover its whole world does not move
6810    ///
6811    /// The steps are the ones that centre a level on `point`, and a caller whose
6812    /// volume is already the world it is in wants none of them — so a caller
6813    /// passes the point it wants the *centre* at rather than the camera outright
6814    /// when the two differ. `apps/lantern` and `apps/shard` are that case and
6815    /// their own modules say so.
6816    ///
6817    /// # A step stalls, and a frame that does not step costs a comparison
6818    ///
6819    /// The recapture is [`ForwardRenderer::capture_probe_visibility`]'s pass
6820    /// over fewer rows, and it waits on [`Device::wait_idle`] exactly as that
6821    /// one does — so a step drains the device before it rewrites anything and
6822    /// leaves it drained. That is a stall, and it is why the probe records price a step
6823    /// separately from a frame. A call that steps nothing returns before the
6824    /// wait, so the ordinary frame pays a rounding per level and per axis and
6825    /// nothing else.
6826    ///
6827    /// It may therefore be called from a frame loop, but **not after**
6828    /// [`ForwardRenderer::begin_frame`] has been called for the frame being
6829    /// recorded: the header it moves is the one that frame's uniform block has
6830    /// already been written from.
6831    ///
6832    /// A renderer that has never captured re-centres the header and captures
6833    /// nothing: there is no image to write slabs into, every group still names
6834    /// the placeholder, and the first
6835    /// [`ForwardRenderer::capture_probe_visibility`] covers the scrolled volume
6836    /// whole.
6837    ///
6838    /// # It moves the geometry and not the light
6839    ///
6840    /// What a step re-captures is the *visibility* of the probes it exposed,
6841    /// which is what the maps are about. The **rows** are not touched, so under
6842    /// [`ProbeUpdate::Authored`] a probe
6843    /// that a step brought in keeps the irradiance the probe that left had —
6844    /// authored for somewhere else. A volume that scrolls therefore wants
6845    /// [`ProbeUpdate::EveryFrame`], whose
6846    /// gather refills every row from the scene each frame and has no such gap;
6847    /// `docs/backlog.md` carries what an authored one would need instead.
6848    ///
6849    /// # Errors
6850    ///
6851    /// [`HalError`] from the recapture or from the position rewrite. The volume
6852    /// keeps the steps it had on either failing path, so a renderer that could
6853    /// not capture a slab does not go on drawing with rows about somewhere else.
6854    pub fn follow_probe_volume(
6855        &mut self,
6856        device: &dyn Device,
6857        queue: QueueHandle,
6858        point: [f32; 3],
6859    ) -> Result<u32, HalError> {
6860        let mut moved = self.probe_volume;
6861        let rows = moved.follow(point);
6862        if rows.is_empty() && moved.steps == self.probe_volume.steps {
6863            return Ok(0);
6864        }
6865        // **Before anything is written**, so a caller may make this call from
6866        // its frame loop: the layers the recapture rewrites and the position
6867        // table beside them are read by whatever frames are still in flight, and
6868        // neither is a ring. A frame that does not step never reaches this line,
6869        // which is what keeps the ordinary frame free of it.
6870        device.wait_idle()?;
6871        if let Some(captured) = &self.probe_visibility {
6872            let placed: Vec<crate::probe_visibility::Occluder> = self
6873                .instances
6874                .live()
6875                .into_iter()
6876                .map(|record| crate::probe_visibility::Occluder {
6877                    mesh: record.mesh,
6878                    transform: Mat4::from_cols_array(&record.transform),
6879                })
6880                .collect();
6881            crate::probe_capture::recapture(
6882                device,
6883                queue,
6884                &moved,
6885                &self.probe_occluders,
6886                &placed,
6887                &rows,
6888                captured.image,
6889            )?;
6890        }
6891        // After the capture, so a volume whose slabs could not be drawn keeps
6892        // the header its maps are about.
6893        if let Some(gather) = &self.probe_gather {
6894            gather.rewrite_positions(device, &moved)?;
6895        }
6896        self.probe_volume = moved;
6897        Ok(u32::try_from(rows.len()).unwrap_or(u32::MAX))
6898    }
6899
6900    /// Where the irradiance clipmap stands right now — the header the frame
6901    /// block carries, [`ForwardRenderer::follow_probe_volume`]'s scroll
6902    /// included.
6903    #[must_use]
6904    pub const fn probe_volume(&self) -> crcbl_shaders::probe::ProbeVolume {
6905        self.probe_volume
6906    }
6907
6908    /// `draws` split by the **whole** material mode, each partition under the
6909    /// depth-only pipeline that honours it — what the depth prepass and every
6910    /// shadow view record instead of one call list under one pipeline.
6911    ///
6912    /// Four pipelines for [`DEPTH_MODES`]' four values, which is what makes the
6913    /// split total: the opaque buckets are drawn with
6914    /// [`shadow_pipeline`](Self::shadow_pipeline) — `depthVertexMain` and no
6915    /// fragment stage — the masked ones with
6916    /// [`depth_masked_pipeline`](Self::depth_masked_pipeline), which can
6917    /// `discard`, and each of those has a [`CullMode::None`] twin for the
6918    /// buckets whose material is double-sided. A scene with one cutout in it
6919    /// pays a fragment stage for that mesh's draws and for no others; before
6920    /// this it paid for the whole frame, which on lavapipe roughly doubled the
6921    /// prepass and added two thirds to the shadow pass.
6922    ///
6923    /// **Both depth passes and not just the atlas.** A double-sided plate whose
6924    /// back face the prepass culled writes no depth there, so the colour pass's
6925    /// `GreaterOrEqual` test against it rejects the fragment and the surface is
6926    /// missing from the frame; and a cascade that culled it casts no shadow.
6927    fn depth_partitions(&self, draws: &BucketDraws) -> Vec<BucketDraws> {
6928        self.partitions(
6929            draws,
6930            mesh::GpuMaterial::MODE_MASK,
6931            &[
6932                (DEPTH_MODES[0], Some(self.shadow_pipeline.single)),
6933                (
6934                    DEPTH_MODES[1],
6935                    self.depth_masked_pipeline.map(|masked| masked.single),
6936                ),
6937                (DEPTH_MODES[2], self.shadow_pipeline.double),
6938                (
6939                    DEPTH_MODES[3],
6940                    self.depth_masked_pipeline.and_then(|masked| masked.double),
6941                ),
6942            ],
6943        )
6944    }
6945
6946    /// `draws` split by the material's **side** alone, each partition under the
6947    /// matching half of `pipelines` — what the colour pass and the two
6948    /// reflective shadow maps record.
6949    ///
6950    /// Two partitions where [`depth_partitions`](Self::depth_partitions) has
6951    /// four, and the difference is the whole of what these passes do not care
6952    /// about: their pipelines carry a fragment stage either way and cut the
6953    /// alpha mask inside it, so a masked bucket and an opaque one are the same
6954    /// draw here. What they cannot express inside the stage is the cull mode.
6955    fn sided_partitions(&self, draws: &BucketDraws, pipelines: SidedPipelines) -> Vec<BucketDraws> {
6956        self.partitions(draws, mesh::GpuMaterial::DOUBLE_SIDED, &pipelines.by_side())
6957    }
6958
6959    /// Resolves a description's mesh and material indices into the table ids the
6960    /// GPU reads.
6961    ///
6962    /// The whole record every time, because [`InstancePool::set`] writes the
6963    /// whole record: an instance that lost either id would name entry 0 of that
6964    /// table, which is a mesh and a material rather than an absence.
6965    fn gpu_instance(&self, desc: &InstanceDesc) -> mesh::GpuInstance {
6966        mesh::GpuInstance {
6967            transform: desc.transform.to_cols_array(),
6968            mesh: self.mesh_ids[desc.mesh],
6969            material: self.material_ids[desc.material],
6970            flags: self.material_mode_bits(desc.material),
6971            ..mesh::GpuInstance::default()
6972        }
6973    }
6974
6975    /// The material mode of description material `material`, in the bits an
6976    /// instance record carries it in.
6977    ///
6978    /// **Read out of the table rather than out of the description**, because the
6979    /// table is what a `set` would move and the row is what the shader shades
6980    /// through. It is the other half of the record's routing key: `draw_gen`
6981    /// buckets an instance by [`mesh`](mesh::GpuInstance::mesh) and by this,
6982    /// which is how a masked material costs a fragment stage in the depth passes
6983    /// for its own mesh alone.
6984    ///
6985    /// The mode is captured **here**, when the record is written — see
6986    /// [`GpuInstance::MATERIAL_MODE_SHIFT`](mesh::GpuInstance::MATERIAL_MODE_SHIFT)
6987    /// for what that means for a material rewritten afterwards.
6988    fn material_mode_bits(&self, material: usize) -> u32 {
6989        self.materials.mode(self.material_ids[material]) << mesh::GpuInstance::MATERIAL_MODE_SHIFT
6990    }
6991
6992    // --- skinning: reserving the region, placing the object, ordering the
6993    // dispatch ---
6994
6995    /// The vertex pool every mesh here is resident in — what
6996    /// [`SkinningDesc::vertices`](crate::skinning::SkinningDesc::vertices)
6997    /// takes.
6998    ///
6999    /// The skinning pass reads a bind pose out of this buffer and writes the
7000    /// deformed vertices back into another run of it, which is what makes a
7001    /// skinned draw an ordinary draw. It must be *this* pool's buffer: a
7002    /// [`Skinning`] built against any other writes vertices no draw here can
7003    /// reach.
7004    #[must_use]
7005    pub const fn vertex_buffer(&self) -> BufferHandle {
7006        self.pool.vertex_buffer()
7007    }
7008
7009    /// Where that pool's **attribute** region begins, in words — what
7010    /// [`SkinningDesc::attribute_base`](crate::skinning::SkinningDesc::attribute_base)
7011    /// takes.
7012    ///
7013    /// The buffer holds two streams, so a pass that writes it needs the
7014    /// boundary as well as the handle; a [`Skinning`] built with the wrong one
7015    /// writes a mesh's attributes over another mesh's positions. See
7016    /// [`MeshPool::attribute_base`](crate::MeshPool::attribute_base).
7017    #[must_use]
7018    pub const fn attribute_base(&self) -> u32 {
7019        self.pool.attribute_base()
7020    }
7021
7022    /// Reserves a skinned region for description mesh `mesh`.
7023    ///
7024    /// The whole of what a caller needs to skin something, in one value: hand
7025    /// [`SkinnedMesh::skin_range`] a palette and a set of bindings to get the
7026    /// frame's [`SkinRange`], hand the result to
7027    /// [`begin_skinned_frame`](Self::begin_skinned_frame), and place it with
7028    /// [`add_skinned_instance`](Self::add_skinned_instance). The bases and the
7029    /// parity never have to be spelled by the caller at all — see
7030    /// [`crate::skinning::SkinnedMesh`], where the ping-pong lives.
7031    ///
7032    /// **The mesh keeps its own entry and the region takes none**, so the same
7033    /// description mesh can be drawn skinned through this and in its bind pose
7034    /// through [`add_instance`](Self::add_instance) in the same frame, both
7035    /// resolving through the one table entry it already had.
7036    ///
7037    /// Give it back with [`release_skinned`](Self::release_skinned).
7038    ///
7039    /// # Errors
7040    ///
7041    /// Whatever [`SkinnedMesh::reserve`] refuses: a vertex pool with no room for
7042    /// both halves. **Two vertex runs per skinned primitive** is what a scene's
7043    /// [`Capacities`](crate::scene::Capacities) has to have been sized for.
7044    ///
7045    /// # Panics
7046    ///
7047    /// If `mesh` is past the end of the description this renderer was built
7048    /// from, on [`add_instance`](Self::add_instance)'s terms — and if it names a
7049    /// [`Geometry::Dag`], which cannot be drawn out of a skinned region at all.
7050    /// A DAG is refused rather than skinned wrongly: its coarser levels are
7051    /// separate vertex runs no dispatch writes, so a cut that descended past
7052    /// level 0 would draw whatever the pool happened to be holding there.
7053    pub fn reserve_skinned(&mut self, mesh: usize) -> Result<SkinnedMesh, MeshPoolError> {
7054        let source = self.skinnable_meshes[mesh].unwrap_or_else(|| {
7055            panic!(
7056                "description mesh {mesh} is a Geometry::Dag, whose coarser levels are vertex \
7057                 runs no skinning dispatch writes; only a flat mesh can be skinned"
7058            )
7059        });
7060        SkinnedMesh::reserve(&mut self.pool, source)
7061    }
7062
7063    /// Gives `skinned`'s region back to the vertex pool.
7064    ///
7065    /// The device must not still be drawing it: this records no barrier, on
7066    /// [`SkinnedMesh::release`]'s terms. Objects placed through it are **not**
7067    /// removed — [`remove_instance`](Self::remove_instance) is what does that,
7068    /// and an instance left behind goes on drawing its source mesh's geometry
7069    /// out of vertices the pool has handed back. Remove the objects first.
7070    pub fn release_skinned(&mut self, skinned: SkinnedMesh) {
7071        skinned.release(&mut self.pool);
7072    }
7073
7074    /// Places a skinned object in the scene.
7075    ///
7076    /// [`add_instance`](Self::add_instance) with a reserved region in place of a
7077    /// description mesh. The renderer keeps the object in a list of its own and
7078    /// **re-points it every [`begin_skinned_frame`](Self::begin_skinned_frame)**
7079    /// at the half of the region that frame's dispatch fills, so the parity is
7080    /// never something a caller writes.
7081    ///
7082    /// A skinned object driven by plain [`begin_frame`](Self::begin_frame) is
7083    /// therefore left pointing wherever it last was, which after the first frame
7084    /// is the pose of the frame before — the reason the two entry points are
7085    /// separate calls rather than a flag.
7086    ///
7087    /// # Errors
7088    ///
7089    /// [`InstancePoolError::PoolFull`], on
7090    /// [`add_instance`](Self::add_instance)'s terms.
7091    ///
7092    /// # Panics
7093    ///
7094    /// If [`SkinnedInstanceDesc::material`] is past the end of the description
7095    /// this renderer was built from, on
7096    /// [`add_instance`](Self::add_instance)'s terms.
7097    pub fn add_skinned_instance(
7098        &mut self,
7099        desc: &SkinnedInstanceDesc<'_>,
7100    ) -> Result<InstanceHandle, InstancePoolError> {
7101        // Parity zero, and it never reaches the GPU as such: the instance pool
7102        // uploads by delta at `begin_skinned_frame`, which re-points every entry
7103        // of the list below before it flushes. What this writes is the rest of
7104        // the record.
7105        let instance = self.skinned_gpu_instance(desc, 0);
7106        let handle = self.instances.insert(&instance)?;
7107        self.skinned_instances.push(SkinnedInstance {
7108            handle,
7109            bases: skinned_bases(desc.mesh),
7110            pointed: false,
7111        });
7112        Ok(handle)
7113    }
7114
7115    /// Rewrites the skinned object `handle` names — its region, its material and
7116    /// its transform.
7117    ///
7118    /// [`set_instance`](Self::set_instance) for an object placed by
7119    /// [`add_skinned_instance`](Self::add_skinned_instance), and the call a
7120    /// character's transform changes through. A stale handle writes nothing.
7121    ///
7122    /// Passing a handle this renderer has never seen skinned adopts it: the
7123    /// object joins the re-pointed list from here on. That is what lets a caller
7124    /// swap a bind-pose instance over to a region without removing and replacing
7125    /// it.
7126    ///
7127    /// # Panics
7128    ///
7129    /// On [`add_skinned_instance`](Self::add_skinned_instance)'s terms.
7130    pub fn set_skinned_instance(&mut self, handle: InstanceHandle, desc: &SkinnedInstanceDesc<'_>) {
7131        let mut instance = self.skinned_gpu_instance(desc, 0);
7132        instance.flags |= self.kept_flags(handle);
7133        if !self.instances.set(handle, &instance) {
7134            return;
7135        }
7136        let bases = skinned_bases(desc.mesh);
7137        match self
7138            .skinned_instances
7139            .iter_mut()
7140            .find(|entry| entry.handle == handle)
7141        {
7142            // **A different region is a fresh entry.** The half this object has
7143            // never been drawn out of holds whatever its reservation came with,
7144            // so the next pointing owes it rest rather than a previous
7145            // deformation — see [`SkinnedInstance::pointed`]. The pair of bases
7146            // is what "different" means here: two calls naming one region give
7147            // the same two runs, so rewriting an object's material or transform
7148            // is not a change of region.
7149            Some(entry) => {
7150                entry.pointed &= entry.bases == bases;
7151                entry.bases = bases;
7152            }
7153            None => self.skinned_instances.push(SkinnedInstance {
7154                handle,
7155                bases,
7156                pointed: false,
7157            }),
7158        }
7159    }
7160
7161    /// A skinned object's record, at one parity — [`gpu_instance`](Self::gpu_instance)
7162    /// with the region's base vertex carried in the record and the bit that says
7163    /// to read it.
7164    ///
7165    /// The mesh id is the **source** mesh's, not a second entry's, so the bucket
7166    /// this instance is scattered into, the levels it selects through and the
7167    /// box it is culled against are the ones the undeformed mesh already had.
7168    fn skinned_gpu_instance(
7169        &self,
7170        desc: &SkinnedInstanceDesc<'_>,
7171        parity: u32,
7172    ) -> mesh::GpuInstance {
7173        let base_vertex = desc.mesh.region().base(parity);
7174        mesh::GpuInstance {
7175            transform: desc.transform.to_cols_array(),
7176            mesh: desc.mesh.mesh_id(),
7177            material: self.material_ids[desc.material],
7178            // The override bit **and** the material mode: a skinned instance is
7179            // routed by the same key as a rigid one, so a skinned cutout lands
7180            // in its mesh's masked bucket rather than in the opaque twin.
7181            flags: mesh::GpuInstance::BASE_VERTEX_OVERRIDE | self.material_mode_bits(desc.material),
7182            base_vertex,
7183            // At rest, which is what a record this call writes has to be: the
7184            // object has not been drawn out of this region yet, so the other
7185            // half holds whatever its reservation came with. A frame that runs
7186            // [`point_skinned_instances`](Self::point_skinned_instances) is
7187            // what starts pointing this at the half before.
7188            previous_base_vertex: base_vertex,
7189            ..mesh::GpuInstance::default()
7190        }
7191    }
7192
7193    /// Points every skinned object at the half of its region a frame of this
7194    /// parity fills **and at the half the frame before it filled**, and forgets
7195    /// the ones whose instance has gone.
7196    ///
7197    /// Called between the instance ring's rotation and its upload, which is the
7198    /// whole reason those two are separate calls — see
7199    /// [`InstancePool::rotate`](crate::instance_pool::InstancePool::rotate).
7200    ///
7201    /// The second base is what a skinned fragment's motion vector is subtracted
7202    /// against — see
7203    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
7204    /// **A region this frame's `ranges` left out was not skinned this frame**,
7205    /// so the half this points at as the current one already holds an earlier
7206    /// frame's pose. That is pre-existing — it is what a caller driving a
7207    /// skinned object through plain [`begin_frame`](Self::begin_frame) gets, and
7208    /// it predates this second base — and the previous half is then no worse off
7209    /// than the current one.
7210    fn point_skinned_instances(&mut self, parity: u32) {
7211        let Self {
7212            instances,
7213            skinned_instances,
7214            ..
7215        } = self;
7216        skinned_instances.retain_mut(|entry| {
7217            // `SkinnedRegion::base`'s indexing and `SkinnedRegion::previous_base`'s,
7218            // applied to the entry's own copy of the pair — see
7219            // [`SkinnedInstance::bases`].
7220            let base_vertex = entry.bases[(parity & 1) as usize];
7221            let previous_base_vertex = if entry.pointed {
7222                entry.bases[((parity ^ 1) & 1) as usize]
7223            } else {
7224                // Nothing has been written into the other half for this object,
7225                // so it is put at rest — see [`SkinnedInstance::pointed`].
7226                base_vertex
7227            };
7228            entry.pointed = true;
7229            // The two bases and nothing else: the transform, the material and
7230            // the mesh the caller last set survive, and so does the transform
7231            // the record moved *from* — which
7232            // [`InstancePool::set`](crate::instance_pool::InstancePool::set)
7233            // would overwrite with this frame's, leaving a skinned object's own
7234            // travel out of the motion target. See
7235            // [`InstancePool::set_bases`](crate::instance_pool::InstancePool::set_bases).
7236            // Its answer is also what says the instance is still there, so an
7237            // object a caller removed drops out of the list here.
7238            instances.set_bases(entry.handle, base_vertex, previous_base_vertex)
7239        });
7240    }
7241
7242    /// The lights in the frame **beside the sun**, which
7243    /// [`begin_frame`](Self::begin_frame) still takes on its own.
7244    ///
7245    /// Topic 44's light list, minus its first row: the
7246    /// sun is row 0 of every frame's list and the ones set here follow it, in
7247    /// the order given. That order is the one a froxel keeps a prefix of when it
7248    /// runs out of budget — see [`ForwardRenderer::light_capacity`] and the
7249    /// overflow counter beside it — so it is a caller's lever and not an
7250    /// accident.
7251    ///
7252    /// The sun keeps a parameter of its own because it is the light that owns
7253    /// the ambient term and the shadow cascades, neither of which a [`Light`]
7254    /// has. What it stopped being is a special case in the *shader*, which is
7255    /// what the list bought.
7256    ///
7257    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7258    /// what uploads the rows.
7259    ///
7260    /// # Panics
7261    ///
7262    /// If there are more lights than [`ForwardRenderer::light_capacity`] leaves
7263    /// room for once the sun has its row. Refused rather than truncated: a light
7264    /// missing from the list is missing from every froxel, and **no counter in
7265    /// the frame would report it** — the overflow counter counts what a froxel's
7266    /// budget refused, which is a different number.
7267    pub fn set_lights(&mut self, lights: &[Light]) {
7268        assert!(
7269            lights.len() < self.primary.lights.capacity() as usize,
7270            "{} lights beside the sun, in a list of {}",
7271            lights.len(),
7272            self.primary.lights.capacity()
7273        );
7274        self.extra_lights.clear();
7275        self.extra_lights.extend_from_slice(lights);
7276    }
7277
7278    /// Rows the light list holds, the sun's included.
7279    #[must_use]
7280    pub const fn light_capacity(&self) -> u32 {
7281        self.primary.lights.capacity()
7282    }
7283
7284    /// This frame's froxel grid, as [`begin_frame`](Self::begin_frame) sized it
7285    /// from the viewport and the camera.
7286    ///
7287    /// Exposed for the reason [`lod_params`](Self::lod_params) is: a test that
7288    /// wants to know which froxel a point was shaded out of has to use the grid
7289    /// the frame really used, and re-deriving it would be a second copy of the
7290    /// arithmetic rather than a reading of the first.
7291    #[must_use]
7292    pub const fn grid(&self) -> Grid {
7293        self.primary.grid
7294    }
7295
7296    /// `frame`'s froxel grid buffer, for a test copying out what the clustering
7297    /// pass decided.
7298    ///
7299    /// # Panics
7300    ///
7301    /// If `frame` is not a slot this was built with.
7302    #[must_use]
7303    pub fn light_grid_buffer(&self, frame: usize) -> BufferHandle {
7304        self.primary.lights.grid(frame)
7305    }
7306
7307    /// The pixel budget the descent compares a group's projected error against.
7308    ///
7309    /// One pixel until this is called — see the constant this crate keeps it
7310    /// in. Larger is coarser: a group
7311    /// projecting *over* the budget is expanded and its children are drawn, so
7312    /// raising it stops the descent higher up the DAG.
7313    ///
7314    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7315    /// what writes it into the frame block.
7316    pub const fn set_lod_error_budget(&mut self, budget: f32) {
7317        self.lod_error_budget = budget;
7318    }
7319
7320    /// The budget this renderer selects under unless
7321    /// [`set_lod_error_budget`](Self::set_lod_error_budget) says otherwise, and
7322    /// the ratio the hold budget sits at below whichever one is in force.
7323    ///
7324    /// Public because a test that drives a camera across a level boundary has to
7325    /// know where the boundary is, and where it is depends on both numbers —
7326    /// re-deriving either in the test would be a second copy to drift.
7327    pub const LOD_ERROR_BUDGET: f32 = LOD_ERROR_BUDGET;
7328    /// See [`LOD_ERROR_BUDGET`](Self::LOD_ERROR_BUDGET).
7329    pub const LOD_HOLD_RATIO: f32 = LOD_HOLD_RATIO;
7330
7331    /// How far below the budget an already-expanded group is held before it
7332    /// collapses again — topic 25's hysteresis, as a fraction of
7333    /// the budget.
7334    ///
7335    /// [`LOD_HOLD_RATIO`](Self::LOD_HOLD_RATIO) until this is called. **A ratio
7336    /// of one removes the band**, which makes the two budgets equal and the
7337    /// previous frame's answer stop mattering — the setting a test uses to show
7338    /// that the band is what stops a drifting camera flickering, on the same
7339    /// code path and one number apart.
7340    ///
7341    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7342    /// what writes it into the two params blocks.
7343    pub const fn set_lod_hold_ratio(&mut self, ratio: f32) {
7344        self.lod_hold_ratio = ratio;
7345    }
7346
7347    /// What the last [`begin_frame`](Self::begin_frame) handed the descent:
7348    /// pixels per unit at one unit from the eye, and the pixel budget.
7349    ///
7350    /// Pixels per unit at one unit from the eye, the budget an unexpanded group
7351    /// starts expanding over, and the budget an expanded one is held down to.
7352    ///
7353    /// What `ClusterDag::expand` takes, so a caller reading
7354    /// [`cluster_selection`](Self::cluster_selection) back can run the same
7355    /// frames host-side rather than re-deriving the numbers from the camera and
7356    /// hoping they agree. `[0.0, 0.0, 0.0]` before the first frame.
7357    #[must_use]
7358    pub const fn lod_params(&self) -> [f32; 3] {
7359        self.primary.lod_params
7360    }
7361
7362    /// The same three numbers the **shadow cascades** selected under, which is
7363    /// [`lod_params`](Self::lod_params) with both budgets multiplied by
7364    /// [`SHADOW_LOD_BIAS`] — topic 25's shadow LOD bias, as the
7365    /// parameters it actually reaches the GPU as.
7366    ///
7367    /// The pixels-per-unit is the camera's, unchanged, because the cascades
7368    /// select from the camera's eye at the camera's scale; see
7369    /// [`begin_frame`](Self::begin_frame). `[0.0, 0.0, 0.0]` before the first
7370    /// frame.
7371    #[must_use]
7372    pub const fn shadow_lod_params(&self) -> [f32; 3] {
7373        self.shadow_lod_params
7374    }
7375
7376    /// Where description mesh `mesh`'s clusters are in the cluster pool — every
7377    /// level of it, as one run — or `None` off the mesh path, where there is no
7378    /// cluster pool at all.
7379    ///
7380    /// The base a reader adds a `(level, cluster)` to in order to index
7381    /// [`cluster_selection`](Self::cluster_selection): the levels are laid down
7382    /// finest first and contiguously, so level `d` cluster `c` is at
7383    /// `base + (clusters of levels below d) + c`. A flat mesh is one level, so
7384    /// its run is its clusters and `c` indexes it directly.
7385    ///
7386    /// # Panics
7387    ///
7388    /// If `mesh` is past the end of the description this renderer was built
7389    /// from, on [`add_instance`](Self::add_instance)'s terms.
7390    #[must_use]
7391    pub fn cluster_range(&self, mesh: usize) -> Option<ClusterRange> {
7392        (!self.mesh_clusters.is_empty()).then(|| self.mesh_clusters[mesh])
7393    }
7394
7395    /// The buffer `frame`'s amplification stage recorded its chosen cut into:
7396    /// one `u32` per resident cluster, `1` where the cluster was drawn.
7397    ///
7398    /// `None` where there is no amplification stage, which is every device that
7399    /// reports no [`Features::TASK_SHADER`] and every non-mesh geometry path.
7400    ///
7401    /// **This is topic 25's observable and nothing in the frame
7402    /// reads it.** A frame whose every cluster came from one level is a
7403    /// plausible picture and matches any golden blessed from it, so a golden
7404    /// cannot show per-cluster selection happening at all; this can. It is
7405    /// `TRANSFER_SRC`, and copying it out is the caller's to record.
7406    ///
7407    /// [`Features::TASK_SHADER`]: crcbl_hal::Features::TASK_SHADER
7408    #[must_use]
7409    pub fn cluster_selection(&self, frame: usize) -> Option<BufferHandle> {
7410        self.primary.cluster_selection.get(frame).copied()
7411    }
7412
7413    /// The same, for `cascade`'s shadow pass: the cut that cascade's
7414    /// amplification stage chose this frame.
7415    ///
7416    /// **The shadow LOD bias' observable.** A budget the cascades merely *were
7417    /// passed* is a parameter; the cut they reached under it is the behaviour,
7418    /// and this is the only thing that carries it out of a frame — the colour
7419    /// pass overwrites [`cluster_selection`](Self::cluster_selection) after the
7420    /// cascades have run. Indexed and read exactly as that buffer is, through
7421    /// [`cluster_range`](Self::cluster_range).
7422    ///
7423    /// `None` where there is no amplification stage, and where `cascade` is not
7424    /// one of [`shadow::CASCADES`].
7425    #[must_use]
7426    pub fn shadow_selection(&self, frame: usize, cascade: usize) -> Option<BufferHandle> {
7427        self.shadow_selection
7428            .get(frame)
7429            .and_then(|cascades| cascades.get(cascade))
7430            .copied()
7431    }
7432
7433    /// The buckets description mesh `mesh`'s levels draw through, finest first —
7434    /// element `d` is level `d`'s bucket, and it is empty on the mesh path.
7435    ///
7436    /// **This is the uniform cut's observable**, and it is the indirect
7437    /// arguments rather than a buffer of its own: `draw_gen.slang` scatters an
7438    /// instance into the bucket for the level it selected, so exactly one of
7439    /// these buckets comes out of a frame with a non-zero instance count and
7440    /// which one it is *is* the chosen level. A reader takes
7441    /// [`DrawGen::args_offset`](crate::draw_gen::DrawGen::args_offset) of each
7442    /// and looks at
7443    /// [`DrawIndexedArgs::instance_count`](crcbl_shaders::draw_gen::DrawIndexedArgs::instance_count).
7444    ///
7445    /// Empty on [`GeometryPath::MeshShader`], where a mesh is one bucket and the
7446    /// level is chosen per cluster instead — see
7447    /// [`cluster_selection`](Self::cluster_selection), which is that path's
7448    /// observable.
7449    ///
7450    /// **These are the buckets of the scene's first material mode** — `OPAQUE`
7451    /// in any scene that has an opaque material, since the table is every
7452    /// mesh's levels once per mode the scene holds, mode by mode in
7453    /// `DEPTH_MODES` order. An instance of another mode selects the same level
7454    /// and lands in that level's bucket in its own mode's run, which this does
7455    /// not name; every scene in this tree that reads this accessor is all
7456    /// opaque, so "exactly one of these has a non-zero instance count" holds for
7457    /// them as it always did.
7458    ///
7459    /// # Panics
7460    ///
7461    /// If `mesh` is past the end of the description this renderer was built
7462    /// from, on [`add_instance`](Self::add_instance)'s terms.
7463    #[must_use]
7464    pub fn level_buckets(&self, mesh: usize) -> &[u32] {
7465        if self.mesh_level_buckets.is_empty() {
7466            return &[];
7467        }
7468        &self.mesh_level_buckets[mesh]
7469    }
7470
7471    /// `frame`'s indirect draw arguments, [`crcbl_shaders::draw_gen::DRAW_ARGS_SIZE`]
7472    /// bytes per bucket — what a reader of
7473    /// [`level_buckets`](Self::level_buckets) copies out.
7474    ///
7475    /// # Panics
7476    ///
7477    /// If `frame` is not a slot this renderer was built with.
7478    #[must_use]
7479    pub fn draw_args(&self, frame: usize) -> BufferHandle {
7480        self.primary.draws.args(frame)
7481    }
7482
7483    /// `frame`'s survivor list for the primary camera and the culling
7484    /// statistics beside it — `cull.slang`'s entries, tags and all, in the first
7485    /// [`DrawGen::visible_capacity`](crate::DrawGen::visible_capacity) words of
7486    /// the first buffer, and their count in word
7487    /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
7488    /// of the second — for a test holding the GPU's occlusion verdicts against
7489    /// [`crate::cull`]'s oracle. The first buffer holds the routes and runs
7490    /// behind the list; see [`crate::draw_gen`].
7491    ///
7492    /// # Panics
7493    ///
7494    /// If `frame` is not a slot this renderer was built with.
7495    #[must_use]
7496    pub fn camera_cull_buffers(&self, frame: usize) -> (BufferHandle, BufferHandle) {
7497        (
7498            self.primary.draws.visible(frame),
7499            self.primary.draws.visible_count(frame),
7500        )
7501    }
7502
7503    /// What the primary camera's cull reads, as the oracle in [`crate::cull`]
7504    /// takes it: every instance slot the pool has handed out, and the whole mesh
7505    /// table — both decoded from the host's own copies of what was uploaded.
7506    #[must_use]
7507    pub fn cull_records(&self) -> (Vec<mesh::GpuInstance>, Vec<mesh::GpuMesh>) {
7508        (self.instances.records(), self.pool.table_entries())
7509    }
7510
7511    /// The generator behind shadow cull `cull` — a cascade's below
7512    /// [`shadow::CASCADES`], a light slot's after —
7513    /// for a test reading back what a point light's face culls kept.
7514    ///
7515    /// # Panics
7516    ///
7517    /// If `cull` is not one of the renderer's shadow culls.
7518    #[must_use]
7519    pub fn shadow_generator(&self, cull: usize) -> &DrawGen {
7520        &self.shadow_draws[cull]
7521    }
7522
7523    /// The primary camera's farthest-depth pyramid — every level's image, view
7524    /// and extent, level 1 first — or empty before a frame culled by occlusion.
7525    ///
7526    /// For a test reading a level back: the images carry `TRANSFER_SRC` for
7527    /// exactly that, and they hold the last frame's early depth once that frame
7528    /// has finished.
7529    #[must_use]
7530    pub fn occlusion_pyramid(&self) -> Vec<(crcbl_hal::ImageHandle, ImageViewHandle, (u32, u32))> {
7531        self.primary.occlusion_pyramid.level_images()
7532    }
7533
7534    /// The most passes [`add_passes`](Self::add_passes) adds to one frame.
7535    ///
7536    /// [`DrawGen::MAX_PASSES`] per cull — the camera's, and one per shadow cull
7537    /// beside it — plus [`LightGrid::MAX_PASSES`] for the froxel grid and the
7538    /// passes that draw. **A ceiling, not a count**: a frame whose shadow slots
7539    /// are not all filled runs fewer culls, which is what makes a free tile
7540    /// free.
7541    ///
7542    /// Derived rather than written down, because a number written down is one
7543    /// that stops matching the frame the day a pass is added — which is exactly
7544    /// how the samples' hand-picked `8` came to time the first eight passes of a
7545    /// fourteen-pass frame. A caller sizing
7546    /// [`PassTimers`](crate::timing::PassTimers) wants
7547    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES), which adds this to
7548    /// what the overlay renderers record.
7549    pub const MAX_PASSES: u32 = DrawGen::MAX_PASSES * (1 + SHADOW_CULLS as u32)
7550        + DrawGen::LATE_PASSES
7551        + LightGrid::MAX_PASSES
7552        + RENDER_PASSES;
7553
7554    /// Adds the forward and tonemap passes to `graph`, rendering into `target`,
7555    /// and returns the HDR scene target they went through.
7556    ///
7557    /// `target` is normally the imported swapchain image. Everything else — the
7558    /// HDR scene colour, the depth buffer, and every barrier between them — is
7559    /// the graph's.
7560    ///
7561    /// The returned [`ImageId`] is the `Rgba16Float` frame the tonemap read:
7562    /// the scene colour **with the screen-space reflections already added**, not
7563    /// the target the forward pass wrote. A caller that wants to add a pass of
7564    /// its own after the tonemap — a debug overlay, or a readback proving the
7565    /// HDR range is real — declares a read of it and the graph works out the
7566    /// transition, exactly as it does for the tonemap.
7567    ///
7568    /// The two are the same description and different images, which is the
7569    /// design's off-switch as data rather than as a branch: a frame with
7570    /// [`RenderEffects::REFLECTIONS`] off adds neither pass, returns the forward
7571    /// pass's own id, and is bit-identical.
7572    ///
7573    /// # Which passes this adds is [`effects`](Self::effects)
7574    ///
7575    /// Resolved by the [`begin_frame`](Self::begin_frame) that opened this frame
7576    /// and read here — see [`crate::effects`] for the four layers and for what
7577    /// each toggle removes. Every effect is on by default, which is the frame
7578    /// every caller drew before the toggles existed.
7579    ///
7580    /// A switched-off effect is **fewer passes and one different bound
7581    /// descriptor**, never a shader permutation: the shadow atlas keeps its
7582    /// reversed-Z clear and reads as fully lit, the occlusion binding falls back
7583    /// to the renderer's white 1×1, and the reflection pair simply is not there.
7584    ///
7585    /// # The ground grid comes last, and after the tonemap
7586    ///
7587    /// [`set_ground_grid`](Self::set_ground_grid) is what puts it in the frame,
7588    /// and it is off by default. When it is on, its pass is added **after** the
7589    /// tonemap and writes `target` rather than the HDR scene colour, depth-tested
7590    /// against the scene depth: the grid is reference chrome, and a grid drawn
7591    /// before the tonemap would be exposed and tonemapped like geometry, so its
7592    /// colour would move with how bright the scene is. See [`crate::grid`].
7593    ///
7594    /// # `pool` is where the shadow atlas's incoming state comes from
7595    ///
7596    /// It must be the same pool the caller is about to
7597    /// [`compile`](RenderGraph::compile) and
7598    /// [`execute`](crate::CompiledGraph::execute) against, because the atlas and
7599    /// its placeholder are imports this renderer owns across frames and the
7600    /// pool's ledger is the record of what the last executed graph left them in
7601    /// — [`TransientPool::imported_image_use`], with [`None`] read as
7602    /// [`ResourceState::Undefined`]. Reading it here rather than carrying a
7603    /// field of our own is what keeps the declaration and the audit
7604    /// ([`InitialClaim::Tracked`]) one answer instead of two that drift: a frame
7605    /// whose `compile` fails is a frame that never ran, and a field advanced at
7606    /// build time would already have moved on without it.
7607    ///
7608    /// # Panics
7609    ///
7610    /// If `extent` is not the extent the [`begin_frame`](Self::begin_frame)
7611    /// that opened this frame was handed: the frame's internal extent, its
7612    /// blocks and the passes it builds were all decided there.
7613    pub fn add_passes<'a>(
7614        &'a mut self,
7615        graph: &mut RenderGraph<'a>,
7616        pool: &TransientPool,
7617        target: ImageId,
7618        extent: (u32, u32),
7619    ) -> ImageId {
7620        self.add_frame_passes(
7621            graph,
7622            pool,
7623            FrameTargets::primary(target, extent, None),
7624            |_, _| {},
7625        )
7626    }
7627
7628    /// [`add_passes`](Self::add_passes) for a frame that **skins**: the same
7629    /// frame with `skinning`'s dispatch in front of every pass that draws.
7630    ///
7631    /// # This takes the pass rather than its [`BufferId`], and that is the point
7632    ///
7633    /// [`Skinning::add_pass`] hands back the id of the vertex pool so that a
7634    /// mesh pass can declare a read of it and be ordered after the dispatch. The
7635    /// obvious seam is therefore an id parameter here — and it is the wrong one,
7636    /// because every way of getting it wrong is silent. A caller can pass the id
7637    /// of a *different* import, add the skinning pass after this one, or not add
7638    /// it at all, and in each case the graph orders nothing, the draws read the
7639    /// region before the compute write has been made visible, and what comes out
7640    /// is a mesh that flickers between two poses on hardware and looks perfect
7641    /// under a validation layer.
7642    ///
7643    /// So this takes the [`Skinning`] and **adds the pass itself**, first, with
7644    /// this renderer's own frame slot, and declares the read on the three passes
7645    /// that pull vertices out of the pool — the shadow atlas, the depth prepass
7646    /// and the forward pass. There is no order for a caller to get right,
7647    /// because there is only one call.
7648    ///
7649    /// A frame whose [`begin_skinned_frame`](Self::begin_skinned_frame) was
7650    /// handed no ranges adds no dispatch and no declarations, and is the frame
7651    /// [`add_passes`](Self::add_passes) would have built.
7652    ///
7653    /// # It records one pass more than [`MAX_PASSES`](Self::MAX_PASSES)
7654    ///
7655    /// That constant is the bound on [`add_passes`](Self::add_passes) and stays
7656    /// so; the skinning dispatch is [`Skinning::MAX_PASSES`], and
7657    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES) — what a caller
7658    /// sizes [`PassTimers`](crate::PassTimers) with — already sums the two.
7659    ///
7660    /// # Panics
7661    ///
7662    /// If `extent` is not the extent the [`begin_skinned_frame`](Self::begin_skinned_frame)
7663    /// that opened this frame was handed: the frame's internal extent, its
7664    /// blocks and the passes it builds were all decided there.
7665    pub fn add_skinned_passes<'a>(
7666        &'a mut self,
7667        graph: &mut RenderGraph<'a>,
7668        pool: &TransientPool,
7669        target: ImageId,
7670        extent: (u32, u32),
7671        skinning: &Skinning,
7672    ) -> ImageId {
7673        self.add_frame_passes(
7674            graph,
7675            pool,
7676            FrameTargets::primary(target, extent, Some(skinning)),
7677            |_, _| {},
7678        )
7679    }
7680
7681    /// [`add_skinned_passes`](Self::add_skinned_passes) with one game-owned
7682    /// overlay inserted after the display-space frame is complete and before
7683    /// antialiasing or render-scale reconstruction.
7684    ///
7685    /// The callback receives the display target and its matching scene depth
7686    /// attachment at the internal render extent. It may add graph passes that
7687    /// sample `display` and attach `depth` read-only; it must leave both images
7688    /// in states its declarations name. The forward renderer continues with its
7689    /// existing resolve and upscale passes after the callback returns.
7690    ///
7691    /// # Panics
7692    ///
7693    /// On [`add_skinned_passes`](Self::add_skinned_passes)' terms.
7694    pub fn add_skinned_passes_with_overlay<'a, F>(
7695        &'a mut self,
7696        graph: &mut RenderGraph<'a>,
7697        pool: &TransientPool,
7698        target: ImageId,
7699        extent: (u32, u32),
7700        skinning: &Skinning,
7701        overlay: F,
7702    ) -> ImageId
7703    where
7704        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7705    {
7706        self.add_frame_passes(
7707            graph,
7708            pool,
7709            FrameTargets::primary(target, extent, Some(skinning)),
7710            overlay,
7711        )
7712    }
7713
7714    /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
7715    /// for a frame that also draws secondary views — see
7716    /// [`create_view`](Self::create_view).
7717    ///
7718    /// **The scene's passes are recorded once**: one skinning dispatch (where
7719    /// `skinning` is `Some`), one shadow atlas, one probe gather. Then each view
7720    /// in `views` records its own cull, clustering and frame into its own
7721    /// target, and the primary camera's frame into `target` comes last — so
7722    /// `overlay` may read a view's target, which is already drawn by then.
7723    ///
7724    /// Every view named must have been begun this frame by
7725    /// [`begin_view`](Self::begin_view).
7726    ///
7727    /// # Panics
7728    ///
7729    /// If a [`ViewTarget`] in [`FrameTargets::views`] names [`ViewId::PRIMARY`],
7730    /// a view this renderer did not build, a view not begun this frame, or a
7731    /// view twice — or if [`FrameTargets`]' extent is not the one the frame's
7732    /// [`begin_frame`](Self::begin_frame) was handed, or a view's is not the
7733    /// one its [`begin_view`](Self::begin_view) was.
7734    pub fn add_passes_with_views<'a, F>(
7735        &'a mut self,
7736        graph: &mut RenderGraph<'a>,
7737        pool: &TransientPool,
7738        frame: FrameTargets<'_>,
7739        overlay: F,
7740    ) -> ImageId
7741    where
7742        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7743    {
7744        self.add_frame_passes(graph, pool, frame, overlay)
7745    }
7746
7747    /// The body of every `add_*passes` entry point, which differ in their
7748    /// arguments and in nothing else.
7749    fn add_frame_passes<'a, F>(
7750        &'a mut self,
7751        graph: &mut RenderGraph<'a>,
7752        pool: &TransientPool,
7753        frame: FrameTargets<'_>,
7754        overlay: F,
7755    ) -> ImageId
7756    where
7757        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7758    {
7759        let FrameTargets {
7760            target,
7761            extent,
7762            skinning,
7763            views,
7764        } = frame;
7765        // **From here down `extent` is the extent the frame is *drawn* at**,
7766        // which is the caller's at a render scale of `1.0` and smaller below it.
7767        // Every use of it in this function sizes a transient, and every one of
7768        // those transients belongs to the internal frame; `target` is the only
7769        // thing here at the caller's extent, and it is an id whose image already
7770        // knows how big it is. `begin_frame_body` shadows it the same way and
7771        // for the same reason, so the two halves of a frame cannot disagree.
7772        //
7773        // `upscaling` is derived from the two extents rather than from the scale
7774        // itself, which is what makes it exact: a target small enough that the
7775        // scaled extent rounds back onto it adds no pass, because there would be
7776        // nothing for the pass to do.
7777        //
7778        // **Both are the ones `begin_frame` froze** — see
7779        // [`View::frame_extent`]. A render scale moved since then is the next
7780        // frame's, on [`Self::set_render_scale`]'s word, and a target of
7781        // another size is refused rather than drawn out of blocks and passes
7782        // decided for this one.
7783        assert_eq!(
7784            extent, self.primary.frame_target_extent,
7785            "`add_passes` was handed a target of {extent:?}, and the `begin_frame` that \
7786             opened this frame one of {:?}: hand both the same extent",
7787            self.primary.frame_target_extent
7788        );
7789        let target_extent = extent;
7790        let extent = self.primary.frame_extent;
7791        let upscaling = extent != target_extent;
7792        let frame = self.frame;
7793        let instance_count = self.instances.slot_count();
7794        let emit = self.emit;
7795
7796        // Every secondary view the caller asked for, checked before anything of
7797        // theirs is recorded: a view that does not exist, or one nothing began
7798        // this frame, would draw out of blocks written for some other frame.
7799        let secondary: Vec<(ViewTarget, (u32, u32))> = views
7800            .iter()
7801            .map(|view| {
7802                assert!(
7803                    view.view != ViewId::PRIMARY,
7804                    "the primary camera draws into the target `add_passes_with_views` takes, \
7805                     not into a `ViewTarget`"
7806                );
7807                let built = self
7808                    .views
7809                    .get(view.view.index() - 1)
7810                    .and_then(Option::as_ref)
7811                    .unwrap_or_else(|| panic!("{:?} is not a view this renderer built", view.view));
7812                assert_eq!(
7813                    built.begun, self.frame_serial,
7814                    "{:?} was not begun this frame; call `begin_view` after `begin_frame`",
7815                    view.view
7816                );
7817                assert!(
7818                    views.iter().filter(|other| other.view == view.view).count() == 1,
7819                    "{:?} was named twice in one frame",
7820                    view.view
7821                );
7822                assert_eq!(
7823                    view.extent, built.frame_target_extent,
7824                    "{:?} was handed a target of {:?} here and one of {:?} by `begin_view`: \
7825                     hand both the same extent",
7826                    view.view, view.extent, built.frame_target_extent
7827                );
7828                (*view, built.frame_extent)
7829            })
7830            .collect();
7831
7832        // **The skinning dispatch, before anything else is added.** It imports
7833        // the vertex pool and hands back that node's id; every pass below that
7834        // pulls vertices declares a read of it, and the graph is what turns the
7835        // two declarations into the barrier between the compute write and the
7836        // draws. `None` is a frame with nothing to skin, which adds no pass and
7837        // declares nothing — see `Skinning::add_pass`.
7838        let skinned = skinning.and_then(|skinning| skinning.add_pass(graph, frame));
7839
7840        // The camera's cull dispatch and the draw-argument dispatch, and the
7841        // light clustering after them — before anything draws, and before the
7842        // shadow atlas, which is where they always ran. See [`View::add_cull`].
7843        let cull = self.primary.add_cull(graph, pool, frame, instance_count);
7844
7845        // Topic 25's record of each cascade's cut. Each is written by
7846        // exactly one mesh pass, so what the graph orders here is this frame's
7847        // write against the next frame's use of the same slot. Each arrives in
7848        // the state the previous frame left it in, which is the one declared as
7849        // final.
7850        let tile_selection: Vec<BufferId> = self
7851            .shadow_selection
7852            .get(self.frame)
7853            .into_iter()
7854            .flatten()
7855            .enumerate()
7856            .map(|(tile, &buffer)| {
7857                import_read_write(graph, &format!("shadow-selection-{tile}"), buffer)
7858            })
7859            .collect();
7860
7861        // **This frame's slot of the probe ring**, which is the buffer every
7862        // one of this frame's bind groups names — see [`crate::probe`] for why
7863        // there is more than one. Imported in `ShaderRead` and handed back in
7864        // it: the build's staging copy left it there and no pass in the frame
7865        // writes it yet.
7866        let probe_buffer = self.probes.buffer(frame);
7867        let probe_table = graph.import_buffer(
7868            "probes",
7869            ImportedBuffer {
7870                buffer: probe_buffer,
7871                initial: ResourceState::ShaderRead,
7872                final_state: ResourceState::ShaderRead,
7873            },
7874        );
7875
7876        // The occlusion placeholder, imported once and read by every pass whose
7877        // bind group names it: the shadow pass's views, the depth prepass's copy
7878        // of the camera's group, and — on a frame drawing without
7879        // `RenderEffects::AMBIENT_OCCLUSION` — the forward pass itself. It was
7880        // uploaded at build, so it is already in `ShaderRead` and the graph has
7881        // nothing to transition; declaring it is what keeps that true if a later
7882        // pass wants it in some other state.
7883        let occlusion_placeholder = graph.import_image(
7884            "ssao-placeholder",
7885            ImportedImage {
7886                image: self.ambient_occlusion_placeholder.image,
7887                view: self.ambient_occlusion_placeholder.view,
7888                format: Format::R8Unorm,
7889                extent: (1, 1),
7890                initial: ResourceState::ShaderRead,
7891                claim: InitialClaim::Tracked,
7892                final_state: ResourceState::ShaderRead,
7893            },
7894        );
7895
7896        // The contact-shadow placeholder, imported beside the occlusion one and
7897        // on its terms exactly: every group of the mesh layout names this
7898        // binding, and on a frame drawing without `RenderEffects::CONTACT_SHADOWS`
7899        // it is what the forward pass binds.
7900        let contact_placeholder = graph.import_image(
7901            "contact-shadows-placeholder",
7902            ImportedImage {
7903                image: self.contact_shadow_placeholder.image,
7904                view: self.contact_shadow_placeholder.view,
7905                format: Format::R8Unorm,
7906                extent: (1, 1),
7907                initial: ResourceState::ShaderRead,
7908                claim: InitialClaim::Tracked,
7909                final_state: ResourceState::ShaderRead,
7910            },
7911        );
7912
7913        // §3.2's base-colour page, in every bind group of `mesh_layout` and so
7914        // read by all three of the passes that draw geometry. Like the
7915        // placeholder above it is already in `ShaderRead` and the graph has
7916        // nothing to transition on a frame nothing writes it — **the
7917        // declaration is for the frames something does**. A caller that copies a
7918        // render-to-texture view into one of its layers imports the same handle,
7919        // gets this same id back (`RenderGraph::import_image`), and the graph
7920        // then has an edge to order its write against these reads. Without the
7921        // declaration there is no such edge: the page is bound out of a
7922        // descriptor the graph never hears about, and a copy scheduled anywhere
7923        // but the tail of the frame leaves it in `TransferDst` for the passes
7924        // that sample it.
7925        let base_color_page =
7926            graph.import_image(Self::BASE_COLOR_PAGE_LABEL, self.base_color_page_import());
7927        // §2's normal page beside it, declared for exactly the reason above: it
7928        // is in every group of `mesh_layout` too, so a caller copying into one
7929        // of its layers needs the same edge against these draws.
7930        let normal_page = graph.import_image(Self::NORMAL_PAGE_LABEL, self.normal_page_import());
7931        // §2's other two pages beside them, declared for exactly the same
7932        // reason: both are in every group of `mesh_layout`, so a caller copying
7933        // into one of their layers needs the same edge against these draws.
7934        let mro_page = graph.import_image(Self::MRO_PAGE_LABEL, self.mro_page_import());
7935        let emissive_page =
7936            graph.import_image(Self::EMISSIVE_PAGE_LABEL, self.emissive_page_import());
7937
7938        // What this frame draws, resolved by the `begin_frame` that opened it —
7939        // see [`crate::effects`]. Read once here so every conditional below is
7940        // about one value rather than about four reads of a field.
7941        let effects = self.frame_effects;
7942        // Read here for `effects`' reason and for one more: the passes below
7943        // borrow `self` field by field, and a `&self` method called between
7944        // them would borrow the whole of it.
7945        let draws_sky = self.draws_sky();
7946        // What the frame's water draws, or `None` for a frame with none — read
7947        // here for `draws_sky`'s reason, and the same value every view records
7948        // from.
7949        let water = self.water.frame(self.frame);
7950        // The same, for the grass field, as `begin_frame` froze it: the value
7951        // every view's passes were built and its blocks written for.
7952        let grass = self.frame_grass;
7953        // Whether this frame ends by drawing the shadow atlas over itself — the
7954        // resolved view rather than the switch, so a caller who left the atlas
7955        // up and then asked for normals gets normals — as `begin_frame` froze
7956        // it, because that call built the viewer and wrote its block.
7957        let draws_atlas_view = self.frame_atlas_view;
7958
7959        let pages = MaterialPages {
7960            base_color: base_color_page,
7961            normal: normal_page,
7962            mro: mro_page,
7963            emissive: emissive_page,
7964        };
7965        let (shadow_atlas, shadow_draws, shadow_tile_clears, rsm_images) = self.add_shadow_pass(
7966            graph,
7967            pool,
7968            &tile_selection,
7969            ShadowReads {
7970                occlusion_placeholder,
7971                pages,
7972                skinned,
7973                probes: probe_table,
7974            },
7975        );
7976
7977        // The wireframe twin where a caller switched the view on, and `None`
7978        // everywhere else — see `set_wireframe`. Written on `ground_grid`'s
7979        // terms, and the `filter` is what keeps "switched on" from outrunning
7980        // "built": the field is only `Some` after a build that succeeded.
7981        //
7982        // The depth prepass below takes the depth-only pipeline and is untouched
7983        // by this, which is the half that makes a wireframe frame legible: the
7984        // occlusion pair still reads solid depth. **It is also what makes this
7985        // one variable rather than two**: the colour pass's depth attachment
7986        // branches on it as well, because a wireframe is not the geometry the
7987        // prepass drew — see `MeshModules::color_depth_stencil`.
7988        let wireframe = self.wireframe_pipeline.filter(|_| self.wireframe_on);
7989        let bucket_draws = BucketDraws {
7990            // Replaced per partition below, in both passes that draw this list —
7991            // see [`ForwardRenderer::sided_partitions`] and
7992            // [`ForwardRenderer::depth_partitions`]. The field is what the
7993            // partitions inherit everything else from.
7994            pipeline: self.mesh_pipeline.single,
7995            layout: self.mesh_pipeline_layout,
7996            indices: self.pool.index_buffer(),
7997            emit,
7998            calls: self
7999                .bucket_constants
8000                .iter()
8001                .enumerate()
8002                .map(|(bucket, constant_offset)| {
8003                    let bucket = u32::try_from(bucket)
8004                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8005                    (
8006                        *constant_offset,
8007                        self.primary.draws.args_offset(bucket),
8008                        self.primary.draws.count_offset(bucket),
8009                        self.primary.draws.mesh_args_offset(bucket),
8010                    )
8011                })
8012                .collect(),
8013            region_step: self.region_step,
8014            // Packed per partition, where the partition's buckets are known.
8015            ranges: None,
8016            flat: None,
8017        };
8018
8019        // Every draw this frame records: the shadow pass's, one per bucket — or
8020        // per range of buckets, or per partition behind a task stage — in
8021        // **each** of the depth prepass and the forward pass, and one full-screen
8022        // triangle per full-screen pass. Assigned before the passes below borrow
8023        // the fields they need, so it is the count for the frame being built
8024        // rather than the one before it — and off this frame's resolved effects
8025        // rather than off a constant, so a switched-off effect's triangle is not
8026        // counted as submitted.
8027        //
8028        // The ground grid is added on top rather than folded into
8029        // `fullscreen_passes`: it is not a [`RenderEffects`] bit and is not
8030        // resolved by the toggle order — it is a caller's opt-in, off by
8031        // default — so what decides it is the field and not this frame's
8032        // effects.
8033        self.recorded_fullscreen = fullscreen_passes(effects, extent, upscaling, self.frame_ssao_blurs)
8034                + u64::from(self.ground_grid().is_some() && !draws_atlas_view)
8035                + if draws_sky { SkyPass::PASSES } else { 0 }
8036                // The composite on an atmosphere frame whose fog effect is off,
8037                // on the sky's terms: it is there for the air in front of the
8038                // scene, which the atmosphere decides and no effect bit does.
8039                // With the effect on, `fullscreen_passes` already counted it.
8040                + if self.primary.frame_aerial
8041                    && !effects.contains(RenderEffects::VOLUMETRIC_FOG)
8042                {
8043                    u64::from(Volumetric::COMPOSITE_PASSES)
8044                } else {
8045                    0
8046                }
8047                // The water copy's triangle, on the sky's terms: content rather
8048                // than an effect bit, so the bodies decide it.
8049                + if water.is_some() { Water::FULLSCREEN_PASSES } else { 0 }
8050                // The atlas viewer, on the ground grid's terms: not an effect
8051                // bit and not resolved by the toggle order, so what decides it
8052                // is the debug view and not this frame's effects. It *replaces*
8053                // the tonemap `fullscreen_passes` counted and the grid above —
8054                // see `View::add_passes` — so its passes stand in for the one.
8055                + if draws_atlas_view {
8056                    u64::from(AtlasView::PASSES) - 1
8057                } else {
8058                    0
8059                };
8060        // The debug draw layer's own call, on the ground grid's terms: not an
8061        // effect bit, and decided by whether this frame's slot has a segment in
8062        // it. One direct draw of one instance covering every segment appended,
8063        // which is why it joins the full-screen triangles rather than the
8064        // indirect draws — `counters` counts both as submitted *and* drawn,
8065        // because the CPU knows what they cover.
8066        self.recorded_debug_draw = u64::from(self.debug_draw.records_pass(self.frame));
8067        // The shadow pass's tile resets, on the same terms: one over-sized
8068        // triangle of one instance per tile it redrew, and none at all on a
8069        // frame that cleared the whole attachment — see
8070        // [`MeshModules::depth_clear_pipeline`].
8071        self.recorded_tile_clears = shadow_tile_clears;
8072        // One indexed draw per body the frame's water holds.
8073        self.recorded_water_draws = water
8074            .as_ref()
8075            .map_or(0, |water: &WaterFrame| water.draws.len() as u64);
8076        // One indirect draw per tile slot the frame's field holds, per look it
8077        // draws.
8078        self.recorded_grass_draws = grass.as_ref().map_or(0, |grass: &GrassFrame| {
8079            u64::from(grass.slots) * u64::from(grass.draws_per_slot())
8080        });
8081        // The late depth prepass is a third list of calls, on a frame whose
8082        // camera culls in two phases.
8083        let camera_passes: u64 = if self.primary.draws.frame_mode(frame)
8084            == crcbl_shaders::draw_gen::DrawMode::Occlusion
8085        {
8086            3
8087        } else {
8088            2
8089        };
8090        let prepass_partitions = self.depth_partitions(&bucket_draws);
8091        // And the colour pass's own split, which is by **side** alone: its
8092        // pipeline has a fragment stage either way, so an alpha mask is nothing
8093        // it has to route around and a cull mode is. The wireframe twin pair
8094        // substitutes for the shaded one here exactly as the single pipeline
8095        // used to.
8096        let color_partitions =
8097            self.sided_partitions(&bucket_draws, wireframe.unwrap_or(self.mesh_pipeline));
8098        // Off the partitions the passes below record, because where a call
8099        // draws a range of buckets the two splits pack into different numbers
8100        // of ranges — see [`BucketDraws::call_count`].
8101        let calls = |partitions: &[BucketDraws]| -> u64 {
8102            partitions.iter().map(BucketDraws::call_count).sum()
8103        };
8104        self.recorded_draws = shadow_draws
8105            + (camera_passes - 1) * calls(&prepass_partitions)
8106            + calls(&color_partitions)
8107            + self.recorded_grass_draws
8108            + self.direct_draws();
8109
8110        // --- the probe gather ---
8111        //
8112        // The irradiance probes' updater, second half: the map
8113        // the pass above drew, read into every row of the table. **Here rather
8114        // than beside that pass** because the write is `&mut` — the group naming
8115        // the map's transient views is cached across frames, and a group naming a
8116        // transient cannot be built where the others are; see
8117        // [`crate::ssao::cached_group`].
8118        //
8119        // It is before the depth prepass and the forward pass, which is the
8120        // ordering that matters: both declare a read of these rows, so the graph
8121        // barriers this write against them.
8122        //
8123        // Which map layer a row is weighed against is the row's own index, so
8124        // the view is resolved exactly as the drawing passes resolve it — the
8125        // placeholder until `capture_probe_visibility` has run, and off entirely
8126        // where `r_probe_visibility` is off. A gather against the placeholder
8127        // occludes nothing, which is the honest answer for a scene that never
8128        // captured.
8129        let probe_visibility_view = match &self.probe_visibility {
8130            Some(captured) if crate::probe_visibility::enabled() => captured.view,
8131            _ => self.probe_visibility_placeholder.view,
8132        };
8133        let frame = self.frame;
8134        if let Some((gather, images)) = self.probe_gather.as_mut().zip(rsm_images) {
8135            gather.add_pass(graph, frame, images, probe_visibility_view, probe_table);
8136        }
8137
8138        let passes = FramePasses {
8139            slot: frame,
8140            emit,
8141            target_format: self.target_format,
8142            ssao_blurs: self.frame_ssao_blurs,
8143            draws_sky,
8144            water,
8145            grass,
8146            skinned,
8147            probe_buffer,
8148            probe_table,
8149            occlusion_placeholder,
8150            contact_placeholder,
8151            pages,
8152            shadow_atlas,
8153            probe_visibility: probe_visibility_view,
8154            mesh_layout: self.mesh_layout,
8155            wireframe,
8156            prepass_partitions,
8157            color_partitions,
8158            tonemap: TonemapPipeline {
8159                sampler: self.sampler,
8160                layout: self.tonemap_layout,
8161                pipeline_layout: self.tonemap_pipeline_layout,
8162                pipeline: self.tonemap_pipeline,
8163            },
8164        };
8165        // From here the frame is borrowed field by field, because every view's
8166        // passes hold its own caches for the life of the graph.
8167        let Self {
8168            primary,
8169            views: built,
8170            debug_draw,
8171            ground_grid,
8172            ground_grid_on,
8173            atlas_viewer,
8174            cull_stats,
8175            ..
8176        } = self;
8177
8178        // **Every secondary view before the primary camera's frame**, so a pass
8179        // the primary records — an overlay compositing a scope's picture onto
8180        // the lens it is seen through — reads a view that is already drawn. Each
8181        // records its whole frame straight through: its own cull, its own
8182        // clustering, and every pass the primary records after them, against the
8183        // atlas and the probe rows the scene passes above left behind.
8184        for (index, slot) in built.iter_mut().enumerate() {
8185            let Some((view_target, view_extent)) = secondary
8186                .iter()
8187                .find(|(view, _)| view.view.index() == index + 1)
8188            else {
8189                continue;
8190            };
8191            let view = slot
8192                .as_mut()
8193                .unwrap_or_else(|| unreachable!("checked against the built views above"));
8194            let view_cull = view.add_cull(graph, pool, frame, instance_count);
8195            view.add_passes(
8196                graph,
8197                &passes,
8198                view_cull,
8199                ViewOutput {
8200                    target: view_target.target,
8201                    target_extent: view_target.extent,
8202                    extent: *view_extent,
8203                },
8204                Overlays::default(),
8205                |_, _| {},
8206            );
8207        }
8208
8209        // The statistics buffer's id, read before the cull moves into the pass
8210        // recording below: the copy that reads it is the frame's last pass.
8211        let stats_id = cull.generated.visible_count_id;
8212        let tonemapped = primary.add_passes(
8213            graph,
8214            &passes,
8215            cull,
8216            ViewOutput {
8217                target,
8218                target_extent,
8219                extent,
8220            },
8221            Overlays {
8222                debug_draw: Some(debug_draw),
8223                ground_grid: ground_grid.as_ref().filter(|_| *ground_grid_on),
8224                atlas_viewer: atlas_viewer.as_mut().filter(|_| draws_atlas_view),
8225            },
8226            overlay,
8227        );
8228
8229        // **Last, and that is the point.** Three passes add to the statistics
8230        // buffer — the cull dispatch, the light grid's overflow counter and the
8231        // amplification stage inside the forward pass — so a copy scheduled any
8232        // earlier would take a total the frame had not finished writing. The
8233        // graph puts it in `TransferSrc` for this and back into the state the
8234        // next frame on this slot imports it in; there is not a barrier written
8235        // here.
8236        if let Some(stats) = cull_stats.as_mut() {
8237            stats.add_copy_pass(graph, stats_id);
8238        }
8239
8240        tonemapped
8241    }
8242
8243    /// Adds the cull dispatches and the depth-only pass that fill the shadow
8244    /// atlas, and returns the atlas as the graph knows it.
8245    ///
8246    /// Every tile is one viewport of one render pass. A pass per tile would be
8247    /// one clear of the same image and one more barrier per tile, and the graph
8248    /// would have to be told each of them only touches part of it — where one
8249    /// pass with a viewport per tile is what a shadow *atlas* is for in the first
8250    /// place.
8251    ///
8252    /// **Only the occupied tiles get a cull and a viewport.** The cascades
8253    /// always are; a light tile is occupied when
8254    /// [`shadow::Selection`] gave it to a light. A free one keeps the
8255    /// reversed-Z clear the pass wrote, which is `0.0` — "nothing stored, as far
8256    /// away as depth goes" — so anything that did sample it would come back
8257    /// fully lit rather than fully shadowed.
8258    ///
8259    /// # With [`RenderEffects::SHADOWS`] off, every tile is a free one
8260    ///
8261    /// That is the whole switch, and it is the same mechanism a free tile
8262    /// already had rather than a second one: no cull is dispatched and no
8263    /// viewport is drawn, the pass records its clear and nothing else, and every
8264    /// comparison against the atlas comes back fully lit. The pass itself stays
8265    /// on the frame that switches it off — it is what *writes* that clear, and a
8266    /// frame that skipped it would leave the atlas holding the last frame that
8267    /// did draw into it, or undefined memory on the first frame of all.
8268    ///
8269    /// # A cached atlas records nothing at all
8270    ///
8271    /// Topic 45's static-caching rung. When
8272    /// [`ForwardRenderer::shadow_atlas_cached`] says the image already holds
8273    /// what this frame would draw, this adds **no cull and no pass**: the atlas
8274    /// is imported so the passes that sample it have an edge to the resource,
8275    /// and it keeps the contents an earlier frame left in it. That is why the
8276    /// image is a persistent one with a tracked ledger entry rather than a
8277    /// transient — nothing else in the frame can alias it, so what it holds is
8278    /// what the last pass to write it wrote.
8279    ///
8280    /// # Per group, and what pays for the tiles it keeps
8281    ///
8282    /// Topic 45's cadence rung. A **group** — a cascade, or a
8283    /// light slot's whole run of tiles — is redrawn or held on its own, and
8284    /// [`ForwardRenderer::shadow_group_redrawn`] is what says which. A frame
8285    /// that holds nothing clears the whole attachment, which is the recording
8286    /// that shipped before the rung; a frame that holds something **loads** the
8287    /// attachment instead and resets each tile it redraws with
8288    /// [`MeshModules::depth_clear_pipeline`], which is the portable statement of
8289    /// a clear bounded to one tile.
8290    ///
8291    /// The attachment's own [`LoadOp::Clear`] cannot serve there: it covers
8292    /// every tile including the ones being kept, and the region-bounded
8293    /// alternatives are not portable — Metal's load action and WebGPU's
8294    /// `loadOp` have no render area to bound them, so a clear that covered part
8295    /// of the image on Vulkan and all of it on Metal would be a held tile that
8296    /// survives on one backend and is erased on another.
8297    fn add_shadow_pass(
8298        &self,
8299        graph: &mut RenderGraph<'_>,
8300        pool: &TransientPool,
8301        selection: &[BufferId],
8302        reads: ShadowReads,
8303    ) -> (ImageId, u64, u64, Option<RsmImages>) {
8304        let shadows = self.frame_effects.contains(RenderEffects::SHADOWS);
8305        let (atlas_width, atlas_height) = shadow::atlas_extent();
8306        let atlas = graph.import_image(
8307            "shadow-atlas",
8308            ImportedImage {
8309                image: self.shadow_atlas,
8310                view: self.shadow_atlas_view,
8311                format: Format::D32Float,
8312                extent: (atlas_width, atlas_height),
8313                // What the previous executed frame left it in — `Undefined` on
8314                // the first, which is what makes the graph give it a layout at
8315                // all.
8316                initial: imported_state(pool, self.shadow_atlas),
8317                // The renderer keeps this image across frames, so the pool's
8318                // ledger is the record of what happened to it and the line above
8319                // is that record read back rather than a second copy of it.
8320                claim: InitialClaim::Tracked,
8321                final_state: ResourceState::ShaderRead,
8322            },
8323        );
8324        // The cached frame's whole answer: the image above and nothing that
8325        // touches it. It is already in `ShaderRead` — the frame that drew it
8326        // handed it back that way — so the graph has no transition to make, and
8327        // the passes that sample it read the maps an earlier frame left there.
8328        if self.shadow_atlas_cached {
8329            // **And no reflective shadow map either**, which cannot happen while
8330            // the updater is on: `begin_frame` keeps cascade 0 off the hold in
8331            // exactly that case, so a frame reaching here has nothing to draw
8332            // the map from. See `probe_update_runs`.
8333            return (atlas, 0, 0, None);
8334        }
8335        let placeholder = graph.import_image(
8336            "shadow-placeholder",
8337            ImportedImage {
8338                image: self.shadow_placeholder,
8339                view: self.shadow_placeholder_view,
8340                format: Format::D32Float,
8341                extent: (1, 1),
8342                // **Its own ledger entry, not the atlas's.** The two move
8343                // together today — both are imported by this function on every
8344                // frame and both are handed back in `ShaderRead` — so one lookup
8345                // would answer both, and that is exactly the coincidence a
8346                // second declared state here stops depending on.
8347                initial: imported_state(pool, self.shadow_placeholder),
8348                claim: InitialClaim::Tracked,
8349                final_state: ResourceState::ShaderRead,
8350            },
8351        );
8352
8353        // Which light slots have a light this frame, resolved once: a slot's
8354        // cull is dispatched and its faces are drawn together or not at all, and
8355        // `begin_frame` filled that generator's parameters under exactly this
8356        // condition.
8357        //
8358        // **And only the ones this frame redraws**, since the cadence rung: a
8359        // held slot keeps the texels it has, so recording its cull and its
8360        // draws would be the same picture at the full price.
8361        let occupied: Vec<(usize, shadow::Assignment, &Light)> = self
8362            .shadow_lights
8363            .slots()
8364            .iter()
8365            .enumerate()
8366            .filter(|_| shadows)
8367            .filter(|(slot, _)| self.shadow_group_redrawn[shadow_cull(*slot)])
8368            .filter_map(|(slot, held)| {
8369                let held = (*held)?;
8370                Some((slot, held, self.extra_lights.get(held.light)?))
8371            })
8372            .collect();
8373
8374        // One cull dispatch per cascade and per occupied slot, before the pass
8375        // that draws from them — **not one per tile**, which is topic 18's
8376        // fourth decision: a point light's six faces draw one visible set.
8377        let cascades: Vec<usize> = if shadows {
8378            (0..shadow::CASCADES)
8379                .filter(|cascade| self.shadow_group_redrawn[*cascade])
8380                .collect()
8381        } else {
8382            Vec::new()
8383        };
8384        // **Cascade 0's cull, on a frame that is not drawing it into the
8385        // atlas.** `begin_frame` fits it whenever the updater is on, shadows or
8386        // no shadows — see `rsm_cull_ready` — so this is the case where the map
8387        // is drawn and the atlas keeps its clear. Chained **last**, because the
8388        // occupied slots' entries are indexed by `cascades.len() + index` a few
8389        // lines below and an insertion before them would hand a light's draws to
8390        // the wrong viewport.
8391        let rsm_only_cull = self.rsm_cull_ready && !cascades.contains(&0);
8392        // The punctual producer's faces, which are also the light slots'
8393        // atlas views — see `punctual_faces`, the one list both halves of the
8394        // updater walk.
8395        let punctual = self.punctual_faces();
8396        // And their culls on a frame that is not drawing the atlas, which
8397        // `occupied` is empty on for the same reason `cascades` is. Deduplicated
8398        // because a point light's six faces draw one visible set, and chained
8399        // **after** the entries `views` indexes positionally below.
8400        let punctual_only_culls: Vec<usize> = if shadows {
8401            Vec::new()
8402        } else {
8403            punctual
8404                .iter()
8405                .map(|face| face.cull)
8406                .collect::<std::collections::BTreeSet<_>>()
8407                .into_iter()
8408                .collect()
8409        };
8410        let generated: Vec<(usize, GeneratedDraws)> = cascades
8411            .iter()
8412            .copied()
8413            .chain(occupied.iter().map(|(slot, _, _)| shadow_cull(*slot)))
8414            .chain(rsm_only_cull.then_some(0))
8415            .chain(punctual_only_culls)
8416            .map(|cull| {
8417                (
8418                    cull,
8419                    self.shadow_draws[cull].add_passes(
8420                        graph,
8421                        self.frame,
8422                        self.instances.slot_count(),
8423                    ),
8424                )
8425            })
8426            .collect();
8427
8428        // What the pass body records, in order: which view's bind group, which
8429        // rectangle of the atlas its viewport covers, and which of the culls
8430        // above it draws from. Paired rather than positional, because the free
8431        // slots are missing from every one of these lists and a bare index into
8432        // one would hand a light's draws to the wrong viewport the moment one
8433        // slot is free and a later one is not.
8434        //
8435        // **The rectangle rather than the slot**, resolved here: the body runs
8436        // in a closure that outlives this borrow, and asking the selection for
8437        // it there would be a second reading of an allocation that has to be the
8438        // one the frame block was written from.
8439        //
8440        // **And which draw region of that cull**: region 0, every survivor, for
8441        // a cascade and a spot; and for a point light whose cull tagged its
8442        // casters by face, the region of the face being drawn — see
8443        // `set_point_face_culls`.
8444        let mut views: Vec<(usize, shadow::TileRect, usize, u32)> = cascades
8445            .iter()
8446            .enumerate()
8447            .map(|(position, cascade)| {
8448                (
8449                    *cascade,
8450                    self.shadow_lights.atlas_rect(*cascade),
8451                    position,
8452                    0,
8453                )
8454            })
8455            .collect();
8456        for (index, (slot, held, light)) in occupied.iter().enumerate() {
8457            // A spot draws face 0 alone; a point light draws all six, each
8458            // through its own matrix into its own tile. `shadow::tile_span` is
8459            // the same function `Selection` allocated the run with, so a face
8460            // here and a tile there cannot disagree about how many there are.
8461            let by_face = self.shadow_draws[shadow_cull(*slot)].frame_mode(self.frame)
8462                == crcbl_shaders::draw_gen::DrawMode::Faces;
8463            for face in 0..shadow::tile_span(light) {
8464                views.push((
8465                    shadow_view(*slot, face),
8466                    self.shadow_lights
8467                        .atlas_rect(shadow::light_tile(held.base + face)),
8468                    cascades.len() + index,
8469                    face_region(by_face, face),
8470                ));
8471            }
8472        }
8473
8474        let mut pass = graph
8475            .add_render_pass("shadow")
8476            // **Stored, unlike the scene's depth.** This is the one depth buffer
8477            // in the engine that something downstream reads, which is what
8478            // `PassBuilder::clear_depth`'s docs said would need a `StoreOp` the
8479            // day a prepass existed.
8480            .depth(
8481                atlas,
8482                // **Loaded on a frame that is keeping a tile**, which is the
8483                // cadence rung's whole seam: a clear here covers the image, so
8484                // the tiles this frame *does* redraw are reset one at a time by
8485                // the pipeline below instead. A frame keeping nothing clears,
8486                // which is what shipped.
8487                if self.shadow_atlas_clears {
8488                    LoadOp::Clear
8489                } else {
8490                    LoadOp::Load
8491                },
8492                StoreOp::Store,
8493                crcbl_hal::ClearValue {
8494                    depth: crcbl_hal::depth::CLEAR,
8495                    ..crcbl_hal::ClearValue::default()
8496                },
8497            )
8498            // Declared so the graph gives it a shader-read layout: it is in
8499            // every cascade's bind group, standing in for the atlas this pass is
8500            // writing. See `ForwardRenderer::shadow_placeholder`.
8501            .read_image(placeholder)
8502            // Likewise, and it is in every one of those groups too — see
8503            // `ForwardRenderer::ambient_occlusion_placeholder`. Nothing samples
8504            // it here either: the depth-only pipeline has no fragment stage.
8505            .read_image(reads.occlusion_placeholder)
8506            // And §3.2's page, which `mesh_layout` names in every group — a
8507            // cascade's included. See `ForwardRenderer::base_color_page_import`
8508            // for what the declaration buys a caller that writes the page.
8509            .read_image(reads.pages.base_color)
8510            // And §2's other three pages beside it, in those same groups and
8511            // sampled by no cascade — see
8512            // `ForwardRenderer::normal_page_import`.
8513            .read_image(reads.pages.normal)
8514            .read_image(reads.pages.mro)
8515            .read_image(reads.pages.emissive)
8516            // And the probe rows, which are in those groups too and which no
8517            // cascade reads — declared on the placeholder's and the pages'
8518            // terms, plus one of their own: the rows are device-local and a copy
8519            // destination so the irradiance probes' gather can
8520            // write them, and a pass that binds a buffer it has not declared is
8521            // one the graph cannot order that write against.
8522            .read_buffer(reads.probes);
8523        // Each tile's mesh pass records the cut it descended to, into a buffer
8524        // of its own — see `ForwardRenderer::shadow_selection`. Empty where
8525        // there is no amplification stage to descend anything.
8526        //
8527        // Declared for every tile rather than for the occupied ones: the state
8528        // is what the buffer is *in*, which does not depend on whether this
8529        // frame happened to write it, and a free tile's buffer still has to
8530        // arrive in the state the next frame's import claims.
8531        for &buffer in selection {
8532            pass = pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8533        }
8534        // The skinned vertices this pass may pull, and the reason it is declared
8535        // here as well as on the colour passes: a cascade draws the same
8536        // geometry out of the same pool, so a shadow that fell before the
8537        // dispatch was visible would be cast by the previous pose — a shadow
8538        // that does not match its caster, on a frame whose picture is otherwise
8539        // right.
8540        if let Some(vertices) = reads.skinned {
8541            pass = pass.read_buffer(vertices);
8542        }
8543        for (_, draws) in &generated {
8544            pass = read_draw_sources(pass, draws, self.emit);
8545        }
8546
8547        let groups = self.shadow_groups[self.frame].clone();
8548        // **What the reflective shadow map is drawn from**, read out here rather
8549        // than reconstructed by the caller: cascade 0's bind group — whose
8550        // uniform block already holds that cascade's `view_proj`, which is what
8551        // "reusing cascade 0's matrix" means — and the `GeneratedDraws` its cull
8552        // produced a moment ago. Both are `Copy`, so recording a second pass
8553        // from them costs no second cull and no second matrix.
8554        //
8555        // [`None`] on a frame that is not drawing cascade 0 at all: shadows off,
8556        // or a `r_shadow_cadence` past one that held the group anyway. The rows
8557        // then keep what the last gather wrote — see [`ProbeUpdate::EveryFrame`],
8558        // which says so.
8559        let cascade_zero: Option<(BindGroupHandle, GeneratedDraws)> = self
8560            .rsm_cull_ready
8561            .then(|| {
8562                generated
8563                    .iter()
8564                    .find(|(cull, _)| *cull == 0)
8565                    .map(|(_, draws)| (groups[CASCADE_ZERO_VIEW], *draws))
8566            })
8567            .flatten();
8568        // **What the punctual reflective shadow map is drawn from**, resolved
8569        // here for `cascade_zero`'s reason and on its terms: each face's own
8570        // bind group — whose uniform block already holds that face's
8571        // `view_proj` — and the `GeneratedDraws` its slot's cull produced a
8572        // moment ago. Both are `Copy`, so the second pass costs no second cull
8573        // and no second matrix.
8574        //
8575        // Found by cull id rather than by position, so this list and the atlas's
8576        // cannot be knocked out of step by a slot the other one skipped.
8577        //
8578        // And the face's draw region, on the atlas's terms: a point light whose
8579        // cull tagged its casters draws each face from that face's region.
8580        let punctual_views: Vec<(BindGroupHandle, shadow::TileRect, GeneratedDraws, u32)> =
8581            punctual
8582                .iter()
8583                .filter_map(|face| {
8584                    let (_, draws) = generated.iter().find(|(cull, _)| *cull == face.cull)?;
8585                    let by_face = self.shadow_draws[face.cull].frame_mode(self.frame)
8586                        == crcbl_shaders::draw_gen::DrawMode::Faces;
8587                    Some((
8588                        groups[face.view],
8589                        face.tile,
8590                        *draws,
8591                        face_region(by_face, face.face),
8592                    ))
8593                })
8594                .collect();
8595        // The culls those faces draw from, **once each**: a point light's six
8596        // faces draw one visible set, so declaring a face's sources would
8597        // declare the same buffers six times in one pass.
8598        let punctual_sources: Vec<GeneratedDraws> = punctual
8599            .iter()
8600            .map(|face| face.cull)
8601            .collect::<std::collections::BTreeSet<_>>()
8602            .into_iter()
8603            .filter_map(|cull| {
8604                let (_, draws) = generated.iter().find(|(candidate, _)| *candidate == cull)?;
8605                Some(*draws)
8606            })
8607            .collect();
8608        let bucket_draws = BucketDraws {
8609            // Replaced per partition below; the field is what the tile clears
8610            // and the reflective shadow map inherit, and neither binds it.
8611            pipeline: self.shadow_pipeline.single,
8612            layout: self.mesh_pipeline_layout,
8613            indices: self.pool.index_buffer(),
8614            emit: self.emit,
8615            calls: self
8616                .bucket_constants
8617                .iter()
8618                .enumerate()
8619                .map(|(bucket, constant_offset)| {
8620                    let bucket = u32::try_from(bucket)
8621                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8622                    (
8623                        *constant_offset,
8624                        self.primary.draws.args_offset(bucket),
8625                        self.primary.draws.count_offset(bucket),
8626                        self.primary.draws.mesh_args_offset(bucket),
8627                    )
8628                })
8629                .collect(),
8630            region_step: self.region_step,
8631            // Packed per partition, where the partition's buckets are known.
8632            ranges: None,
8633            flat: None,
8634        };
8635        // Kept back for the reflective shadow map below, which is the same
8636        // per-bucket call list under a different pipeline — the depth prepass
8637        // plays exactly this trick with the camera's. Cloned before the pass
8638        // body takes the original.
8639        let bucket_calls = bucket_draws.clone();
8640        // The atlas's own split by material mode: an opaque bucket's tile is
8641        // drawn with no fragment stage in a scene that has a cutout in it. Every
8642        // view draws every partition — one call per bucket, per range of
8643        // buckets, or behind a task stage one flat call, per view, under a
8644        // pipeline per mode.
8645        let tile_partitions = self.depth_partitions(&bucket_draws);
8646
8647        // Counted off the two loops the body below runs, before it takes them:
8648        // every partition's calls per occupied view. `ForwardRenderer::counters`
8649        // is what reports it, and reading it back off the same `Vec`s is what
8650        // makes it move when the tile allocation does.
8651        let recorded = views.len() as u64
8652            * tile_partitions
8653                .iter()
8654                .map(BucketDraws::call_count)
8655                .sum::<u64>();
8656        // And the tile resets beside them, which are direct draws of one
8657        // instance rather than indirect ones: a frame that cleared the whole
8658        // attachment records none, and a frame that loaded it records one per
8659        // tile it redraws.
8660        let clears = if self.shadow_atlas_clears {
8661            0
8662        } else {
8663            views.len() as u64
8664        };
8665
8666        // What the image will hold once this body has run, carried into it so
8667        // that *recording* the pass is not what claims the atlas was drawn — see
8668        // [`ForwardRenderer::shadow_atlas_drawn`].
8669        let ran = Arc::clone(&self.shadow_pass_ran);
8670        let pass_id = self.shadow_pass_id;
8671        // The tiles this pass redraws have to be reset before anything is drawn
8672        // into them, and on a frame that loaded the attachment there is nothing
8673        // else that will — see [`MeshModules::depth_clear_pipeline`]. A frame
8674        // that cleared has already had every tile reset by the attachment, so
8675        // this is `None` and the recording is the one that shipped.
8676        let clear = (!self.shadow_atlas_clears).then_some(self.shadow_clear_pipeline);
8677        // **The reset draw has to bind a group, and only a browser says so.**
8678        // `MeshModules::depth_clear_pipeline` builds this pipeline from
8679        // `mesh_pipeline_layout`, so its layout declares group 0 whether or not
8680        // the one triangle's vertex shader reads a byte of it — and WebGPU
8681        // refuses a draw with any group the *layout* declares left unset, where
8682        // Vulkan and the others only care about what the shader dereferences. An
8683        // unbound reset therefore fails no native run and rejects the whole
8684        // browser frame: `No bind group set at group index 0` arrives when the
8685        // encoder is finished, so every pass recorded after it is thrown away
8686        // with it and the canvas stays at the clear colour.
8687        //
8688        // Any bucket's offset does: the block is what the mesh draws index and
8689        // this draw reads none of it, so what matters is that the offset is one
8690        // the layout accepts rather than which bucket it names.
8691        let clear_layout = bucket_draws.layout;
8692        let clear_offset = bucket_draws
8693            .calls
8694            .first()
8695            .map_or(0, |(constant_offset, ..)| *constant_offset);
8696        pass.execute(move |ctx| {
8697            ran.store(pass_id, Ordering::Relaxed);
8698            let encoder = ctx.encoder();
8699            if let Some(clear) = clear {
8700                encoder.bind_graphics_pipeline(clear);
8701                for (view, tile, _, _) in &views {
8702                    set_shadow_tile(encoder, *tile);
8703                    encoder.bind_group(0, groups[*view], &[clear_offset], clear_layout);
8704                    encoder.draw(0..TILE_CLEAR_VERTICES, 0..1);
8705                }
8706            }
8707            for partition in &tile_partitions {
8708                partition.open(encoder);
8709                for (view, tile, cull, region) in &views {
8710                    set_shadow_tile(encoder, *tile);
8711                    partition.record_region(encoder, groups[*view], &generated[*cull].1, *region);
8712                }
8713            }
8714        });
8715
8716        // --- the reflective shadow map ---
8717        //
8718        // The irradiance probes' updater, first half, recorded
8719        // here because this is where cascade 0's bind group and its
8720        // already-generated draws are. **A pass of its own at its own extent**,
8721        // and [`crate::rsm`]'s header argues why it cannot ride the atlas above:
8722        // one colour attachment there spans the whole 3072² image for data only
8723        // one 768² tile is read from, and it would give all fourteen light tiles
8724        // a fragment stage.
8725        //
8726        // No viewport is set: the graph opens a pass with a full-target viewport
8727        // and scissor already, and every attachment here is the map's own square.
8728        // Both or nothing: the map is drawn with pipelines `build` made only
8729        // for a volume that is updated, so a renderer without them has no map
8730        // to record and no gather to feed.
8731        let (Some((cascade_group, cascade_draws)), Some(rsm_pipeline)) =
8732            (cascade_zero, self.rsm_pipeline)
8733        else {
8734            return (atlas, recorded, clears, None);
8735        };
8736        let extent = rsm::extent();
8737        let sun = RsmTargets {
8738            albedo: graph.create_image("rsm-albedo", rsm::albedo_target(extent)),
8739            normal: graph.create_image("rsm-normal", rsm::normal_target(extent)),
8740            world: graph.create_image("rsm-world", rsm::world_target(extent)),
8741        };
8742        // Its own depth, cleared and discarded: it resolves which surface a
8743        // texel of the map holds and nothing reads it afterwards.
8744        let rsm_depth = graph.create_image("rsm-depth", rsm::depth_target(extent));
8745        let mut rsm = graph
8746            .add_render_pass("rsm")
8747            // **Cleared, and the world target's clear is load-bearing**: `w` is
8748            // the coverage flag `RsmOutput::world` writes, so a texel the pass
8749            // draws nothing into reads back zero there and the gather skips it.
8750            // Without the clear the world origin would stand in for every part
8751            // of the cascade the geometry does not cover.
8752            .clear_color(sun.albedo, [0.0; 4])
8753            .clear_color(sun.normal, [0.0; 4])
8754            .clear_color(sun.world, [0.0; 4])
8755            .clear_depth(rsm_depth)
8756            // The same declarations the cascade above makes, for the same
8757            // reason: every group of the mesh layout names these, and this pass
8758            // binds one of those groups. Unlike the cascade, this one has a
8759            // fragment stage — so the pages really are sampled here.
8760            .read_image(placeholder)
8761            .read_image(reads.occlusion_placeholder)
8762            .read_image(reads.pages.base_color)
8763            .read_image(reads.pages.normal)
8764            .read_image(reads.pages.mro)
8765            .read_image(reads.pages.emissive)
8766            .read_buffer(reads.probes);
8767        if let Some(vertices) = reads.skinned {
8768            rsm = rsm.read_buffer(vertices);
8769        }
8770        // Cascade 0's cluster-selection buffer, which the mesh path's stages
8771        // write — declared on the atlas pass's terms, and only for the one view
8772        // this pass draws.
8773        if let Some(&buffer) = selection.get(CASCADE_ZERO_VIEW) {
8774            rsm = rsm.use_buffer(buffer, ResourceState::ShaderReadWrite);
8775        }
8776        rsm = read_draw_sources(rsm, &cascade_draws, self.emit);
8777        // Split by side, on the colour pass's terms: this stage cuts the alpha
8778        // mask itself, so the only thing it cannot say inside the fragment stage
8779        // is which faces the rasteriser keeps.
8780        let rsm_partitions = self.sided_partitions(&bucket_calls, rsm_pipeline);
8781        let rsm_recorded: u64 = rsm_partitions.iter().map(BucketDraws::call_count).sum();
8782        rsm.execute(move |ctx| {
8783            let encoder = ctx.encoder();
8784            for partition in &rsm_partitions {
8785                partition.open(encoder);
8786                partition.record(encoder, cascade_group, &cascade_draws);
8787            }
8788        });
8789
8790        // --- the punctual reflective shadow map ---
8791        //
8792        // The irradiance probes' punctual producer: the same
8793        // pipeline and the same per-bucket call list as the pass above, under
8794        // one viewport per shadowed light face instead of one whole map. A spot
8795        // is a tile and a point light is six, which is `shadow::tile_span` — so
8796        // this is the atlas pass's own view loop drawn into a second, much
8797        // smaller set of targets.
8798        //
8799        // **Recorded whether or not the frame lights a punctual face**, unlike
8800        // the map above. The clear is a legitimate answer — a frame with no
8801        // shadowed punctual light has no punctual bounce, and the coverage flag
8802        // in `w` says so at every texel — and a pass that came and went with the
8803        // lights would be a pass list that changes shape with the scene, which
8804        // is what `RENDER_PASSES` and every timing reader are written against.
8805        let punctual_extent = rsm::punctual_extent();
8806        let punctual_targets = RsmTargets {
8807            albedo: graph.create_image("rsm-punctual-albedo", rsm::albedo_target(punctual_extent)),
8808            normal: graph.create_image("rsm-punctual-normal", rsm::normal_target(punctual_extent)),
8809            world: graph.create_image("rsm-punctual-world", rsm::world_target(punctual_extent)),
8810        };
8811        let punctual_depth =
8812            graph.create_image("rsm-punctual-depth", rsm::depth_target(punctual_extent));
8813        let mut punctual_pass = graph
8814            .add_render_pass("rsm-punctual")
8815            // Cleared on the map above's terms, and the world target's clear is
8816            // load-bearing for its reason as well as for one of this map's own:
8817            // the tiles the cascades would hold are drawn into by nothing at
8818            // all, and a coverage flag of zero is what keeps the gather out of
8819            // them.
8820            .clear_color(punctual_targets.albedo, [0.0; 4])
8821            .clear_color(punctual_targets.normal, [0.0; 4])
8822            .clear_color(punctual_targets.world, [0.0; 4])
8823            .clear_depth(punctual_depth)
8824            .read_image(placeholder)
8825            .read_image(reads.occlusion_placeholder)
8826            .read_image(reads.pages.base_color)
8827            .read_image(reads.pages.normal)
8828            .read_image(reads.pages.mro)
8829            .read_image(reads.pages.emissive)
8830            .read_buffer(reads.probes);
8831        if let Some(vertices) = reads.skinned {
8832            punctual_pass = punctual_pass.read_buffer(vertices);
8833        }
8834        // Each face's own cluster-selection buffer, which the mesh path's stages
8835        // write — declared on the atlas pass's terms, and only for the views
8836        // this pass draws.
8837        for face in &punctual {
8838            if let Some(&buffer) = selection.get(face.view) {
8839                punctual_pass = punctual_pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8840            }
8841        }
8842        for draws in &punctual_sources {
8843            punctual_pass = read_draw_sources(punctual_pass, draws, self.emit);
8844        }
8845        let punctual_partitions = self.sided_partitions(&bucket_calls, rsm_pipeline);
8846        let punctual_recorded = punctual_views.len() as u64
8847            * punctual_partitions
8848                .iter()
8849                .map(BucketDraws::call_count)
8850                .sum::<u64>();
8851        punctual_pass.execute(move |ctx| {
8852            let encoder = ctx.encoder();
8853            // The partition is **outside** the view loop, on the shadow atlas's
8854            // terms: one pipeline bind covers every face of that side.
8855            for partition in &punctual_partitions {
8856                partition.open(encoder);
8857                for (group, tile, draws, region) in &punctual_views {
8858                    set_shadow_tile(encoder, *tile);
8859                    partition.record_region(encoder, *group, draws, *region);
8860                }
8861            }
8862        });
8863
8864        let images = RsmImages {
8865            sun,
8866            punctual: punctual_targets,
8867        };
8868        (
8869            atlas,
8870            recorded + rsm_recorded + punctual_recorded,
8871            clears,
8872            Some(images),
8873        )
8874    }
8875
8876    /// Which lights hold the atlas's light tiles this frame, and where each
8877    /// map was laid out.
8878    ///
8879    /// **The observable topic 45's priority rung otherwise has
8880    /// none for.** A map's *size* leaves no trace in the picture that a golden
8881    /// can hold anyone to: a light demoted to a quarter of a cell draws a
8882    /// slightly softer shadow, which is a perfectly plausible frame and one a
8883    /// re-bless accepts. [`Selection::atlas_rect`](crate::shadow::Selection)
8884    /// off this is what says which level the allocator actually handed out, and
8885    /// `crates/crcbl/tests/mesh_e2e/shadow_tiles.rs` is what reads it.
8886    ///
8887    /// Named for the selection's own subject rather than for its type, because
8888    /// [`Self::shadow_selection`] above is a *buffer* — the cut a cascade
8889    /// descended to — and two accessors of one name is a caller reaching for
8890    /// the wrong one.
8891    ///
8892    /// It is this frame's answer, written by [`Self::begin_frame`]: before the
8893    /// first frame every slot is free.
8894    /// Whether this frame took the shadow atlas as an earlier frame left it,
8895    /// rather than drawing it again.
8896    ///
8897    /// Topic 45's static-caching rung, read back. True means
8898    /// this frame recorded **no** shadow cull and no shadow pass, and every map
8899    /// sampled through [`Self::shadow_lights`]'s rectangles is the one the last
8900    /// frame that did draw put there — so a caller comparing two frames' pass
8901    /// lists, draw counts or GPU timings has to know which of them redrew.
8902    ///
8903    /// Decided by [`Self::begin_frame`] out of everything each group of the
8904    /// atlas is a function of — see `ForwardRenderer::shadow_group_record` —
8905    /// and it answers `false` before the first frame, because no frame has been
8906    /// opened and so none of them has held anything.
8907    ///
8908    /// **Whole-atlas, and since the cadence rung a frame can be neither.** A
8909    /// frame that redraws one map and holds another answers `false` here and
8910    /// `false` from [`Self::shadow_slot_redrawn`] for the maps it held; the two
8911    /// together are what say which.
8912    #[must_use]
8913    pub const fn shadow_atlas_cached(&self) -> bool {
8914        self.shadow_atlas_cached
8915    }
8916
8917    /// Whether this frame redrew cascade `cascade`'s map, rather than keeping
8918    /// the one an earlier frame put there.
8919    ///
8920    /// Topic 45's cadence rung, read back. **The observable
8921    /// that rung otherwise has none for**: a held map draws a shadow lagging its
8922    /// caster by a frame or two, which is a perfectly plausible picture and one
8923    /// a golden accepts — so nothing but this distinguishes a cadence that is
8924    /// working from one that is not running at all.
8925    ///
8926    /// `false` for a `cascade` past [`shadow::CASCADES`] and before the first
8927    /// frame, which is the same answer for the same reason: no map was drawn
8928    /// there.
8929    #[must_use]
8930    pub fn shadow_cascade_redrawn(&self, cascade: usize) -> bool {
8931        cascade < shadow::CASCADES && self.shadow_group_redrawn[cascade]
8932    }
8933
8934    /// Whether this frame redrew the maps of light slot `slot` —
8935    /// [`shadow::Selection::slots`]' index — rather than keeping the ones an
8936    /// earlier frame put there.
8937    ///
8938    /// [`Self::shadow_cascade_redrawn`]'s answer for the light region, and a
8939    /// point light's [`shadow::POINT_FACES`] faces answer together: they cull
8940    /// once and draw one visible set, so they are redrawn or held as one.
8941    #[must_use]
8942    pub fn shadow_slot_redrawn(&self, slot: usize) -> bool {
8943        slot < shadow::LIGHT_SLOTS && self.shadow_group_redrawn[shadow_cull(slot)]
8944    }
8945
8946    /// How many tiles of the atlas this frame redrew.
8947    ///
8948    /// What [`shadow::r_shadow_faces`] is spent in, read back — so a test can
8949    /// say the budget bound rather than that it was configured. A cascade costs
8950    /// one and a point light's cube costs [`shadow::POINT_FACES`].
8951    #[must_use]
8952    pub const fn shadow_faces_redrawn(&self) -> u32 {
8953        self.shadow_faces_redrawn
8954    }
8955
8956    /// Pins the shadow cadence for this renderer, or hands it back to the
8957    /// console.
8958    ///
8959    /// [`Self::set_effect_request`]'s shape at this knob:
8960    /// [`shadow::r_shadow_cadence`] and [`shadow::r_shadow_faces`] are
8961    /// process-global, so they are the *default* rather than the only answer —
8962    /// an application drawing two views at two qualities, or a test that needs a
8963    /// frame nothing else in the process can move, pins its own.
8964    ///
8965    /// [`None`] hands it back, which is what a renderer starts at.
8966    ///
8967    /// Read once per [`Self::begin_frame`], on `ForwardRenderer::frame_effects`'
8968    /// terms: this call decides it and `add_passes` acts on it.
8969    pub const fn set_shadow_cadence(&mut self, cadence: Option<shadow::Cadence>) {
8970        self.shadow_cadence_request = cadence;
8971    }
8972
8973    /// Whether this frame ignored the cadence for at least one map because the
8974    /// region that map covers had moved out from under it.
8975    ///
8976    /// Topic 45's "a moving light or camera cut resets it",
8977    /// made precise: a map is *reset* rather than merely out of date when the
8978    /// centre it is projected from has moved further than the map's own reach —
8979    /// a light further than its own radius, or a cascade's eye further than the
8980    /// sphere that cascade was fitted to. Holding such a map is not a shadow
8981    /// that lags; it is a shadow of somewhere else.
8982    ///
8983    /// A frame whose atlas was **relaid** — a light gained, lost or resized a
8984    /// tile, or shadows were switched on or off — answers `true` as well, and
8985    /// that frame redraws every map it has: the only clear this seam can make
8986    /// covers the whole image, so there is nothing left to hold.
8987    #[must_use]
8988    pub const fn shadow_cadence_reset(&self) -> bool {
8989        self.shadow_cadence_reset
8990    }
8991
8992    #[must_use]
8993    pub const fn shadow_lights(&self) -> &shadow::Selection {
8994        &self.shadow_lights
8995    }
8996
8997    /// The shadow atlas, for a caller that wants to read it back.
8998    ///
8999    /// **The observable this whole slice can otherwise hide behind.** A shadow
9000    /// pass that renders nothing leaves every texel at
9001    /// [`depth::CLEAR`](crcbl_hal::depth::CLEAR) and produces a frame in which
9002    /// everything is lit — which is a perfectly plausible picture and matches
9003    /// any golden blessed from it. Copying this image back and finding a texel
9004    /// that is not the clear value is what distinguishes the two.
9005    ///
9006    /// It is created with
9007    /// [`ImageUsage::TRANSFER_SRC`](crcbl_hal::ImageUsage::TRANSFER_SRC) for
9008    /// exactly that, and its extent is [`shadow::atlas_extent`].
9009    #[must_use]
9010    pub const fn shadow_atlas(&self) -> crcbl_hal::ImageHandle {
9011        self.shadow_atlas
9012    }
9013
9014    /// The view [`shadow_atlas`](Self::shadow_atlas) is bound and imported
9015    /// through, for a reader importing the atlas into a graph of its own.
9016    #[must_use]
9017    pub const fn shadow_atlas_view(&self) -> ImageViewHandle {
9018        self.shadow_atlas_view
9019    }
9020
9021    /// The base-colour page every material row samples through
9022    /// [`GpuMaterial::base_color_texture`](crcbl_shaders::mesh::GpuMaterial::base_color_texture),
9023    /// as the image and the view [`crate::texture`] uploaded.
9024    ///
9025    /// **What a render-to-texture view copies into.** A second camera drawing
9026    /// into an image is only half of a monitor: the surface that *shows* it
9027    /// samples a page layer, and nothing above this crate can name the image
9028    /// that layer lives in.
9029    ///
9030    /// A caller that wants to *write* it wants
9031    /// [`base_color_page_import`](Self::base_color_page_import) instead: the
9032    /// graph can only order a copy against the draws that sample the page while
9033    /// both are declared, and the two declarations have to agree field for
9034    /// field. This one is the raw handles, for a caller that binds or reads them
9035    /// outside a graph.
9036    ///
9037    /// It is created with
9038    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST),
9039    /// because the upload that filled it is a copy, so a per-frame copy into it
9040    /// needs no new usage flag. Its extent is
9041    /// [`PageDesc::extent`](crate::scene::PageDesc::extent) of
9042    /// [`PageKind::BaseColor`] squared and it has one layer per
9043    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of that kind;
9044    /// the description is the caller's, so the caller already knows both. A
9045    /// description naming no base-colour layer gets a 1×1 placeholder instead —
9046    /// see this module's `PAGE_PLACEHOLDER_TEXEL`.
9047    #[must_use]
9048    pub const fn base_color_page(&self) -> UploadedTexture {
9049        self.base_color_page
9050    }
9051
9052    /// What [`add_passes`](Self::add_passes) names the base-colour page in the
9053    /// graph.
9054    ///
9055    /// [`RenderGraph::import_image`] keeps the label of whichever import ran
9056    /// first, so a caller importing the page too passes this rather than a
9057    /// string of its own — otherwise every barrier record and
9058    /// [`dump`](crate::CompiledGraph::dump) line would name the page differently
9059    /// depending on which subsystem got there first.
9060    pub const BASE_COLOR_PAGE_LABEL: &'static str = "base-colour-page";
9061
9062    /// The base-colour page **as this renderer declares it to a graph**.
9063    ///
9064    /// [`add_passes`](Self::add_passes) imports exactly this value under
9065    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL) and declares a read
9066    /// of it on every pass whose bind group names the page, so a caller that
9067    /// writes the page — a render-to-texture view copied into one layer — gets
9068    /// the graph to order its write against those draws.
9069    ///
9070    /// **A caller that writes it imports this value rather than one of its
9071    /// own.** [`RenderGraph::import_image`] hands the second importer the id the
9072    /// first got, which is what puts the write and the reads on one state
9073    /// tracker, and it does that only while the two declarations agree in every
9074    /// field — a disagreement is [`GraphError::ImportDeclarationConflict`] at
9075    /// [`compile`](RenderGraph::compile). Reading the declaration off the
9076    /// renderer that owns the page is what makes them one answer instead of two
9077    /// constants that have to be kept equal by hand.
9078    ///
9079    /// [`InitialClaim::Tracked`] with [`ResourceState::ShaderRead`] both ways:
9080    /// [`crate::texture`] leaves an uploaded page in that state, and the
9081    /// trailing barrier the `final_state` asks for puts it back there at the end
9082    /// of every frame — so the pool's ledger and this declaration are the same
9083    /// answer, which is what `Tracked` has the graph check.
9084    ///
9085    /// [`GraphError::ImportDeclarationConflict`]: crate::graph::GraphError::ImportDeclarationConflict
9086    #[must_use]
9087    pub const fn base_color_page_import(&self) -> ImportedImage {
9088        ImportedImage {
9089            image: self.base_color_page.image,
9090            view: self.base_color_page.view,
9091            format: BASE_COLOR_PAGE_FORMAT,
9092            extent: self.page_extents[PageKind::BaseColor.index()],
9093            initial: ResourceState::ShaderRead,
9094            claim: InitialClaim::Tracked,
9095            final_state: ResourceState::ShaderRead,
9096        }
9097    }
9098
9099    /// Topic 43 §2's **normal** page, the raw handles.
9100    ///
9101    /// [`base_color_page`](Self::base_color_page)'s counterpart, on every one of
9102    /// its terms: one `D2Array` image, one layer per
9103    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of
9104    /// [`PageKind::Normal`], at **that kind's own extent**, and created with
9105    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST) so a
9106    /// per-frame copy into a layer needs no new usage flag. What it is *not* is
9107    /// the same format: it is `Rgba8Unorm`, where the base-colour page is
9108    /// `Rgba8UnormSrgb`, and topic 44's rung 2 is where that
9109    /// is argued.
9110    #[must_use]
9111    pub const fn normal_page(&self) -> UploadedTexture {
9112        self.normal_page
9113    }
9114
9115    /// What [`add_passes`](Self::add_passes) names the normal page in the graph,
9116    /// on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
9117    pub const NORMAL_PAGE_LABEL: &'static str = "normal-page";
9118
9119    /// The normal page **as this renderer declares it to a graph**, on
9120    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly
9121    /// — including that a caller writing a layer imports *this* value rather
9122    /// than one of its own, so the write and the draws land on one state
9123    /// tracker.
9124    #[must_use]
9125    pub const fn normal_page_import(&self) -> ImportedImage {
9126        ImportedImage {
9127            image: self.normal_page.image,
9128            view: self.normal_page.view,
9129            format: NORMAL_PAGE_FORMAT,
9130            extent: self.page_extents[PageKind::Normal.index()],
9131            initial: ResourceState::ShaderRead,
9132            claim: InitialClaim::Tracked,
9133            final_state: ResourceState::ShaderRead,
9134        }
9135    }
9136
9137    /// Topic 43 §2's packed
9138    /// **metallic-roughness-occlusion** page, the raw handles.
9139    ///
9140    /// [`normal_page`](Self::normal_page)'s counterpart, on every one of its
9141    /// terms and at the same `Rgba8Unorm` format: a layer of it is glTF's
9142    /// occlusion, roughness and metallic in `r`, `g` and `b`, which are numbers
9143    /// rather than a colour — see this module's `MRO_PAGE_FORMAT`.
9144    #[must_use]
9145    pub const fn mro_page(&self) -> UploadedTexture {
9146        self.mro_page
9147    }
9148
9149    /// What [`add_passes`](Self::add_passes) names the
9150    /// metallic-roughness-occlusion page in the graph, on
9151    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
9152    pub const MRO_PAGE_LABEL: &'static str = "metallic-roughness-occlusion-page";
9153
9154    /// The metallic-roughness-occlusion page **as this renderer declares it to a
9155    /// graph**, on [`base_color_page_import`](Self::base_color_page_import)'s
9156    /// terms exactly.
9157    #[must_use]
9158    pub const fn mro_page_import(&self) -> ImportedImage {
9159        ImportedImage {
9160            image: self.mro_page.image,
9161            view: self.mro_page.view,
9162            format: MRO_PAGE_FORMAT,
9163            extent: self.page_extents[PageKind::MetallicRoughnessOcclusion.index()],
9164            initial: ResourceState::ShaderRead,
9165            claim: InitialClaim::Tracked,
9166            final_state: ResourceState::ShaderRead,
9167        }
9168    }
9169
9170    /// Topic 43 §2's **emissive** page, the raw
9171    /// handles.
9172    ///
9173    /// [`base_color_page`](Self::base_color_page)'s counterpart down to the
9174    /// format: an emissive texel is a colour, so this image is
9175    /// `Rgba8UnormSrgb` and the sampler decodes it — see this module's
9176    /// `EMISSIVE_PAGE_FORMAT`.
9177    #[must_use]
9178    pub const fn emissive_page(&self) -> UploadedTexture {
9179        self.emissive_page
9180    }
9181
9182    /// What [`add_passes`](Self::add_passes) names the emissive page in the
9183    /// graph, on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
9184    pub const EMISSIVE_PAGE_LABEL: &'static str = "emissive-page";
9185
9186    /// The emissive page **as this renderer declares it to a graph**, on
9187    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly.
9188    #[must_use]
9189    pub const fn emissive_page_import(&self) -> ImportedImage {
9190        ImportedImage {
9191            image: self.emissive_page.image,
9192            view: self.emissive_page.view,
9193            format: EMISSIVE_PAGE_FORMAT,
9194            extent: self.page_extents[PageKind::Emissive.index()],
9195            initial: ResourceState::ShaderRead,
9196            claim: InitialClaim::Tracked,
9197            final_state: ResourceState::ShaderRead,
9198        }
9199    }
9200
9201    /// The model matrix for a cube spinning at `seconds` into the run.
9202    ///
9203    /// Two axes at incommensurable rates, so the animation never repeats and
9204    /// every face comes into view — which is what makes "the cube is spinning"
9205    /// observable rather than a claim about a matrix.
9206    #[must_use]
9207    pub fn spin(seconds: f32) -> Mat4 {
9208        Mat4::from_quat(
9209            Quat::from_axis_angle(Vec3::Y, seconds * 0.9)
9210                * Quat::from_axis_angle(Vec3::X, seconds * 0.55),
9211        )
9212    }
9213
9214    /// The format the tonemap pass renders into.
9215    #[must_use]
9216    pub const fn target_format(&self) -> Format {
9217        self.target_format
9218    }
9219
9220    /// Switches the infinite ground grid on with `style`, or off with [`None`].
9221    ///
9222    /// **Off by default.** Every sample and every golden image predates the
9223    /// grid, so a renderer nobody has called this on records exactly the passes
9224    /// it always did — see [`crate::grid`] for what the pass is and
9225    /// [`add_passes`](Self::add_passes) for where in the frame it lands.
9226    ///
9227    /// The first `Some` builds the pipeline and the uniform ring; later calls
9228    /// only replace the style, and a `None` leaves both built. Releasing them
9229    /// here would mean releasing blocks the frames in flight may still be
9230    /// reading, so they are released by [`destroy`](Self::destroy) alone — the
9231    /// one call that already requires an idle device.
9232    ///
9233    /// # Errors
9234    ///
9235    /// [`HalError`] if the grid's pipeline or its blocks could not be created.
9236    /// Nothing is left switched on when that happens: the grid stays as it was.
9237    pub fn set_ground_grid(
9238        &mut self,
9239        device: &dyn Device,
9240        style: Option<GridStyle>,
9241    ) -> Result<(), HalError> {
9242        let Some(style) = style else {
9243            self.ground_grid_on = false;
9244            return Ok(());
9245        };
9246        let grid = match self.ground_grid.as_mut() {
9247            Some(grid) => grid,
9248            None => {
9249                // Built for the tonemap's target and the scene depth, because
9250                // those are the two attachments the pass is given — see
9251                // `add_passes`. Both are pipeline state, so a renderer whose
9252                // target format changed would need a new `Grid`; nothing in this
9253                // crate changes it after `build`, and `target_format` is kept
9254                // for exactly that reason.
9255                let grid = GroundGrid::new(
9256                    device,
9257                    self.primary.uniforms.len(),
9258                    self.target_format,
9259                    SCENE_DEPTH_FORMAT,
9260                )?;
9261                self.ground_grid.insert(grid)
9262            }
9263        };
9264        grid.set_style(style);
9265        self.ground_grid_on = true;
9266        Ok(())
9267    }
9268
9269    /// The debug draw layer's immediate-mode buffer, to append to.
9270    ///
9271    /// The UI's debug item 5 (`docs/notes/tooling.md`): any system appends lines, boxes,
9272    /// spheres and frusta during the frame, and
9273    /// [`begin_frame`](Self::begin_frame) uploads and clears what is there — so
9274    /// a segment lives exactly the frame it was appended in and nothing has to
9275    /// be un-appended. See [`crate::debug_draw`] for where the pass lands and
9276    /// for the console switch that has to be on before anything is drawn.
9277    ///
9278    /// **Appending is free while the layer is off**, but building the geometry
9279    /// is the caller's: a system whose overlay costs something to compute asks
9280    /// [`DebugDraw::enabled`] first.
9281    pub fn debug_draw(&mut self) -> &mut DebugDraw {
9282        &mut self.debug_draw
9283    }
9284
9285    /// How the ground grid is drawn, or [`None`] where it is switched off.
9286    ///
9287    /// The read-back half of [`set_ground_grid`](Self::set_ground_grid), and the
9288    /// observable a test asking "is the grid on" wants: a renderer that built
9289    /// the grid and then switched it off answers [`None`], because what it draws
9290    /// is what the question is about.
9291    #[must_use]
9292    pub fn ground_grid(&self) -> Option<&GridStyle> {
9293        self.ground_grid
9294            .as_ref()
9295            .filter(|_| self.ground_grid_on)
9296            .map(GroundGrid::style)
9297    }
9298
9299    /// Whether this frame adds [`crate::sky_pass`]'s background pass.
9300    ///
9301    /// [`Sky::NONE`] with no atmosphere is the value a renderer nobody called
9302    /// [`set_sky`](Self::set_sky) or
9303    /// [`set_atmosphere`](Self::set_atmosphere) on holds, and it is checked
9304    /// here rather than left to the shader for the reason [`crate::sky_pass`]
9305    /// gives: a black gradient drawn over [`SCENE_CLEAR`] would *change* those
9306    /// frames, where adding no pass leaves them exactly as they were.
9307    fn draws_sky(&self) -> bool {
9308        self.sky != Sky::NONE || self.atmosphere.is_some()
9309    }
9310
9311    /// Brings [`Self::sky_view`] up to the sun this frame has, a stripe of rows
9312    /// per frame.
9313    ///
9314    /// Called once per [`Self::begin_frame`]. The comparison is on the
9315    /// normalised parameters rather than on the [`Atmosphere`] a caller handed
9316    /// over, so re-setting the same sun spelled a different length is not a
9317    /// rebuild — and a caller that sets the same value every frame, which is
9318    /// the ordinary shape of a scene's update, pays the comparison and nothing
9319    /// else.
9320    ///
9321    /// # The first LUT is marched whole; every later one is marched in stripes
9322    ///
9323    /// A renderer that has no LUT has no sky to draw, so the first march after
9324    /// [`set_atmosphere`](Self::set_atmosphere) runs to completion inside this
9325    /// call and a caller that draws a single frame gets that frame's sky. After
9326    /// that there is always a finished LUT to show, so a sun that moved starts
9327    /// a [`SkyViewBuild`] and this steps it [`SKY_VIEW_BUILD_ROWS`] rows per
9328    /// frame — the frames in between keep drawing the LUT the last completed
9329    /// march produced, and no frame pays the whole march.
9330    ///
9331    /// # A sun that moves again restarts the march rather than finishing it
9332    ///
9333    /// The build in flight is kept only while its own sun is still the one the
9334    /// caller wants; a sun that moved during it is a new build from row zero,
9335    /// because finishing the old one would swap in a LUT for a sun that is
9336    /// already wrong and then immediately start marching again. **A sun that
9337    /// moves every frame therefore never completes a build and goes on showing
9338    /// the last one it finished** — a sky frozen at the sun it last caught up
9339    /// with, rather than a sky that stutters at whatever the march last passed.
9340    /// That is the trade this makes: the frame cost is bounded and the sky
9341    /// lags, where the whole-march rebuild it replaced had the sky exact and
9342    /// the frame cost unbounded. A caller that wants the sky exact stops the
9343    /// sun on a value and leaves it there: the march then completes, and the
9344    /// frames it takes are `SKY_VIEW_HEIGHT` over [`SKY_VIEW_BUILD_ROWS`].
9345    ///
9346    /// **The aerial-perspective LUT is marched in the same steps** — see
9347    /// [`SkyViewBuild`] — so the air in front of the scene arrives on the same
9348    /// frame as the sky and lags the sun by the same frames, never a sun apart
9349    /// from it. A change of [`Atmosphere::km_per_unit`] alone is a new march
9350    /// on the same terms, since it is part of the parameters compared.
9351    fn refresh_sky_view(&mut self) {
9352        let Some(atmosphere) = self.atmosphere else {
9353            self.sky_view = None;
9354            self.sky_view_build = None;
9355            return;
9356        };
9357        let parameters = atmosphere.parameters();
9358        if self
9359            .sky_view
9360            .as_ref()
9361            .is_some_and(|presented| presented.parameters == parameters)
9362        {
9363            self.sky_view_build = None;
9364            return;
9365        }
9366        if self.sky_view.is_none() {
9367            self.sky_view_build = None;
9368            self.sky_view = Some(PresentedSky::new(parameters, SkyView::build(&parameters)));
9369            return;
9370        }
9371        let mut build = match self.sky_view_build.take() {
9372            Some(build) if build.atmosphere() == parameters => build,
9373            _ => SkyViewBuild::start(&parameters),
9374        };
9375        if build.step(SKY_VIEW_BUILD_ROWS) {
9376            self.sky_view = Some(PresentedSky::new(parameters, build.finish()));
9377        } else {
9378            self.sky_view_build = Some(build);
9379        }
9380    }
9381
9382    /// Sets the multiplier the tonemap pass applies before its clamp, clamped
9383    /// into [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`].
9384    ///
9385    /// **The default is [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`]**, which is
9386    /// the value `tonemap.slang` held as a compile-time constant until this
9387    /// became a runtime one — so a renderer nobody calls this on draws the frame
9388    /// it always drew, and every golden image is untouched.
9389    ///
9390    /// It takes effect on the next
9391    /// [`begin_frame`](Self::begin_frame), which is what writes the block: a
9392    /// frame already recorded reads the value it was recorded with.
9393    ///
9394    /// **The clamp is here rather than at the call site** so that no caller can
9395    /// reach a picture it cannot get back from, and so that a control which
9396    /// steps by reading this back and setting a multiple of it — which is what
9397    /// [`exposure`](Self::exposure) is for — cannot wind up past the end and
9398    /// then need as many presses to come back.
9399    pub const fn set_exposure(&mut self, exposure: f32) {
9400        // `max` then `min` rather than `f32::clamp`: `clamp` propagates a NaN,
9401        // and a NaN reaching the block is a frame of NaN pixels with no key to
9402        // press to get out of it. `f32::max` returns the bound instead, so a NaN
9403        // lands on `EXPOSURE_MIN` — dark, and one press from being bright again.
9404        self.exposure = exposure.max(EXPOSURE_MIN).min(EXPOSURE_MAX);
9405    }
9406
9407    /// How far auto-exposure may travel toward its measurement in one frame.
9408    ///
9409    /// **[`None`] is the whole distance**, which is what a renderer nobody
9410    /// calls this on does and what the pass did before adaptation existed — so
9411    /// no golden moved when this arrived. A view that wants the roll asks, and
9412    /// asks *every frame*, because [`ExposureAdaptation`] carries that frame's
9413    /// own delta: this crate has no clock, and the frame time lives where the
9414    /// frame loop is.
9415    ///
9416    /// It takes effect on the next [`begin_frame`](Self::begin_frame), which is
9417    /// what writes the block, and it does nothing at all on a frame that did not
9418    /// ask for [`RenderEffects::AUTO_EXPOSURE`] — the passes that read it are
9419    /// the ones that bit adds.
9420    pub const fn set_exposure_adaptation(&mut self, adaptation: Option<ExposureAdaptation>) {
9421        self.exposure_adaptation = adaptation;
9422    }
9423
9424    /// What [`set_exposure_adaptation`](Self::set_exposure_adaptation) was last
9425    /// handed.
9426    #[must_use]
9427    pub const fn exposure_adaptation(&self) -> Option<ExposureAdaptation> {
9428        self.exposure_adaptation
9429    }
9430
9431    /// Which operator the tonemap pass runs on the exposed scene colour.
9432    ///
9433    /// **The ACES fit by default**, because this renderer shades in linear HDR
9434    /// and the roll-off is what that range is for. What a caller asks *for* here
9435    /// is therefore usually the other one: `tonemap.slang`'s clamp is the
9436    /// identity on `0..=1`, so display-referred content reaches the swapchain
9437    /// exactly, and a fixture that predicts a code value from a host model of
9438    /// the shading needs the frame to stay scene-referred. Every 2D sample in
9439    /// this tree draws through `crate::sprite_pass` and `crate::ui_pass`
9440    /// instead, so none of them reaches this pass at all.
9441    ///
9442    /// It takes effect on the next [`begin_frame`](Self::begin_frame), for
9443    /// [`set_exposure`](Self::set_exposure)'s reason: the block is written
9444    /// there, and a frame already recorded reads the value it was recorded
9445    /// with.
9446    ///
9447    /// **There is nothing to refuse and no `supports_` probe beside it.** The
9448    /// selector is a lane of a uniform block read by a branch every device
9449    /// already runs, so unlike the wireframe there is no second pipeline for a
9450    /// device to decline to build.
9451    pub const fn set_tonemap_curve(&mut self, curve: tonemap::TonemapCurve) {
9452        self.tonemap_curve = curve;
9453    }
9454
9455    /// The operator in force, on [`exposure`](Self::exposure)'s terms: the
9456    /// value the next frame will be drawn with.
9457    #[must_use]
9458    pub const fn tonemap_curve(&self) -> tonemap::TonemapCurve {
9459        self.tonemap_curve
9460    }
9461
9462    /// How large the internal render target is as a fraction of the extent
9463    /// [`begin_frame`](Self::begin_frame) is handed, clamped to
9464    /// `MIN_RENDER_SCALE..=1.0`.
9465    ///
9466    /// **This is the largest performance knob this renderer has.** Every pass
9467    /// before the upscale costs what its extent costs, so a scale of `0.7` is
9468    /// roughly half the shading work of `1.0`; the UI is composited onto the
9469    /// target afterwards at native resolution, so text stays sharp while the 3D
9470    /// frame gets cheap. `docs/notes/rendering.md` (_What the deleted
9471    /// 48-post-processing plan left behind_) is where that trade is written down.
9472    ///
9473    /// **`1.0` is not a special case with a fast path, it is the absence of the
9474    /// feature.** At full scale the internal extent *is* the caller's, the post
9475    /// chain writes the target directly, and no upscale pass is recorded — which
9476    /// is what makes a renderer nobody has called this on draw the frame it drew
9477    /// before the knob existed, bit for bit.
9478    ///
9479    /// **Above `1.0` is clamped away rather than supported.** Supersampling
9480    /// wants a box or Lanczos reduction and `upscale.slang` is a Catmull-Rom
9481    /// *reconstruction*; running it as a minification filter would alias, which
9482    /// is the opposite of what a caller asking for it wants. A non-finite scale
9483    /// is clamped to `1.0` for the same reason a `NaN` extent would be refused:
9484    /// the failure it produces is a zero-sized target somewhere downstream.
9485    ///
9486    /// Takes effect on the next [`begin_frame`](Self::begin_frame), on
9487    /// [`set_exposure`](Self::set_exposure)'s terms exactly — a frame already
9488    /// recorded is drawn at the scale it was recorded with.
9489    pub fn set_render_scale(&mut self, scale: f32) {
9490        self.render_scale = if scale.is_finite() {
9491            scale.clamp(MIN_RENDER_SCALE, 1.0)
9492        } else {
9493            1.0
9494        };
9495    }
9496
9497    /// The render scale in force, after the clamp
9498    /// [`set_render_scale`](Self::set_render_scale) applied.
9499    ///
9500    /// The read-back half, on [`exposure`](Self::exposure)'s terms.
9501    #[must_use]
9502    pub const fn render_scale(&self) -> f32 {
9503        self.render_scale
9504    }
9505
9506    /// The anisotropy the base-colour page is sampled with, in force from the
9507    /// next [`begin_frame`](Self::begin_frame).
9508    ///
9509    /// Topic 43's filtering rung, the player's half:
9510    /// [`anisotropy_for`](Self::anisotropy_for) is what a renderer nobody has
9511    /// called this on samples with, and this is what a settings row moves it
9512    /// to. Clamped to `1.0..=max_sampler_anisotropy` where the device was
9513    /// granted [`Features::SAMPLER_ANISOTROPY`] and to exactly `1.0` where it
9514    /// was not — the row can turn the filter off or push it to the device's
9515    /// ceiling, and nothing it asks reaches a `create_sampler` that would
9516    /// refuse it. A value that is not a number is the default, on
9517    /// [`set_render_scale`](Self::set_render_scale)'s terms.
9518    ///
9519    /// **A sampler is a resource a bind group holds by handle**, so a new
9520    /// anisotropy is a new sampler, and every group of the mesh layout has to
9521    /// be rebuilt to name it. That happens per frame slot, at the slot's own
9522    /// `begin_frame`, which is the moment the ring guarantees the slot's
9523    /// previous submission has retired — the guarantee every host write in
9524    /// that call already leans on — so a frame in flight goes on naming the
9525    /// sampler it was recorded with, and the replaced sampler is destroyed once
9526    /// no slot names it. This call creates the sampler and nothing else, and
9527    /// asking for the anisotropy already in force creates nothing.
9528    ///
9529    /// # Errors
9530    ///
9531    /// `create_sampler`'s, and the renderer is unchanged — the sampler in force
9532    /// stays in force.
9533    pub fn set_anisotropy(&mut self, device: &dyn Device, anisotropy: f32) -> Result<(), HalError> {
9534        let caps = device.caps();
9535        let ceiling = if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9536            caps.limits.max_sampler_anisotropy
9537        } else {
9538            1.0
9539        };
9540        let wanted = if anisotropy.is_finite() {
9541            anisotropy.clamp(1.0, ceiling)
9542        } else {
9543            Self::anisotropy_for(&caps)
9544        };
9545        // Bit-equal rather than within an epsilon: both sides came out of the
9546        // same clamp, and a row that lands on the value in force must not
9547        // rebuild every group for it.
9548        if wanted.to_bits() == self.anisotropy.to_bits() {
9549            return Ok(());
9550        }
9551        let sampler = Self::create_page_sampler(device, wanted)?;
9552        self.retired_pages
9553            .push(RetiredPage::Sampler(std::mem::replace(
9554                &mut self.base_color_sampler,
9555                sampler,
9556            )));
9557        self.anisotropy = wanted;
9558        Ok(())
9559    }
9560
9561    /// The anisotropy in force, after the clamp
9562    /// [`set_anisotropy`](Self::set_anisotropy) applied.
9563    ///
9564    /// The read-back half, on [`render_scale`](Self::render_scale)'s terms.
9565    #[must_use]
9566    pub const fn anisotropy(&self) -> f32 {
9567        self.anisotropy
9568    }
9569
9570    /// The anisotropy the base-colour page's sampler is created with on a
9571    /// device of `caps`: [`DEFAULT_ANISOTROPY`] clamped to
9572    /// [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) where
9573    /// [`Features::SAMPLER_ANISOTROPY`] was granted, and `1.0` where it was
9574    /// not.
9575    ///
9576    /// **Granted, not supported.** The feature is optional at every open site
9577    /// — [`Features::GPU_DRIVEN`] does not carry it — and a device opened
9578    /// without asking refuses a sampler above one even on hardware that has
9579    /// it, which is the shape every backend's `create_sampler` documents. So
9580    /// the question is what this device was opened *with*, and a caller that
9581    /// wants the plan's default has to name the feature beside the others it
9582    /// asks for. `crcbl-webgpu` withholds the feature and reports a ceiling of
9583    /// one, so a browser samples isotropically until `docs/backlog.md`'s
9584    /// ceiling decision is taken.
9585    #[must_use]
9586    pub fn anisotropy_for(caps: &DeviceCaps) -> f32 {
9587        if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9588            DEFAULT_ANISOTROPY.min(caps.limits.max_sampler_anisotropy)
9589        } else {
9590            1.0
9591        }
9592    }
9593
9594    /// The base-colour page's sampler at `anisotropy`, which the caller has
9595    /// already held to the device — [`anisotropy_for`](Self::anisotropy_for)
9596    /// at build, [`set_anisotropy`](Self::set_anisotropy)'s clamp after.
9597    ///
9598    /// **Trilinear over the whole chain, anisotropic where the device is** —
9599    /// topic 43's filtering rung: a minified surface
9600    /// reads the level its footprint matches instead of shimmering through
9601    /// level 0, a magnified one blends four texels instead of stepping between
9602    /// them, and a surface at a grazing angle keeps its detail along the long
9603    /// axis of its footprint rather than blurring to the short one. A second
9604    /// sampler object rather than sharing the tonemap's, so a capture names
9605    /// each for what it filters.
9606    ///
9607    /// **`Repeat`, not `ClampToEdge`**, and that is what `mesh.slang`'s
9608    /// `TILING_PHYSICAL` needs: a physical UV runs to `world_extent /
9609    /// tile_metres`, past `0..1` on any face wider than one tile, and only a
9610    /// wrapping address mode makes the page tile across it rather than
9611    /// smearing its edge row. `TILING_AUTHORED` is unaffected — its UV is the
9612    /// vertex's, which the meshes author inside `0..1`, so a wrapped and a
9613    /// clamped read return the same nearest texel for it.
9614    fn create_page_sampler(
9615        device: &dyn Device,
9616        anisotropy: f32,
9617    ) -> Result<SamplerHandle, HalError> {
9618        device.create_sampler(&SamplerDesc {
9619            label: Some("material base colour"),
9620            mag_filter: FilterMode::Linear,
9621            min_filter: FilterMode::Linear,
9622            mip_filter: FilterMode::Linear,
9623            address_mode: [SamplerAddressMode::Repeat; 3],
9624            anisotropy,
9625            ..SamplerDesc::default()
9626        })
9627    }
9628
9629    /// The extent the next frame handed `target` is actually drawn at, at the
9630    /// render scale in force.
9631    ///
9632    /// Test-only: a frame takes its extents at the scale its `begin_frame`
9633    /// froze, through [`scaled_extent`](Self::scaled_extent), and this is the
9634    /// prediction a test checks that against.
9635    #[cfg(all(test, not(target_arch = "wasm32")))]
9636    fn internal_extent(&self, target: (u32, u32)) -> (u32, u32) {
9637        Self::scaled_extent(self.render_scale, target)
9638    }
9639
9640    /// The extent a frame handed `target` is drawn at under `scale` — what a
9641    /// frame's own extents are taken at, with
9642    /// [`frame_render_scale`](Self::frame_render_scale).
9643    ///
9644    /// Rounds rather than truncates, and floors at one texel in each dimension:
9645    /// a zero here would reach a transient image description, and an image of
9646    /// zero extent is a device error rather than a small frame. A caller who
9647    /// minimised the window already hands a zero extent through, and that path
9648    /// is unchanged — `max(1)` on a zero is one either way.
9649    fn scaled_extent(scale: f32, target: (u32, u32)) -> (u32, u32) {
9650        if scale >= 1.0 {
9651            return target;
9652        }
9653        let scale = f64::from(scale);
9654        (
9655            ((f64::from(target.0) * scale).round() as u32).max(1),
9656            ((f64::from(target.1) * scale).round() as u32).max(1),
9657        )
9658    }
9659
9660    /// The exposure in force, after the clamp
9661    /// [`set_exposure`](Self::set_exposure) applied.
9662    ///
9663    /// The read-back half, on [`ground_grid`](Self::ground_grid)'s terms: what a
9664    /// caller wants is the number the frame is drawn with, not the one it asked
9665    /// for — which is also what makes a multiplicative step land on the end of
9666    /// the range rather than run past it.
9667    #[must_use]
9668    pub const fn exposure(&self) -> f32 {
9669        self.exposure
9670    }
9671
9672    /// Whether `device` can draw the wireframe view at all.
9673    ///
9674    /// The question [`set_wireframe`](Self::set_wireframe) answers with an
9675    /// error, asked **before** anything is switched on — so an application can
9676    /// tell its user that this device has no wireframe rather than binding a key
9677    /// that fails, and can say so once at start-up instead of on every press.
9678    /// WebGPU has no line fill mode at all, so the browser is the case this
9679    /// exists for and not a hypothetical.
9680    ///
9681    /// An associated function rather than a method: it is a fact about the
9682    /// device, and a caller wants it before it has decided anything.
9683    #[must_use]
9684    pub fn supports_wireframe(device: &dyn Device) -> bool {
9685        device.caps().supports(Features::POLYGON_MODE_LINE)
9686    }
9687
9688    /// Asks every camera's cull to drop what is hidden or too small to see —
9689    /// topic 03 §3.3's occlusion cull and its
9690    /// small-feature test. See [`crate::occlusion_cull`].
9691    ///
9692    /// [`OcclusionCulling::occlusion`] **changes no pixel**: the first phase
9693    /// guesses from the previous frame's depth, the second tests every rejected
9694    /// instance against this frame's, and only the second's rejections are
9695    /// dropped. [`OcclusionCulling::small_feature_pixels`] does change pixels,
9696    /// and is off unless a threshold is named.
9697    ///
9698    /// Taken from the next [`begin_frame`](Self::begin_frame), and combined with
9699    /// the `r_occlusion_cull` and `r_small_feature_px` console switches — either
9700    /// side turning a cull on turns it on. A wireframe frame culls by the frustum
9701    /// alone, because a wireframe shows the edges a depth test would hide.
9702    pub fn set_occlusion_culling(&mut self, culling: OcclusionCulling) {
9703        self.occlusion_culling = culling;
9704    }
9705
9706    /// Whether a point light's shadow cull tags each caster with the faces of
9707    /// its cube it reaches, so each face draws only those — **on** by default.
9708    ///
9709    /// Off is the cull this replaced: one test against the light's box, and
9710    /// every caster in it drawn into all six faces for the rasteriser to clip.
9711    /// The two write the same atlas, texel for texel — the six faces' pyramids
9712    /// tile the box, so a caster a face drops has no texel in that face's tile —
9713    /// and the switch exists so a test can hold them against each other and a
9714    /// price can be read off both.
9715    pub fn set_point_face_culls(&mut self, on: bool) {
9716        self.point_face_culls = on;
9717    }
9718
9719    /// **A test hook**: from the next [`begin_frame`](Self::begin_frame),
9720    /// rewrites every block the shadow atlas's depth pass is fed with `tamper`
9721    /// on its way to the GPU, or stops doing so with [`None`] — the default,
9722    /// and the only value a frame outside a test runs under.
9723    ///
9724    /// Applied **after** the atlas cache has read the blocks, so the rewrite is
9725    /// invisible to the decision whether to redraw a map and visible only to the
9726    /// depth pass that draws it. That is what makes it a probe of the shaders:
9727    /// `crcbl`'s `mesh_e2e` `shadow_block_reads` draws the atlas with each
9728    /// [`UniformsReader::ColourOnly`] entry of [`FRAME_UNIFORMS_READERS`]
9729    /// perturbed through here and holds the depth to the untampered frame's, bit
9730    /// for bit. It reaches the atlas's views alone — not the probe updater's
9731    /// shadows-off writes, which draw nothing into the atlas.
9732    pub fn set_shadow_view_tamper(&mut self, tamper: Option<fn(&mut mesh::FrameUniforms)>) {
9733        self.shadow_view_tamper = tamper;
9734    }
9735
9736    /// What [`set_occlusion_culling`](Self::set_occlusion_culling) last asked
9737    /// for, before the console switches and the wireframe are applied.
9738    #[must_use]
9739    pub const fn occlusion_culling(&self) -> OcclusionCulling {
9740        self.occlusion_culling
9741    }
9742
9743    /// The culls the next frame runs: [`occlusion_culling`](Self::occlusion_culling)
9744    /// with the console switches applied, and nothing on a wireframe frame.
9745    #[must_use]
9746    pub fn resolved_occlusion_culling(&self) -> OcclusionCulling {
9747        if self.wireframe_on {
9748            return OcclusionCulling::OFF;
9749        }
9750        let console_pixels = crate::occlusion_cull::r_small_feature_px.get_f32();
9751        OcclusionCulling {
9752            occlusion: self.occlusion_culling.occlusion
9753                || crate::occlusion_cull::r_occlusion_cull.get_bool(),
9754            small_feature_pixels: self
9755                .occlusion_culling
9756                .small_feature_pixels
9757                .or((console_pixels > 0.0).then_some(console_pixels)),
9758        }
9759    }
9760
9761    /// Draws the scene's triangles as lines, or goes back to filling them.
9762    ///
9763    /// **Off by default.** Every sample and every golden image predates the
9764    /// view, so a renderer nobody has called this on records exactly the frame
9765    /// it always did.
9766    ///
9767    /// # What it is, and what it is not
9768    ///
9769    /// The **colour pass** alone changes fill mode. The depth prepass and the
9770    /// shadow cascades keep drawing filled triangles, because they are what the
9771    /// occlusion pair and the shadow lookups read and depth drawn as lines is
9772    /// depth with holes in it. So a wireframe frame is the same geometry, the
9773    /// same shading and the same lights, rasterised as edges: what was inside a
9774    /// triangle becomes the clear colour, and what was on its edge stays lit.
9775    ///
9776    /// # It is built on the first `true`
9777    ///
9778    /// The pipeline is compiled here rather than beside the filled one at
9779    /// [`with_scene`](Self::with_scene), and that is the trade this
9780    /// call makes: one pipeline compile on the first press — a hitch, in a view
9781    /// the user just asked for — against a second compile in the start-up of
9782    /// every sample, golden run and headless test that never asks for one. Later
9783    /// calls only flip the switch, and a `false` leaves the pipeline built, for
9784    /// [`set_ground_grid`](Self::set_ground_grid)'s reason: releasing something
9785    /// the frames in flight may still be recording against is what
9786    /// [`destroy`](Self::destroy) — which already requires an idle device — is
9787    /// for.
9788    ///
9789    /// # Errors
9790    ///
9791    /// [`HalError::UnsupportedFeatures`] naming
9792    /// [`Features::POLYGON_MODE_LINE`](crcbl_hal::Features::POLYGON_MODE_LINE)
9793    /// when `on` is `true` on a device that has not got it — ask
9794    /// [`supports_wireframe`](Self::supports_wireframe) first. Refused rather
9795    /// than quietly filled: a caller who asked for a wireframe and got a solid
9796    /// frame back with no error has no way to tell that from a wireframe of a
9797    /// solid-looking model.
9798    ///
9799    /// [`HalError`] from the pipeline otherwise. **Nothing is left switched on
9800    /// when either happens**: the view stays as it was.
9801    pub fn set_wireframe(&mut self, device: &dyn Device, on: bool) -> Result<(), HalError> {
9802        if !on {
9803            self.wireframe_on = false;
9804            return Ok(());
9805        }
9806        if self.wireframe_pipeline.is_none() {
9807            if !Self::supports_wireframe(device) {
9808                return Err(HalError::UnsupportedFeatures {
9809                    missing: Features::POLYGON_MODE_LINE,
9810                });
9811            }
9812            let modules = MeshModules::new(device, self.emit, self.culls_clusters)?;
9813            let line = |cull| {
9814                modules.color_pipeline(
9815                    device,
9816                    self.mesh_pipeline_layout,
9817                    PolygonMode::Line,
9818                    cull,
9819                    "wireframe",
9820                )
9821            };
9822            let [back, none] = MeshModules::SIDES;
9823            // The twin only where the shaded pass has one — see
9824            // [`SidedPipelines`] — so a wireframe covers exactly the buckets
9825            // the shaded frame beside it draws.
9826            let single = line(back);
9827            let double = self.mesh_pipeline.double.map(|_| line(none)).transpose();
9828            modules.destroy(device);
9829            // **Both or neither.** A caller that got one twin back would draw a
9830            // frame missing every double-sided surface and nothing would say
9831            // so; released here rather than kept, because `destroy` is what
9832            // releases what this field holds and it holds nothing yet.
9833            let pipelines = match (single, double) {
9834                (Ok(single), Ok(double)) => SidedPipelines { single, double },
9835                (Ok(built), Err(error)) | (Err(error), Ok(Some(built))) => {
9836                    device.destroy_graphics_pipeline(built);
9837                    return Err(error);
9838                }
9839                (Err(error), Ok(None) | Err(_)) => return Err(error),
9840            };
9841            self.wireframe_pipeline = Some(pipelines);
9842        }
9843        self.wireframe_on = true;
9844        Ok(())
9845    }
9846
9847    /// Whether the colour pass draws lines instead of filled triangles.
9848    ///
9849    /// The read-back half of [`set_wireframe`](Self::set_wireframe), and the
9850    /// observable a test asking "is this frame a wireframe" wants: a renderer
9851    /// that built the pipeline and then switched it off answers `false`, because
9852    /// what it draws is what the question is about.
9853    #[must_use]
9854    pub const fn wireframe(&self) -> bool {
9855        self.wireframe_on
9856    }
9857
9858    /// Draws each surface's **world-space** normal instead of shading it, so a
9859    /// modeller can see whether the normals a document carries are sane.
9860    ///
9861    /// **Off by default**, on [`set_wireframe`](Self::set_wireframe)'s terms: it
9862    /// is a tool's view of a document, and every sample and every golden image
9863    /// predates it. It takes effect on the next
9864    /// [`begin_frame`](Self::begin_frame), which is what writes the block.
9865    ///
9866    /// # What the colours mean
9867    ///
9868    /// The conventional encoding, `n * 0.5 + 0.5` into RGB: +X reads red, +Y
9869    /// green, +Z blue, and a face whose winding was inverted reads the
9870    /// **complement** of the colour it should have. A missing or degenerate
9871    /// normal reads as whatever the vertex data actually holds rather than as the
9872    /// plausible shading a light would have given it, which is the point.
9873    ///
9874    /// # World space, not view space
9875    ///
9876    /// The two diagnose different things and this one is world space, so a face
9877    /// keeps its colour while the camera orbits: "is this face inverted" is then
9878    /// something a modeller *sees*, instead of inferring it from a picture that
9879    /// re-colours whenever they move. View-space normals answer the other
9880    /// question — is this normal smooth, is this seam split — by re-colouring on
9881    /// purpose, and they are not a thing this block could express anyway: it
9882    /// carries `view_proj` and no separate view matrix, so there is no rotation in
9883    /// the shader to take a normal into eye space with.
9884    ///
9885    /// # It builds nothing and adds no pass
9886    ///
9887    /// Unlike the wireframe, which needs a second pipeline and so a device that
9888    /// can build one: this is one lane of the frame's uniform block — see
9889    /// [`FrameUniforms::NORMALS_VIEW_ON`] — read by a branch in the fragment
9890    /// stage every device already runs. There is nothing to refuse and nothing to
9891    /// release, which is why it cannot fail and there is no `supports_` probe
9892    /// beside it.
9893    ///
9894    /// The tonemap still applies: at
9895    /// [`DEFAULT_EXPOSURE`](crcbl_shaders::tonemap::DEFAULT_EXPOSURE) its operator
9896    /// is the identity on `0..=1` and the encoded normal reaches the swapchain
9897    /// exactly, and at any other exposure the picture is scaled per channel — so
9898    /// which channel dominates a face never changes, but a caller reading exact
9899    /// values wants [`set_exposure`](Self::set_exposure) left alone.
9900    ///
9901    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
9902    pub const fn set_normals_view(&mut self, on: bool) {
9903        self.normals_view = on;
9904    }
9905
9906    /// Sets the exponential height fog the colour pass composites over every
9907    /// shaded surface.
9908    ///
9909    /// Topic 43 §4's cheapest large win: distance
9910    /// reads as distance, a valley fills while a hilltop stays clear, and it
9911    /// costs four numbers in a block every pipeline already binds.
9912    ///
9913    /// # It adds no pass and cannot fail
9914    ///
9915    /// On [`set_normals_view`](Self::set_normals_view)'s terms exactly — two
9916    /// rows of the frame's uniform block, read by arithmetic in the fragment
9917    /// stage every device already runs. There is nothing to build, so there is
9918    /// nothing to refuse and no `supports_` probe beside it.
9919    ///
9920    /// # Off is exactly off
9921    ///
9922    /// [`Fog::NONE`] is the default and a zero density is an *exact* identity,
9923    /// not an approximate one: the optical depth is zero, its transmittance is
9924    /// exactly one, and `mesh.slang` composites as `lit * t + fog * (1 - t)`
9925    /// rather than as a `lerp`, which at `t == 1` would return
9926    /// `fog + (lit - fog)` and lose the low bits of an HDR radiance far from
9927    /// the fog colour. So this feature moves no frame it is not switched on
9928    /// for.
9929    ///
9930    /// # What it does not fog
9931    ///
9932    /// The screen-space reflections `ssr_blur.slang` adds **after** this pass,
9933    /// which arrive unfogged onto an already-fogged surface — see
9934    /// `docs/backlog.md`. Fog is applied where the radiance is finished, and
9935    /// the reflection composite is one pass later.
9936    pub const fn set_fog(&mut self, fog: Fog) {
9937        self.fog = fog;
9938    }
9939
9940    /// Lights the scene with a gradient sky, on top of whatever ambient and
9941    /// irradiance grid it already has.
9942    ///
9943    /// Topic 43 §8's rung. [`Sky`] is three
9944    /// radiances — zenith, horizon, ground — and what reaches a surface is that
9945    /// gradient projected onto the L1 basis the probe grid already uses, so a
9946    /// surface facing up receives the sky and one facing down the ground's
9947    /// bounce. Three colours, no extra pass.
9948    ///
9949    /// # It adds no pass and cannot fail
9950    ///
9951    /// On [`set_fog`](Self::set_fog)'s terms exactly — three rows of the
9952    /// frame's uniform block and three dot products in a fragment stage every
9953    /// device already runs. Nothing to build, so nothing to refuse and no
9954    /// `supports_` probe beside it.
9955    ///
9956    /// # Off is exactly off
9957    ///
9958    /// [`Sky::NONE`] is the default and a black gradient projects to every
9959    /// coefficient zero — each is a product with a zero factor — so the
9960    /// fragment stage adds `max(0, 0)` and the ambient sum is the one it was
9961    /// before this existed, bit for bit.
9962    ///
9963    /// # What it does not do
9964    ///
9965    /// **Draw anything.** The background is still the scene target's clear
9966    /// colour, and a scene lit by a sky it cannot see is what this rung leaves
9967    /// behind until the pass that draws the gradient lands. The environment
9968    /// `ssr.slang` falls back to on a missed ray is still the probe grid's, so
9969    /// a mirror under a sky still reflects whatever the probes hold.
9970    pub const fn set_sky(&mut self, sky: Sky) {
9971        self.sky = sky;
9972    }
9973
9974    /// Replaces the gradient with Hillaire's atmosphere, or `None` to put the
9975    /// gradient back.
9976    ///
9977    /// Topic 43 §8. A frame with an atmosphere takes
9978    /// it for all three of the things a sky is: the background the sky pass
9979    /// draws, the L1 ambient term `mesh.slang` adds, and the environment
9980    /// `ssr.slang` falls back to when a ray hits nothing. The
9981    /// [`Sky`] a caller may also have set is not read on those frames.
9982    ///
9983    /// # What it costs
9984    ///
9985    /// **A march on the host, not on the device.** The first
9986    /// [`begin_frame`](Self::begin_frame) after this is called marches
9987    /// [`crcbl_shaders::atmosphere::SkyView`] whole, which is tens of
9988    /// milliseconds of CPU — a renderer with no LUT has no sky, so that one is
9989    /// paid where it is asked for. Every later move of the sun is marched
9990    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame with the last finished LUT still
9991    /// drawn, so no frame after the first pays the whole march;
9992    /// `refresh_sky_view` is where that is written down, including what a sun
9993    /// that moves *every* frame gets. A frame whose
9994    /// sun has not moved costs the comparison that finds nothing to do and
9995    /// nothing else: the LUT's two projections are cached beside it. The device
9996    /// pays four buffer loads and a blend, which is what the gradient pays.
9997    ///
9998    /// # Off is exactly off
9999    ///
10000    /// `None` is the default, and a renderer nobody calls this on writes the
10001    /// same block, adds the same passes and draws the same frame it did before
10002    /// this existed — `sky.slang`'s arm is
10003    /// [`crcbl_shaders::sky::ATMOSPHERE_OFF`], which is exactly zero.
10004    ///
10005    /// # What it does not do
10006    ///
10007    /// **Draw the sun.** The LUT holds the scattered sky and not the disc, as
10008    /// the paper's does; the sun itself is the [`DirectionalLight`] the forward
10009    /// pass already shades with, and pointing the two the same way is the
10010    /// caller's job.
10011    ///
10012    /// **Put the air in front of a surface.** That is the paper's third LUT and
10013    /// this engine's froxel column, and neither reads this.
10014    pub fn set_atmosphere(&mut self, atmosphere: Option<Atmosphere>) {
10015        self.atmosphere = atmosphere;
10016    }
10017
10018    /// The bodies of water every view draws — `docs/plan/55-water.md`'s rung 1,
10019    /// and this crate's `water` module for how.
10020    ///
10021    /// Replaces whatever was set before. Each body is meshed here, by
10022    /// [`crcbl_water::surface_mesh`], and the result is uploaded to each frame
10023    /// slot as that slot next begins, so the call touches no device and a frame
10024    /// still in flight keeps the buffers it was submitted with. The first frame
10025    /// with a body builds each view's water passes — a hitch, cold, on that
10026    /// frame.
10027    ///
10028    /// # Off is exactly off
10029    ///
10030    /// An empty slice is the default, and a renderer with no bodies records no
10031    /// water pass at all: the frame it draws is the one it drew before this
10032    /// existed, bit for bit. Water is content, not a
10033    /// [`RenderEffects`] bit, on [`set_sky`](Self::set_sky)'s terms.
10034    ///
10035    /// # Errors
10036    ///
10037    /// [`crcbl_water::BodyError`] for the first body that cannot be meshed —
10038    /// too few points, a non-finite coordinate, an outline that crosses itself,
10039    /// a negative coefficient — and then **nothing is replaced**: the bodies set
10040    /// before this call go on drawing.
10041    pub fn set_water(
10042        &mut self,
10043        bodies: &[crcbl_water::WaterBody],
10044    ) -> Result<(), crcbl_water::BodyError> {
10045        self.water.set(bodies)
10046    }
10047
10048    /// The bodies of water this renderer draws, as they were last set.
10049    #[must_use]
10050    pub fn water(&self) -> &[crcbl_water::WaterBody] {
10051        self.water.bodies()
10052    }
10053
10054    /// The field of grass every view draws — `docs/plan/57-grass.md`'s rungs G1
10055    /// and G3, and this crate's `grass` module for how.
10056    ///
10057    /// Replaces whatever was set before. The field's ground, cover map, blade
10058    /// table and per-tile blocks are uploaded here, and the buffers a dispatch
10059    /// writes are created here; a field replaced while a frame is in flight
10060    /// leaves its resources alive until the ring has come round, so the call is
10061    /// safe at any point between frames. The field is drawn from the next
10062    /// [`begin_frame`](Self::begin_frame) on, which builds each view's grass
10063    /// passes the first time it sees one — a hitch, cold, on that frame.
10064    ///
10065    /// # Off is exactly off
10066    ///
10067    /// [`None`] is the default, and a renderer with no field records no grass
10068    /// pass at all: the frame it draws is the one it drew before this existed,
10069    /// bit for bit. Grass is content, not a [`RenderEffects`] bit, on
10070    /// [`set_water`](Self::set_water)'s terms.
10071    ///
10072    /// # Errors
10073    ///
10074    /// [`crate::grass::SetError::Field`] for a description the field itself
10075    /// refuses — no tiles, a zero texel scale, an empty blade table — and then
10076    /// **nothing is replaced**: the field set before this call goes on drawing.
10077    /// [`crate::grass::SetError::Hal`] for a seam call that failed, on the same
10078    /// terms.
10079    pub fn set_grass(
10080        &mut self,
10081        device: &dyn Device,
10082        queue: QueueHandle,
10083        field: Option<&crate::grass::GrassField>,
10084    ) -> Result<(), crate::grass::SetError> {
10085        self.grass.set(device, queue, field)
10086    }
10087
10088    /// The field of grass this renderer draws, as it was last set.
10089    #[must_use]
10090    pub fn grass(&self) -> Option<&crate::grass::GrassField> {
10091        self.grass.field()
10092    }
10093
10094    /// The two buffers the grass generation pass writes, or [`None`] for a
10095    /// renderer with no field.
10096    ///
10097    /// What `crcbl`'s `render_e2e` copies back to check the placement blade by
10098    /// blade and to read each slot's instance count, on
10099    /// [`froxel_buffers`](Self::froxel_buffers)' terms — see
10100    /// [`crate::grass::GrassBuffers`] for the layout. They hold whatever the
10101    /// last frame that generated left there, which for a field nobody has drawn
10102    /// yet is undefined rather than empty.
10103    #[must_use]
10104    pub fn grass_buffers(&self) -> Option<crate::grass::GrassBuffers> {
10105        self.grass.buffers()
10106    }
10107
10108    /// The two authored wind layers `docs/plan/56-wind.md`'s decision 1 names,
10109    /// as the GPU copy of the field samples them.
10110    ///
10111    /// [`None`] restores the calm placeholder: one texel of no deflection and
10112    /// one of zero intensity, which is what makes a field with no weather set
10113    /// stand still. A replaced pair waits for the ring exactly as a replaced
10114    /// field does, and like a field it is drawn from the next `begin_frame` on:
10115    /// the frame freezes its layers with its field.
10116    ///
10117    /// The new pair is uploaded in one batch that is **not waited for**, on
10118    /// the build's terms: `queue` must be the device's graphics queue, and
10119    /// the batch's staging is retired by a later `begin_frame`.
10120    ///
10121    /// # Errors
10122    ///
10123    /// [`crate::grass::WindLayerError`] for a layer that is not four bytes a
10124    /// texel of the grid it came with, a `queue` that is not the device's
10125    /// graphics queue, or a seam call that failed.
10126    pub fn set_wind_layers(
10127        &mut self,
10128        device: &dyn Device,
10129        queue: QueueHandle,
10130        layers: Option<&crate::grass::WindLayers>,
10131    ) -> Result<(), crate::grass::WindLayerError> {
10132        crcbl_frame::require_frame_queue(device, queue, "a forward renderer's wind layers")?;
10133        let pending = self.grass.set_wind_layers(device, queue, layers)?;
10134        self.uploads_in_flight.push(pending);
10135        Ok(())
10136    }
10137
10138    /// The wind's uniform block for the frames from here on —
10139    /// `crcbl_wind::WindField::gpu_params`, which is where the authoritative
10140    /// `f64` formula is narrowed to `f32`.
10141    ///
10142    /// Everything in it is camera-relative or already wrapped, so a caller
10143    /// writes it once per frame from the field's own state and never from a
10144    /// world-scale coordinate. The default is a base speed of zero, which is
10145    /// calm.
10146    pub const fn set_wind(&mut self, params: crcbl_shaders::wind::WindParams) {
10147        self.wind = params;
10148    }
10149
10150    /// The wind block this renderer writes, as it was last set.
10151    #[must_use]
10152    pub const fn wind(&self) -> crcbl_shaders::wind::WindParams {
10153        self.wind
10154    }
10155
10156    /// The atmosphere this renderer draws, if it has one.
10157    #[must_use]
10158    pub const fn atmosphere(&self) -> Option<Atmosphere> {
10159        self.atmosphere
10160    }
10161
10162    /// Draws each cluster tinted by the DAG level it was decimated to, instead
10163    /// of shading it.
10164    ///
10165    /// **The picture cluster LOD's whole claim rests on**: one mesh spanning
10166    /// several levels across its own surface is a statement a test can assert
10167    /// and nobody can see, and this is what makes it visible. The mesh path
10168    /// tints per cluster; the two indirect paths select one level per instance
10169    /// and have no per-cluster level at all, so they draw one flat grey — which
10170    /// is the comparison rather than a shortfall.
10171    ///
10172    /// Costs what [`set_normals_view`](Self::set_normals_view) costs: one lane
10173    /// of the frame's uniform block, read by a branch every device already runs.
10174    /// Nothing to build, nothing to refuse, nothing to release.
10175    ///
10176    /// **Wins over the normals view when both are on**, because the two share a
10177    /// lane and the fragment stage tests this one first.
10178    pub const fn set_lod_view(&mut self, on: bool) {
10179        self.lod_view = on;
10180    }
10181
10182    /// Whether the colour pass tints clusters by their DAG level.
10183    ///
10184    /// **What was asked for, not what is drawn.** The three debug views share
10185    /// one lane and resolve in one order, so a renderer with this and
10186    /// [`set_heatmap`](Self::set_heatmap) both on draws the heatmap and still
10187    /// answers `true` here — the caller's setting is what a caller's toggle has
10188    /// to read back, and [`debug_view`](Self::debug_view) is what says which one
10189    /// the frame actually took.
10190    #[must_use]
10191    pub const fn lod_view(&self) -> bool {
10192        self.lod_view
10193    }
10194
10195    /// Shades each cluster by the **projected screen-space error** the LOD
10196    /// selection judged it on, instead of shading it.
10197    ///
10198    /// The LOD tint's sibling, and the other half of topic 25's
10199    /// pair: [`set_lod_view`](Self::set_lod_view) answers "which level am I
10200    /// looking at", and this answers "how close to the budget is this, and where
10201    /// is the selection about to switch". The number is the one
10202    /// `draw_gen.slang`'s `group_is_expanded` compared against the budget — a
10203    /// cluster's *producing* group's error, projected from this frame's eye at
10204    /// this frame's pixels per unit.
10205    ///
10206    /// # What the colours mean
10207    ///
10208    /// A ramp that climbs in luminance from a cold floor to white, with a hue
10209    /// break at each of the two budgets: the hold budget where the hysteresis
10210    /// band starts, and the expand budget at the top, which is white. So the two
10211    /// budgets draw themselves as contour lines across the surface, and
10212    /// "brighter is closer to switching" reads even in a greyscale screenshot.
10213    /// `mesh_cluster.slang`'s `HEAT_UNDER_LOW` carries the ramp in full, and
10214    /// `crcbl_shaders`' `the_heatmap_ramp_climbs_in_luminance` is what holds it
10215    /// to being readable as an ordering.
10216    ///
10217    /// A cluster nothing simplified — the original surface, at the bottom of the
10218    /// DAG — costs exactly zero and takes the ramp's floor.
10219    ///
10220    /// # Mesh path only, and that is the capability rather than a shortfall
10221    ///
10222    /// A per-cluster error exists only where selection is per cluster.
10223    /// [`GeometryPath::IndirectCount`] and [`GeometryPath::IndirectPerBatch`]
10224    /// choose one level per *instance*, so there is no per-cluster number for
10225    /// them to shade by and `mesh.slang`'s vertex stage writes the same flat grey
10226    /// the LOD tint gets. Standing the two beside each other is the comparison.
10227    ///
10228    /// # It builds nothing and adds no pass
10229    ///
10230    /// One lane of the frame's uniform block, on
10231    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly — plus one
10232    /// storage-buffer read in the mesh stage, which the mesh path's layout
10233    /// already carries. Nothing to build, nothing to refuse, nothing to release.
10234    ///
10235    /// **Wins over both the LOD tint and the normals view when several are on**;
10236    /// see [`debug_view`](Self::debug_view), which is that order stated once.
10237    ///
10238    /// [`GeometryPath::IndirectCount`]: crcbl_hal::GeometryPath::IndirectCount
10239    /// [`GeometryPath::IndirectPerBatch`]: crcbl_hal::GeometryPath::IndirectPerBatch
10240    pub const fn set_heatmap(&mut self, on: bool) {
10241        self.heatmap = on;
10242    }
10243
10244    /// Whether the colour pass shades clusters by their projected error.
10245    ///
10246    /// **What was asked for, not what is drawn**, on
10247    /// [`lod_view`](Self::lod_view)'s terms.
10248    #[must_use]
10249    pub const fn heatmap(&self) -> bool {
10250        self.heatmap
10251    }
10252
10253    /// Draws the ambient-occlusion channel alone, as grey, instead of shading.
10254    ///
10255    /// One is white and fully occluded is black — the buffer the forward pass
10256    /// multiplies its ambient term by, shown as itself. **This is how the AO
10257    /// ladder — GTAO against the eight-tap hemisphere — is compared at all:** a
10258    /// composited frame shows occlusion times albedo times ambient, and a
10259    /// difference in the first is not separable from a difference in the other
10260    /// two by looking at the result.
10261    ///
10262    /// # What it draws with occlusion switched off
10263    ///
10264    /// White, everywhere. A frame without
10265    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 white image in place of
10266    /// a computed channel, and this view shows that image rather than pretending
10267    /// to a channel nothing computed — "no occlusion was computed" and "nothing
10268    /// occludes here" are the same value to the shading, and the view does not
10269    /// get to disagree with the shading about it.
10270    ///
10271    /// # It builds nothing and adds no pass
10272    ///
10273    /// One lane of the frame's uniform block, on
10274    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly. Unlike the
10275    /// tint and the heatmap it needs nothing from the geometry stage, so it
10276    /// draws on every [`GeometryPath`] rather than on
10277    /// the mesh-shader one alone.
10278    ///
10279    /// **Wins over every other view when several are on**; see
10280    /// [`debug_view`](Self::debug_view), which is that order stated once.
10281    pub const fn set_occlusion_view(&mut self, on: bool) {
10282        self.occlusion_view = on;
10283    }
10284
10285    /// Whether the colour pass draws the occlusion channel instead of shading.
10286    ///
10287    /// **What was asked for, not what is drawn**, on
10288    /// [`lod_view`](Self::lod_view)'s terms.
10289    #[must_use]
10290    pub const fn occlusion_view(&self) -> bool {
10291        self.occlusion_view
10292    }
10293
10294    /// Draws each fragment's motion vector instead of shading it.
10295    ///
10296    /// The two components are stretched by
10297    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) and centred
10298    /// on grey, into red and green, with blue left at zero. A pixel at rest is
10299    /// grey in both channels to within one half-float step —
10300    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) says why
10301    /// not exactly — and a surface travelling right and down the screen
10302    /// brightens both.
10303    ///
10304    /// # It is the motion-vector target's only reader today
10305    ///
10306    /// The forward pass writes a motion vector into a third colour attachment on
10307    /// every frame — see [`crate::targets::motion`] — and no pass reads it
10308    /// yet; TAA (`docs/backlog.md`) is the first that will. This
10309    /// view is therefore what says the subtraction behind it is the right one,
10310    /// which is why it exists ahead of a consumer.
10311    ///
10312    /// # It builds nothing and adds no pass
10313    ///
10314    /// One lane of the frame's uniform block, on
10315    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10316    /// the occlusion view it needs nothing from the geometry stage that a
10317    /// shaded frame does not already produce — so it draws on every
10318    /// [`GeometryPath`].
10319    ///
10320    /// **Wins over every other view when several are on**; see
10321    /// [`debug_view`](Self::debug_view), which is that order stated once.
10322    pub const fn set_motion_view(&mut self, on: bool) {
10323        self.motion_view = on;
10324    }
10325
10326    /// Whether the colour pass draws the motion vector instead of shading.
10327    ///
10328    /// **What was asked for, not what is drawn**, on
10329    /// [`lod_view`](Self::lod_view)'s terms.
10330    #[must_use]
10331    pub const fn motion_view(&self) -> bool {
10332        self.motion_view
10333    }
10334
10335    /// Draws the occlusion channel's **bent direction** instead of shading.
10336    ///
10337    /// The three channels beside the visibility scalar, passed through as the
10338    /// colour: the conventional `n * 0.5 + 0.5`, so +X reads red, +Y green and
10339    /// +Z blue, which is the mapping
10340    /// [`set_normals_view`](Self::set_normals_view) already uses for a surface
10341    /// normal. A fragment the occlusion pass had no direction for reads as the
10342    /// mid grey the zero sentinel encodes to.
10343    ///
10344    /// # What it is for
10345    ///
10346    /// The bent direction is what the ambient term is sampled *along*, and a
10347    /// composited frame cannot show it: ambient times albedo times a
10348    /// direction-dependent irradiance is one colour, and a direction that is
10349    /// subtly wrong looks like a lighting choice. This draws the direction
10350    /// alone, which is how a corner that leans the wrong way out of its own
10351    /// wall is a thing a reviewer sees rather than infers.
10352    ///
10353    /// # What it draws with occlusion switched off
10354    ///
10355    /// Mid grey, everywhere. A frame without
10356    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 placeholder holding
10357    /// [`BENT_NORMAL_NONE`](crcbl_shaders::ssao::BENT_NORMAL_NONE) in those
10358    /// three channels, and this view shows that image rather than pretending to
10359    /// a direction nothing computed — which is the same answer the shading
10360    /// takes, since `mesh.slang` reads that sentinel as "use the shading
10361    /// normal".
10362    ///
10363    /// # It builds nothing and adds no pass
10364    ///
10365    /// One lane of the frame's uniform block, on
10366    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10367    /// the occlusion view it needs nothing from the geometry stage — so it
10368    /// draws on every [`GeometryPath`].
10369    ///
10370    /// **Wins over every other view when several are on**; see
10371    /// [`debug_view`](Self::debug_view), which is that order stated once.
10372    pub const fn set_bent_normal_view(&mut self, on: bool) {
10373        self.bent_normal_view = on;
10374    }
10375
10376    /// Whether the colour pass draws the bent direction instead of shading.
10377    ///
10378    /// **What was asked for, not what is drawn**, on
10379    /// [`lod_view`](Self::lod_view)'s terms.
10380    #[must_use]
10381    pub const fn bent_normal_view(&self) -> bool {
10382        self.bent_normal_view
10383    }
10384
10385    /// Tints the shaded picture by the **cascade** each sun-lit fragment's
10386    /// shadow was sampled from.
10387    ///
10388    /// Topic 45's eighth decision made the cascade switch a
10389    /// band rather than a step, and this is the picture that band is judged in:
10390    /// each fragment's shading multiplied by
10391    /// [`CASCADE_TINTS`](crcbl_shaders::mesh::CASCADE_TINTS) of the cascade it
10392    /// selected, and inside the band by the *blend* of the two — the same weight
10393    /// the visibility itself was mixed with. So the boundary reads as a
10394    /// gradient, and a seam where two cascades disagree shows up as a step in
10395    /// the gradient rather than as a ring somebody has to already suspect.
10396    ///
10397    /// # It keeps the shaded picture, which is why it loses to every other view
10398    ///
10399    /// Every other view replaces the frame; this one multiplies it, so the geometry
10400    /// stays readable underneath and the shadow the cascades produced is still
10401    /// in the picture being coloured. That is also what puts it last in
10402    /// [`debug_view`](Self::debug_view)'s order: with a replacing view on there
10403    /// is no shading left for a tint to reach.
10404    ///
10405    /// # What it draws where no cascade covers a fragment
10406    ///
10407    /// Nothing at all —
10408    /// [`CASCADE_TINT_NONE`](crcbl_shaders::mesh::CASCADE_TINT_NONE) is white.
10409    /// A surface facing away from the sun and one past the last cascade's reach
10410    /// are both that, because neither was sampled through a cascade, and a
10411    /// frame drawn without [`RenderEffects::SHADOWS`](crate::RenderEffects::SHADOWS) is
10412    /// white everywhere for the same reason. Colouring those would be inventing
10413    /// a cascade for a pixel no map covers.
10414    ///
10415    /// # It builds nothing and adds no pass
10416    ///
10417    /// One lane of the frame's uniform block, on
10418    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10419    /// the occlusion view it needs nothing from the geometry stage — so it draws
10420    /// on every [`GeometryPath`].
10421    pub const fn set_cascade_view(&mut self, on: bool) {
10422        self.cascade_view = on;
10423    }
10424
10425    /// Whether the colour pass tints the picture by the sun's cascades.
10426    ///
10427    /// **What was asked for, not what is drawn**, on
10428    /// [`lod_view`](Self::lod_view)'s terms — and here that gap is the usual
10429    /// case rather than the corner one: this view loses to every other one, so a
10430    /// renderer with any of them also on answers `true` here and draws that one.
10431    #[must_use]
10432    pub const fn cascade_view(&self) -> bool {
10433        self.cascade_view
10434    }
10435
10436    /// Draws the **shadow atlas itself** over the finished frame: the
10437    /// `D32Float` image `crate::shadow` budgets, letterboxed at its own aspect,
10438    /// each texel's stored depth as a grey and a border round every occupied
10439    /// slot.
10440    ///
10441    /// Sundial's atlas viewer, and the answer to a
10442    /// question no other view can be asked: which slot holds which map, and
10443    /// which slots hold nothing. A tile that was never rendered into, or
10444    /// rendered at the wrong viewport, lights a scene *fully* — so the frame it
10445    /// produces is plausible and every golden blessed from it passes. Here it is
10446    /// a rectangle that is visibly empty.
10447    ///
10448    /// # It is a pass, and it is the only debug view that is
10449    ///
10450    /// Every other view rides in one lane of the frame's uniform block and is a
10451    /// branch in `mesh.slang`, because every other view is a function of the
10452    /// fragment being shaded. The atlas is not: it is one image the whole frame
10453    /// shares. So this switch adds `crate::atlas_view`'s full-screen pass to
10454    /// the frame instead — after the tonemap, in display space, for that
10455    /// module's reason — and the frame block is byte-identical either way.
10456    ///
10457    /// # Where it resolves, and what it costs when it is off
10458    ///
10459    /// Below every replacing view and above
10460    /// [`set_cascade_view`](Self::set_cascade_view)'s tint — see
10461    /// [`debug_view`](Self::debug_view), which is that order stated once. A
10462    /// frame that resolved anything else records **no pass**, no pipeline bind
10463    /// and no block read, which is what makes the off position bit-identical on
10464    /// `crate::sky_pass`'s terms.
10465    pub const fn set_atlas_view(&mut self, on: bool) {
10466        self.atlas_view = on;
10467    }
10468
10469    /// Whether the frame draws the shadow atlas over the picture.
10470    ///
10471    /// **What was asked for, not what is drawn**, on
10472    /// [`lod_view`](Self::lod_view)'s terms: a renderer with a replacing view
10473    /// also on answers `true` here and draws that one.
10474    #[must_use]
10475    pub const fn atlas_view(&self) -> bool {
10476        self.atlas_view
10477    }
10478
10479    /// Pins the eye topic 25's selection is projected from, so the
10480    /// cut stops following the camera.
10481    ///
10482    /// [`None`] is the default and means "the camera's own eye", which is what
10483    /// every frame before this existed did. `Some(eye)` selects detail for a
10484    /// viewer standing at `eye` while the frame is still drawn, culled and lit
10485    /// from wherever the camera actually is.
10486    ///
10487    /// # What it is for
10488    ///
10489    /// Per-cluster LOD is only checkable from somewhere other than the point
10490    /// that chose it. Looked at from the selecting eye, a cut that is far too
10491    /// coarse and a cut that is exactly right produce the same silhouette —
10492    /// that is what a screen-space error budget *means* — so the one viewpoint
10493    /// where a wrong cut cannot be seen is the viewpoint every unfrozen frame is
10494    /// judged from. Pin the eye and fly away from it, and the boundaries between
10495    /// levels become geometry a reviewer can walk up to and look at edge-on.
10496    ///
10497    /// # Only the selection freezes
10498    ///
10499    /// The frame has three places a viewer position is read, and this moves
10500    /// exactly one of them:
10501    ///
10502    /// * **the selection** — `draw_gen.slang`'s `select_level`, which reads
10503    ///   `DrawGenParams::camera_position` and is the only thing that decides the
10504    ///   cut. It writes the group hysteresis state that the mesh path's
10505    ///   amplification stage then descends, so freezing this one field freezes
10506    ///   the cut on the per-cluster path and the two indirect paths alike. This
10507    ///   is what moves.
10508    /// * **the frustum culls** — `cull.slang`'s instance test and
10509    ///   `mesh_cluster.slang`'s per-cluster one, whose planes are extracted from
10510    ///   the frame's own view-projection and never read a camera position at
10511    ///   all. Unaffected, and it has to be: a frame culled against a frustum the
10512    ///   reviewer has flown out of would draw nothing.
10513    /// * **the normal cone** — `mesh_cluster.slang`'s `cluster_survives`, which
10514    ///   reads [`FrameUniforms::camera_position`] and asks which way a cluster
10515    ///   faces *relative to the viewer*. That question is about the eye the
10516    ///   picture is drawn from, not the eye it was selected for; frozen, a
10517    ///   reviewer who flew round to the other side of the face would have every
10518    ///   cluster now facing them rejected for facing away from a viewpoint
10519    ///   nobody is standing at. It stays live.
10520    ///
10521    /// The split is not new. `DrawGenParams::camera_position` and
10522    /// [`FrameUniforms::camera_position`] are already separate fields carrying
10523    /// different values on a shadow cascade — that one holds the sun while this
10524    /// one stays the camera, because detail is denominated in the camera's
10525    /// pixels and facing is asked about the light. This freezes the same seam
10526    /// from the other side, and needs no new binding, no new shader input and no
10527    /// shader change of any kind.
10528    ///
10529    /// # It freezes the cascades' selection too
10530    ///
10531    /// [`begin_frame`](Self::begin_frame) hands the same eye to every shadow
10532    /// cascade's draw generator, because a cascade selects detail for the
10533    /// *camera* — see [`SHADOW_LOD_BIAS`]. A frozen camera cut over a live
10534    /// shadow cut would be a shadow silhouette sliding under a fixed one, which
10535    /// is a difference in the picture that belongs to neither.
10536    ///
10537    /// # The heatmap reads the live eye, and says so
10538    ///
10539    /// [`set_heatmap`](Self::set_heatmap) shades a cluster by its producing
10540    /// group's projected error, computed in the mesh stage from
10541    /// [`FrameUniforms::camera_position`] — the eye that stays live. So under a
10542    /// frozen selection the two overlays answer different questions: the cut is
10543    /// the one chosen at the pinned eye, and the heat is what the error would be
10544    /// if it were chosen from here now. That is readable — flying towards the
10545    /// face brightens the clusters the frozen cut is not refining, which is the
10546    /// selection's sensitivity made visible — but it does mean the ramp's
10547    /// contours stop coinciding with the level boundaries while frozen.
10548    /// [`set_lod_view`](Self::set_lod_view) is the overlay that composes
10549    /// unconditionally: a cluster's level is a property of the cut and of
10550    /// nothing else.
10551    ///
10552    /// Carrying the pinned eye into the mesh stage as well would need a second
10553    /// position in the frame block, which is a new shader input in every backend
10554    /// for one overlay's benefit; `docs/backlog.md` holds that trade-off.
10555    ///
10556    /// [`FrameUniforms::camera_position`]: crcbl_shaders::mesh::FrameUniforms::camera_position
10557    pub const fn set_frozen_selection_eye(&mut self, eye: Option<Vec3>) {
10558        self.frozen_selection_eye = eye;
10559    }
10560
10561    /// Where the selection is pinned, or [`None`] while it follows the camera.
10562    ///
10563    /// The read-back half of
10564    /// [`set_frozen_selection_eye`](Self::set_frozen_selection_eye), and what a
10565    /// debug panel says "frozen at" out of — "frozen" without the position is a
10566    /// row nobody can act on.
10567    #[must_use]
10568    pub const fn frozen_selection_eye(&self) -> Option<Vec3> {
10569        self.frozen_selection_eye
10570    }
10571
10572    /// Which of the debug views the next frame will actually draw.
10573    ///
10574    /// **The one place the precedence is decided**, and every other statement of
10575    /// it in this crate reads it back from here. The switches ride in one float
10576    /// lane of the frame block — see
10577    /// [`FrameUniforms::HEATMAP_VIEW_ON`](crcbl_shaders::mesh::FrameUniforms::HEATMAP_VIEW_ON)
10578    /// — and the shaders test the outermost threshold first, so a sentinel for
10579    /// an outer view clears every threshold below it. Resolving here rather than
10580    /// letting each caller guess is what stops "which view is on" being answered
10581    /// differently by a menu row, a debug panel and the picture.
10582    #[must_use]
10583    pub const fn debug_view(&self) -> DebugView {
10584        if self.bent_normal_view {
10585            DebugView::BentNormal
10586        } else if self.motion_view {
10587            DebugView::Motion
10588        } else if self.occlusion_view {
10589            DebugView::AmbientOcclusion
10590        } else if self.heatmap {
10591            DebugView::Heatmap
10592        } else if self.lod_view {
10593            DebugView::LodTint
10594        } else if self.normals_view {
10595            DebugView::Normals
10596        } else if self.atlas_view {
10597            // **Below every view above it, and above the tint below.**
10598            //
10599            // Below, because every branch before this one is a question about
10600            // the *picture* — a cluster's error, a surface's normal, the
10601            // occlusion channel — and this one is not a picture of the scene at
10602            // all. A caller who left the atlas up and then asked for normals has
10603            // asked to look at the frame again, and the frame is what the branch
10604            // above draws; the atlas is one keystroke away and is not lost by
10605            // being deferred to.
10606            //
10607            // Above, because the cascade tint multiplies the shaded picture and
10608            // this replaces it: a tint on a frame the atlas overwrote would be a
10609            // tint on the atlas, which is a colour standing for nothing.
10610            DebugView::ShadowAtlas
10611        } else if self.cascade_view {
10612            // **Innermost, and the only view that sits below the others rather
10613            // than above them.** Every branch before this one draws something
10614            // *instead of* the shaded picture and returns before the shading; a
10615            // cascade tint is a multiply on that shading, so there is nothing
10616            // for it to modulate while one of them is showing and a caller with
10617            // both on has asked for the picture the outer one draws. The lane
10618            // says the same thing from the other end — the cascade sentinel is
10619            // negative, so it clears none of the shaders' thresholds — and
10620            // `crcbl_shaders`'
10621            // `the_cascade_view_threshold_lies_below_every_replacing_view` is
10622            // what holds that half.
10623            DebugView::Cascades
10624        } else {
10625            DebugView::Shaded
10626        }
10627    }
10628
10629    /// [`debug_view`](Self::debug_view) as the value the frame block's lane
10630    /// carries.
10631    const fn debug_view_lane(&self) -> f32 {
10632        match self.debug_view() {
10633            DebugView::BentNormal => mesh::FrameUniforms::BENT_NORMAL_VIEW_ON,
10634            DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
10635            DebugView::AmbientOcclusion => mesh::FrameUniforms::OCCLUSION_VIEW_ON,
10636            DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
10637            DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
10638            DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
10639            DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
10640            // **The off sentinel, and it is not an omission.** This view is a
10641            // pass rather than a branch in `mesh.slang` — see
10642            // [`crate::atlas_view`] — so the colour pass draws exactly the
10643            // shaded picture it always drew and the pass afterwards replaces it.
10644            // A lane of its own would be a threshold no shader tests.
10645            DebugView::ShadowAtlas | DebugView::Shaded => mesh::FrameUniforms::NORMALS_VIEW_OFF,
10646        }
10647    }
10648
10649    /// Whether the colour pass draws world-space normals instead of shading.
10650    ///
10651    /// The read-back half of [`set_normals_view`](Self::set_normals_view), on
10652    /// [`wireframe`](Self::wireframe)'s terms: what it draws is what the question
10653    /// is about.
10654    #[must_use]
10655    pub const fn normals_view(&self) -> bool {
10656        self.normals_view
10657    }
10658
10659    /// The cull and draw-argument passes, and the buffers they produce.
10660    ///
10661    /// What a caller reads the culling statistics out of — topic 03 §3.6's
10662    /// delayed readback ring is [`DrawGen::visible_count`] — and what
10663    /// `crcbl-vk`'s end-to-end suite copies back to check the generated
10664    /// arguments against the draws this pass used to record itself.
10665    #[must_use]
10666    pub const fn draws(&self) -> &DrawGen {
10667        &self.primary.draws
10668    }
10669
10670    /// `frame`'s auto-exposure measurement: the bins the histogram pass filled
10671    /// and the exposure the reduce wrote out of them.
10672    ///
10673    /// What `crcbl`'s `mesh_e2e` copies back to check the histogram bin by bin
10674    /// against `crcbl_shaders::exposure`, on [`draws`](Self::draws)' terms — see
10675    /// [`ExposureBuffers`]. Both hold whatever the last frame that measured left
10676    /// there, so a frame drawn without
10677    /// [`RenderEffects::AUTO_EXPOSURE`](crate::RenderEffects::AUTO_EXPOSURE)
10678    /// hands back the frame before it rather than nothing.
10679    ///
10680    /// # Panics
10681    ///
10682    /// If `frame` is not a slot this renderer was built with.
10683    #[must_use]
10684    pub fn exposure_buffers(&self, frame: usize) -> ExposureBuffers {
10685        self.primary.auto_exposure.buffers(frame)
10686    }
10687
10688    /// `frame`'s froxel column: the buffers the froxel volume's
10689    /// three passes write, and the block they read.
10690    ///
10691    /// What `crcbl`'s `mesh_e2e` copies back to check the column froxel by
10692    /// froxel against `crcbl_shaders::volumetric`, on
10693    /// [`draws`](Self::draws)' terms — see [`FroxelBuffers`].
10694    ///
10695    /// # Panics
10696    ///
10697    /// If `frame` is not a slot this renderer was built with.
10698    #[must_use]
10699    pub fn froxel_buffers(&self, frame: usize) -> FroxelBuffers {
10700        self.primary.volumetric.buffers(frame)
10701    }
10702
10703    /// The three layers a caller supplies to the toggle resolution order — see
10704    /// [`crate::effects`].
10705    ///
10706    /// Read back rather than only written, so a caller changing one layer does
10707    /// not have to remember the other two: take this, edit the field it owns,
10708    /// hand it back to [`set_effect_request`](Self::set_effect_request).
10709    #[must_use]
10710    pub const fn effect_request(&self) -> EffectRequest {
10711        self.effect_request
10712    }
10713
10714    /// Replaces all three requested layers, and resolves them at the next
10715    /// [`begin_frame`](Self::begin_frame).
10716    ///
10717    /// **The frame in flight does not move.** `begin_frame` freezes what it
10718    /// resolved and [`add_passes`](Self::add_passes) records that, because the
10719    /// two halves of a frame have to agree about which culls were parametrised:
10720    /// `begin_frame` skips a shadow cull's parameter write when shadows are off
10721    /// and `add_passes` skips its dispatch, and a request landing between the two
10722    /// would dispatch a cull against numbers nothing zeroed.
10723    pub const fn set_effect_request(&mut self, request: EffectRequest) {
10724        self.effect_request = request;
10725    }
10726
10727    /// Replaces the **camera** layer with what `stack` asks for, and leaves the
10728    /// other three where they are.
10729    ///
10730    /// The file half of [`crate::stack`] reaching the renderer: a view that has
10731    /// a render stack writes it here, and the player's `[engine.video]` clamp,
10732    /// the antialiasing rung they picked and any programmatic override are
10733    /// untouched — which is the property that makes the four layers four rather
10734    /// than one. A caller that wants to move more than this layer builds an
10735    /// [`EffectRequest`] and uses
10736    /// [`set_effect_request`](Self::set_effect_request).
10737    ///
10738    /// **The frame in flight does not move**, on `set_effect_request`'s terms
10739    /// and for its reason: this writes the request and
10740    /// [`begin_frame`](Self::begin_frame) is what resolves it.
10741    pub const fn set_camera_stack(&mut self, stack: &CameraStack) {
10742        self.effect_request.camera = stack.compile();
10743    }
10744
10745    /// What the frame the last [`begin_frame`](Self::begin_frame) opened draws.
10746    ///
10747    /// The resolved set, not a layer: every effect in it has survived the
10748    /// camera's stack, the player's quality clamp, any programmatic override and
10749    /// the device — which is the one question a test asking "did this frame have
10750    /// shadows in it" wants answered.
10751    ///
10752    /// [`RenderEffects::all`] before the first frame, which is what a renderer
10753    /// nobody has changed would draw.
10754    #[must_use]
10755    pub const fn effects(&self) -> RenderEffects {
10756        self.frame_effects
10757    }
10758
10759    /// What a frame begun **now** would draw: the whole order applied to the
10760    /// current request.
10761    ///
10762    /// [`effects`](Self::effects)' question one frame earlier, and the one a
10763    /// caller reporting its own configuration wants — a debug panel built at
10764    /// startup has no frame behind it yet, and printing what the last one drew
10765    /// would print a default.
10766    ///
10767    /// **A debug view takes the antialiasing resolve off** — either tier of it
10768    /// — whatever the four layers said. Those views are readouts rather than
10769    /// pictures — a pixel's colour *is* the cluster's projected error or its
10770    /// DAG level, read back against a legend — and a filter that blends two
10771    /// clusters' shades invents a ramp position no cluster occupies.
10772    /// `apps/quarry`'s heatmap and LOD tests are the consumers that count a
10773    /// frame's distinct colours.
10774    #[must_use]
10775    pub fn resolved_effects(&self) -> RenderEffects {
10776        let resolved = self.effect_request.resolve(self.device_effects);
10777        if matches!(self.debug_view(), DebugView::Shaded) {
10778            resolved
10779        } else {
10780            // **Both tiers**, because the slot is what a readout cannot have
10781            // rather than one filter in particular.
10782            resolved.difference(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2))
10783        }
10784    }
10785
10786    /// Which tonemap operator the next frame runs:
10787    /// [`tonemap_curve`](Self::tonemap_curve)'s answer for a shaded frame, and
10788    /// the clamp for a readout.
10789    ///
10790    /// **[`resolved_effects`](Self::resolved_effects)' argument, applied to the
10791    /// operator instead of to the resolve.** A debug view's pixels *are* data —
10792    /// an encoded normal, an occlusion channel, a cascade's colour code — and a
10793    /// curve is a monotone remapping of every one of them. `apps/alcove`'s
10794    /// `--bent-view` reads a normal back and compares it against the geometry's
10795    /// own, which under ACES is 49 code values out; the clamp is the identity on
10796    /// `0..=1`, so it is the operator that leaves a readout readable. A caller
10797    /// that wants a curved readout has none, deliberately: there is no reading
10798    /// it would make easier.
10799    #[must_use]
10800    pub const fn resolved_tonemap_curve(&self) -> tonemap::TonemapCurve {
10801        if matches!(self.debug_view(), DebugView::Shaded) {
10802            self.tonemap_curve
10803        } else {
10804            tonemap::TonemapCurve::Clamp
10805        }
10806    }
10807
10808    /// Which effects this **device** permits, which is the fourth layer and
10809    /// clamps last.
10810    ///
10811    /// Every one of them today — see [`ForwardRenderer::device_effects`], which
10812    /// is where that is argued per effect rather than asserted.
10813    #[must_use]
10814    pub const fn device_effects(&self) -> RenderEffects {
10815        self.device_effects
10816    }
10817
10818    /// Which [`GeometryPath`] this renderer was **built for** — not what the
10819    /// device reports, but what it actually built.
10820    ///
10821    /// The device may prefer a path below its capability ceiling when a higher
10822    /// one uses emulation. This reports the preference actually built, rather
10823    /// than the ceiling: [`GeometryPath::MeshShader`] here means
10824    /// `build` created a mesh pipeline out of `mesh_cluster.slang` and its
10825    /// cluster buffers, and created **no** raster pipeline for the pass to fall
10826    /// back to. So a frame this renderer drew came out of a mesh stage, and a
10827    /// silent degradation is not a state it has — which is the claim a golden
10828    /// image on its own could never make, because a fall-through draws the same
10829    /// picture.
10830    #[must_use]
10831    pub const fn geometry_path(&self) -> GeometryPath {
10832        match self.emit {
10833            EmitTail::Mesh => GeometryPath::MeshShader,
10834            EmitTail::Count => GeometryPath::IndirectCount,
10835            EmitTail::PerBatch => GeometryPath::IndirectPerBatch,
10836        }
10837    }
10838
10839    /// Whether this renderer **built** §3.5's per-cluster cull — an
10840    /// amplification stage in front of the mesh stage, rejecting a surviving
10841    /// instance's back-facing and off-screen clusters.
10842    ///
10843    /// `false` on the two indirect tails, which draw index ranges and have no
10844    /// stage to put it in, and on a device with `Features::MESH_SHADER` and no
10845    /// `Features::TASK_SHADER` — a real and supported state, not a degradation:
10846    /// that device draws every cluster of every surviving instance and the
10847    /// picture is the same one.
10848    ///
10849    /// The instance cull runs on every path either way, and is unaffected by
10850    /// this.
10851    ///
10852    /// It is asked of the renderer rather than of the device for
10853    /// [`ForwardRenderer::geometry_path`]'s reason: this reports what was
10854    /// built, so `true` means
10855    /// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count)'s
10856    /// cluster word is a number the frame produced rather than the zero the
10857    /// clearing pass left.
10858    #[must_use]
10859    pub const fn culls_clusters(&self) -> bool {
10860        self.culls_clusters
10861    }
10862
10863    /// Whether this renderer can choose **which level** of a
10864    /// [`Geometry::Dag`] mesh an object is drawn at, and therefore whether
10865    /// [`ForwardRenderer::add_instance`] may be given one at all.
10866    ///
10867    /// Topic 25's selection happens in the amplification stage where
10868    /// there is one, and in the cull pass where the tail is indirect and a level
10869    /// is an ordinary index range. **One device shape has neither**: a mesh stage
10870    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
10871    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) draws through
10872    /// `mesh_cluster.slang`'s un-amplified `meshMain`, which emits every cluster
10873    /// of the bucket — and a DAG's bucket is every level end to end, so the frame
10874    /// is several overlapping copies of one surface. That is a real and supported
10875    /// device state rather than a degradation, so this reports it instead of
10876    /// refusing to build.
10877    ///
10878    /// A [`Geometry::Flat`] mesh is one level and is unaffected: its clusters
10879    /// carry [`ClusterSelect::ALWAYS`] and every path draws it from every camera,
10880    /// which is why this is asked only before placing a DAG.
10881    ///
10882    /// Asked of the renderer rather than of the device for
10883    /// [`ForwardRenderer::culls_clusters`]' reason: it reports what was built.
10884    ///
10885    /// [`ClusterSelect::ALWAYS`]: crcbl_shaders::cluster_select::ClusterSelect::ALWAYS
10886    #[must_use]
10887    pub const fn selects_levels(&self) -> bool {
10888        !self.emit.is_mesh() || self.culls_clusters
10889    }
10890
10891    /// Which frame-in-flight slot the last [`ForwardRenderer::begin_frame`]
10892    /// rotated to, which is the slot every per-frame buffer is indexed by.
10893    #[must_use]
10894    pub const fn frame(&self) -> usize {
10895        self.frame
10896    }
10897
10898    /// What the last [`add_passes`](Self::add_passes) recorded, and what it
10899    /// cannot know.
10900    ///
10901    /// Zero draws until a frame has been built: this reports what was recorded,
10902    /// not what a frame would record.
10903    ///
10904    /// # The triangles are [`None`] here, on every geometry path
10905    ///
10906    /// Every draw this renderer records except the full-screen passes' and the
10907    /// debug draw layer's is **indirect**:
10908    /// the instance count and the index range live in the argument buffer
10909    /// `draw_gen.slang` wrote, so the CPU records the call and learns nothing
10910    /// about what it covered. That is true of
10911    /// [`GeometryPath::MeshShader`] and of
10912    /// both indirect tails alike — the three differ in which call is recorded,
10913    /// not in who decides the counts — so
10914    /// [`FrameCounters::triangles`](crate::counters::FrameCounters::triangles)
10915    /// is [`None`] whatever the device supports. Nothing counts a triangle on
10916    /// the GPU either, and a cluster count times a nominal triangles-per-cluster
10917    /// would read as authoritative and be neither.
10918    ///
10919    /// # The instances drawn come back off the GPU, a few frames late
10920    ///
10921    /// [`FrameCounters::drawn`](crate::counters::FrameCounters::drawn) is
10922    /// `cull.slang`'s survivor count, off [`crate::cull_stats`]'s delayed ring,
10923    /// plus the frame's direct draws — the ones here whose instance the CPU
10924    /// knows about, and the ones that are also in
10925    /// [`instances`](crate::counters::FrameCounters::instances). So the pair is
10926    /// comparable: the same quantity submitted and kept.
10927    ///
10928    /// **The camera's cull alone.** The shadow culls test other frustums and
10929    /// their survivors are counted into buffers of their own; adding them here
10930    /// would give a "drawn" larger than "submitted" on any frame with a shadow
10931    /// in it.
10932    ///
10933    /// It is [`None`] — the row says `indirect` — for the first few frames of a
10934    /// renderer's life, while the ring has not come round, and for good on a
10935    /// device that would not give out a readback.
10936    /// [`cull_frame`](crate::counters::FrameCounters::cull_frame) is which frame
10937    /// the number is about whenever there is one.
10938    ///
10939    /// [`FrameCounters::instances`](crate::counters::FrameCounters::instances)
10940    /// is known and is the plan's "submitted" half: the live instances
10941    /// [`add_passes`](Self::add_passes) hands the cull dispatches, plus the
10942    /// frame's direct draws — every full-screen pass's triangle and the debug
10943    /// draw layer's line list.
10944    #[must_use]
10945    pub fn counters(&self) -> FrameCounters {
10946        if self.recorded_draws == 0 {
10947            return FrameCounters::default();
10948        }
10949        let stats = self.cull_stats();
10950        let direct = self.direct_draws();
10951        FrameCounters {
10952            draws: self.recorded_draws,
10953            instances: self.instances.len() as u64 + direct,
10954            // Each direct draw is submitted and drawn, and none of them is in
10955            // the cull's count — they are draws of one instance, added on both
10956            // sides so the two halves of the row measure the same thing. Off the
10957            // frame that *was* recorded rather than off a constant, so a frame
10958            // with an effect switched off does not count a triangle it never
10959            // submitted.
10960            // Less what the occlusion cull's second phase rejected, which were
10961            // survivors of the frustum and were not drawn.
10962            drawn: stats
10963                .map(|stats| stats.instances.saturating_sub(stats.occlusion.late_rejects) + direct),
10964            triangles: None,
10965            // The survivors alone: the panel row is "clusters drawn", and the
10966            // frustum and cone rejection counts beside them are a different
10967            // question — `CullStats::clusters` carries all three for a caller
10968            // that wants the split, which `apps/quarry`'s own panel row is.
10969            clusters: stats
10970                .and_then(|stats| stats.clusters)
10971                .map(|cull| cull.survivors),
10972            cull_frame: stats.map(|stats| stats.frame),
10973        }
10974    }
10975
10976    /// The draws this renderer records **directly** — the ones whose instance
10977    /// the CPU knows about, as opposed to the indirect calls whose counts live
10978    /// in a buffer a shader wrote.
10979    ///
10980    /// Every full-screen pass's over-sized triangle, plus the debug draw
10981    /// layer's line list on a frame that has one. One instance each, which is
10982    /// why [`counters`](Self::counters) adds this to both halves of its
10983    /// submitted/drawn pair.
10984    fn direct_draws(&self) -> u64 {
10985        self.recorded_fullscreen * FULLSCREEN_DRAWS
10986            + self.recorded_debug_draw
10987            + self.recorded_tile_clears
10988            + self.recorded_water_draws
10989    }
10990
10991    /// What the camera's cull kept, on the frame the ring has reached.
10992    ///
10993    /// Topic 03 §3.6's one permitted readback, and [`None`] until it has come
10994    /// round — see [`crate::cull_stats`] for the latency and for what makes it
10995    /// free of any wait. [`counters`](Self::counters) is where this reaches the
10996    /// panel; it is exposed on its own because the frame number and the cluster
10997    /// word are both things a test asserts about directly.
10998    #[must_use]
10999    pub fn cull_stats(&self) -> Option<crate::cull_stats::CullStats> {
11000        self.cull_stats.as_ref().and_then(CullStatsRing::latest)
11001    }
11002
11003    /// Describes the imported swapchain image the frame ends in.
11004    ///
11005    /// A helper rather than something every caller writes, because getting
11006    /// `initial`/`final_state` wrong is exactly the hand-written barrier this
11007    /// slice removed: an acquired image's contents are undefined, and the
11008    /// compositor may only be handed one in [`ResourceState::Present`].
11009    #[must_use]
11010    pub fn present_target(
11011        image: crcbl_hal::ImageHandle,
11012        view: ImageViewHandle,
11013        format: Format,
11014        extent: (u32, u32),
11015    ) -> ImportedImage {
11016        ImportedImage {
11017            image,
11018            view,
11019            format,
11020            extent,
11021            initial: ResourceState::Undefined,
11022            // The acquire's semaphore, not a barrier, is what orders this frame
11023            // after the last use of the image — which is what makes `Undefined`
11024            // honest here and what makes it uncheckable. See `InitialClaim`.
11025            claim: InitialClaim::Acquired,
11026            final_state: ResourceState::Present,
11027        }
11028    }
11029
11030    /// Releases everything, in dependency order. The device must be idle.
11031    ///
11032    /// The start-up uploads are waited for first all the same: a renderer
11033    /// destroyed before any frame has a build batch nothing else has waited
11034    /// for, and its copies write the placeholders and fills released below.
11035    pub fn destroy(mut self, device: &dyn Device) {
11036        self.wait_for_uploads(device, "destroy");
11037        if let Some(stats) = self.cull_stats {
11038            stats.destroy(device);
11039        }
11040        // The cameras first: their groups name the scene's buffers, pages and
11041        // atlas below, and they own nothing the scene's groups name.
11042        for view in self.views.into_iter().flatten() {
11043            view.destroy(device);
11044        }
11045        self.primary.destroy(device);
11046        // After every view, whose grass and water groups name these buffers.
11047        self.grass.destroy(device);
11048        self.water.destroy(device);
11049        device.destroy_sampler(self.sampler);
11050        device.destroy_graphics_pipeline(self.tonemap_pipeline);
11051        device.destroy_pipeline_layout(self.tonemap_pipeline_layout);
11052        device.destroy_bind_group_layout(self.tonemap_layout);
11053
11054        let depth_and_rsm = [
11055            Some(self.shadow_pipeline),
11056            self.depth_masked_pipeline,
11057            self.rsm_pipeline,
11058        ];
11059        for pipeline in depth_and_rsm
11060            .into_iter()
11061            .flatten()
11062            .flat_map(SidedPipelines::handles)
11063        {
11064            device.destroy_graphics_pipeline(pipeline);
11065        }
11066        device.destroy_graphics_pipeline(self.shadow_clear_pipeline);
11067        for groups in self.shadow_groups {
11068            for group in groups {
11069                device.destroy_bind_group(group);
11070            }
11071        }
11072        for buffers in self.shadow_uniforms {
11073            for buffer in buffers {
11074                device.destroy_buffer(buffer);
11075            }
11076        }
11077        for buffers in self.shadow_selection {
11078            for buffer in buffers {
11079                device.destroy_buffer(buffer);
11080            }
11081        }
11082        for draws in self.shadow_draws {
11083            draws.destroy(device);
11084        }
11085        // After every generator: the cameras' above and the shadow culls'.
11086        DrawGenPipelines::release(self.draw_pipelines, device);
11087        device.destroy_sampler(self.shadow_sampler);
11088        device.destroy_image_view(self.shadow_atlas_view);
11089        device.destroy_image(self.shadow_atlas);
11090        device.destroy_image_view(self.shadow_placeholder_view);
11091        device.destroy_image(self.shadow_placeholder);
11092
11093        if let Some(grid) = self.ground_grid {
11094            grid.destroy(device);
11095        }
11096        // Nothing to release on a renderer nobody drew a segment through — see
11097        // [`crate::debug_draw`], whose pipeline is built on first use.
11098        self.debug_draw.destroy(device);
11099        if let Some(atlas_viewer) = self.atlas_viewer {
11100            atlas_viewer.destroy(device);
11101        }
11102        self.ambient_occlusion_placeholder.destroy(device);
11103        self.contact_shadow_placeholder.destroy(device);
11104        self.probe_visibility_placeholder.destroy(device);
11105        if let Some(captured) = self.probe_visibility {
11106            captured.destroy(device);
11107        }
11108        self.specular_dfg.destroy(device);
11109        self.ltc_table.destroy(device);
11110        self.normal_page.destroy(device);
11111        self.mro_page.destroy(device);
11112        self.emissive_page.destroy(device);
11113
11114        // The wireframe pair is released here and nowhere else —
11115        // `set_wireframe(.., false)` deliberately is not, because this call is
11116        // the one that requires an idle device.
11117        let colour = [Some(self.mesh_pipeline), self.wireframe_pipeline];
11118        for pipeline in colour
11119            .into_iter()
11120            .flatten()
11121            .flat_map(SidedPipelines::handles)
11122        {
11123            device.destroy_graphics_pipeline(pipeline);
11124        }
11125        device.destroy_pipeline_layout(self.mesh_pipeline_layout);
11126        device.destroy_bind_group_layout(self.mesh_layout);
11127        self.base_color_page.destroy(device);
11128        device.destroy_sampler(self.base_color_sampler);
11129        for retired in self.retired_pages {
11130            retired.destroy(device);
11131        }
11132        device.destroy_buffer(self.draw_constants);
11133        if let Some(clusters) = self.clusters {
11134            clusters.destroy(device);
11135        }
11136        // Before the probe table, because its bind groups name that table's
11137        // rows — the same ordering the light grid is under above.
11138        if let Some(gather) = self.probe_gather {
11139            gather.destroy(device);
11140        }
11141        self.probes.destroy(device);
11142        self.materials.destroy(device);
11143        self.instances.destroy(device);
11144        self.pool.destroy(device);
11145    }
11146}
11147
11148/// What the shadow pass a frame recorded would leave the image holding, held
11149/// until the frame after can say whether its body ran.
11150///
11151/// Topic 45's static-caching rung, per group: recording a pass
11152/// is not drawing one, so nothing here is believed until
11153/// [`ForwardRenderer::shadow_pass_ran`] carries this [`ShadowCommit::id`] back
11154/// out of the graph.
11155#[derive(Clone, Debug)]
11156struct ShadowCommit {
11157    /// The [`ForwardRenderer::shadow_pass_id`] the body publishes.
11158    id: u64,
11159    /// `[group]`: what the group's entry of
11160    /// [`ForwardRenderer::shadow_group_held`] becomes for every group the pass
11161    /// redraws, and [`None`] for the groups it holds.
11162    groups: Vec<Option<(u64, Vec3, f32)>>,
11163    /// The layout the pass draws under, where it clears the whole attachment —
11164    /// and [`None`] where it loads, because a loading pass leaves every tile it
11165    /// does not redraw exactly as it found it.
11166    layout: Option<Vec<shadow::TileRect>>,
11167}
11168
11169/// The shader modules a mesh pipeline is built from, with its entry points
11170/// already resolved.
11171///
11172/// **A type rather than a run of locals in `build`** because there are now two
11173/// callers: `build`, which makes the colour pipeline and its depth-only twin,
11174/// and [`ForwardRenderer::set_wireframe`], which makes the colour pipeline again
11175/// in [`PolygonMode::Line`] long after `build` released its modules. The
11176/// alternative was a second copy of a descriptor that names two modules, their
11177/// entry points, the colour targets and a depth state — the pair that drifts.
11178///
11179/// Short-lived: created, used to build pipelines, and [`MeshModules::destroy`]ed
11180/// in the same function. A module is not needed once the pipeline exists.
11181struct MeshModules {
11182    /// `mesh.slang`'s module — the vertex stage on the indirect path, and the
11183    /// fragment stage on both.
11184    mesh: ShaderModuleHandle,
11185    /// `vertexMain`, unused on the mesh-shader path.
11186    vertex: &'static str,
11187    /// `depthVertexMain`, which [`MeshModules::depth_pipeline`] takes in
11188    /// [`MeshModules::vertex`]'s place: the same transform off stream 0 of the
11189    /// vertex pool and no attribute region at all. Unused on the mesh-shader
11190    /// path, where the geometry stage is `mesh_cluster.slang`'s either way.
11191    depth_vertex: &'static str,
11192    /// `depthClearVertexMain`, which [`MeshModules::depth_clear_pipeline`]
11193    /// builds the tile clear from: three corners off `SV_VertexID` and no input
11194    /// at all, so it resets one tile of the atlas without reading a vertex.
11195    ///
11196    /// **The same stage on every path**, unlike the two above: a device with a
11197    /// mesh stage still has a vertex stage, and a clear that produced no
11198    /// geometry is a primitive, not a cluster.
11199    depth_clear_vertex: &'static str,
11200    fragment: &'static str,
11201    /// `depthMaskedFragmentMain`, which [`MeshModules::depth_masked_pipeline`]
11202    /// puts *behind* [`MeshModules::vertex`] — the alpha mask and no target at
11203    /// all.
11204    ///
11205    /// **The same stage on both paths**, unlike the two vertex entry points
11206    /// above: it reads `mesh.slang`'s own `VertexOutput`, which is what
11207    /// `vertexMain` writes on the raster path and what `mesh_cluster.slang`'s
11208    /// mesh stage writes on the mesh one. So the cutout is one comparison in one
11209    /// place rather than one per geometry path.
11210    depth_masked_fragment: &'static str,
11211    /// `rsmFragmentMain`, which [`MeshModules::rsm_pipeline`] takes in
11212    /// [`MeshModules::fragment`]'s place: the same geometry stage, three targets
11213    /// describing the surface rather than shading it.
11214    ///
11215    /// **The reason the shaded stage above is looked up by name.** A module with
11216    /// two fragment entry points has no unambiguous one, which is what `entry`
11217    /// answers `None` for.
11218    rsm_fragment: &'static str,
11219    /// `mesh_cluster.slang`'s, on the mesh-shader path alone.
11220    cluster: Option<ClusterStages>,
11221}
11222
11223/// The geometry half of a mesh-shader pipeline: `mesh_cluster.slang`'s module
11224/// and the stages taken out of it.
11225struct ClusterStages {
11226    /// The module the mesh stage is built from, and the one the task stage is,
11227    /// which are **two modules rather than one**.
11228    ///
11229    /// `mesh_cluster.slang` compiles to a combined module carrying every entry
11230    /// point and to one module per stage, and these are the per-stage ones. A
11231    /// module holding a task entry point and its mesh partner carries two
11232    /// `TaskPayloadWorkgroupEXT` variables — the task writes one, the mesh stage
11233    /// reads the other — and an NVIDIA driver then delivers a payload of zeroes,
11234    /// which draws cluster 0 of instance slot 0 of every bucket and nothing
11235    /// else. See `crcbl_shaders::EntryPoint`.
11236    mesh_module: ShaderModuleHandle,
11237    /// The task stage's own module, on the same terms. [`None`] exactly when
11238    /// [`task`](Self::task) is.
11239    task_module: Option<ShaderModuleHandle>,
11240    /// Which of the module's two mesh entry points this path builds — the
11241    /// amplified one where the device has a task stage to feed it.
11242    mesh: &'static str,
11243    /// §3.5's per-cluster cull, where the device has the stage to run it in.
11244    /// [`None`] is not a degradation: `meshMain` draws the same picture out of
11245    /// the same clusters, having rejected none of them, which is what a device
11246    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
11247    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) gets.
11248    task: Option<&'static str>,
11249}
11250
11251impl MeshModules {
11252    /// **Three targets, one fragment stage.** `mesh.slang`'s `FragmentOutput`
11253    /// writes the shaded colour, then topic 47's
11254    /// reflectivity channel, then topic 43 §9's motion
11255    /// vector — and both pipeline shapes name that same entry point, so each
11256    /// target is one more element of this array and not a second pipeline, a
11257    /// second entry point or a new interpolant. The refusal the AO section
11258    /// records was about the depth prepass, which has no fragment stage and no
11259    /// colour target at all; it does not reach this array.
11260    ///
11261    /// Element order is `SV_Target` order, and each format is the one the
11262    /// matching `TransientImageDesc` creates: a pipeline built for a format the
11263    /// attachment is not in is a validation error on WebGPU and a silent
11264    /// reinterpretation elsewhere.
11265    const COLOR_TARGETS: [ColorTargetState; 3] = [
11266        ColorTargetState::opaque(Format::Rgba16Float),
11267        ColorTargetState::opaque(Format::Rgba8Unorm),
11268        ColorTargetState::opaque(MOTION_FORMAT),
11269    ];
11270
11271    /// **Three targets again, and a different three.** `mesh.slang`'s
11272    /// `RsmOutput` writes the surface's diffuse albedo, its world normal encoded
11273    /// `n * 0.5 + 0.5`, and its world position with a coverage flag in `w` —
11274    /// which is what the irradiance probes' gather needs of a
11275    /// texel and nothing more.
11276    ///
11277    /// Element order is `SV_Target` order and each format is the one the
11278    /// matching description in [`crate::rsm`] creates: a pipeline built for a
11279    /// format the attachment is not in is a validation error on WebGPU and a
11280    /// silent reinterpretation elsewhere. `the_targets_carry_the_formats_the_shader_writes`
11281    /// in that module is the other half of the pair.
11282    const RSM_TARGETS: [ColorTargetState; 3] = [
11283        ColorTargetState::opaque(Format::Rgba16Float),
11284        ColorTargetState::opaque(Format::Rgba8Unorm),
11285        ColorTargetState::opaque(Format::Rgba32Float),
11286    ];
11287
11288    /// Invocations per mesh workgroup, which is `mesh_cluster.slang`'s
11289    /// `[numthreads(THREADS, 1, 1)]` — and `THREADS` is
11290    /// `MAX_CLUSTER_VERTICES`, one lane per vertex a cluster can hold.
11291    ///
11292    /// Taken from the crate that owns the shader source rather than written
11293    /// out, as
11294    /// [`MeshPipelineDesc::mesh_workgroup_size`](crcbl_hal::MeshPipelineDesc::mesh_workgroup_size)
11295    /// requires: only Metal reads this field, so a literal that disagreed with
11296    /// the shader would launch the wrong number of threads on one backend and
11297    /// nowhere else.
11298    const MESH_WORKGROUP_SIZE: [u32; 3] =
11299        [crcbl_shaders::meshlet::MAX_CLUSTER_VERTICES as u32, 1, 1];
11300
11301    /// Invocations per task workgroup: `taskMain` is
11302    /// `[numthreads(TASK_LANES, 1, 1)]`, one lane per (cluster, instance slot)
11303    /// pair of its chunk. Taken from the crate that owns the shader, on
11304    /// [`MESH_WORKGROUP_SIZE`](Self::MESH_WORKGROUP_SIZE)'s terms.
11305    const TASK_WORKGROUP_SIZE: [u32; 3] = [crcbl_shaders::meshlet::TASK_LANES, 1, 1];
11306
11307    /// The two cull modes a sided shape is built with, in
11308    /// [`SidedPipelines`]' order: [`single`](SidedPipelines::single) culls
11309    /// back faces, [`double`](SidedPipelines::double) culls nothing.
11310    const SIDES: [CullMode; 2] = [CullMode::Back, CullMode::None];
11311
11312    /// Loads whichever modules `emit` needs and resolves their entry points.
11313    ///
11314    /// # Errors
11315    ///
11316    /// [`HalError::ShaderCompilation`] if the committed manifest names no such
11317    /// entry point, and [`HalError`] from either module. A failure after the
11318    /// first module was created releases it rather than leaking it.
11319    fn new(device: &dyn Device, emit: EmitTail, culls_clusters: bool) -> Result<Self, HalError> {
11320        // Entry points resolved before the module exists: a manifest that
11321        // disagreed with the SPIR-V would otherwise fail inside the descriptor
11322        // literal, with the module already created and nothing holding it.
11323        //
11324        // **The vertex stage is named rather than looked up by stage**, for
11325        // `mesh_cluster.slang`'s reason below: since the depth-only stage landed
11326        // this module has two vertex entry points, and a stage lookup answers
11327        // `None` for two matches. Which of the two a pipeline names is the whole
11328        // of what the split-stream vertex pool bought.
11329        let vertex = named_entry(&MESH, "vertexMain", Stage::Vertex)?;
11330        let depth_vertex = named_entry(&MESH, "depthVertexMain", Stage::Vertex)?;
11331        let depth_clear_vertex = named_entry(&MESH, "depthClearVertexMain", Stage::Vertex)?;
11332        // **Named rather than looked up by stage, on the vertex entry points'
11333        // terms exactly.** Since the irradiance probes' updater
11334        // landed, this module has *two* fragment entry points — the shaded one
11335        // and `rsmFragmentMain` — and `entry` answers `None` for two matches, so
11336        // a stage lookup here refuses the build outright with "exposes no
11337        // unambiguous Fragment entry point".
11338        let fragment = named_entry(&MESH, "fragmentMain", Stage::Fragment)?;
11339        let depth_masked_fragment = named_entry(&MESH, "depthMaskedFragmentMain", Stage::Fragment)?;
11340        let rsm_fragment = named_entry(&MESH, "rsmFragmentMain", Stage::Fragment)?;
11341        // **Named rather than looked up by stage**, because the module has two
11342        // mesh entry points and a stage lookup would refuse an ambiguous one —
11343        // see `named_entry`. Which of the two this names is the whole of the
11344        // amplification decision.
11345        let cluster_stages = emit
11346            .is_mesh()
11347            .then(|| {
11348                let mesh = named_entry(
11349                    &MESH_CLUSTER,
11350                    if culls_clusters {
11351                        "amplifiedMeshMain"
11352                    } else {
11353                        "meshMain"
11354                    },
11355                    Stage::Mesh,
11356                )?;
11357                let task = culls_clusters
11358                    .then(|| named_entry(&MESH_CLUSTER, "taskMain", Stage::Task))
11359                    .transpose()?;
11360                Ok::<_, HalError>((mesh, task))
11361            })
11362            .transpose()?;
11363
11364        let mesh = device.create_shader_module(&ShaderModuleDesc {
11365            label: Some("mesh.slang"),
11366            spirv: MESH.spirv(),
11367            wgsl: MESH.wgsl(),
11368            msl: MESH.msl(),
11369            // **Both containers, and still one module.** A DXIL container holds
11370            // exactly one entry point, so this is a list where its three
11371            // neighbours are single artifacts; the backend that consumes it
11372            // picks the container named by the stage it is building. Nothing
11373            // here branches on a backend, and the three that ignore DXIL see
11374            // the same module they always did.
11375            dxil: &MESH.dxil_containers(),
11376        })?;
11377        let cluster = match cluster_stages {
11378            None => None,
11379            Some((cluster_mesh, task)) => {
11380                // **The mesh stage's module is `mesh_cluster.slang`; the
11381                // fragment stage's is still `mesh.slang`'s.** A pipeline takes a
11382                // module per stage, so the shading — Lambert, the GGX lobe, the
11383                // material row, the page sample — is the same code both paths
11384                // run rather than a copy that agrees today.
11385                // `mesh_cluster.slang`'s header carries the argument, and its
11386                // `VertexOutput` is what the two agree through.
11387                // **One module per stage, each carrying that stage's own
11388                // SPIR-V.** Only the SPIR-V differs between them: MSL is one
11389                // artifact per source whatever the stage, and a DXIL container
11390                // is already per entry point, so both are handed over unchanged
11391                // and the backends that read them see what they always did.
11392                let stage_module = |entry_point: &str| {
11393                    device.create_shader_module(&ShaderModuleDesc {
11394                        label: Some("mesh_cluster.slang"),
11395                        // The combined module where this stage has none of its
11396                        // own, which is every stage of every other shader.
11397                        spirv: MESH_CLUSTER
11398                            .spirv_for(entry_point)
11399                            .unwrap_or_else(|| MESH_CLUSTER.spirv()),
11400                        // `None`, and it is the whole reason this is a second
11401                        // file: WGSL cannot express a mesh stage at all.
11402                        wgsl: MESH_CLUSTER.wgsl(),
11403                        msl: MESH_CLUSTER.msl(),
11404                        dxil: &MESH_CLUSTER.dxil_containers(),
11405                    })
11406                };
11407                let mesh_module = match stage_module(cluster_mesh) {
11408                    Ok(module) => module,
11409                    Err(error) => {
11410                        device.destroy_shader_module(mesh);
11411                        return Err(error);
11412                    }
11413                };
11414                let task_module = match task.map(stage_module).transpose() {
11415                    Ok(module) => module,
11416                    Err(error) => {
11417                        device.destroy_shader_module(mesh);
11418                        device.destroy_shader_module(mesh_module);
11419                        return Err(error);
11420                    }
11421                };
11422                Some(ClusterStages {
11423                    mesh_module,
11424                    task_module,
11425                    mesh: cluster_mesh,
11426                    task,
11427                })
11428            }
11429        };
11430        Ok(Self {
11431            mesh,
11432            vertex,
11433            depth_vertex,
11434            depth_clear_vertex,
11435            fragment,
11436            depth_masked_fragment,
11437            rsm_fragment,
11438            cluster,
11439        })
11440    }
11441
11442    /// The rasteriser state every pipeline shape here shares, because the only
11443    /// things that differ between them are which stage produces the geometry and
11444    /// which side of it survives.
11445    ///
11446    /// [`CullMode::Back`] is what a single-sided bucket asks for, and it has
11447    /// been on from the first mesh. The cube's winding is asserted by
11448    /// `crcbl-shaders`' own tests, so a face that vanished would be a *test*
11449    /// failure rather than a debugging session — and a mesh drawn without
11450    /// culling would let a winding mistake survive into P7's geometry pool. The
11451    /// mesh stage emits its corner triples in the index buffer's own order, so
11452    /// the winding it produces is the same one.
11453    ///
11454    /// [`CullMode::None`] is what a double-sided bucket asks for — glTF 2.0
11455    /// §3.9.6's first half — and the twin built with it is the only way a back
11456    /// face reaches `mesh.slang` at all. See [`SidedPipelines`].
11457    fn primitive(polygon_mode: PolygonMode, cull_mode: CullMode) -> PrimitiveState {
11458        PrimitiveState {
11459            cull_mode,
11460            polygon_mode,
11461            ..PrimitiveState::default()
11462        }
11463    }
11464
11465    /// What a pipeline built with `cull` adds to its label, so a capture and
11466    /// `crcbl_hal::null`'s recorder tell a [`SidedPipelines::double`] twin from
11467    /// the [`SidedPipelines::single`] it was built beside.
11468    ///
11469    /// Empty for the culling modes, because those pipelines' labels are the ones
11470    /// every existing capture and every test lookup already names.
11471    fn side_label(cull: CullMode) -> &'static str {
11472        match cull {
11473            CullMode::None => " double-sided",
11474            CullMode::Front | CullMode::Back => "",
11475        }
11476    }
11477
11478    /// Milestone 3's depth test, and the seam's default is already reversed-Z:
11479    /// `Greater` against `D32Float`, writes on. The clear value that agrees with
11480    /// it comes from the graph (`PassBuilder::clear_depth`), and the projection
11481    /// matrix that agrees with **both** comes from [`crate::camera`].
11482    fn depth_stencil() -> Option<DepthStencilState> {
11483        Some(DepthStencilState::default())
11484    }
11485
11486    /// The colour pass's depth state, which is not the same shape as
11487    /// [`MeshModules::depth_stencil`] because the depth prepass has already
11488    /// drawn this geometry.
11489    ///
11490    /// **Filled: [`DepthStencilState::equal_depth_read_only`], so the shading is
11491    /// paid for once per pixel.** The prepass runs the same draws through
11492    /// `depthVertexMain` — or, on the mesh path, through the very same geometry
11493    /// stage — so the depth already in the attachment is this pass's own answer,
11494    /// and a `GreaterOrEqual` test with writes off keeps exactly the fragments
11495    /// that would have won the write. What it removes is the clustered-forward
11496    /// shading of every fragment a nearer one goes on to cover.
11497    ///
11498    /// **Lines: the writing default, because a wireframe is not the geometry the
11499    /// prepass drew.** [`PolygonMode::Line`] rasterises the triangle's edges,
11500    /// and an edge pixel's depth is interpolated along the line rather than
11501    /// across the face, so testing it for equality against a filled prepass
11502    /// rejects most of the wireframe. That frame keeps the pass shape this pass
11503    /// had before the prepass existed — see the colour pass's depth attachment,
11504    /// which branches on the same condition.
11505    fn color_depth_stencil(polygon_mode: PolygonMode) -> Option<DepthStencilState> {
11506        match polygon_mode {
11507            PolygonMode::Fill => Some(DepthStencilState::equal_depth_read_only(Format::D32Float)),
11508            _ => Self::depth_stencil(),
11509        }
11510    }
11511
11512    /// The colour pass's pipeline, filled or wireframe, culling back faces or
11513    /// nothing.
11514    ///
11515    /// `label` names the caller — `"forward"` for the frame's own, `"wireframe"`
11516    /// for [`ForwardRenderer::set_wireframe`]'s — and [`MeshModules::side_label`]
11517    /// names the side, so a capture tells all four apart.
11518    fn color_pipeline(
11519        &self,
11520        device: &dyn Device,
11521        layout: PipelineLayoutHandle,
11522        polygon_mode: PolygonMode,
11523        cull: CullMode,
11524        label: &str,
11525    ) -> Result<GraphicsPipelineHandle, HalError> {
11526        let primitive = Self::primitive(polygon_mode, cull);
11527        let depth_stencil = Self::color_depth_stencil(polygon_mode);
11528        let side = Self::side_label(cull);
11529        let fragment = Some(ShaderEntry {
11530            module: self.mesh,
11531            entry_point: self.fragment,
11532        });
11533        match self.cluster.as_ref() {
11534            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11535                label: Some(&format!("{label}{side} mesh cluster")),
11536                layout,
11537                task: cluster
11538                    .task
11539                    .zip(cluster.task_module)
11540                    .map(|(entry_point, module)| ShaderEntry {
11541                        module,
11542                        entry_point,
11543                    }),
11544                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11545                mesh: ShaderEntry {
11546                    module: cluster.mesh_module,
11547                    entry_point: cluster.mesh,
11548                },
11549                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11550                fragment,
11551                primitive,
11552                depth_stencil,
11553                multisample: MultisampleState::default(),
11554                color_targets: &Self::COLOR_TARGETS,
11555            }),
11556            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11557                label: Some(&format!("{label}{side} mesh")),
11558                layout,
11559                vertex: ShaderEntry {
11560                    module: self.mesh,
11561                    entry_point: self.vertex,
11562                },
11563                fragment,
11564                primitive,
11565                depth_stencil,
11566                multisample: MultisampleState::default(),
11567                color_targets: &Self::COLOR_TARGETS,
11568            }),
11569        }
11570    }
11571
11572    /// The depth-only twin of [`MeshModules::color_pipeline`], built out of the
11573    /// same modules and the same layout: no fragment stage, no colour target,
11574    /// and a vertex stage that fetches stream 0 of the vertex pool alone.
11575    ///
11576    /// **The transform is identical and the fetch is not, which is the point.**
11577    /// Topic 18 asks for a shadow pass "identical on every `GeometryPath` —
11578    /// depth pass plus whatever emit tail the device selected", and what makes
11579    /// that work is a frame block whose `view_proj` is the cascade's matrix
11580    /// rather than a second transform path: a cascade that disagreed with the
11581    /// colour pass about where a vertex is would produce shadows that do not
11582    /// line up with their casters, which is indistinguishable from a bias
11583    /// problem. `depthVertexMain` is that same clip position written the same
11584    /// way, with everything the discarded varyings needed — the attribute
11585    /// region and the previous frame's position — left unread;
11586    /// topic 43 §2 split the pool for exactly this
11587    /// pass, and this is where it is spent.
11588    ///
11589    /// **The mesh-shader path still runs the colour pipeline's geometry
11590    /// stage.** `mesh_cluster.slang` emits one `VertexOutput`, so a depth-only
11591    /// mesh stage is a second entry point in that module and its own rung; a
11592    /// device with a mesh stage goes on reading whole vertices here.
11593    ///
11594    /// Always [`PolygonMode::Fill`]: it fills the shadow atlas and the depth
11595    /// prepass, and depth drawn as lines is depth with holes in it — which the
11596    /// occlusion pair would read as geometry that is not there.
11597    fn depth_pipeline(
11598        &self,
11599        device: &dyn Device,
11600        layout: PipelineLayoutHandle,
11601        cull: CullMode,
11602    ) -> Result<GraphicsPipelineHandle, HalError> {
11603        let primitive = Self::primitive(PolygonMode::Fill, cull);
11604        let side = Self::side_label(cull);
11605        match self.cluster.as_ref() {
11606            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11607                label: Some(&format!("shadow cascade{side} mesh cluster")),
11608                layout,
11609                task: cluster
11610                    .task
11611                    .zip(cluster.task_module)
11612                    .map(|(entry_point, module)| ShaderEntry {
11613                        module,
11614                        entry_point,
11615                    }),
11616                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11617                mesh: ShaderEntry {
11618                    module: cluster.mesh_module,
11619                    entry_point: cluster.mesh,
11620                },
11621                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11622                fragment: None,
11623                primitive,
11624                depth_stencil: Self::depth_stencil(),
11625                multisample: MultisampleState::default(),
11626                color_targets: &[],
11627            }),
11628            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11629                label: Some(&format!("shadow cascade{side}")),
11630                layout,
11631                vertex: ShaderEntry {
11632                    module: self.mesh,
11633                    entry_point: self.depth_vertex,
11634                },
11635                fragment: None,
11636                primitive,
11637                depth_stencil: Self::depth_stencil(),
11638                multisample: MultisampleState::default(),
11639                color_targets: &[],
11640            }),
11641        }
11642    }
11643
11644    /// [`MeshModules::depth_pipeline`] with an alpha mask in it: the same depth
11645    /// state and the same absent colour targets, `depthMaskedFragmentMain`
11646    /// behind the geometry stage, and [`MeshModules::vertex`] in
11647    /// [`MeshModules::depth_vertex`]'s place.
11648    ///
11649    /// Topic 43 §3's cutout, in the two passes that
11650    /// write depth without shading. A masked instance drawn through the pipeline
11651    /// above writes its full silhouette: it occludes itself through the hole it
11652    /// can see through, and it casts the shadow of a leaf that has none.
11653    ///
11654    /// **The vertex stage is the colour pass's, and it has to be.** A cutout
11655    /// needs the UV, which lives in the attribute region `depthVertexMain`
11656    /// exists not to read — so this stage reads a whole vertex, exactly as
11657    /// [`MeshModules::rsm_pipeline`] does beside it and for the same reason.
11658    /// What that buys is one fragment entry point for both geometry paths: the
11659    /// mesh path already emits `mesh.slang`'s `VertexOutput`, so the mask is
11660    /// compared in one place rather than once per path.
11661    ///
11662    /// **Which draws are recorded with it is the bucket's own material mode**,
11663    /// not the frame's — see [`ForwardRenderer::depth_partitions`]. A scene that
11664    /// masks nothing has no bucket in this partition, records through the
11665    /// pipeline above with no fragment stage anywhere, and is never compiled
11666    /// this pipeline at all; a scene that masks one mesh pays the fragment stage
11667    /// for that mesh's draws alone.
11668    fn depth_masked_pipeline(
11669        &self,
11670        device: &dyn Device,
11671        layout: PipelineLayoutHandle,
11672        cull: CullMode,
11673    ) -> Result<GraphicsPipelineHandle, HalError> {
11674        let primitive = Self::primitive(PolygonMode::Fill, cull);
11675        let side = Self::side_label(cull);
11676        let fragment = Some(ShaderEntry {
11677            module: self.mesh,
11678            entry_point: self.depth_masked_fragment,
11679        });
11680        match self.cluster.as_ref() {
11681            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11682                label: Some(&format!("shadow cascade masked{side} mesh cluster")),
11683                layout,
11684                task: cluster
11685                    .task
11686                    .zip(cluster.task_module)
11687                    .map(|(entry_point, module)| ShaderEntry {
11688                        module,
11689                        entry_point,
11690                    }),
11691                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11692                mesh: ShaderEntry {
11693                    module: cluster.mesh_module,
11694                    entry_point: cluster.mesh,
11695                },
11696                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11697                fragment,
11698                primitive,
11699                depth_stencil: Self::depth_stencil(),
11700                multisample: MultisampleState::default(),
11701                color_targets: &[],
11702            }),
11703            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11704                label: Some(&format!("shadow cascade masked{side}")),
11705                layout,
11706                vertex: ShaderEntry {
11707                    module: self.mesh,
11708                    entry_point: self.vertex,
11709                },
11710                fragment,
11711                primitive,
11712                depth_stencil: Self::depth_stencil(),
11713                multisample: MultisampleState::default(),
11714                color_targets: &[],
11715            }),
11716        }
11717    }
11718
11719    /// The reflective shadow map's pipeline: the colour pipeline's geometry
11720    /// stage, `rsmFragmentMain` in the shaded stage's place, and
11721    /// [`MeshModules::RSM_TARGETS`] in [`MeshModules::COLOR_TARGETS`]'s.
11722    ///
11723    /// The irradiance probes' updater draws the sun's near
11724    /// cascade a second time through this — see [`crate::rsm`], which owns the
11725    /// attachments, and `ForwardRenderer::add_shadow_pass`, which records the
11726    /// pass out of that cascade's own bind group and its own already-generated
11727    /// draws.
11728    ///
11729    /// **[`MeshModules::vertex`] and not [`MeshModules::depth_vertex`]**, unlike
11730    /// the cascade this rides beside: a fragment stage that writes a world
11731    /// position, a normal and an albedo needs the varyings `depthVertexMain`
11732    /// exists to leave unread. On the mesh path it is the very same geometry
11733    /// stage the colour pass runs, for the reason `depth_pipeline` gives.
11734    ///
11735    /// **Its own depth, written**, rather than the colour pass's read-only
11736    /// equality test: nothing has drawn this view's depth before it, and the
11737    /// pass is what decides which surface a texel of the map holds.
11738    fn rsm_pipeline(
11739        &self,
11740        device: &dyn Device,
11741        layout: PipelineLayoutHandle,
11742        cull: CullMode,
11743    ) -> Result<GraphicsPipelineHandle, HalError> {
11744        let primitive = Self::primitive(PolygonMode::Fill, cull);
11745        let side = Self::side_label(cull);
11746        let fragment = Some(ShaderEntry {
11747            module: self.mesh,
11748            entry_point: self.rsm_fragment,
11749        });
11750        match self.cluster.as_ref() {
11751            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11752                label: Some(&format!("rsm{side} mesh cluster")),
11753                layout,
11754                task: cluster
11755                    .task
11756                    .zip(cluster.task_module)
11757                    .map(|(entry_point, module)| ShaderEntry {
11758                        module,
11759                        entry_point,
11760                    }),
11761                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11762                mesh: ShaderEntry {
11763                    module: cluster.mesh_module,
11764                    entry_point: cluster.mesh,
11765                },
11766                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11767                fragment,
11768                primitive,
11769                depth_stencil: Self::depth_stencil(),
11770                multisample: MultisampleState::default(),
11771                color_targets: &Self::RSM_TARGETS,
11772            }),
11773            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11774                label: Some(&format!("rsm{side}")),
11775                layout,
11776                vertex: ShaderEntry {
11777                    module: self.mesh,
11778                    entry_point: self.vertex,
11779                },
11780                fragment,
11781                primitive,
11782                depth_stencil: Self::depth_stencil(),
11783                multisample: MultisampleState::default(),
11784                color_targets: &Self::RSM_TARGETS,
11785            }),
11786        }
11787    }
11788
11789    /// The pipeline that resets one tile of the shadow atlas, so a pass can keep
11790    /// some tiles and redraw others.
11791    ///
11792    /// Topic 45's cadence rung needs a tile cleared on its own,
11793    /// and the attachment's [`LoadOp`] cannot do it — a clear there covers the
11794    /// whole image, and the region-bounded forms are not portable. This is the
11795    /// portable statement of the same thing: `mesh.slang`'s
11796    /// `depthClearVertexMain` covers the viewport the shadow pass has already
11797    /// set over the tile, and the depth state below writes
11798    /// [`depth::CLEAR`](crcbl_hal::depth) over whatever was there.
11799    ///
11800    /// **[`CompareOp::Always`] and writes on**, which is the pair that makes it a
11801    /// clear rather than a draw: the tile holds the previous frame's depths, and
11802    /// under the engine's [`CompareOp::Greater`] a clear value of zero would
11803    /// fail against every one of them and leave the tile exactly as it was.
11804    ///
11805    /// **[`CullMode::None`]**, unlike [`MeshModules::primitive`]: the triangle
11806    /// is generated from `SV_VertexID` rather than wound by an artist, so a
11807    /// culling rule meant for scene geometry would decide whether the clear
11808    /// happens at all.
11809    ///
11810    /// **A vertex pipeline on every path**, including the mesh-shader one: a
11811    /// device with a mesh stage still has a vertex stage, and the clear has no
11812    /// clusters to descend.
11813    fn depth_clear_pipeline(
11814        &self,
11815        device: &dyn Device,
11816        layout: PipelineLayoutHandle,
11817    ) -> Result<GraphicsPipelineHandle, HalError> {
11818        device.create_graphics_pipeline(&GraphicsPipelineDesc {
11819            label: Some("shadow tile clear"),
11820            // The mesh layout, so binding this pipeline in the middle of the
11821            // shadow pass does not disturb the bind group the draws around it
11822            // are recorded with. The stage reads none of it.
11823            layout,
11824            vertex: ShaderEntry {
11825                module: self.mesh,
11826                entry_point: self.depth_clear_vertex,
11827            },
11828            fragment: None,
11829            primitive: PrimitiveState {
11830                cull_mode: CullMode::None,
11831                polygon_mode: PolygonMode::Fill,
11832                ..PrimitiveState::default()
11833            },
11834            depth_stencil: Some(DepthStencilState {
11835                depth_compare: CompareOp::Always,
11836                ..DepthStencilState::default()
11837            }),
11838            multisample: MultisampleState::default(),
11839            color_targets: &[],
11840        })
11841    }
11842
11843    /// Releases every module. The pipelines built from them stay valid.
11844    fn destroy(self, device: &dyn Device) {
11845        device.destroy_shader_module(self.mesh);
11846        if let Some(cluster) = self.cluster {
11847            device.destroy_shader_module(cluster.mesh_module);
11848            if let Some(task) = cluster.task_module {
11849                device.destroy_shader_module(task);
11850            }
11851        }
11852    }
11853}
11854
11855/// The entry point for `stage`, or an error naming the shader.
11856///
11857/// Unreachable in practice — `crcbl-shaders`' own tests assert both modules
11858/// expose both stages — but the alternative is an `expect` in engine code.
11859fn entry(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&'static str, HalError> {
11860    shader.entry_point(stage).ok_or_else(|| {
11861        HalError::ShaderCompilation(format!(
11862            "{}.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and its \
11863             manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11864            shader.name()
11865        ))
11866    })
11867}
11868
11869/// The entry point called `name`, checked to be `stage`'s.
11870///
11871/// [`entry`] cannot serve `mesh_cluster.slang`: it has **two** mesh entry
11872/// points — one behind the amplification stage and one without it — and a
11873/// lookup by stage answers `None` for two matches rather than picking one, for
11874/// the good reason that picking one would draw the wrong geometry.
11875///
11876/// The stage is still checked rather than taken on trust: a name that resolved
11877/// to the wrong stage would be a pipeline built with an amplification stage in
11878/// its mesh slot, and the failure would arrive as a driver error rather than as
11879/// this sentence.
11880pub(crate) fn named_entry(
11881    shader: &crcbl_shaders::Shader,
11882    name: &'static str,
11883    stage: Stage,
11884) -> Result<&'static str, HalError> {
11885    let found = shader
11886        .entry_points()
11887        .iter()
11888        .find(|entry| entry.name() == name && entry.stage() == stage);
11889    found.map(crcbl_shaders::EntryPoint::name).ok_or_else(|| {
11890        HalError::ShaderCompilation(format!(
11891            "{}.slang exposes no {stage:?} entry point called `{name}`; the committed SPIR-V and \
11892             its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11893            shader.name()
11894        ))
11895    })
11896}
11897
11898// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
11899#[cfg(all(test, not(target_arch = "wasm32")))]
11900mod tests {
11901    mod draw_pipelines;
11902    mod frame_extents;
11903    mod instance_upload;
11904    mod lazy_content;
11905    mod lazy_passes;
11906    mod load_service;
11907    mod mesh_variants;
11908    mod page_reload;
11909    mod partial_builds;
11910    mod shadow_reach;
11911    mod upload_waits;
11912
11913    use super::*;
11914    use crate::effects::{Antialiasing, EffectOverride};
11915    use crate::scene::{
11916        DEMO_CUBE, DEMO_DUNES, DEMO_OPEN_BOX, DEMO_PYRAMID, DEMO_TEXTURED, DEMO_TINTED,
11917        DEMO_UNTINTED,
11918    };
11919    use crcbl_hal::null::{Event, NullInstance, ObjectKind, Recorder};
11920    use crcbl_hal::{DeviceDesc, DrawIndirect, Features, Instance, QueueKind};
11921
11922    #[test]
11923    fn refused_mesh_color_pipelines_release_successful_depth_pipelines() {
11924        let recorder = Recorder::new();
11925        let mut limits = crcbl_hal::Limits::desktop();
11926        limits.max_color_attachments = 2;
11927        let features = Features::COMPUTE | Features::MESH_SHADER;
11928        let instance = NullInstance::new(crcbl_hal::DeviceCaps { features, limits })
11929            .with_recorder(recorder.clone());
11930        let device = instance
11931            .create_device(&DeviceDesc {
11932                label: None,
11933                adapter: crcbl_hal::AdapterId(0),
11934                required_features: features,
11935                optional_features: Features::empty(),
11936                compatible_surface: None,
11937            })
11938            .unwrap();
11939        let queue = device.queue(QueueKind::Graphics).unwrap();
11940        let before = recorder.total_live_objects();
11941        let error = ForwardRenderer::with_scene_on_path(
11942            device.as_ref(),
11943            queue,
11944            Format::Rgba8UnormSrgb,
11945            &scene::demo(),
11946            GeometryPath::MeshShader,
11947        )
11948        .expect_err("three-target color pipelines must be refused");
11949        assert!(
11950            error
11951                .to_string()
11952                .contains("3 colour targets exceeds max_color_attachments 2"),
11953            "{error}"
11954        );
11955        assert!(
11956            recorder.events().iter().any(|event| matches!(
11957                event,
11958                Event::Created {
11959                    kind: ObjectKind::GraphicsPipeline,
11960                    ..
11961                }
11962            )),
11963            "the refusal must exercise cleanup of successful pipelines"
11964        );
11965        assert_eq!(
11966            recorder.total_live_objects(),
11967            before,
11968            "partial pipeline construction leaked resources"
11969        );
11970        recorder.assert_valid();
11971    }
11972
11973    #[test]
11974    fn exact_geometry_path_overrides_preference_and_default_keeps_it() {
11975        let recorder = Recorder::new();
11976        let instance = NullInstance::gpu_driven()
11977            .with_geometry_preference(GeometryPath::IndirectPerBatch)
11978            .with_recorder(recorder.clone());
11979        let device = instance
11980            .create_device(&DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)))
11981            .unwrap();
11982        let queue = device.queue(QueueKind::Graphics).unwrap();
11983        assert_eq!(device.caps().geometry_path(), GeometryPath::IndirectCount);
11984        let default = ForwardRenderer::with_scene(
11985            device.as_ref(),
11986            queue,
11987            Format::Rgba8UnormSrgb,
11988            &scene::demo(),
11989        )
11990        .unwrap();
11991        assert_eq!(default.geometry_path(), GeometryPath::IndirectPerBatch);
11992        default.destroy(device.as_ref());
11993        recorder.clear();
11994        let mut exact = ForwardRenderer::with_scene_on_path(
11995            device.as_ref(),
11996            queue,
11997            Format::Rgba8UnormSrgb,
11998            &scene::demo(),
11999            GeometryPath::IndirectCount,
12000        )
12001        .unwrap();
12002        assert_eq!(exact.geometry_path(), GeometryPath::IndirectCount);
12003        let rendered = frame(device.as_ref(), &mut exact, queue);
12004        let commands = commands_in_pass(&recorder, "forward");
12005        assert!(commands.iter().any(|command| matches!(
12006            command,
12007            crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
12008        )));
12009        assert!(
12010            !commands
12011                .iter()
12012                .any(|command| matches!(command, crcbl_hal::null::Command::DrawIndexedIndirect(_)))
12013        );
12014        rendered.finish(device.as_ref(), exact);
12015    }
12016
12017    /// **A device with a draw index draws a range of buckets per call, and one
12018    /// without it a call per bucket** — both indirect tails, read off the
12019    /// recorded stream of a whole frame.
12020    ///
12021    /// The ranged frame records one bind and one multi-draw per range in the
12022    /// depth prepass, whose draws together cover every bucket exactly once,
12023    /// and no count draw anywhere; the per-bucket frame records the call per
12024    /// bucket it always did. Both frames' counters are what they recorded.
12025    #[test]
12026    fn a_draw_index_puts_the_geometry_passes_on_a_call_per_range() {
12027        use crcbl_hal::null::Command;
12028
12029        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
12030            for ranged in [false, true] {
12031                let optional = if ranged {
12032                    Features::GPU_DRIVEN | Features::DRAW_INDEX
12033                } else {
12034                    DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features
12035                };
12036                let (recorder, device, queue) = open_with(optional);
12037                let mut renderer = ForwardRenderer::with_scene_on_path(
12038                    device.as_ref(),
12039                    queue,
12040                    Format::Rgba8UnormSrgb,
12041                    &scene::demo(),
12042                    path,
12043                )
12044                .expect("the demo scene builds");
12045                assert_eq!(renderer.range_limit.is_some(), ranged, "{path:?}");
12046                let buckets = renderer.bucket_modes.len();
12047                assert!(buckets > 1, "one bucket packs into one call either way");
12048                let rendered = frame(device.as_ref(), &mut renderer, queue);
12049
12050                let commands = commands_in_pass(&recorder, "depth-prepass");
12051                let binds = commands
12052                    .iter()
12053                    .filter(|command| matches!(command, Command::BindGroup { slot: 0, .. }))
12054                    .count();
12055                let draws: Vec<u32> = commands
12056                    .iter()
12057                    .filter_map(|command| match command {
12058                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
12059                        Command::DrawIndexedIndirectCount(draw) => {
12060                            assert!(!ranged, "{path:?}: a ranged pass records no count draw");
12061                            assert_eq!(draw.max_draw_count, 1);
12062                            Some(1)
12063                        }
12064                        _ => None,
12065                    })
12066                    .collect();
12067                assert_eq!(binds, draws.len(), "{path:?}: one bind per call");
12068                assert_eq!(
12069                    draws.iter().sum::<u32>() as usize,
12070                    buckets,
12071                    "{path:?}: every bucket drawn once"
12072                );
12073                if ranged {
12074                    assert!(
12075                        draws.len() < buckets,
12076                        "{path:?}: {draws:?} is a call per bucket over {buckets} buckets"
12077                    );
12078                } else {
12079                    assert_eq!(draws, vec![1; buckets], "{path:?}");
12080                }
12081                assert!(
12082                    !recorder
12083                        .commands()
12084                        .iter()
12085                        .any(|command| ranged
12086                            && matches!(command, Command::DrawIndexedIndirectCount(_))),
12087                    "{path:?}: a ranged frame records no count draw"
12088                );
12089                assert_eq!(
12090                    renderer.counters().draws,
12091                    recorded_draws(&recorder) as u64,
12092                    "{path:?}, ranged {ranged}"
12093                );
12094                rendered.finish(device.as_ref(), renderer);
12095                recorder.assert_valid();
12096            }
12097        }
12098    }
12099
12100    /// **A scene holding every material mode draws each pipeline's buckets as
12101    /// one ranged call**, because the bucket table is numbered mode-major: the
12102    /// depth prepass records one call per depth pipeline and the colour pass
12103    /// one per sided pipeline, on both indirect tails.
12104    ///
12105    /// Numbered mesh by mesh, the same scene alternates modes bucket by bucket
12106    /// and every partition's runs are one bucket long, so the prepass would
12107    /// record a call per bucket — the counts below are what tell the two
12108    /// numberings apart, and the sums are what say every bucket still drew.
12109    #[test]
12110    fn every_mode_partition_of_a_ranged_frame_is_one_call() {
12111        use crcbl_hal::null::Command;
12112        use crcbl_shaders::mesh::GpuMaterial;
12113
12114        let scene = {
12115            let mut scene = crate::scene::demo();
12116            while scene.materials.len() < 4 {
12117                scene.materials.push(GpuMaterial::UNTINTED);
12118            }
12119            let rows = [
12120                0,
12121                GpuMaterial::ALPHA_MODE_MASK,
12122                GpuMaterial::DOUBLE_SIDED,
12123                GpuMaterial::MODE_MASK,
12124            ];
12125            for (row, flags) in scene.materials.iter_mut().zip(rows) {
12126                row.flags = flags;
12127            }
12128            scene
12129        };
12130        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
12131            let (recorder, device, queue) = open_with(Features::GPU_DRIVEN | Features::DRAW_INDEX);
12132            let mut renderer = ForwardRenderer::with_scene_on_path(
12133                device.as_ref(),
12134                queue,
12135                Format::Rgba8UnormSrgb,
12136                &scene,
12137                path,
12138            )
12139            .expect("the four-mode demo builds");
12140            assert!(renderer.range_limit.is_some(), "{path:?}");
12141            let buckets = renderer.bucket_modes.len();
12142            let per_mode = buckets / DEPTH_MODES.len();
12143            assert_eq!(
12144                per_mode * DEPTH_MODES.len(),
12145                buckets,
12146                "{path:?}: four twins"
12147            );
12148            assert!(
12149                per_mode > 1,
12150                "{path:?}: a mode of one bucket is one call under either numbering"
12151            );
12152            let rendered = frame(device.as_ref(), &mut renderer, queue);
12153
12154            let draws = |label: &str| -> Vec<u32> {
12155                commands_in_pass(&recorder, label)
12156                    .iter()
12157                    .filter_map(|command| match command {
12158                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
12159                        _ => None,
12160                    })
12161                    .collect()
12162            };
12163            let prepass = draws("depth-prepass");
12164            assert_eq!(
12165                prepass,
12166                vec![u32::try_from(per_mode).expect("a few buckets"); DEPTH_MODES.len()],
12167                "{path:?}: one call per depth pipeline, each a whole mode"
12168            );
12169            let forward = draws("forward");
12170            assert_eq!(
12171                forward,
12172                vec![u32::try_from(2 * per_mode).expect("a few buckets"); 2],
12173                "{path:?}: one call per sided pipeline, each two adjacent modes"
12174            );
12175            rendered.finish(device.as_ref(), renderer);
12176            recorder.assert_valid();
12177        }
12178    }
12179
12180    /// **Behind an amplification stage the mesh tail records one flat call per
12181    /// partition, and without one a range of buckets per call on a device with
12182    /// a draw index and a call per bucket without** — read off the recorded
12183    /// stream of a whole frame.
12184    ///
12185    /// The flat calls are [`flat_dispatch_calls`]: one structure each, the
12186    /// colour pass's sided segments in region 0, under the segment's first
12187    /// bucket's block — whatever the bucket count, and whether or not the
12188    /// device granted a draw index, which the flat call does not read. Without
12189    /// the stage the colour pass's calls, unrolled a structure at a time, are
12190    /// exactly the per-bucket dispatches [`mesh_dispatch_calls`] names — every
12191    /// bucket's own extents, each once. Either way the counters are what the
12192    /// frame recorded.
12193    #[test]
12194    fn the_mesh_tail_records_a_flat_call_per_partition_behind_a_task_stage() {
12195        use crcbl_hal::null::Command;
12196
12197        // `None` is the demo scene; `Some(n)` is `n` copies of its cube, one
12198        // bucket each, in one material mode — so one run of `n` buckets.
12199        for cubes in [None, Some(4), Some(33)] {
12200            for task in [Features::TASK_SHADER, Features::empty()] {
12201                for ranged in [false, true] {
12202                    let case = format!("{cubes:?} cubes, {task:?}, ranged {ranged}");
12203                    let recorder = Recorder::new();
12204                    let optional = if ranged {
12205                        task | Features::DRAW_INDEX
12206                    } else {
12207                        task
12208                    };
12209                    let (device, queue) = open_mesh_path(&recorder, optional);
12210                    let mut scene = scene::demo();
12211                    if let Some(cubes) = cubes {
12212                        scene.meshes = vec![scene.meshes[DEMO_CUBE].clone(); cubes as usize];
12213                        scene.capacities.meshes = cubes;
12214                        scene.capacities.vertices =
12215                            cubes * crcbl_shaders::mesh::CUBE_VERTEX_COUNT as u32;
12216                        scene.capacities.indices =
12217                            cubes * crcbl_shaders::mesh::CUBE_INDEX_COUNT as u32;
12218                    }
12219                    let mut renderer = ForwardRenderer::with_scene_on_path(
12220                        device.as_ref(),
12221                        queue,
12222                        Format::Rgba8UnormSrgb,
12223                        &scene,
12224                        GeometryPath::MeshShader,
12225                    )
12226                    .expect("the mesh renderer builds");
12227                    assert_eq!(renderer.range_limit.is_some(), ranged, "{case}");
12228                    assert_eq!(renderer.culls_clusters(), !task.is_empty(), "{case}");
12229                    let buckets = renderer.bucket_constants.len();
12230                    assert!(buckets > 1, "one bucket packs into one call either way");
12231                    let rendered = frame(device.as_ref(), &mut renderer, queue);
12232
12233                    let commands = commands_in_pass(&recorder, "forward");
12234                    let bound: Vec<u32> = commands
12235                        .iter()
12236                        .filter_map(|command| match command {
12237                            Command::BindGroup {
12238                                slot: 0,
12239                                dynamic_offsets,
12240                                ..
12241                            } => Some(dynamic_offsets[0]),
12242                            _ => None,
12243                        })
12244                        .collect();
12245                    let calls: Vec<DrawIndirect> = commands
12246                        .iter()
12247                        .filter_map(|command| match command {
12248                            Command::DrawMeshTasksIndirect(draw) => Some(*draw),
12249                            Command::DrawMeshTasks { .. }
12250                            | Command::DrawIndexedIndirect(_)
12251                            | Command::DrawIndexedIndirectCount(_) => {
12252                                panic!("{case}: the mesh tail recorded {command:?}")
12253                            }
12254                            _ => None,
12255                        })
12256                        .collect();
12257                    assert_eq!(bound.len(), calls.len(), "{case}: one bind per call");
12258                    assert!(
12259                        calls
12260                            .iter()
12261                            .all(|call| call.stride
12262                                == crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32),
12263                        "{case}: one structure a bucket, or a flat call's one"
12264                    );
12265                    if task.is_empty() {
12266                        // Each call a structure at a time: what a call per
12267                        // bucket would have recorded for the buckets it
12268                        // stands for.
12269                        let mut unrolled: Vec<DrawIndirect> = calls
12270                            .iter()
12271                            .flat_map(|call| {
12272                                (0..call.draw_count).map(|draw| DrawIndirect {
12273                                    offset: call.offset + u64::from(draw) * u64::from(call.stride),
12274                                    draw_count: 1,
12275                                    ..*call
12276                                })
12277                            })
12278                            .collect();
12279                        unrolled.sort_by_key(|draw| draw.offset);
12280                        assert_eq!(
12281                            unrolled,
12282                            mesh_dispatch_calls(&renderer),
12283                            "{case}: every bucket's own extents, each once"
12284                        );
12285                        let counts: Vec<u32> = calls.iter().map(|call| call.draw_count).collect();
12286                        match (ranged, cubes) {
12287                            (false, _) => assert_eq!(counts, vec![1; buckets], "{case}"),
12288                            (true, Some(cubes)) => assert_eq!(counts, vec![cubes], "{case}"),
12289                            (true, None) => assert!(
12290                                calls.len() < buckets,
12291                                "{case}: {counts:?} is a call per bucket over {buckets} buckets"
12292                            ),
12293                        }
12294                    } else {
12295                        let (expected, firsts) = flat_dispatch_calls(
12296                            &renderer,
12297                            crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED,
12298                        );
12299                        assert_eq!(calls, expected, "{case}: one flat call per sided partition");
12300                        assert_eq!(
12301                            bound,
12302                            firsts
12303                                .iter()
12304                                .map(|&bucket| renderer.bucket_constants[bucket as usize])
12305                                .collect::<Vec<_>>(),
12306                            "{case}: each under its segment's first bucket's block"
12307                        );
12308                    }
12309                    assert_eq!(
12310                        renderer.counters().draws,
12311                        recorded_draws(&recorder) as u64,
12312                        "{case}"
12313                    );
12314                    rendered.finish(device.as_ref(), renderer);
12315                    recorder.assert_valid();
12316                }
12317            }
12318        }
12319    }
12320
12321    /// **Draw `d` of a ranged mesh call reads the words bucket `first + d`'s own
12322    /// block carries**, in every draw region.
12323    ///
12324    /// The host half of `mesh_cluster.slang`'s "One call for a range of
12325    /// buckets": a ranged call binds its first bucket's block alone, and the
12326    /// SPIR-V stages add the draw index to its `start_at` and `bucket` and to
12327    /// the two table words it names. So each bucket's block has to sit one word
12328    /// past the one before in all four, and the table words have to hold the
12329    /// bucket's own cluster base and count — read out of the bytes that reached
12330    /// the device, since a block written wrong leaves the renderer's fields
12331    /// right.
12332    #[test]
12333    fn a_mesh_block_names_the_words_a_ranged_draw_reads() {
12334        let recorder = Recorder::new();
12335        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
12336        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12337            .expect("the mesh renderer builds");
12338        let blocks = recorder
12339            .buffer_bytes(renderer.draw_constants)
12340            .expect("the blocks are live");
12341        let tables = recorder
12342            .buffer_bytes(renderer.primary.draws.tables())
12343            .expect("the tables are live");
12344        let word = |bytes: &[u8], at: usize| {
12345            u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes"))
12346        };
12347        let buckets = renderer.bucket_constants.len();
12348        assert!(buckets > 1, "a range needs two buckets to step between");
12349        let bucket_count = u32::try_from(buckets).expect("a few buckets");
12350        let stride = renderer.bucket_constants[1] - renderer.bucket_constants[0];
12351        let block = |region: u32, bucket: u32| {
12352            let at = ((region * bucket_count + bucket) * stride) as usize;
12353            let field = |index: usize| word(&blocks, at + index * 4);
12354            crcbl_shaders::meshlet::ClusterDrawConstants {
12355                start_at: field(0),
12356                cluster_base: field(1),
12357                cluster_count: field(2),
12358                bucket: field(3),
12359                group_stride: field(4),
12360                level_groups_at: field(5),
12361                cluster_base_at: field(6),
12362                cluster_count_at: field(7),
12363                chunk_starts_at: field(8),
12364                chunk_starts_end: field(9),
12365            }
12366        };
12367        let mut bases = Vec::new();
12368        for region in 0..crcbl_shaders::draw_gen::DRAW_REGIONS {
12369            let first = block(region, 0);
12370            for bucket in 0..bucket_count {
12371                let own = block(region, bucket);
12372                assert_eq!(
12373                    word(&tables, own.cluster_base_at as usize * 4),
12374                    own.cluster_base,
12375                    "region {region} bucket {bucket}: the base word holds the base"
12376                );
12377                assert_eq!(
12378                    word(&tables, own.cluster_count_at as usize * 4),
12379                    own.cluster_count,
12380                    "region {region} bucket {bucket}: the count word holds the count"
12381                );
12382                // What draw `bucket` of a call bound at bucket 0's block reads
12383                // — and a flat call's workgroup that found bucket `bucket` by
12384                // searching the chunk starts from bucket 0's word to the
12385                // region's end.
12386                assert_eq!(
12387                    (
12388                        first.start_at + bucket,
12389                        first.bucket + bucket,
12390                        first.cluster_base_at + bucket,
12391                        first.cluster_count_at + bucket,
12392                        first.group_stride,
12393                        first.level_groups_at,
12394                        first.chunk_starts_at + bucket,
12395                        first.chunk_starts_end,
12396                    ),
12397                    (
12398                        own.start_at,
12399                        own.bucket,
12400                        own.cluster_base_at,
12401                        own.cluster_count_at,
12402                        own.group_stride,
12403                        own.level_groups_at,
12404                        own.chunk_starts_at,
12405                        own.chunk_starts_end,
12406                    ),
12407                    "region {region} bucket {bucket}"
12408                );
12409                assert_eq!(
12410                    own.chunk_starts_at,
12411                    crcbl_shaders::draw_gen::chunk_start_word(
12412                        renderer.primary.draws.visible_capacity(),
12413                        bucket_count,
12414                        region,
12415                        bucket,
12416                    ),
12417                    "region {region} bucket {bucket}: the word draw_gen writes its chunks' start into"
12418                );
12419                assert_eq!(
12420                    own.chunk_starts_end - own.chunk_starts_at,
12421                    bucket_count - bucket,
12422                    "region {region} bucket {bucket}: the search ends at the region's end word"
12423                );
12424                if region == 0 {
12425                    bases.push(own.cluster_base);
12426                }
12427            }
12428        }
12429        assert!(
12430            bases.windows(2).any(|pair| pair[0] != pair[1]),
12431            "the buckets' meshes start at different clusters, so a range reading its \
12432             first bucket's base for every draw would be seen: {bases:?}"
12433        );
12434        renderer.destroy(device.as_ref());
12435        recorder.assert_valid();
12436    }
12437
12438    #[test]
12439    fn exact_geometry_path_builds_supported_tails_and_refuses_missing_features_without_allocating()
12440    {
12441        for features in [
12442            Features::GPU_DRIVEN,
12443            Features::COMPUTE | Features::MESH_SHADER,
12444        ] {
12445            let recorder = Recorder::new();
12446            let instance = NullInstance::new(crcbl_hal::DeviceCaps {
12447                features,
12448                limits: crcbl_hal::Limits::desktop(),
12449            })
12450            .with_recorder(recorder.clone());
12451            let device = instance
12452                .create_device(&DeviceDesc {
12453                    label: None,
12454                    adapter: crcbl_hal::AdapterId(0),
12455                    required_features: Features::COMPUTE,
12456                    optional_features: features,
12457                    compatible_surface: None,
12458                })
12459                .expect("null device opens");
12460            let queue = device.queue(QueueKind::Graphics).unwrap();
12461            for (path, required) in [
12462                (GeometryPath::IndirectPerBatch, Features::empty()),
12463                (GeometryPath::IndirectCount, Features::DRAW_INDIRECT_COUNT),
12464                (GeometryPath::MeshShader, Features::MESH_SHADER),
12465            ] {
12466                recorder.clear();
12467                let result = ForwardRenderer::with_scene_on_path(
12468                    device.as_ref(),
12469                    queue,
12470                    Format::Rgba8UnormSrgb,
12471                    &scene::demo(),
12472                    path,
12473                );
12474                if features.contains(required) {
12475                    let renderer = result.expect("supported exact tail builds");
12476                    assert_eq!(renderer.geometry_path(), path);
12477                    renderer.destroy(device.as_ref());
12478                } else {
12479                    assert!(
12480                        matches!(result, Err(HalError::UnsupportedFeatures { missing }) if missing == required)
12481                    );
12482                    assert!(
12483                        recorder.events().is_empty(),
12484                        "unsupported selection must not touch device objects"
12485                    );
12486                }
12487                recorder.assert_valid();
12488            }
12489        }
12490    }
12491
12492    pub(super) fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
12493        open_with(DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features)
12494    }
12495
12496    /// [`open`] asking for `optional_features` instead of
12497    /// [`DeviceDesc::for_adapter`]'s.
12498    ///
12499    /// The null preset *has* more than the default request asks for, and a
12500    /// granted feature set is the intersection of the two — so this is how a test
12501    /// reaches a device with something the ordinary one lacks. What it exists for
12502    /// is [`Features::POLYGON_MODE_LINE`]: with the default request, `open`'s
12503    /// device has no line fill mode, which is the other half of the wireframe
12504    /// pair of tests below.
12505    fn open_with(optional_features: Features) -> (Recorder, Box<dyn Device>, QueueHandle) {
12506        let recorder = Recorder::new();
12507        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
12508        let adapter = instance.adapters().remove(0);
12509        let device = instance
12510            .create_device(&DeviceDesc {
12511                optional_features,
12512                ..DeviceDesc::for_adapter(adapter.id)
12513            })
12514            .expect("the null backend always opens");
12515        let queue = device.queue(QueueKind::Graphics).expect("always present");
12516        (recorder, device, queue)
12517    }
12518
12519    /// Puts one of [`scene::demo`]'s meshes in the frame the way a caller does.
12520    ///
12521    /// **Insertion order is what the caller decides**, and it is load-bearing:
12522    /// the slot an object lands in is topic 25's hysteresis key. So
12523    /// every test below places its objects in the order the frame used to hold
12524    /// them — the cube first, wherever there is one.
12525    /// The label of every graphics pipeline `recorder`'s device has created, in
12526    /// creation order — so `labels[handle.index()]` names the pipeline a bind
12527    /// of `handle` bound.
12528    ///
12529    /// What lets two renderers' bind streams be compared: `build` compiles only
12530    /// the mesh pipelines its scene draws with, so two scenes' renderers hand
12531    /// out different handle values for the same pipeline, and a label is what
12532    /// stays the same. Valid only while no graphics pipeline was destroyed,
12533    /// since the pool reuses a freed slot — which this asserts.
12534    fn graphics_pipeline_labels(recorder: &Recorder) -> Vec<String> {
12535        let events = recorder.events();
12536        assert!(
12537            !events.iter().any(|event| matches!(
12538                event,
12539                Event::Destroyed {
12540                    kind: ObjectKind::GraphicsPipeline
12541                }
12542            )),
12543            "a graphics pipeline was destroyed, so a handle's index is no longer its creation \
12544             order"
12545        );
12546        events
12547            .into_iter()
12548            .filter_map(|event| match event {
12549                Event::Created {
12550                    kind: ObjectKind::GraphicsPipeline,
12551                    label,
12552                } => Some(label.unwrap_or_default()),
12553                _ => None,
12554            })
12555            .collect()
12556    }
12557
12558    fn place_demo(
12559        renderer: &mut ForwardRenderer,
12560        mesh: usize,
12561        material: usize,
12562        transform: Mat4,
12563    ) -> InstanceHandle {
12564        renderer
12565            .add_instance(&InstanceDesc {
12566                mesh,
12567                material,
12568                transform,
12569            })
12570            .expect("a pool of thousands has room for a handful of objects")
12571    }
12572
12573    /// [`scene::demo`]'s cube, placed **first** so it takes the pool slot it has
12574    /// always had.
12575    ///
12576    /// `begin_frame` used to write this object for every caller; the tests below
12577    /// that are about a frame with something in it place it themselves now.
12578    pub(super) fn place_cube(renderer: &mut ForwardRenderer, transform: Mat4) -> InstanceHandle {
12579        place_demo(renderer, DEMO_CUBE, DEMO_UNTINTED, transform)
12580    }
12581
12582    /// The whole renderer builds and tears down against a backend with no
12583    /// driver, which is what makes it testable on every CI leg.
12584    #[test]
12585    fn the_forward_renderer_builds_and_leaks_nothing() {
12586        let (recorder, device, queue) = open();
12587        let before = recorder.total_live_objects();
12588        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12589            .expect("the null backend accepts every descriptor");
12590        assert_eq!(renderer.target_format(), Format::Rgba8UnormSrgb);
12591        assert!(recorder.total_live_objects() > before);
12592        renderer.destroy(device.as_ref());
12593        assert_eq!(
12594            recorder.total_live_objects(),
12595            before,
12596            "every object created must be destroyed"
12597        );
12598        recorder.assert_valid();
12599    }
12600
12601    /// The uniform ring really rotates, or a spinning cube is a
12602    /// read-after-write hazard across submissions.
12603    #[test]
12604    fn the_uniform_ring_rotates() {
12605        let (_, device, queue) = open();
12606        let mut renderer =
12607            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12608        let camera = Camera::default();
12609        let light = DirectionalLight::default();
12610
12611        let mut seen = Vec::new();
12612        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12613            renderer
12614                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12615                .expect("write");
12616            seen.push(renderer.primary.uniforms[renderer.frame]);
12617        }
12618        assert_ne!(
12619            seen[0], seen[1],
12620            "consecutive frames must not share a buffer"
12621        );
12622        assert_eq!(seen[0], seen[FRAMES_IN_FLIGHT], "and the ring must wrap");
12623        renderer.destroy(device.as_ref());
12624    }
12625
12626    /// **The tonemap's block is a ring too, and it carries the exposure the
12627    /// caller set.**
12628    ///
12629    /// The bytes are the observable rather than the field, because the field is
12630    /// what a renderer that never wired the block up would also have: the claim
12631    /// is that the number reaches the buffer `tonemap.slang` reads, and only the
12632    /// null recorder's write log can say so.
12633    ///
12634    /// The default is checked first — a renderer nobody has called
12635    /// [`ForwardRenderer::set_exposure`] on writes the value the shader's
12636    /// `EXPOSURE` constant held, under
12637    /// [`ForwardRenderer::set_tonemap_curve`]'s own default.
12638    #[test]
12639    fn the_tonemap_block_holds_the_exposure_and_rotates_with_the_frame() {
12640        let (recorder, device, queue) = open();
12641        let mut renderer =
12642            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12643        let camera = Camera::default();
12644        let light = DirectionalLight::default();
12645
12646        renderer
12647            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12648            .expect("write");
12649        assert_eq!(
12650            recorder
12651                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12652                .expect("begin_frame wrote the block"),
12653            crcbl_shaders::tonemap::TonemapParams {
12654                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12655                curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12656                auto_exposure: false,
12657                coverage_alpha: false,
12658            }
12659            .to_bytes(),
12660            "an untouched renderer must write the exposure the constant used to hold, \
12661             under the operator this renderer starts on",
12662        );
12663
12664        // A value that is neither the default nor a bound, so a block left at
12665        // either would fail.
12666        renderer.set_exposure(3.5);
12667        let mut slots = Vec::new();
12668        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12669            renderer
12670                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12671                .expect("write");
12672            slots.push(renderer.primary.tonemap_uniforms[renderer.frame]);
12673            assert_eq!(
12674                recorder
12675                    .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12676                    .expect("begin_frame wrote the block"),
12677                crcbl_shaders::tonemap::TonemapParams {
12678                    exposure: 3.5,
12679                    curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12680                    auto_exposure: false,
12681                    coverage_alpha: false,
12682                }
12683                .to_bytes(),
12684                "the frame's own block must carry the exposure in force",
12685            );
12686        }
12687        assert_ne!(
12688            slots[0], slots[1],
12689            "consecutive frames must not share a block"
12690        );
12691        assert_eq!(slots[0], slots[FRAMES_IN_FLIGHT], "and the ring must wrap");
12692
12693        renderer.destroy(device.as_ref());
12694    }
12695
12696    /// **The curve reaches the block, and a caller can move it off the
12697    /// default.**
12698    ///
12699    /// The selector is a lane of the same ring the exposure rides in, and a lane
12700    /// nothing wrote would read as
12701    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp)
12702    /// whatever a caller asked for — a setter that compiles, a frame that looks
12703    /// right, and a curve that never runs. Since the renderer now *starts* on
12704    /// the fit, that failure would read as a working default, so the check runs
12705    /// in both directions: the untouched block carries the fit, and asking for
12706    /// the clamp changes the bytes on every frame of the ring.
12707    #[test]
12708    fn the_tonemap_block_carries_the_curve_a_caller_selected() {
12709        use crcbl_shaders::tonemap::TonemapCurve;
12710
12711        let (recorder, device, queue) = open();
12712        let mut renderer =
12713            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12714        let camera = Camera::default();
12715        let light = DirectionalLight::default();
12716
12717        assert_eq!(
12718            renderer.tonemap_curve(),
12719            TonemapCurve::Aces,
12720            "a renderer nobody configured must run the operator the goldens were blessed under",
12721        );
12722        renderer
12723            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12724            .expect("write");
12725        let by_default = recorder
12726            .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12727            .expect("begin_frame wrote the block");
12728
12729        renderer.set_tonemap_curve(TonemapCurve::Clamp);
12730        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Clamp);
12731        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12732            renderer
12733                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12734                .expect("write");
12735            let written = recorder
12736                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12737                .expect("begin_frame wrote the block");
12738            assert_eq!(
12739                written,
12740                crcbl_shaders::tonemap::TonemapParams {
12741                    exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12742                    curve: TonemapCurve::Clamp,
12743                    auto_exposure: false,
12744                    coverage_alpha: false,
12745                }
12746                .to_bytes(),
12747                "every frame of the ring must carry the selected curve",
12748            );
12749            assert_ne!(
12750                written, by_default,
12751                "and it must differ from the block a default renderer writes",
12752            );
12753        }
12754
12755        // **A readout runs the clamp whatever was selected**, and the selection
12756        // survives it: the caller's curve is still the caller's, the frame's is
12757        // the identity, and the shaded frame after gets the curve back. Asked of
12758        // the fit, which is the selection a readout has something to lose under.
12759        renderer.set_tonemap_curve(TonemapCurve::Aces);
12760        renderer.set_normals_view(true);
12761        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Aces);
12762        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Clamp);
12763        renderer
12764            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12765            .expect("write");
12766        assert_eq!(
12767            recorder
12768                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12769                .expect("begin_frame wrote the block"),
12770            crcbl_shaders::tonemap::TonemapParams {
12771                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12772                curve: TonemapCurve::Clamp,
12773                auto_exposure: false,
12774                coverage_alpha: false,
12775            }
12776            .to_bytes(),
12777            "a debug view's block must carry the clamp, since its pixels are data",
12778        );
12779        renderer.set_normals_view(false);
12780        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Aces);
12781
12782        renderer.destroy(device.as_ref());
12783    }
12784
12785    /// **The exposure is clamped where it is set**, so no caller can reach a
12786    /// frame it cannot get back from.
12787    ///
12788    /// Each case is a different way of leaving the range, and the NaN one is the
12789    /// reason [`ForwardRenderer::set_exposure`] does not use `f32::clamp`: that
12790    /// propagates a NaN into the block, which is a frame of NaN pixels with no
12791    /// key to press to escape it.
12792    #[test]
12793    fn the_exposure_setter_clamps_to_a_range_a_caller_can_come_back_from() {
12794        let (_, device, queue) = open();
12795        let mut renderer =
12796            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12797        assert!(
12798            (renderer.exposure() - crcbl_shaders::tonemap::DEFAULT_EXPOSURE).abs() < f32::EPSILON,
12799            "the default is {}",
12800            renderer.exposure(),
12801        );
12802
12803        for (asked, expected) in [
12804            (2.0, 2.0),
12805            (EXPOSURE_MAX * 4.0, EXPOSURE_MAX),
12806            (f32::INFINITY, EXPOSURE_MAX),
12807            (EXPOSURE_MIN / 4.0, EXPOSURE_MIN),
12808            (0.0, EXPOSURE_MIN),
12809            (-8.0, EXPOSURE_MIN),
12810            (f32::NEG_INFINITY, EXPOSURE_MIN),
12811            (f32::NAN, EXPOSURE_MIN),
12812        ] {
12813            renderer.set_exposure(asked);
12814            assert!(
12815                (renderer.exposure() - expected).abs() < f32::EPSILON,
12816                "{asked} was clamped to {}, not {expected}",
12817                renderer.exposure(),
12818            );
12819        }
12820
12821        renderer.destroy(device.as_ref());
12822    }
12823
12824    /// **The debug views resolve in one order, however they are set.**
12825    ///
12826    /// Every one of them rides in one float lane and the shaders test the
12827    /// outermost threshold first, so a renderer with two switches on draws
12828    /// exactly one picture — and which one has to be a rule rather than
12829    /// whichever branch a caller's setter happened to run last. Every
12830    /// combination of the switches is walked, because a precedence written as an
12831    /// `if` chain is right for most of them by accident: a chain in the wrong
12832    /// order agrees with this one on every combination where at most one switch
12833    /// is set.
12834    ///
12835    /// **The two innermost views are the exception the walk is worth most for.**
12836    /// [`DebugView::Cascades`] keeps the shaded picture rather than replacing
12837    /// it, so it resolves *last* and its sentinel runs the other way down the
12838    /// lane; [`DebugView::ShadowAtlas`] resolves just above it and carries the
12839    /// *off* sentinel, because it is a pass rather than a branch. Every
12840    /// combination where either is set beside a replacing view is a combination
12841    /// an order written any other way answers differently, and there is no
12842    /// single-switch case that could tell them apart.
12843    ///
12844    /// [`ForwardRenderer::debug_view`] is asserted beside the lane, so the value
12845    /// a panel reads back and the value the shader branches on cannot drift —
12846    /// they are the same function.
12847    #[test]
12848    fn the_debug_views_resolve_in_one_order_however_they_are_set() {
12849        // `w` of the second `float4` of the block — the lane
12850        // `the_normals_view_moves_the_ambients_last_lane_and_no_other_byte`
12851        // spells out, and for its reason.
12852        const AMBIENT_W: usize = 64 + 16 + 12;
12853
12854        let (recorder, device, queue) = open();
12855        let mut renderer =
12856            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12857        let camera = Camera::default();
12858        let light = DirectionalLight::default();
12859
12860        for bent in [false, true] {
12861            for motion in [false, true] {
12862                for occlusion in [false, true] {
12863                    for heatmap in [false, true] {
12864                        for lod in [false, true] {
12865                            for normals in [false, true] {
12866                                for (atlas, cascades) in
12867                                    [false, true].into_iter().flat_map(|atlas| {
12868                                        [false, true].map(|cascades| (atlas, cascades))
12869                                    })
12870                                {
12871                                    renderer.set_bent_normal_view(bent);
12872                                    renderer.set_motion_view(motion);
12873                                    renderer.set_occlusion_view(occlusion);
12874                                    renderer.set_heatmap(heatmap);
12875                                    renderer.set_lod_view(lod);
12876                                    renderer.set_normals_view(normals);
12877                                    renderer.set_atlas_view(atlas);
12878                                    renderer.set_cascade_view(cascades);
12879                                    let set = format!(
12880                                        "bent={bent} motion={motion} occlusion={occlusion} \
12881                                 heatmap={heatmap} lod={lod} normals={normals} \
12882                                 atlas={atlas} cascades={cascades}"
12883                                    );
12884                                    // Each switch reads back what it was set to, whatever
12885                                    // the others are: a caller's toggle is about the
12886                                    // caller's setting, and only `debug_view` is about the
12887                                    // picture.
12888                                    assert_eq!(renderer.bent_normal_view(), bent);
12889                                    assert_eq!(renderer.motion_view(), motion);
12890                                    assert_eq!(renderer.occlusion_view(), occlusion);
12891                                    assert_eq!(renderer.heatmap(), heatmap);
12892                                    assert_eq!(renderer.lod_view(), lod);
12893                                    assert_eq!(renderer.normals_view(), normals);
12894                                    assert_eq!(renderer.atlas_view(), atlas);
12895                                    assert_eq!(renderer.cascade_view(), cascades);
12896
12897                                    let expected = if bent {
12898                                        DebugView::BentNormal
12899                                    } else if motion {
12900                                        DebugView::Motion
12901                                    } else if occlusion {
12902                                        DebugView::AmbientOcclusion
12903                                    } else if heatmap {
12904                                        DebugView::Heatmap
12905                                    } else if lod {
12906                                        DebugView::LodTint
12907                                    } else if normals {
12908                                        DebugView::Normals
12909                                    } else if atlas {
12910                                        // **Below every replacing view above and
12911                                        // above the tint below**, which is the
12912                                        // half of this order no single-switch
12913                                        // case reaches: with a replacing view
12914                                        // also set the frame is that view's, and
12915                                        // with the tint also set the frame is the
12916                                        // atlas.
12917                                        DebugView::ShadowAtlas
12918                                    } else if cascades {
12919                                        // **Last, which is the half of this order a
12920                                        // chain in any other arrangement would get
12921                                        // right by accident.** The cascade tint is a
12922                                        // multiply on the shaded picture, so every
12923                                        // combination that also names a replacing
12924                                        // view has to resolve to *that* view — and
12925                                        // those are exactly the combinations an
12926                                        // `if cascades` written one line higher
12927                                        // would answer differently.
12928                                        DebugView::Cascades
12929                                    } else {
12930                                        DebugView::Shaded
12931                                    };
12932                                    assert_eq!(renderer.debug_view(), expected, "{set}");
12933
12934                                    renderer
12935                                        .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12936                                        .expect("write");
12937                                    let block = recorder
12938                                        .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12939                                        .expect("begin_frame wrote the block");
12940                                    let sentinel = match expected {
12941                                        DebugView::BentNormal => {
12942                                            mesh::FrameUniforms::BENT_NORMAL_VIEW_ON
12943                                        }
12944                                        DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
12945                                        DebugView::AmbientOcclusion => {
12946                                            mesh::FrameUniforms::OCCLUSION_VIEW_ON
12947                                        }
12948                                        DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
12949                                        DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
12950                                        DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
12951                                        DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
12952                                        // **The atlas view carries the *off*
12953                                        // sentinel**, which is what makes this
12954                                        // assertion say something rather than
12955                                        // restate `debug_view_lane`: the colour
12956                                        // pass draws the shaded picture and
12957                                        // `crate::atlas_view`'s pass replaces
12958                                        // it, so a lane of its own here would be
12959                                        // a threshold no shader tests.
12960                                        DebugView::ShadowAtlas | DebugView::Shaded => {
12961                                            mesh::FrameUniforms::NORMALS_VIEW_OFF
12962                                        }
12963                                    };
12964                                    assert_eq!(
12965                                        &block[AMBIENT_W..AMBIENT_W + 4],
12966                                        &sentinel.to_le_bytes(),
12967                                        "{set} resolved to {expected:?}, and the lane says otherwise"
12968                                    );
12969                                    // And the resolve comes off for every one of them:
12970                                    // these frames are read back as data, so their colours
12971                                    // have to stay the ones the shader wrote — see
12972                                    // `resolved_effects`. The whole slot rather than one
12973                                    // tier of it, because which tier the default carries
12974                                    // is not what this is about.
12975                                    assert_eq!(
12976                                        renderer.effects().intersects(Antialiasing::SLOT),
12977                                        expected == DebugView::Shaded,
12978                                        "{set}"
12979                                    );
12980                                }
12981                            }
12982                        }
12983                    }
12984                }
12985            }
12986        }
12987
12988        renderer.destroy(device.as_ref());
12989    }
12990
12991    /// **The atlas viewer records one pass, and only on the frame it is the view
12992    /// showing.**
12993    ///
12994    /// The mechanism no other check in this file can see. Every other debug view
12995    /// is a lane of the frame block, so
12996    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`] observes it
12997    /// by reading four bytes; this one is a *pass*, and "the pass was recorded"
12998    /// is a claim about the command stream and about nothing else. A switch that
12999    /// resolved correctly and recorded nothing would satisfy every other
13000    /// assertion in this module and draw the frame unchanged.
13001    ///
13002    /// Three arms, and the third is the one that makes the first two mean
13003    /// something:
13004    ///
13005    /// * off — no pass at all, which is what makes the off position
13006    ///   bit-identical for every golden in this workspace;
13007    /// * on — the pass, with the full-screen triangle in it;
13008    /// * on **beside a replacing view** — no pass, because
13009    ///   [`ForwardRenderer::debug_view`] resolved to that view and the atlas is
13010    ///   not what this frame draws. That is the half a `self.atlas_view` read at
13011    ///   the recording site would get wrong while passing both arms above.
13012    ///
13013    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`]: fn@the_debug_views_resolve_in_one_order_however_they_are_set
13014    /// **The shadow atlas viewer replaces the tonemap and the ground grid, and
13015    /// the draw count follows.**
13016    ///
13017    /// The viewer fills every display pixel with a `DontCare` load, so a
13018    /// tonemapped frame or a grid recorded under it is stored and discarded.
13019    /// The pass counts go red if either comes back; the counter goes red if
13020    /// `counters` still charges the frame for the triangles it no longer
13021    /// records.
13022    #[test]
13023    fn the_atlas_viewer_replaces_the_display_passes_and_the_count_follows() {
13024        let _seam = ssao_split_switch();
13025        let (recorder, device, queue) = open();
13026        let mut renderer =
13027            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13028        renderer
13029            .set_ground_grid(device.as_ref(), Some(GridStyle::default()))
13030            .expect("the null backend builds every pipeline");
13031        renderer.set_atlas_view(true);
13032        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
13033
13034        let viewing = frame(device.as_ref(), &mut renderer, queue);
13035        let opened = |label: &str| {
13036            recorder
13037                .commands()
13038                .iter()
13039                .filter(|command| {
13040                    matches!(command.opens_pass(), Some((_, Some(recorded))) if recorded == label)
13041                })
13042                .count()
13043        };
13044        assert_eq!(opened(crate::atlas_view::LABEL), 1);
13045        assert_eq!(opened("tonemap"), 0, "the viewer discards the tonemap");
13046        assert_eq!(opened("grid"), 0, "and the grid drawn over it");
13047        assert_eq!(
13048            renderer.counters().draws,
13049            recorded_draws(&recorder) as u64,
13050            "the counter charges the frame for exactly the draws it recorded"
13051        );
13052        viewing.finish(device.as_ref(), renderer);
13053    }
13054
13055    #[test]
13056    fn the_atlas_viewer_records_its_pass_only_when_it_is_the_view_showing() {
13057        use crcbl_hal::null::Command;
13058
13059        let (recorder, device, queue) = open();
13060        let device = device.as_ref();
13061        let mut renderer =
13062            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
13063        let (camera, sun) = (Camera::default(), DirectionalLight::default());
13064
13065        // How many times the viewer's pass was opened since `from`, which is
13066        // where the previous arm's commands ended.
13067        let opened = |from: usize| {
13068            recorder.commands()[from..]
13069                .iter()
13070                .filter(|command| {
13071                    matches!(
13072                        command.opens_pass(),
13073                        Some((_, Some(recorded))) if recorded == crate::atlas_view::LABEL
13074                    )
13075                })
13076                .count()
13077        };
13078
13079        let shaded = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
13080        assert_eq!(
13081            opened(0),
13082            0,
13083            "a frame drawing the shaded picture recorded the atlas viewer's pass"
13084        );
13085        let after_shaded = recorder.commands().len();
13086        shaded.release(device);
13087
13088        renderer.set_atlas_view(true);
13089        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
13090        let viewing = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
13091        assert_eq!(
13092            opened(after_shaded),
13093            1,
13094            "the atlas viewer is on and its pass was not recorded exactly once"
13095        );
13096        // And what it recorded is the over-sized triangle and nothing else: a
13097        // pass that bound a pipeline and drew no vertices would open above and
13098        // leave the frame the tonemap wrote.
13099        let drawn: Vec<(u32, u32)> = commands_in_pass(&recorder, crate::atlas_view::LABEL)
13100            .into_iter()
13101            .filter_map(|command| match command {
13102                Command::Draw {
13103                    vertices,
13104                    instances,
13105                } => Some((
13106                    vertices.end - vertices.start,
13107                    instances.end - instances.start,
13108                )),
13109                _ => None,
13110            })
13111            .collect();
13112        assert_eq!(drawn, vec![(crate::atlas_view::FULLSCREEN_VERTICES, 1)]);
13113        let after_viewing = recorder.commands().len();
13114        viewing.release(device);
13115
13116        // The switch left on, and a replacing view asked for over the top of it.
13117        renderer.set_normals_view(true);
13118        assert_eq!(
13119            renderer.debug_view(),
13120            DebugView::Normals,
13121            "the atlas view does not lose to a replacing view, so the arm below asks nothing"
13122        );
13123        let normals = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
13124        assert_eq!(
13125            opened(after_viewing),
13126            0,
13127            "the frame resolved to the normals view and still recorded the atlas viewer's \
13128             pass over the top of it"
13129        );
13130        normals.release(device);
13131
13132        renderer.destroy(device);
13133    }
13134
13135    /// **The heatmap moves the ambient's last lane and no other byte**, and
13136    /// switching it off puts the block back.
13137    ///
13138    /// The normals view's assertion below, for the outermost of the three: the
13139    /// overlay costs one lane, so every golden image ever blessed is untouched
13140    /// by the feature existing. The `lod_params` row the heatmap reads is
13141    /// written every frame whether it is on or not — it is the numbers the
13142    /// selection used — so this compares two frames of the *same* camera and
13143    /// budget, where that row is equal on both sides and any byte outside the
13144    /// lane is a real difference.
13145    #[test]
13146    fn the_heatmap_moves_the_ambients_last_lane_and_no_other_byte() {
13147        const AMBIENT_W: usize = 64 + 16 + 12;
13148
13149        // Held for the whole comparison, and it is not this check's own knob:
13150        // `r_shadow_filter` and `r_shadow_split` land in the block's
13151        // `shadow_filter` row on every `begin_frame`, and the filter checks in
13152        // this module move them under this lock while `cargo test` runs the
13153        // module's checks as threads of one process. Two frames read either side
13154        // of such a move differ at that row, which is outside every lane below —
13155        // one run in twelve, measured 2026-09-04.
13156        let _filter = shadow_filter_switch();
13157        let (recorder, device, queue) = open();
13158        let mut renderer =
13159            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13160        let camera = Camera::default();
13161        let light = DirectionalLight::default();
13162        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
13163            renderer
13164                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13165                .expect("write");
13166            recorder
13167                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
13168                .expect("begin_frame wrote the block")
13169        };
13170
13171        assert!(
13172            !renderer.heatmap(),
13173            "the heatmap has to be off in a renderer nobody has asked",
13174        );
13175        let shaded = block(&mut renderer);
13176        assert_eq!(
13177            &shaded[AMBIENT_W..AMBIENT_W + 4],
13178            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
13179            "an untouched renderer must write the value every golden image was blessed with",
13180        );
13181
13182        renderer.set_heatmap(true);
13183        let heatmap = block(&mut renderer);
13184        assert_eq!(
13185            &heatmap[AMBIENT_W..AMBIENT_W + 4],
13186            &mesh::FrameUniforms::HEATMAP_VIEW_ON.to_le_bytes(),
13187            "the switch has to reach the lane the mesh stage branches on",
13188        );
13189        let outside: Vec<usize> = shaded
13190            .iter()
13191            .zip(heatmap.iter())
13192            .enumerate()
13193            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
13194            .map(|(at, _)| at)
13195            .collect();
13196        assert!(
13197            outside.is_empty(),
13198            "the frame block changed at {outside:?}, which is outside the heatmap's own lane",
13199        );
13200
13201        renderer.set_heatmap(false);
13202        assert_eq!(
13203            block(&mut renderer),
13204            shaded,
13205            "switching the view off has to put the block back, not just stop reporting it",
13206        );
13207
13208        renderer.destroy(device.as_ref());
13209    }
13210
13211    /// **The normals view moves one lane of the frame block and nothing else.**
13212    ///
13213    /// The mechanism, at the level a null device can observe it: which bytes of
13214    /// the buffer `mesh.slang` reads changed. A field on the renderer would say
13215    /// only that a flag moved; the block is what the shader actually branches on.
13216    ///
13217    /// Four claims, and each rules out a different way of passing wrongly:
13218    ///
13219    /// * an untouched renderer writes [`FrameUniforms::NORMALS_VIEW_OFF`] — which
13220    ///   is what makes every golden image untouched by this feature;
13221    /// * switching on writes [`FrameUniforms::NORMALS_VIEW_ON`] into the lane the
13222    ///   shader reads, at the offset `std140` puts it at rather than at one this
13223    ///   test picked;
13224    /// * **those four bytes are the only ones that moved**, so the switch did not
13225    ///   come at the cost of the ambient colour beside it or of any matrix;
13226    /// * and switching off puts the block back exactly, so the view is a toggle
13227    ///   rather than a one-way door.
13228    ///
13229    /// [`FrameUniforms::NORMALS_VIEW_OFF`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_OFF
13230    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
13231    #[test]
13232    fn the_normals_view_moves_the_ambients_last_lane_and_no_other_byte() {
13233        // `w` of the second `float4` of the block: one `float4x4`, one `float4`,
13234        // then three floats of ambient colour. Spelled as the sum rather than as
13235        // `92` so that a member arriving before it is a compile-time question
13236        // about `FrameUniforms`' own layout and not a silent read of a matrix.
13237        const AMBIENT_W: usize = 64 + 16 + 12;
13238
13239        // Held for the whole comparison, and it is not this check's own knob:
13240        // `r_shadow_filter` and `r_shadow_split` land in the block's
13241        // `shadow_filter` row on every `begin_frame`, and the filter checks in
13242        // this module move them under this lock while `cargo test` runs the
13243        // module's checks as threads of one process. Two frames read either side
13244        // of such a move differ at that row, which is outside every lane below —
13245        // one run in twelve, measured 2026-09-04.
13246        let _filter = shadow_filter_switch();
13247        let (recorder, device, queue) = open();
13248        let mut renderer =
13249            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13250        let camera = Camera::default();
13251        let light = DirectionalLight::default();
13252        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
13253            renderer
13254                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13255                .expect("write");
13256            recorder
13257                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
13258                .expect("begin_frame wrote the block")
13259        };
13260
13261        assert!(
13262            !renderer.normals_view(),
13263            "the normals view has to be off in a renderer nobody has asked",
13264        );
13265        let shaded = block(&mut renderer);
13266        assert_eq!(
13267            &shaded[AMBIENT_W..AMBIENT_W + 4],
13268            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
13269            "an untouched renderer must write the value every golden image was blessed with",
13270        );
13271
13272        renderer.set_normals_view(true);
13273        assert!(renderer.normals_view());
13274        let normals = block(&mut renderer);
13275        assert_eq!(
13276            &normals[AMBIENT_W..AMBIENT_W + 4],
13277            &mesh::FrameUniforms::NORMALS_VIEW_ON.to_le_bytes(),
13278            "the switch has to reach the lane the fragment stage branches on",
13279        );
13280        // The bytes that moved, and they all have to be inside the lane — not
13281        // *all* of the lane, because `0.0f` and `1.0f` share their two low bytes
13282        // and an equality against the whole range would be a test about IEEE 754
13283        // rather than about the block.
13284        let outside: Vec<usize> = shaded
13285            .iter()
13286            .zip(normals.iter())
13287            .enumerate()
13288            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
13289            .map(|(at, _)| at)
13290            .collect();
13291        assert!(
13292            outside.is_empty(),
13293            "the frame block changed at {outside:?}, which is outside the normals view's own lane",
13294        );
13295
13296        renderer.set_normals_view(false);
13297        assert!(!renderer.normals_view());
13298        assert_eq!(
13299            block(&mut renderer),
13300            shaded,
13301            "switching the view off has to put the block back, not just stop reporting it",
13302        );
13303
13304        renderer.destroy(device.as_ref());
13305    }
13306
13307    /// **A frame uploads the instances a caller moved, and a frame nobody moved
13308    /// anything in uploads nothing at all.**
13309    ///
13310    /// The second half is the stronger claim and it is the one that needed the
13311    /// cube to become an ordinary instance: `begin_frame` used to take the
13312    /// cube's transform as an argument and write it into the pool every frame,
13313    /// so that slot was dirty in every ring slot forever and a motionless scene
13314    /// paid a spinning one's transfer. The bytes were identical, so no golden
13315    /// image could ever have shown it — the recorder's write log is the only
13316    /// place the difference is visible.
13317    ///
13318    /// The pyramid is here so that "only the one that moved" is a claim about a
13319    /// choice: with one instance in the array, uploading it and uploading
13320    /// everything are the same event.
13321    #[test]
13322    fn only_the_instance_that_moved_is_uploaded() {
13323        let (recorder, device, queue) = open();
13324        let mut renderer =
13325            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13326        let instance_buffers = renderer.instances.buffers().to_vec();
13327        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
13328        place_demo(
13329            &mut renderer,
13330            DEMO_PYRAMID,
13331            DEMO_UNTINTED,
13332            Mat4::from_translation(Vec3::X),
13333        );
13334
13335        // Both instances are dirty in *every* slot when they are inserted, so
13336        // the first frames upload both however well delta upload works. The ring
13337        // has to be walked right through before an upload is evidence about the
13338        // delta rather than about initialisation.
13339        let frame = |renderer: &mut ForwardRenderer| {
13340            renderer
13341                .begin_frame(
13342                    device.as_ref(),
13343                    &Camera::default(),
13344                    &DirectionalLight::default(),
13345                    (64, 48),
13346                )
13347                .expect("write");
13348        };
13349        for _ in 0..FRAMES_IN_FLIGHT {
13350            frame(&mut renderer);
13351        }
13352        let instance_writes = |from: usize| -> Vec<(u64, usize)> {
13353            recorder
13354                .events()
13355                .into_iter()
13356                .skip(from)
13357                .filter_map(|event| match event {
13358                    crcbl_hal::null::Event::BufferWritten {
13359                        buffer,
13360                        offset,
13361                        len,
13362                    } if instance_buffers.contains(&buffer) => Some((offset, len)),
13363                    _ => None,
13364                })
13365                .collect()
13366        };
13367
13368        let before = recorder.events().len();
13369        frame(&mut renderer);
13370        assert_eq!(
13371            instance_writes(before),
13372            [],
13373            "a frame in which nothing moved must upload no instance bytes at all"
13374        );
13375
13376        let before = recorder.events().len();
13377        let model = ForwardRenderer::spin(1.25);
13378        renderer.set_instance(
13379            cube,
13380            &InstanceDesc {
13381                mesh: DEMO_CUBE,
13382                material: DEMO_UNTINTED,
13383                transform: model,
13384            },
13385        );
13386        frame(&mut renderer);
13387        assert_eq!(
13388            renderer
13389                .instances
13390                .get(cube)
13391                .expect("the cube is live")
13392                .transform,
13393            model.to_cols_array(),
13394            "the model matrix must land in the instance, not the uniform block"
13395        );
13396        let cube_at = u64::from(renderer.instances.index(cube).expect("the cube is live"))
13397            * crcbl_shaders::mesh::INSTANCE_STRIDE as u64;
13398        assert_eq!(
13399            instance_writes(before),
13400            [(cube_at, crcbl_shaders::mesh::INSTANCE_STRIDE)],
13401            "a steady-state frame must upload exactly the one instance that changed"
13402        );
13403
13404        renderer.destroy(device.as_ref());
13405        recorder.assert_valid();
13406    }
13407
13408    /// **An object takes one pool slot, a rewrite keeps it, and a removal gives
13409    /// it back for the next object to reuse.**
13410    ///
13411    /// The three-call bookkeeping every caller of the instance API depends on,
13412    /// checked on the pool rather than on the recorder. A `set_instance` that
13413    /// inserted instead would take a fresh slot per call — the pool exhausted in
13414    /// a few thousand frames of a caller that writes a transform per frame, which
13415    /// is what every sample does — and every slot it abandoned would stay
13416    /// **live**, so the frame would draw a copy of the object at each transform
13417    /// it had ever been given. Neither is something a golden image would show
13418    /// until the pool ran out.
13419    ///
13420    /// `only_the_instance_that_moved_is_uploaded` is the delta half of this and
13421    /// reads the recorder; this is the bookkeeping half and reads the pool, which
13422    /// is where an abandoned slot would still be counted.
13423    ///
13424    /// Run over every mesh of [`scene::demo`], because the DAG is the one whose
13425    /// slot carries topic 25's hysteresis state — the reuse below is
13426    /// exactly what [`ForwardRenderer::add_instance`] documents as inheriting a
13427    /// previous occupant's expanded groups.
13428    #[test]
13429    fn an_object_takes_one_slot_and_a_removal_gives_it_back() {
13430        for mesh in [DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES] {
13431            let (recorder, device, queue) = open();
13432            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
13433                .expect("built");
13434            // The null backend takes an indirect tail, so the DAG is placeable
13435            // here; the arm that cannot select a level refuses before an
13436            // application ever calls this.
13437            assert!(
13438                renderer.selects_levels(),
13439                "an indirect tail chooses a level for every mesh, DAG included"
13440            );
13441            // What the pool holds before anything is placed, which is nothing: a
13442            // renderer places no object of its own any more.
13443            let resident = renderer.instances.len();
13444            assert_eq!(resident, 0, "a fresh renderer holds no objects");
13445
13446            let first = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
13447            let handle = place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13448            assert_eq!(
13449                renderer.instances.len(),
13450                resident + 1,
13451                "mesh {mesh}: add_instance takes one slot"
13452            );
13453
13454            // The rewrite is the whole test: the same handle, the same slot
13455            // count, and the new transform in it.
13456            let second = Mat4::from_translation(Vec3::new(-4.0, 5.0, -6.0));
13457            renderer.set_instance(
13458                handle,
13459                &InstanceDesc {
13460                    mesh,
13461                    material: DEMO_UNTINTED,
13462                    transform: second,
13463                },
13464            );
13465            assert_eq!(
13466                renderer.instances.len(),
13467                resident + 1,
13468                "mesh {mesh}: set_instance must rewrite its instance, not insert a second"
13469            );
13470            assert_eq!(
13471                renderer.instances.slot_count(),
13472                u32::try_from(resident + 1).expect("a handful of instances"),
13473                "mesh {mesh}: set_instance must not have reached past the slot it holds"
13474            );
13475            assert_eq!(
13476                renderer
13477                    .instances
13478                    .get(handle)
13479                    .unwrap_or_else(|| panic!("mesh {mesh}: the instance is live"))
13480                    .transform,
13481                second.to_cols_array(),
13482                "mesh {mesh}: set_instance must have written the second transform"
13483            );
13484
13485            // And a removal gives the slot back, so a caller toggling an object
13486            // is not a leak either.
13487            renderer.remove_instance(handle);
13488            assert_eq!(
13489                renderer.instances.len(),
13490                resident,
13491                "mesh {mesh}: remove_instance must free the slot rather than hide the object"
13492            );
13493            place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13494            assert_eq!(
13495                renderer.instances.slot_count(),
13496                u32::try_from(resident + 1).expect("a handful of instances"),
13497                "mesh {mesh}: the object after a removal must reuse the freed slot"
13498            );
13499
13500            renderer.destroy(device.as_ref());
13501            recorder.assert_valid();
13502        }
13503    }
13504
13505    /// **The description resolves to the ids the renderer used to hand itself**:
13506    /// one table entry per description mesh, in description order, with the DAG
13507    /// occupying one per level after them — and every level's vertex base
13508    /// measured from level 0's, which is zero.
13509    ///
13510    /// Upload order is what decides a mesh id, and `cull.slang` reads a bounding
13511    /// box out of the entry the *instance* names. So a description walked in
13512    /// another order, or a DAG whose levels landed among the flat meshes, would
13513    /// leave every instance naming a mesh that is not its own: the cube culled
13514    /// against the pyramid's box, the dunes patch drawn as an open box. Every
13515    /// one of those is a frame that still looks like a frame.
13516    ///
13517    /// The bases are asserted against the table bytes rather than against
13518    /// `ResidentMesh`, because the table is what the GPU reads.
13519    #[test]
13520    fn the_description_resolves_to_the_ids_it_was_written_in() {
13521        let (recorder, device, queue) = open();
13522        let renderer =
13523            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13524
13525        assert_eq!(
13526            renderer.mesh_ids,
13527            [0, 1, 2, 3],
13528            "the four description meshes take the first four table entries, in order"
13529        );
13530
13531        // The DAG's coarser levels follow level 0, so a cut that spans them
13532        // reads entries the flat meshes never occupied.
13533        let scene = scene::demo();
13534        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13535            panic!("the demo description's fourth mesh is the DAG");
13536        };
13537        let level_ids: Vec<u32> = (0..dag.levels.len())
13538            .map(|level| renderer.mesh_ids[DEMO_DUNES] + level as u32)
13539            .collect();
13540        assert!(
13541            level_ids
13542                .iter()
13543                .all(|&id| id > renderer.mesh_ids[DEMO_OPEN_BOX]),
13544            "every dunes level is past the flat residents: {level_ids:?}"
13545        );
13546
13547        // **Level 0 is at the pool's own first vertex**, which is what makes
13548        // every `ClusterSelect::vertex_base` a non-negative offset from it — the
13549        // sum the mesh stage forms with the instance's own base.
13550        let entries: Vec<crcbl_shaders::mesh::GpuMesh> = level_ids
13551            .iter()
13552            .map(|&id| mesh_entry(&recorder, &renderer, id))
13553            .collect();
13554        let level_zero = entries[0].base_vertex;
13555        assert_eq!(
13556            level_zero,
13557            mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_OPEN_BOX]).base_vertex
13558                + crcbl_shaders::mesh::OPEN_BOX_VERTEX_COUNT as u32,
13559            "the DAG starts where the last flat resident ends"
13560        );
13561        let bases: Vec<u32> = entries
13562            .iter()
13563            .map(|entry| {
13564                entry
13565                    .base_vertex
13566                    .checked_sub(level_zero)
13567                    .expect("a level below level 0 would wrap the offset a cluster carries")
13568            })
13569            .collect();
13570        assert_eq!(
13571            bases[0], 0,
13572            "level 0 is the base every other is measured from"
13573        );
13574        assert!(
13575            bases.windows(2).all(|pair| pair[0] < pair[1]),
13576            "each level starts past the one below it: {bases:?}"
13577        );
13578
13579        renderer.destroy(device.as_ref());
13580        recorder.assert_valid();
13581    }
13582
13583    /// **A description that is not [`scene::demo`]: five meshes and two DAGs.**
13584    ///
13585    /// [`ForwardRenderer::with_scene`] is written for any mesh count and any
13586    /// number of DAGs, and until this nothing had put either through it — every
13587    /// golden image and every end-to-end run is `scene::demo()`, whose four
13588    /// meshes hold one DAG between them.
13589    ///
13590    /// What only a second DAG exercises is the **concatenation**: `level_groups`
13591    /// is every DAG's groups laid end to end and a DAG reaches its own run
13592    /// through the `first_group` offset handed to `ClusterDag::selection_records`,
13593    /// which is zero for the first one and therefore invisible while there is
13594    /// only one. A second DAG whose records still named the first's groups would
13595    /// descend a hierarchy belonging to another surface — a cut that is a
13596    /// plausible picture and matches no assertion the CPU makes about the frame.
13597    ///
13598    /// On the mesh path, because that is where the offset is *used*: an indirect
13599    /// tail takes a uniform cut and builds no [`ClusterSelect`] records at all.
13600    ///
13601    /// [`ClusterSelect`]: crcbl_shaders::cluster_select::ClusterSelect
13602    #[test]
13603    fn a_second_dag_reaches_its_own_groups_and_not_the_first_s() {
13604        use crcbl_shaders::cluster_select::{CLUSTER_SELECT_STRIDE, ClusterSelect};
13605
13606        let recorder = Recorder::new();
13607        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
13608
13609        // The engine has one DAG, so a second one is a second copy of it. That
13610        // is the whole point: two DAGs whose *groups* are alike is the case
13611        // where reaching the wrong run still produces a cut, and so the case a
13612        // frame comparison could never catch.
13613        let mut scene = scene::demo();
13614        let mut again = scene.meshes[DEMO_DUNES].clone();
13615        again.label = "dunes again".into();
13616        scene.meshes.push(again);
13617        // Room for the second copy. Doubling rather than measuring, because the
13618        // number that matters is that the description carries its own sizes at
13619        // all — see `Capacities`, which is the caller's to choose.
13620        scene.capacities.vertices *= 2;
13621        scene.capacities.indices *= 2;
13622        let second_dag = scene.meshes.len() - 1;
13623
13624        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13625            panic!("the demo description's fourth mesh is the DAG");
13626        };
13627        let levels = dag.levels.len();
13628        let groups = dag.level_groups().len();
13629        assert!(groups > 0, "a DAG with no groups would select nothing");
13630
13631        let mut renderer =
13632            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13633                .expect("a five-mesh description with two DAGs is one this can make resident");
13634
13635        // Every level of both is its own table entry, laid down in description
13636        // order, so the second DAG's level 0 is a whole hierarchy past the
13637        // first's.
13638        assert_eq!(
13639            renderer.mesh_ids.len(),
13640            scene.meshes.len(),
13641            "one id per description mesh, whatever the count"
13642        );
13643        assert_eq!(
13644            renderer.mesh_ids[second_dag],
13645            renderer.mesh_ids[DEMO_DUNES] + levels as u32,
13646            "the second DAG's level 0 starts past every level of the first"
13647        );
13648
13649        // **The hysteresis state is per instance per resident group**, and
13650        // `group_stride` is what says how many groups that is. One DAG made this
13651        // number a single hierarchy's; two is what tells a stride that sums from
13652        // one that took the first answer it found.
13653        assert_eq!(
13654            renderer.primary.draws.group_stride(),
13655            u32::try_from(groups * 2).expect("a few dozen groups per DAG"),
13656            "every resident DAG's groups are in the stride, not just the first's"
13657        );
13658
13659        // The records themselves: which group each cluster produces and which
13660        // contains it, as the amplification stage reads them.
13661        let clusters = renderer
13662            .clusters
13663            .as_ref()
13664            .expect("the mesh path builds a cluster pool");
13665        let selection = recorder
13666            .buffer_bytes(clusters.selection())
13667            .expect("the selection records are live");
13668        // Entries are laid down in description order, a flat mesh taking one and
13669        // a DAG one per level — so the second DAG's start a hierarchy past the
13670        // first's, which start past the three flat residents.
13671        let first_entry = DEMO_DUNES;
13672        let record = |entry: usize| -> Vec<ClusterSelect> {
13673            let range = clusters.range(entry).expect("one range per entry");
13674            (range.base..range.base + range.count)
13675                .map(|cluster| {
13676                    let at = cluster as usize * CLUSTER_SELECT_STRIDE;
13677                    ClusterSelect::from_bytes(
13678                        selection[at..at + CLUSTER_SELECT_STRIDE]
13679                            .try_into()
13680                            .expect("one whole record"),
13681                    )
13682                })
13683                .collect()
13684        };
13685        // The named group of every record that has one, per DAG — and the count,
13686        // because a comparison over an empty set is a check that cannot fail.
13687        let named = |base: usize| -> Vec<u32> {
13688            (base..base + levels)
13689                .flat_map(record)
13690                .flat_map(|select| {
13691                    let producer = (select.flags & ClusterSelect::HAS_PRODUCER != 0)
13692                        .then_some(select.producer_group);
13693                    let container = (select.flags & ClusterSelect::HAS_CONTAINER != 0)
13694                        .then_some(select.container_group);
13695                    producer.into_iter().chain(container)
13696                })
13697                .collect()
13698        };
13699        let boundary = u32::try_from(groups).expect("a few dozen groups per DAG");
13700        let first = named(first_entry);
13701        let second = named(first_entry + levels);
13702        assert!(
13703            !first.is_empty() && first.len() == second.len(),
13704            "the two copies must name the same number of groups: {} against {}",
13705            first.len(),
13706            second.len()
13707        );
13708        assert!(
13709            first.iter().all(|&group| group < boundary),
13710            "the first DAG's records stay inside its own run: {first:?}"
13711        );
13712        assert!(
13713            second
13714                .iter()
13715                .all(|&group| (boundary..boundary * 2).contains(&group)),
13716            "the second DAG's records must name the groups past the first's, and \
13717             `first_group` is the only thing that puts them there: {second:?}"
13718        );
13719
13720        // And both are placeable through the runtime API, which is what a
13721        // description of a shape no `set_*` method names is *for*.
13722        let place = |renderer: &mut ForwardRenderer, mesh: usize, x: f32| {
13723            renderer
13724                .add_instance(&InstanceDesc {
13725                    mesh,
13726                    material: DEMO_UNTINTED,
13727                    transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)),
13728                })
13729                .expect("the pool has room")
13730        };
13731        let near = place(&mut renderer, DEMO_DUNES, -64.0);
13732        let far = place(&mut renderer, second_dag, 64.0);
13733        let index = |handle| {
13734            renderer
13735                .instances
13736                .index(handle)
13737                .expect("a just-added instance is live")
13738        };
13739        assert_ne!(
13740            index(near),
13741            index(far),
13742            "two instances take two slots, and the index is the hysteresis key"
13743        );
13744        assert_eq!(
13745            renderer.instances.get(far).expect("live").mesh,
13746            renderer.mesh_ids[second_dag],
13747            "an InstanceDesc's mesh index resolves through the description, not through \
13748             a table id the caller cannot know"
13749        );
13750
13751        renderer.destroy(device.as_ref());
13752        recorder.assert_valid();
13753    }
13754
13755    /// **A description the renderer cannot make resident is refused before the
13756    /// first device object exists**, so a rejection leaks nothing.
13757    ///
13758    /// `build` hands the geometry pool and the material table to the rollback
13759    /// and then creates a dozen objects with `?` between them. A check that ran
13760    /// part way down that list would be a new early exit on the wrong side of a
13761    /// handover, and the pool would go with it — which is exactly the leak
13762    /// `Rollback` exists to prevent and which
13763    /// `the_forward_renderer_builds_and_leaks_nothing` cannot see, because it
13764    /// only walks the happy path.
13765    ///
13766    /// Each arm below is a *different* refusal, so a check that stopped running
13767    /// would show up as one arm leaking rather than as all of them — and each
13768    /// names a fragment of the message it must be refused *with*, or an arm
13769    /// would pass on some other check's answer.
13770    /// **A description with no meshes is refused by name**, before anything
13771    /// is created, rather than reaching the mesh table's sizing with nothing
13772    /// to size it from.
13773    #[test]
13774    fn a_scene_with_no_meshes_is_refused_by_name() {
13775        let (recorder, device, queue) = open();
13776        let before = recorder.total_live_objects();
13777        let mut scene = scene::demo();
13778        scene.meshes.clear();
13779        let error =
13780            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13781                .expect_err("a scene of no meshes must be refused");
13782        assert!(
13783            error.to_string().contains("at least one mesh"),
13784            "the refusal says what is missing: {error}"
13785        );
13786        assert_eq!(
13787            recorder.total_live_objects(),
13788            before,
13789            "the refusal created something"
13790        );
13791    }
13792
13793    #[test]
13794    fn a_refused_description_creates_nothing_at_all() {
13795        /// One way of writing a description the renderer cannot build, and the
13796        /// words that say it was this refusal rather than another.
13797        type Break = (&'static str, fn(&mut SceneDesc<'static>), &'static str);
13798
13799        let cases: [Break; 9] = [
13800            (
13801                "a row naming a layer the page has not got",
13802                |scene| {
13803                    scene.materials[DEMO_TEXTURED].base_color_texture = 7;
13804                },
13805                "material row 2 samples base-colour page layer 7",
13806            ),
13807            // And the same on the two kinds rung 3 added, because `check_scene`
13808            // reads a different column of the row for each: a check written per
13809            // kind is only worth what its arms cover, and a column nobody broke
13810            // here could be read out of the wrong material field for ever.
13811            // `demo` names no layer of either, so any index at all is past the
13812            // end.
13813            (
13814                "a row naming a packed-page layer the page has not got",
13815                |scene| {
13816                    scene.materials[DEMO_TEXTURED].metallic_roughness_occlusion_texture = 3;
13817                },
13818                "material row 2 samples metallic-roughness-occlusion page layer 3",
13819            ),
13820            (
13821                "a row naming an emissive layer the page has not got",
13822                |scene| {
13823                    scene.materials[DEMO_TEXTURED].emissive_texture = 3;
13824                },
13825                "material row 2 samples emissive page layer 3",
13826            ),
13827            // The one page refusal a caller can actually spell: `push_layer`
13828            // takes bytes it cannot measure against the extent.
13829            (
13830                "a page layer of the wrong length",
13831                |scene| {
13832                    scene.page = scene::PageDesc::empty();
13833                    scene
13834                        .page
13835                        .set_extent(PageKind::BaseColor, scene::PAGE_EXTENT);
13836                    scene.page.push_layer(PageKind::BaseColor, vec![0x00; 4]);
13837                    scene.materials[DEMO_TEXTURED].base_color_texture = scene::CHECKER_LAYER;
13838                },
13839                "base-colour page layer 0 carries 4 bytes",
13840            ),
13841            (
13842                "a DAG level with no vertices",
13843                |scene| {
13844                    let Geometry::Dag { levels, .. } = &mut scene.meshes[DEMO_DUNES].geometry
13845                    else {
13846                        panic!("the demo description's fourth mesh is the DAG");
13847                    };
13848                    levels.pop();
13849                },
13850                "vertex array(s) for a DAG of",
13851            ),
13852            // The four capacities, each of which is a pool a caller sized and
13853            // a description outgrew. Written as a capacity the description is
13854            // too large for rather than as a description too large for the
13855            // default, because that is the shape of the mistake: the numbers on
13856            // `Capacities` are the ones an application picks.
13857            (
13858                "more vertices than the pool holds",
13859                |scene| {
13860                    scene.capacities.vertices = 1;
13861                },
13862                "the vertex pool holds 1 and the description needs",
13863            ),
13864            (
13865                "more indices than the pool holds",
13866                |scene| {
13867                    scene.capacities.indices = 1;
13868                },
13869                "the index pool holds 1 and the description needs",
13870            ),
13871            (
13872                "more meshes than the table holds",
13873                |scene| {
13874                    scene.capacities.meshes = 1;
13875                },
13876                "the mesh table holds 1 and the description needs",
13877            ),
13878            (
13879                "more material rows than the table holds",
13880                |scene| {
13881                    scene.capacities.materials = 2;
13882                },
13883                "the material table holds 2 and the description needs 3",
13884            ),
13885        ];
13886
13887        for (what, break_it, says) in cases {
13888            let (recorder, device, queue) = open();
13889            let before = recorder.total_live_objects();
13890            let mut scene = scene::demo();
13891            break_it(&mut scene);
13892            let error =
13893                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13894                    .expect_err(&format!("{what} must be refused"));
13895            assert!(
13896                matches!(error, HalError::InvalidDescriptor(_)),
13897                "{what} must be refused as an invalid descriptor, not as {error:?}"
13898            );
13899            assert!(
13900                error.to_string().contains(says),
13901                "{what} must be refused with a message saying so, and this one says {error}"
13902            );
13903            assert_eq!(
13904                recorder.total_live_objects(),
13905                before,
13906                "{what} was refused after something had been created, and the rollback \
13907                 is the only thing that could have released it"
13908            );
13909            recorder.assert_valid();
13910        }
13911
13912        // **And the refusal that is not free**, which is the half of the
13913        // handover every arm above walks past: `check_scene` settles what the
13914        // whole description says, and what one mesh's *bytes* say is the pool's,
13915        // which only sees them one upload at a time. Vertex bytes that are not a
13916        // whole number of vertices reach `MeshPool::upload` — so the third of
13917        // the four meshes is refused with the pool created, two device-local
13918        // buffers in it and the first two meshes already staged into them.
13919        // `build_geometry` is what releases that, and it can only do so because
13920        // the pool is not the rollback's until it has returned.
13921        let (recorder, device, queue) = open();
13922        let before = recorder.total_live_objects();
13923        // So the count below is this build's and not `open`'s.
13924        recorder.clear();
13925        let mut scene = scene::demo();
13926        let Geometry::Flat { vertices, .. } = &mut scene.meshes[DEMO_OPEN_BOX].geometry else {
13927            panic!("the demo description's third mesh is flat");
13928        };
13929        vertices.to_mut().push(0);
13930        let error =
13931            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13932                .expect_err("a mesh of part of a vertex must be refused");
13933        assert!(
13934            error.to_string().contains("is not a whole number of"),
13935            "the pool's own refusal reaches the caller with its numbers, and this \
13936             one says {error}"
13937        );
13938        assert!(
13939            recorder
13940                .events()
13941                .iter()
13942                .any(|event| matches!(event, crcbl_hal::null::Event::Created { .. })),
13943            "this arm is evidence about the rollback only if the refusal came after \
13944             something had been created"
13945        );
13946        assert_eq!(
13947            recorder.total_live_objects(),
13948            before,
13949            "a mesh refused part way through the list left the geometry pool behind, \
13950             which is exactly what `build_geometry` being self-cleaning is for"
13951        );
13952        recorder.assert_valid();
13953    }
13954
13955    /// **The one capacity a description cannot be checked against, and the one
13956    /// an application is expected to handle while it runs.**
13957    ///
13958    /// Every other number on [`scene::Capacities`] sizes something the
13959    /// description fills once, so `check_scene` refuses an over-large one before
13960    /// a device object exists. Objects are placed at any point in a renderer's
13961    /// life, so the only honest answer for that one is the error
13962    /// [`ForwardRenderer::add_instance`] returns — and it returns
13963    /// [`InstancePoolError`] rather than a [`HalError`], so the capacity and
13964    /// what is in it survive to the caller that chose them.
13965    ///
13966    /// It also gives [`Capacities::instances`](scene::Capacities::instances) a
13967    /// value of its own rather than the default, which is what makes the pool
13968    /// fillable at all: a renderer that ignored the number the description
13969    /// carries and reserved the default would draw every frame in the tree
13970    /// identically and refuse nothing here.
13971    #[test]
13972    fn a_full_instance_pool_reaches_the_application_that_sized_it() {
13973        let (recorder, device, queue) = open();
13974        let mut scene = scene::demo();
13975        scene.capacities.instances = 2;
13976        let mut renderer =
13977            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13978                .expect("a scene with room for two objects builds");
13979        let place = |renderer: &mut ForwardRenderer| {
13980            renderer.add_instance(&InstanceDesc {
13981                mesh: DEMO_CUBE,
13982                material: DEMO_UNTINTED,
13983                transform: Mat4::IDENTITY,
13984            })
13985        };
13986        place(&mut renderer).expect("the first of two");
13987        place(&mut renderer).expect("the second of two");
13988        let error = place(&mut renderer).expect_err("a third object has no slot to go in");
13989        assert!(
13990            matches!(
13991                error,
13992                InstancePoolError::PoolFull {
13993                    capacity: 2,
13994                    in_use: 2
13995                }
13996            ),
13997            "a full pool must reach the caller as a full pool, with the capacity it \
13998             chose; this arrived as {error}"
13999        );
14000        renderer.destroy(device.as_ref());
14001        recorder.assert_valid();
14002    }
14003
14004    /// **One mesh and one material row is a scene, and it draws.**
14005    ///
14006    /// The floor is gone. `with_scene` used to refuse anything shorter than
14007    /// [`scene::demo`] — four meshes and three rows — because the five `set_*`
14008    /// demo wrappers named those entries by position, and the renderer's own
14009    /// `dunes_clusters` and `dunes_level_buckets` indexed the description at
14010    /// `DEMO_DUNES` besides. So an application's own description was not merely
14011    /// refused: with the check removed it would have panicked out of `build`.
14012    ///
14013    /// A frame is recorded rather than only a build, because that is where the
14014    /// positional indexing was: the bucket table, the cluster ranges and the
14015    /// draw-argument blocks are all one-per-description-mesh, and a renderer that
14016    /// still assumed four would come apart here rather than at `with_scene`.
14017    #[test]
14018    fn a_description_smaller_than_the_demo_is_a_scene() {
14019        use std::borrow::Cow;
14020
14021        let scene = SceneDesc {
14022            meshes: vec![scene::MeshDesc {
14023                label: Cow::Borrowed("the only mesh"),
14024                geometry: Geometry::Flat {
14025                    vertices: Cow::Owned(crcbl_shaders::mesh::cube_vertex_bytes()),
14026                    uv_range: crcbl_shaders::mesh::demo_uv_range(),
14027                    indices: Cow::Owned(crcbl_shaders::mesh::cube_indices()),
14028                    clusters: crcbl_shaders::meshlet::cube_clusters(),
14029                    flags: 0,
14030                },
14031            }],
14032            materials: vec![mesh::GpuMaterial::UNTINTED],
14033            page: scene::PageDesc::empty(),
14034            probes: scene::ProbeGrid::default(),
14035            capacities: scene::Capacities::default(),
14036        };
14037        assert!(
14038            scene.meshes.len() < scene::demo().meshes.len()
14039                && scene.materials.len() < scene::demo().materials.len(),
14040            "this description must be smaller than the demo's in both, or it says nothing \
14041             about the floor"
14042        );
14043
14044        let (recorder, device, queue) = open();
14045        let mut renderer =
14046            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14047                .expect("one mesh and one row is a description the renderer can hold");
14048        assert_eq!(
14049            renderer.mesh_ids,
14050            [0],
14051            "the one description mesh takes the one table entry"
14052        );
14053        assert_eq!(
14054            renderer.bucket_constants.len(),
14055            1,
14056            "one bucket per description mesh, and there is one"
14057        );
14058        renderer
14059            .add_instance(&InstanceDesc {
14060                mesh: 0,
14061                material: 0,
14062                transform: Mat4::IDENTITY,
14063            })
14064            .expect("an empty pool has room for the only object");
14065        let recorded = frame(device.as_ref(), &mut renderer, queue);
14066        assert_eq!(
14067            commands_in_pass(&recorder, "forward")
14068                .into_iter()
14069                .filter(|command| matches!(
14070                    command,
14071                    crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
14072                ))
14073                .count(),
14074            1,
14075            "a one-mesh scene records the one bucket's indirect call"
14076        );
14077        recorded.finish(device.as_ref(), renderer);
14078    }
14079
14080    /// **A description that exactly fills what it reserved is built, not
14081    /// refused.**
14082    ///
14083    /// The other side of the capacity check, and the side nothing else in the
14084    /// tree can fail on: every other scene reserves far more than it holds, so a
14085    /// comparison written `>=` instead of `>` would pass the whole suite and
14086    /// refuse only the application that had sized its pools exactly right.
14087    ///
14088    /// The two capacities asserted here are the two a caller can size without
14089    /// re-deriving anything the renderer knows: one mesh table entry per
14090    /// [`Geometry::levels`], which is what that method is documented to answer,
14091    /// and one row per material. The four rows share one comparison, so they
14092    /// stand or fall together.
14093    #[test]
14094    fn a_description_that_exactly_fits_its_capacities_is_built() {
14095        let (recorder, device, queue) = open();
14096        let mut scene = scene::demo();
14097        scene.capacities.meshes = scene
14098            .meshes
14099            .iter()
14100            .map(|desc| u32::try_from(desc.geometry.levels()).expect("a few levels"))
14101            .sum();
14102        scene.capacities.materials =
14103            u32::try_from(scene.materials.len()).expect("a few material rows");
14104        let renderer =
14105            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14106                .expect("a description that fits exactly is not too large for itself");
14107        renderer.destroy(device.as_ref());
14108        recorder.assert_valid();
14109    }
14110
14111    /// **The level tables cover every mesh-table slot an instance can name**,
14112    /// not only the slots the description filled.
14113    ///
14114    /// `draw_gen.slang`'s `mesh_levels_of` reads `gen.mesh_levels_at + mesh *
14115    /// MESH_LEVELS_WORDS` with no bound, and says in its own doc comment that
14116    /// "every entry an instance can name is filled". An instance's mesh id is a
14117    /// bare table index, so a table sized to the description alone makes that
14118    /// read land in whatever the packer put next for any slot the description
14119    /// left empty.
14120    ///
14121    /// Growing the capacity by a known number of slots grows the tables buffer
14122    /// by exactly what those slots occupy: one `MeshLevels` record and one
14123    /// `level_meshes` word each. The arithmetic is the assertion, so nothing
14124    /// here is a number to keep in step by hand.
14125    #[test]
14126    fn the_level_tables_cover_every_slot_the_mesh_table_has() {
14127        const EXTRA: u32 = 4;
14128
14129        let sized = |extra: u32| {
14130            let (recorder, device, queue) = open();
14131            let mut scene = scene::demo();
14132            scene.capacities.meshes += extra;
14133            let renderer =
14134                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14135                    .expect("a description with room to spare");
14136            let size = recorder
14137                .buffer_bytes(renderer.primary.draws.tables())
14138                .expect("the table buffer is live")
14139                .len();
14140            renderer.destroy(device.as_ref());
14141            recorder.assert_valid();
14142            size
14143        };
14144
14145        let grown = sized(EXTRA) - sized(0);
14146        let want = EXTRA as usize * (crcbl_shaders::level_select::MESH_LEVELS_STRIDE + 4);
14147        assert_eq!(
14148            grown, want,
14149            "{EXTRA} more table slots must add {EXTRA} more selection records and {EXTRA} more \
14150             level words, and added {grown} bytes"
14151        );
14152    }
14153
14154    /// The property the whole arrangement exists for: the pool's second
14155    /// resident is **not** at base vertex zero, so a frame containing it is a
14156    /// frame that fails if the base is lost between the pool and the shader.
14157    ///
14158    /// Read out of the **mesh table** rather than out of a renderer field,
14159    /// because the table is where a generated draw's index range comes from:
14160    /// `draw_gen.slang` builds every argument structure out of these bytes and
14161    /// nothing on the CPU is consulted.
14162    ///
14163    /// Without this the pass is back where it started — one mesh, base 0, and a
14164    /// base-vertex bug that no picture can show.
14165    #[test]
14166    fn the_second_mesh_lands_past_the_first() {
14167        let (recorder, device, queue) = open();
14168        let renderer =
14169            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14170        let cube = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_CUBE]);
14171        let pyramid = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_PYRAMID]);
14172
14173        assert_eq!(cube.base_vertex, 0, "the cube is first");
14174        assert_eq!(
14175            pyramid.base_vertex as usize,
14176            crcbl_shaders::mesh::CUBE_VERTEX_COUNT,
14177            "the pyramid must start where the cube ends, or the pools are not \
14178             suballocating at all"
14179        );
14180        assert_eq!(
14181            pyramid.index_count as usize,
14182            crcbl_shaders::mesh::PYRAMID_INDEX_COUNT,
14183            "and the entry carries the whole range, which is what the draw-argument \
14184             pass builds its arguments out of"
14185        );
14186        // And the two buckets read different constant blocks, or both would walk
14187        // the same run of instances.
14188        assert_ne!(
14189            renderer.bucket_constants[DEMO_CUBE], renderer.bucket_constants[DEMO_PYRAMID],
14190            "each bucket needs a block of its own"
14191        );
14192        renderer.destroy(device.as_ref());
14193    }
14194
14195    /// **Each bucket's block points at that bucket's own run**, and the runs do
14196    /// not overlap.
14197    ///
14198    /// This is what replaced "the block names an instance": a draw covers
14199    /// however many instances survived culling, so what it can say for itself is
14200    /// only where to find its slice of the survivors. Two buckets naming one
14201    /// start word would draw each other's objects — with the *right* geometry,
14202    /// because the index range comes from the arguments, which is exactly the
14203    /// kind of plausible wrong picture a golden image struggles with.
14204    ///
14205    /// Read out of the bytes that reached the device rather than out of the
14206    /// renderer's own fields, because the failure is a block written wrong and
14207    /// the field would still be right.
14208    #[test]
14209    fn each_bucket_walks_its_own_run_of_survivors() {
14210        let (recorder, device, queue) = open();
14211        let renderer =
14212            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14213        let blocks = recorder
14214            .buffer_bytes(renderer.draw_constants)
14215            .expect("the blocks are live");
14216        let start_word_at = |offset: u32| {
14217            let at = offset as usize;
14218            u32::from_le_bytes(blocks[at..at + 4].try_into().expect("four bytes"))
14219        };
14220
14221        let draws = &renderer.primary.draws;
14222        let cube = start_word_at(renderer.bucket_constants[DEMO_CUBE]);
14223        let pyramid = start_word_at(renderer.bucket_constants[DEMO_PYRAMID]);
14224        // **Behind the survivors, their routes and the runs**, which share the
14225        // buffer: a block naming a word inside the runs would have the draw read
14226        // an instance index as its start, and one inside the survivor list or
14227        // the routes a start that is the same instances in a different order, or
14228        // a bucket number — both of which draw a plausible picture.
14229        assert_eq!(
14230            cube,
14231            draws.runs_at() + draws.visible_capacity(),
14232            "the first bucket's start word is the first word past one capacity of runs"
14233        );
14234        assert_eq!(
14235            pyramid,
14236            cube + (DEMO_PYRAMID - DEMO_CUBE) as u32,
14237            "and the second's is a word later — a start per bucket, not a run per bucket"
14238        );
14239        assert_eq!(
14240            cube,
14241            draws.bucket_start_word(DEMO_CUBE as u32),
14242            "the block carries what `DrawGen::bucket_start_word` says, because a reader \
14243             copying a run back uses that accessor and the shader uses this block"
14244        );
14245        renderer.destroy(device.as_ref());
14246    }
14247
14248    /// **An instance's record carries its material's mode**, in the bits
14249    /// `draw_gen.slang` routes by.
14250    ///
14251    /// The host half of the per-bucket split, and the half no picture and no
14252    /// pipeline bind can show: the bucket table can be perfectly twinned and
14253    /// every partition bound to the right pipeline while every instance still
14254    /// answers mode zero, in which case the masked twins are empty, the cutout
14255    /// partition draws nothing, and a cutout casts a solid shadow. The record is
14256    /// where that is decided.
14257    ///
14258    /// Both directions, so the check is shown to discriminate: the opaque
14259    /// instance's mode bits have to be **clear**, or a writer that set them
14260    /// unconditionally would satisfy a one-sided assertion. And the two records
14261    /// are asserted to differ in `flags` and nothing else, so this is about the
14262    /// mode rather than about two unrelated instances.
14263    #[test]
14264    fn an_instances_record_carries_its_materials_mode() {
14265        let masked_scene = {
14266            let mut scene = crate::scene::demo();
14267            scene.materials[DEMO_TINTED].flags = crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
14268            scene
14269        };
14270        let (recorder, device, queue) = open();
14271        let device = device.as_ref();
14272        let mut renderer =
14273            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &masked_scene)
14274                .expect("the null backend accepts the demo description");
14275        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14276        let opaque = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14277        let masked = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14278
14279        let record = |handle: InstanceHandle| {
14280            renderer
14281                .instances
14282                .get(handle)
14283                .expect("the instance was inserted and is live")
14284        };
14285        let opaque = record(opaque);
14286        let masked = record(masked);
14287        assert_eq!(
14288            opaque.material_mode(),
14289            0,
14290            "an opaque material's instance carries no mode bits, or every instance in the tree \
14291             routes to a cutout bucket"
14292        );
14293        assert_eq!(
14294            masked.material_mode(),
14295            crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK,
14296            "and a masked material's instance carries its mode, or it scatters into the opaque \
14297             twin and the depth passes write its full silhouette"
14298        );
14299        assert_eq!(
14300            mesh::GpuInstance {
14301                flags: opaque.flags,
14302                material: opaque.material,
14303                ..masked
14304            },
14305            opaque,
14306            "the two records differ in the mode bits and the material id and in nothing else"
14307        );
14308
14309        renderer.destroy(device);
14310        recorder.assert_valid();
14311    }
14312
14313    /// **A scene whose materials are all opaque gets exactly the bucket table
14314    /// it had before material modes existed** — one bucket per (mesh, level),
14315    /// and no twin.
14316    ///
14317    /// The zero-cost half of the per-bucket split, and the one a null device can
14318    /// state exactly. A bucket is not free: every pass records one indirect call
14319    /// per bucket per view, and every generator holds a run start per bucket. So
14320    /// a table that twinned unconditionally would double the recorded draws of
14321    /// every demo and every golden in this tree, none of which mask anything.
14322    ///
14323    /// The oracle is [`level_buckets`](ForwardRenderer::level_buckets), which is
14324    /// built from a mesh's own level count rather than from the table's length —
14325    /// so a build that emitted a twin per mesh has more buckets than levels and
14326    /// this says so. And the twinned scenes below are asserted to be exactly as
14327    /// many times as long as they hold modes, or the comparison would pass on a
14328    /// renderer that had stopped twinning at all.
14329    ///
14330    /// # A twin per mode the scene **holds**, not per mode that exists
14331    ///
14332    /// [`DEPTH_MODES`] has four entries and a bucket is not free — every pass
14333    /// records one indirect call per bucket — so the rule that matters is which
14334    /// values the description's own materials carry. Two rows of two modes are
14335    /// two twins whichever two they are, and the pair below says so both ways:
14336    /// three modes across three rows is three, and three rows collapsed onto two
14337    /// *values* is two even though between them they set both mode bits.
14338    #[test]
14339    fn an_all_opaque_scene_keeps_one_bucket_per_mesh_level() {
14340        use crcbl_shaders::mesh::GpuMaterial;
14341
14342        let (recorder, device, queue) = open();
14343        let device = device.as_ref();
14344        let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
14345        // The uniform-cut path, where a DAG is one bucket per level. The mesh
14346        // path folds a DAG into one bucket and reports no level buckets at all,
14347        // which would leave the oracle below empty.
14348        assert!(
14349            !renderer.emit.is_mesh(),
14350            "this preset built a mesh-shader path, whose level buckets are empty"
14351        );
14352        let levels: usize = (0..crate::scene::demo().meshes.len())
14353            .map(|mesh| renderer.level_buckets(mesh).len())
14354            .sum();
14355        assert!(levels > 0, "the demo has meshes, so it has levels");
14356        assert_eq!(
14357            renderer.bucket_constants.len(),
14358            levels,
14359            "an all-opaque scene's bucket table is one bucket per (mesh, level) and no mode \
14360             twin: {levels} level(s) against {} bucket(s)",
14361            renderer.bucket_constants.len()
14362        );
14363        assert_eq!(
14364            renderer.bucket_modes,
14365            vec![0; levels],
14366            "and every one of them draws the OPAQUE mode"
14367        );
14368        let opaque_meshes = renderer.draw_tables.bucket_meshes.clone();
14369        let opaque_level_buckets: Vec<Vec<u32>> = (0..crate::scene::demo().meshes.len())
14370            .map(|mesh| renderer.level_buckets(mesh).to_vec())
14371            .collect();
14372        renderer.destroy(device);
14373        recorder.assert_valid();
14374
14375        // Every arrangement worth stating, as the modes its material rows carry
14376        // and the number of twins that has to produce. The demo has three rows;
14377        // a fourth is appended where four distinct modes are wanted, which
14378        // nothing instances and which therefore changes nothing but the mode
14379        // set.
14380        for (rows, modes, what) in [
14381            (
14382                vec![GpuMaterial::ALPHA_MODE_MASK, 0, 0],
14383                2,
14384                "one masked row beside two opaque ones",
14385            ),
14386            (
14387                vec![GpuMaterial::DOUBLE_SIDED, 0, 0],
14388                2,
14389                "one double-sided row beside two opaque ones",
14390            ),
14391            (
14392                vec![GpuMaterial::ALPHA_MODE_MASK, GpuMaterial::DOUBLE_SIDED, 0],
14393                3,
14394                "a masked row, a double-sided one and an opaque one",
14395            ),
14396            (
14397                vec![
14398                    GpuMaterial::ALPHA_MODE_MASK,
14399                    GpuMaterial::DOUBLE_SIDED,
14400                    GpuMaterial::ALPHA_MODE_MASK,
14401                ],
14402                2,
14403                "three rows carrying two mode values between them — both mode bits are set \
14404                 somewhere and neither row is opaque, so a rule counting bits rather than \
14405                 values would say three",
14406            ),
14407            (
14408                vec![
14409                    0,
14410                    GpuMaterial::ALPHA_MODE_MASK,
14411                    GpuMaterial::DOUBLE_SIDED,
14412                    GpuMaterial::MODE_MASK,
14413                ],
14414                4,
14415                "one row of each mode, which is the only arrangement that pays for four",
14416            ),
14417        ] {
14418            let scene = {
14419                let mut scene = crate::scene::demo();
14420                while scene.materials.len() < rows.len() {
14421                    scene.materials.push(GpuMaterial::UNTINTED);
14422                }
14423                for (row, flags) in scene.materials.iter_mut().zip(&rows) {
14424                    row.flags = *flags;
14425                }
14426                scene
14427            };
14428            let (recorder, device, queue) = open();
14429            let device = device.as_ref();
14430            let twinned =
14431                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
14432                    .expect("the null backend accepts the demo description");
14433            assert_eq!(
14434                twinned.bucket_constants.len(),
14435                modes * levels,
14436                "{what}: {modes} mode(s) over {levels} level(s) is {} bucket(s), and the table \
14437                 has {}",
14438                modes * levels,
14439                twinned.bucket_constants.len()
14440            );
14441            // The modes present, as a set — which is the claim, since the order
14442            // is `DEPTH_MODES`' and the count above already pins the length.
14443            let held: std::collections::BTreeSet<u32> =
14444                twinned.bucket_modes.iter().copied().collect();
14445            let want: std::collections::BTreeSet<u32> = rows.iter().copied().collect();
14446            assert_eq!(
14447                held, want,
14448                "{what}: the table twins the modes its materials carry and no others"
14449            );
14450            for mode in &held {
14451                assert_eq!(
14452                    twinned
14453                        .bucket_modes
14454                        .iter()
14455                        .filter(|held| *held == mode)
14456                        .count(),
14457                    levels,
14458                    "{what}: every mode present gets every mesh's levels once"
14459                );
14460            }
14461            // **Mode-major**: each held mode is one contiguous run of the
14462            // all-opaque table, in `DEPTH_MODES` order, so a pipeline's
14463            // partition is one range of buckets.
14464            let held_in_order: Vec<u32> = DEPTH_MODES
14465                .into_iter()
14466                .filter(|mode| held.contains(mode))
14467                .collect();
14468            assert_eq!(
14469                twinned.bucket_modes,
14470                held_in_order
14471                    .iter()
14472                    .flat_map(|mode| std::iter::repeat_n(*mode, levels))
14473                    .collect::<Vec<_>>(),
14474                "{what}: every bucket of one mode is contiguous, modes in DEPTH_MODES order"
14475            );
14476            assert_eq!(
14477                twinned.draw_tables.bucket_meshes,
14478                opaque_meshes.repeat(held_in_order.len()),
14479                "{what}: each mode's run is the all-opaque table, mesh by mesh"
14480            );
14481            for (mesh, opaque) in opaque_level_buckets.iter().enumerate() {
14482                assert_eq!(
14483                    twinned.level_buckets(mesh),
14484                    opaque.as_slice(),
14485                    "{what}: mesh {mesh}'s level buckets are the first mode's run"
14486                );
14487            }
14488            // And the `(mesh, mode) → bucket` lookup the scatter routes through
14489            // sends every key to its mode's run, at the mesh's own offset.
14490            let lookup = crcbl_shaders::draw_gen::bucket_lookup(
14491                &twinned.draw_tables.bucket_meshes,
14492                &twinned.bucket_modes,
14493            )
14494            .expect("a small lookup");
14495            for (slot, mode) in held_in_order.iter().enumerate() {
14496                for (offset, mesh) in opaque_meshes.iter().enumerate() {
14497                    let key = 1 + (*mesh * crcbl_shaders::draw_gen::MATERIAL_MODES + *mode);
14498                    assert_eq!(
14499                        lookup[key as usize] as usize,
14500                        slot * levels + offset,
14501                        "{what}: mesh {mesh} in mode {mode}"
14502                    );
14503                }
14504            }
14505            twinned.destroy(device);
14506            recorder.assert_valid();
14507        }
14508    }
14509
14510    /// **The two pyramids differ in exactly one field, and it is the material
14511    /// id — which names a row holding a different colour and a different
14512    /// roughness.**
14513    ///
14514    /// The whole of what §3.2's table buys, stated as the two things that have
14515    /// to be true at once. Placed at the *same* transform, so "differ only in
14516    /// material" is literal rather than nearly: same mesh id, same matrix, same
14517    /// flags, and a `GpuInstance` comparison that would fail on any other
14518    /// field. And the ids they carry name rows the device actually holds —
14519    /// asserted on the bytes in the buffer, because a table the renderer agrees
14520    /// with itself about is not a table a shader can read.
14521    ///
14522    /// The two rows are asserted to differ, or the pair would be evidence of
14523    /// nothing: two instances naming two rows of the same colour draw the same
14524    /// picture whether or not either id was ever used.
14525    #[test]
14526    fn the_two_pyramids_differ_only_in_their_material() {
14527        let (recorder, device, queue) = open();
14528        let mut renderer =
14529            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14530        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14531        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14532        let tinted_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14533
14534        let instance = |handle: InstanceHandle| {
14535            renderer
14536                .instances
14537                .get(handle)
14538                .expect("the instance was inserted and is live")
14539        };
14540        let plain = instance(plain_handle);
14541        let tinted = instance(tinted_handle);
14542        assert_ne!(
14543            plain.material, tinted.material,
14544            "the two pyramids must not share a material row"
14545        );
14546        assert_eq!(
14547            mesh::GpuInstance {
14548                material: tinted.material,
14549                ..plain
14550            },
14551            tinted,
14552            "the two instances must differ in the material id and in nothing else"
14553        );
14554
14555        let bytes = recorder
14556            .buffer_bytes(renderer.materials.buffer())
14557            .expect("the table is live");
14558        let row = |index: u32| {
14559            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14560            mesh::GpuMaterial::from_bytes(
14561                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14562                    .try_into()
14563                    .expect("one row"),
14564            )
14565        };
14566        assert_eq!(
14567            row(plain.material),
14568            mesh::GpuMaterial::UNTINTED,
14569            "the plain pyramid's row must be the factor that changes nothing"
14570        );
14571        assert_eq!(
14572            row(tinted.material),
14573            mesh::GpuMaterial {
14574                base_color: scene::PYRAMID_TINT,
14575                roughness: scene::PYRAMID_ROUGHNESS,
14576                ..mesh::GpuMaterial::UNTINTED
14577            },
14578            "the tinted pyramid's row must be the tint and the tighter lobe"
14579        );
14580        // The shading half of that row, on its own: a roughness equal to the
14581        // neutral row's would leave `crcbl`'s render e2e comparing one lobe
14582        // against itself, and that test would go green on a shader that had
14583        // never read the column.
14584        assert_ne!(
14585            row(plain.material).roughness,
14586            row(tinted.material).roughness,
14587            "the two rows must differ in roughness, or the highlight the render e2e measures \
14588             is not attributable to the material"
14589        );
14590        assert_ne!(
14591            row(plain.material),
14592            row(tinted.material),
14593            "two rows holding the same colour would make the pair prove nothing"
14594        );
14595        // And the tint is the *only* thing that differs between them: a row that
14596        // also changed its page layer would make this pair evidence about two
14597        // columns at once, which is what the third pyramid exists to avoid.
14598        assert_eq!(
14599            row(plain.material).base_color_texture,
14600            row(tinted.material).base_color_texture,
14601            "the factor pair must sample the same page layer"
14602        );
14603
14604        // And the second pyramid leaves the frame the way the first does: the
14605        // instance is removed, not a draw skipped.
14606        renderer.remove_instance(tinted_handle);
14607        assert!(
14608            renderer.instances.get(tinted_handle).is_none(),
14609            "the instance must be given back, or an object nobody asked for stays in the scene"
14610        );
14611
14612        renderer.destroy(device.as_ref());
14613    }
14614
14615    /// **The same claim one column along: the plain and textured pyramids
14616    /// differ in exactly one field, and the rows it names differ in exactly one
14617    /// column — the base-colour page layer.**
14618    ///
14619    /// [`the_two_pyramids_differ_only_in_their_material`]'s argument for §3.2's
14620    /// *texture indices* rather than its *factors*. The factors of the two rows
14621    /// are asserted **equal** here, which is the half that makes the pair
14622    /// evidence about the texture at all: a textured row that also carried a
14623    /// tint would draw a different picture for a reason the frame could not
14624    /// distinguish from the tinted pyramid's.
14625    ///
14626    /// The layer numbers are asserted against the page the renderer actually
14627    /// uploaded, so a row naming a layer that does not exist is caught here
14628    /// rather than as an out-of-range sample on a device.
14629    #[test]
14630    fn the_textured_pyramid_differs_only_in_its_page_layer() {
14631        let (recorder, device, queue) = open();
14632        let mut renderer =
14633            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14634        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14635        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14636        let textured_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TEXTURED, at);
14637
14638        let instance = |handle: InstanceHandle| {
14639            renderer
14640                .instances
14641                .get(handle)
14642                .expect("the instance was inserted and is live")
14643        };
14644        let plain = instance(plain_handle);
14645        let textured = instance(textured_handle);
14646        assert_ne!(
14647            plain.material, textured.material,
14648            "the two pyramids must not share a material row"
14649        );
14650        assert_eq!(
14651            mesh::GpuInstance {
14652                material: textured.material,
14653                ..plain
14654            },
14655            textured,
14656            "the two instances must differ in the material id and in nothing else"
14657        );
14658
14659        let bytes = recorder
14660            .buffer_bytes(renderer.materials.buffer())
14661            .expect("the table is live");
14662        let row = |index: u32| {
14663            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14664            mesh::GpuMaterial::from_bytes(
14665                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14666                    .try_into()
14667                    .expect("one row"),
14668            )
14669        };
14670        assert_eq!(
14671            row(plain.material).base_color,
14672            row(textured.material).base_color,
14673            "the texture pair must share a factor, or the pair is evidence about both columns"
14674        );
14675        assert_eq!(
14676            row(plain.material).base_color_texture,
14677            mesh::GpuMaterial::NO_PAGE
14678        );
14679        assert_eq!(
14680            row(textured.material).base_color_texture,
14681            scene::CHECKER_LAYER
14682        );
14683        assert_ne!(
14684            row(plain.material),
14685            row(textured.material),
14686            "two rows naming the same layer would make the pair prove nothing"
14687        );
14688        // The layer that number names is a layer the page has, and it is not
14689        // one flat colour — a checker of one repeated texel would pass every
14690        // assertion above and draw the picture the untextured row draws.
14691        let page = scene::demo().page;
14692        let layers = page.layers(PageKind::BaseColor);
14693        assert!(
14694            (scene::CHECKER_LAYER as usize) < layers.len(),
14695            "layer {} is past the end of a {}-layer page, which is an out-of-range sample \
14696             nothing below the seam would report",
14697            scene::CHECKER_LAYER,
14698            layers.len()
14699        );
14700        let checker = &layers[scene::CHECKER_LAYER as usize];
14701        assert!(
14702            checker
14703                .as_chunks::<4>()
14704                .0
14705                .iter()
14706                .any(|texel| texel != &checker[..4]),
14707            "a flat checker layer would shade the textured row exactly as the untextured \
14708             one shades, and the pair would prove nothing"
14709        );
14710
14711        renderer.remove_instance(textured_handle);
14712        assert!(
14713            renderer.instances.get(textured_handle).is_none(),
14714            "the instance must be given back, or an object nobody asked for stays in the scene"
14715        );
14716
14717        renderer.destroy(device.as_ref());
14718    }
14719
14720    /// **A [`PageKind`] nothing names costs one texel**, not `extent² × 4` bytes
14721    /// and a third again for its chain.
14722    ///
14723    /// This is what row (d) bought, and it is the half of it no picture can
14724    /// show: the frame a scene with no normal map draws is byte-identical either
14725    /// way, because `mesh.slang` returns before it fetches. What changes is the
14726    /// image the renderer created, and the copies into it are where that is
14727    /// visible. `crcbl/tests/mesh_e2e/normal_map.rs`'s
14728    /// `no_normal_map_returns_the_surface_normal_exactly_and_the_neutral_texel_does_not`
14729    /// is the device-side half saying the frame did not move.
14730    ///
14731    /// [`scene::demo`] is the scene: every one of its rows carries
14732    /// [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) in the normal column, and it is
14733    /// the description every golden in this tree is a variation of.
14734    ///
14735    /// # Sabotage
14736    ///
14737    /// The empty-kind arm of the upload loop uploading a full 64² neutral layer
14738    /// and its chain instead of the placeholder — the shape this replaced. Red
14739    /// on 2026-09-06 with `"a description with no normal map must upload the
14740    /// one-texel placeholder, and this copied 7 level(s) at [Extent3d { width:
14741    /// 64, height: 64, depth_or_layers: 1 }, … ] — a burned neutral layer costs
14742    /// extent² × 4 bytes and a third again for its chain, on every scene in the
14743    /// tree"`.
14744    #[test]
14745    fn a_page_kind_nothing_names_costs_one_texel() {
14746        use crcbl_hal::null::Command;
14747
14748        let scene = scene::demo();
14749        assert!(
14750            scene
14751                .materials
14752                .iter()
14753                .all(|row| row.normal_texture == mesh::GpuMaterial::NO_PAGE),
14754            "a row naming a normal layer would make the description one that *does* name \
14755             the page, and this test would be about the other case"
14756        );
14757        assert!(
14758            scene.page.layers(PageKind::Normal).is_empty()
14759                && scene.page.extent(PageKind::BaseColor) > 1,
14760            "the description must name no normal layer while naming base-colour ones, or \
14761             a placeholder-sized copy says nothing about which page it landed in"
14762        );
14763
14764        let (recorder, device, queue) = open();
14765        let renderer =
14766            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14767                .expect("a description naming no normal page is one this can make resident");
14768
14769        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14770            .commands()
14771            .into_iter()
14772            .filter_map(|command| match command {
14773                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14774                    Some(copy)
14775                }
14776                _ => None,
14777            })
14778            .collect();
14779        let extents: Vec<crcbl_hal::Extent3d> =
14780            copies.iter().map(|copy| copy.image_extent).collect();
14781        assert_eq!(
14782            extents,
14783            vec![crcbl_hal::Extent3d::d2(1, 1)],
14784            "a description with no normal map must upload the one-texel placeholder, and \
14785             this copied {} level(s) at {extents:?} — a burned neutral layer costs \
14786             extent² × 4 bytes and a third again for its chain, on every scene in the tree",
14787            copies.len()
14788        );
14789
14790        // The placeholder is one layer, and the graph declaration says so: a
14791        // caller importing this page to write a layer of its own would get
14792        // `ImportDeclarationConflict` against an extent that was not 1×1.
14793        assert_eq!(
14794            renderer.normal_page_import().extent,
14795            (1, 1),
14796            "the declaration names the placeholder's extent, not the base-colour page's"
14797        );
14798        renderer.destroy(device.as_ref());
14799    }
14800
14801    /// **A page and a material table that are the caller's own, not
14802    /// [`scene::demo`]'s**: a different extent per kind, more layers than the
14803    /// demo page holds, a normal page the demo does not have at all, and rows
14804    /// past the three the demo writes.
14805    ///
14806    /// Every other scene in the tree is `scene::demo()` — with a mesh appended,
14807    /// at most — so until this nothing had put an app-supplied *layer* or an
14808    /// app-supplied *row* through [`ForwardRenderer::with_scene`] at all. A
14809    /// build that uploaded the demo's two layers and stopped, or that inserted
14810    /// its three rows and stopped, would leave every golden byte-identical and
14811    /// pass every other assertion in this module: the demo scene cannot tell a
14812    /// table filled from the description from one filled up to the description's
14813    /// third row.
14814    ///
14815    /// Read off the recorder rather than off the description, because the
14816    /// description is the input. The copies are what reached the image and the
14817    /// table buffer is what the shader indexes, and neither is a restatement of
14818    /// what was handed in.
14819    #[test]
14820    fn an_app_page_and_table_reach_the_device_whole() {
14821        use crcbl_hal::null::Command;
14822
14823        /// Not [`scene::PAGE_EXTENT`], so an extent that had been compiled in
14824        /// rather than read off the page shows up as a copy of the wrong size.
14825        const APP_EXTENT: u32 = 4;
14826
14827        /// **Not [`APP_EXTENT`]**, which is the whole of what row (d)'s per-kind
14828        /// extent bought: a renderer that still sized the normal page from the
14829        /// base-colour page's number would copy this layer at 4² and the copy
14830        /// list below would say so.
14831        const APP_NORMAL_EXTENT: u32 = 2;
14832        let layer_bytes = APP_EXTENT as usize * APP_EXTENT as usize * 4;
14833
14834        // Three base-colour layers, each flat and each a value of its own: a
14835        // build that uploaded one layer twice, or that stopped short, is a
14836        // different sequence of copies. Then one normal layer at the other
14837        // extent, which the demo scene has no page for at all.
14838        let mut page = scene::PageDesc::empty();
14839        page.set_extent(PageKind::BaseColor, APP_EXTENT);
14840        page.set_extent(PageKind::Normal, APP_NORMAL_EXTENT);
14841        let app_layers: Vec<u32> = [0x11_u8, 0x22, 0x33]
14842            .into_iter()
14843            .map(|value| page.push_layer(PageKind::BaseColor, vec![value; layer_bytes]))
14844            .collect();
14845        let app_normal = page.push_layer(
14846            PageKind::Normal,
14847            scene::PageDesc::NEUTRAL_NORMAL
14848                .repeat(APP_NORMAL_EXTENT as usize * APP_NORMAL_EXTENT as usize),
14849        );
14850
14851        let mut scene = scene::demo();
14852        scene.page = page;
14853        // One row per appended layer, and each with a factor of its own as well,
14854        // so a row that landed at another row's id is not a row that happens to
14855        // look like it. The last of them names the normal layer too, so the
14856        // table carries a row through both pages.
14857        for (nth, &layer) in app_layers.iter().enumerate() {
14858            let shade = 0.25 * (nth as f32 + 1.0);
14859            let last = nth + 1 == app_layers.len();
14860            scene.materials.push(mesh::GpuMaterial {
14861                base_color: [shade, shade, shade, 1.0],
14862                base_color_texture: layer,
14863                normal_texture: if last {
14864                    app_normal
14865                } else {
14866                    mesh::GpuMaterial::NO_PAGE
14867                },
14868                ..mesh::GpuMaterial::UNTINTED
14869            });
14870        }
14871        assert!(
14872            scene.materials.len() > scene::demo().materials.len()
14873                && scene.page.layers(PageKind::BaseColor).len()
14874                    > scene::demo().page.layers(PageKind::BaseColor).len(),
14875            "the description under test must exceed the demo's in both, or this is a \
14876             demo test wearing another name"
14877        );
14878        assert_eq!(
14879            scene::demo().page.extent(PageKind::Normal),
14880            0,
14881            "the demo scene must name no normal page, or the normal copies below are \
14882             evidence about the demo's page rather than the caller's"
14883        );
14884
14885        let (recorder, device, queue) = open();
14886        let mut renderer =
14887            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14888                .expect("a page and a table of the caller's own are ones this can make resident");
14889
14890        // The page, layer by layer. Filtered by image because the build uploads
14891        // the ambient-occlusion placeholder through the same path.
14892        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14893            .commands()
14894            .into_iter()
14895            .filter_map(|command| match command {
14896                Command::CopyBufferToImage(copy)
14897                    if copy.image == renderer.base_color_page.image =>
14898                {
14899                    Some(copy)
14900                }
14901                _ => None,
14902            })
14903            .collect();
14904        // Every layer goes up with its chain — three levels for this extent —
14905        // so the copies are layer-major, level-minor, each at its level's own
14906        // extent.
14907        let levels = crcbl_hal::Extent3d::d2(APP_EXTENT, APP_EXTENT)
14908            .full_mip_levels(crcbl_hal::ImageType::D2);
14909        assert_eq!(levels, 3, "a 4² page has three levels down to one texel");
14910        let layer_count = u32::try_from(scene.page.layers(PageKind::BaseColor).len())
14911            .expect("a page of a few layers");
14912        assert_eq!(
14913            copies
14914                .iter()
14915                .map(|copy| (
14916                    copy.image_subresource.base_layer,
14917                    copy.image_subresource.mip
14918                ))
14919                .collect::<Vec<(u32, u32)>>(),
14920            (0..layer_count)
14921                .flat_map(|layer| (0..levels).map(move |level| (layer, level)))
14922                .collect::<Vec<(u32, u32)>>(),
14923            "every level of every layer the description carries must be copied into the page, \
14924             in order"
14925        );
14926        assert!(
14927            copies.iter().all(|copy| {
14928                let side = crate::mip::level_extent(APP_EXTENT, copy.image_subresource.mip);
14929                copy.image_extent == crcbl_hal::Extent3d::d2(side, side)
14930            }),
14931            "the page is the extent the caller wrote, not the demo's, halved per level: \
14932             {copies:?}"
14933        );
14934
14935        // The normal page, at **its own** extent. One layer, two levels for a
14936        // 2² image, and every copy sized from `APP_NORMAL_EXTENT` — a renderer
14937        // that carried one extent for both kinds would put this layer up at 4².
14938        let normal_copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14939            .commands()
14940            .into_iter()
14941            .filter_map(|command| match command {
14942                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14943                    Some(copy)
14944                }
14945                _ => None,
14946            })
14947            .collect();
14948        let normal_levels = crcbl_hal::Extent3d::d2(APP_NORMAL_EXTENT, APP_NORMAL_EXTENT)
14949            .full_mip_levels(crcbl_hal::ImageType::D2);
14950        assert_eq!(
14951            normal_copies
14952                .iter()
14953                .map(|copy| (
14954                    copy.image_subresource.base_layer,
14955                    copy.image_subresource.mip,
14956                    copy.image_extent
14957                ))
14958                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14959            (0..normal_levels)
14960                .map(|level| {
14961                    let side = crate::mip::level_extent(APP_NORMAL_EXTENT, level);
14962                    (0, level, crcbl_hal::Extent3d::d2(side, side))
14963                })
14964                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14965            "the normal page is the extent the caller wrote for *that* kind, halved per \
14966             level: {normal_copies:?}"
14967        );
14968        assert_eq!(
14969            renderer.normal_page_import().extent,
14970            (APP_NORMAL_EXTENT, APP_NORMAL_EXTENT),
14971            "the graph declaration names the normal page's own extent, or a caller \
14972             importing it to write a layer gets ImportDeclarationConflict"
14973        );
14974        assert_eq!(
14975            renderer.base_color_page_import().extent,
14976            (APP_EXTENT, APP_EXTENT),
14977            "and the base-colour declaration names its own, which is a different number"
14978        );
14979
14980        // The table, row by row, out of the buffer `mesh.slang` indexes.
14981        let bytes = recorder
14982            .buffer_bytes(renderer.materials.buffer())
14983            .expect("the table is live");
14984        let row = |id: u32| {
14985            let at = id as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14986            mesh::GpuMaterial::from_bytes(
14987                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14988                    .try_into()
14989                    .expect("one row"),
14990            )
14991        };
14992        assert_eq!(
14993            renderer.material_ids.len(),
14994            scene.materials.len(),
14995            "one id per description row, whatever the count"
14996        );
14997        for (index, wrote) in scene.materials.iter().enumerate() {
14998            assert_eq!(
14999                &row(renderer.material_ids[index]),
15000                wrote,
15001                "description row {index} must be the row its id names"
15002            );
15003        }
15004
15005        // And a caller can place an object through a row only its own
15006        // description has, which is the whole point of the rows being the
15007        // caller's.
15008        let last = scene.materials.len() - 1;
15009        let handle = renderer
15010            .add_instance(&InstanceDesc {
15011                mesh: DEMO_CUBE,
15012                material: last,
15013                transform: Mat4::IDENTITY,
15014            })
15015            .expect("an empty pool of thousands has room for one object");
15016        assert_eq!(
15017            renderer
15018                .instances
15019                .get(handle)
15020                .expect("a just-added instance is live")
15021                .material,
15022            renderer.material_ids[last],
15023            "an InstanceDesc's material index resolves through the description, not \
15024             through a table id the caller cannot know"
15025        );
15026
15027        renderer.destroy(device.as_ref());
15028        recorder.assert_valid();
15029    }
15030
15031    /// **The frame records two compute dispatches and exactly one indirect draw
15032    /// per bucket — whatever is in the scene.**
15033    ///
15034    /// The property topic 03 opens with, checked on the recorded command stream:
15035    /// adding the pyramid adds an instance and changes no command. A pass that
15036    /// had kept a draw per object would record one command here and two there,
15037    /// which is what this used to assert and what the indirect path replaced.
15038    ///
15039    /// It also pins the arguments each call names: bucket `n` reads the `n`-th
15040    /// argument structure and the `n`-th count, at the stride every API fixed.
15041    /// Two calls pointing at one structure is a frame that draws one object
15042    /// twice.
15043    #[test]
15044    fn the_frame_records_one_indirect_call_per_bucket_whatever_the_scene_holds() {
15045        use crcbl_hal::null::Command;
15046
15047        for pyramid in [None, Some(Mat4::from_translation(Vec3::X))] {
15048            let (recorder, device, queue) = open();
15049            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15050                .expect("built");
15051            // The cube in both scenes, so the difference between them is the
15052            // pyramid alone. It also keeps both frames non-empty, and an empty
15053            // one would be a weaker comparison than this claims: `cull`'s
15054            // dispatch covers no workgroups when the pool is empty, and the pass
15055            // records nothing rather than a dispatch of zero — see
15056            // [`DrawGen::add_passes`].
15057            place_cube(&mut renderer, Mat4::IDENTITY);
15058            if let Some(at) = pyramid {
15059                place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
15060            }
15061            let frame = frame(device.as_ref(), &mut renderer, queue);
15062
15063            let stride = crcbl_shaders::draw_gen::DRAW_ARGS_SIZE as u32;
15064            let expected: Vec<(u32, u64, u64)> = (0..renderer.bucket_constants.len())
15065                .map(|bucket| {
15066                    (
15067                        renderer.bucket_constants[bucket],
15068                        bucket as u64 * u64::from(stride),
15069                        bucket as u64 * 4,
15070                    )
15071                })
15072                .collect();
15073
15074            // The dynamic offset last bound before each draw, paired with the
15075            // offsets that draw read its arguments and its count from.
15076            let mut offset = None;
15077            let mut seen: Vec<(u32, u64, u64)> = Vec::new();
15078            let mut dispatches = 0;
15079            for command in recorder.commands() {
15080                if matches!(command, Command::Dispatch { .. }) {
15081                    dispatches += 1;
15082                }
15083            }
15084            for command in commands_in_pass(&recorder, "forward") {
15085                match command {
15086                    Command::BindGroup {
15087                        slot: 0,
15088                        dynamic_offsets,
15089                        ..
15090                    } => offset = dynamic_offsets.first().copied(),
15091                    Command::DrawIndexedIndirectCount(draw) => {
15092                        assert_eq!(draw.stride, stride, "sizeof(VkDrawIndexedIndirectCommand)");
15093                        assert_eq!(
15094                            draw.max_draw_count, 1,
15095                            "one argument structure per bucket, so one is the ceiling"
15096                        );
15097                        seen.push((
15098                            offset.expect("a draw is preceded by its constant block"),
15099                            draw.args_offset,
15100                            draw.count_offset,
15101                        ));
15102                    }
15103                    Command::DrawIndexed { .. } => {
15104                        panic!("the forward pass must not record a CPU-counted draw any more")
15105                    }
15106                    _ => {}
15107                }
15108            }
15109            assert_eq!(
15110                dispatches,
15111                DrawGen::DISPATCHES as usize * (1 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
15112                "the clearing pass, the cull pass and the draw-argument pass's three, in \
15113                 front of the draws — once for the camera and once per shadow cascade — plus \
15114                 topic 18's one clustering dispatch, which is the camera's alone because a \
15115                 cascade shades nothing, plus the resolve's own"
15116            );
15117            assert_eq!(
15118                seen, expected,
15119                "with pyramid = {pyramid:?}, the pass must record one indirect call per \
15120                 bucket, each pointing at its own arguments, its own count and its own \
15121                 block"
15122            );
15123
15124            frame.finish(device.as_ref(), renderer);
15125        }
15126    }
15127
15128    /// **The two `GeometryPath` arms record different calls and nothing else
15129    /// differs.**
15130    ///
15131    /// A device with a GPU-side count takes it from GPU memory; one without —
15132    /// Metal, whose API has multi-draw-indirect and no count buffer — reads each
15133    /// bucket's one argument structure unconditionally. Same buckets, same
15134    /// arguments, same block: the tail is the only thing that moves, which is
15135    /// what topic 03 means by "the lesser path is
15136    /// a constraint on data layout, not a separate renderer".
15137    ///
15138    /// Both presets are run here rather than only the one this machine has,
15139    /// because the arm a device never selects is the arm nothing tests.
15140    #[test]
15141    fn each_geometry_path_records_its_own_indirect_call() {
15142        use crcbl_hal::null::Command;
15143
15144        for (preset, path, counted) in [
15145            (
15146                NullInstance::gpu_driven(),
15147                GeometryPath::IndirectCount,
15148                true,
15149            ),
15150            (
15151                NullInstance::portable(),
15152                GeometryPath::IndirectPerBatch,
15153                false,
15154            ),
15155        ] {
15156            let recorder = Recorder::new();
15157            let instance = preset.with_recorder(recorder.clone());
15158            let adapter = instance.adapters().remove(0);
15159            assert_eq!(
15160                instance
15161                    .adapter_caps(adapter.id)
15162                    .expect("the null backend describes its adapter")
15163                    .geometry_path(),
15164                path,
15165                "the preset must select the path this arm is about"
15166            );
15167            // `DeviceDesc::for_adapter` requires a timeline semaphore, which the
15168            // portable preset does not have; the forward pass does not need one
15169            // either, so this asks for what it uses. The optional set matters:
15170            // a device is opened with the features it *asked* for, and the path
15171            // is derived from those rather than from the adapter's.
15172            let device = instance
15173                .create_device(&DeviceDesc {
15174                    label: None,
15175                    adapter: adapter.id,
15176                    required_features: Features::COMPUTE,
15177                    optional_features: Features::GPU_DRIVEN,
15178                    compatible_surface: None,
15179                })
15180                .expect("the null backend always opens");
15181            assert_eq!(
15182                device.caps().geometry_path(),
15183                path,
15184                "and the opened device still selects it"
15185            );
15186            let queue = device.queue(QueueKind::Graphics).expect("always present");
15187            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15188                .expect("built");
15189            let frame = frame(device.as_ref(), &mut renderer, queue);
15190
15191            let mut counted_calls = 0;
15192            let mut per_batch_calls = 0;
15193            for command in commands_in_pass(&recorder, "forward") {
15194                match command {
15195                    Command::DrawIndexedIndirectCount(_) => counted_calls += 1,
15196                    Command::DrawIndexedIndirect(draw) => {
15197                        assert_eq!(
15198                            draw.draw_count, 1,
15199                            "one argument structure per bucket, read unconditionally"
15200                        );
15201                        per_batch_calls += 1;
15202                    }
15203                    _ => {}
15204                }
15205            }
15206            let buckets = renderer.bucket_constants.len();
15207            let (expected_counted, expected_per_batch) =
15208                if counted { (buckets, 0) } else { (0, buckets) };
15209            assert_eq!(
15210                (counted_calls, per_batch_calls),
15211                (expected_counted, expected_per_batch),
15212                "{path:?} must record one call of its own kind per bucket and none of the other"
15213            );
15214
15215            frame.finish(device.as_ref(), renderer);
15216        }
15217    }
15218
15219    /// Serialises the two checks that move
15220    /// [`r_debug_draw`](crate::debug_draw::r_debug_draw), and puts it back
15221    /// afterwards.
15222    ///
15223    /// A [`ConVar`](crcbl_console::ConVar) is process-global by design, and
15224    /// `cargo test` runs a crate's tests as threads of *one* process: two checks
15225    /// that move the switch are then two writers to one cell, which shows up as
15226    /// a flake rather than as a failure anybody can read.
15227    /// `crcbl::debug_view::for_test` is the same shape one crate up and there
15228    /// for the same reason; this one is smaller because nothing outside these
15229    /// two tests ever writes the cell.
15230    fn debug_draw_switch() -> DebugDrawSwitch {
15231        let guard = DEBUG_DRAW_SWITCH
15232            .lock()
15233            .unwrap_or_else(std::sync::PoisonError::into_inner);
15234        let switch = DebugDrawSwitch { _guard: guard };
15235        switch.set(false);
15236        switch
15237    }
15238
15239    /// What [`debug_draw_switch`] hands back: the switch is this thread's until
15240    /// it drops, and it goes back off when it does.
15241    struct DebugDrawSwitch {
15242        _guard: std::sync::MutexGuard<'static, ()>,
15243    }
15244
15245    impl DebugDrawSwitch {
15246        /// Moves the switch.
15247        fn set(&self, on: bool) {
15248            crate::debug_draw::r_debug_draw
15249                .set(&crcbl_console::Value::Bool(on))
15250                .expect("`r_debug_draw` is a writable bool");
15251        }
15252    }
15253
15254    impl Drop for DebugDrawSwitch {
15255        fn drop(&mut self) {
15256            // Off at both ends, so a check that panicked mid-way does not hand
15257            // the next holder a switched-on layer.
15258            self.set(false);
15259        }
15260    }
15261
15262    /// [`debug_draw_switch`]'s lock.
15263    ///
15264    /// **First of the two**, when a test takes this and [`ssao_blur_switch`]
15265    /// both — see that function for what the opposite order cost.
15266    static DEBUG_DRAW_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15267
15268    /// Takes `r_ssao_blur_passes` for this thread and puts it back at its
15269    /// default when the guard drops.
15270    ///
15271    /// [`debug_draw_switch`]'s shape exactly, for its reason: a plain
15272    /// `cargo test` run shares one process between tests, and a variable this
15273    /// one left moved is a frame the next test did not ask for.
15274    ///
15275    /// **Every test whose assertion depends on the shape of a frame takes this,
15276    /// not only the one that moves the count.** The variable is a process
15277    /// global and `cargo test` runs this module's tests on threads that share
15278    /// it, so a frame built while
15279    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] holds two blurs
15280    /// carries an `ssao-blur-2` pass, a full-screen triangle and a pipeline bind
15281    /// that the test building it never asked for. Taking the guard both
15282    /// serialises against that test and pins the count for the frames this one
15283    /// builds.
15284    ///
15285    /// Two shapes need it, and the second is easy to miss. A test comparing a
15286    /// frame against a **literal pass list** breaks whenever the count is two.
15287    /// A test comparing **two frames it built itself** — a difference in draws,
15288    /// an equality between pass lists, a "one pass longer" claim — breaks only
15289    /// when the count *moves between them*, which is a narrower window and why
15290    /// this reproduced at roughly one run in eight rather than every run.
15291    ///
15292    /// Both were established by experiment on 2026-09-01 rather than by
15293    /// reading: pinning the count at two reddens the first shape, and making
15294    /// `crate::ssao::blur_passes` alternate reddens the second.
15295    ///
15296    /// **A test taking this and [`debug_draw_switch`] takes that one first.**
15297    /// These are two plain mutexes with no ordering between them, so two tests
15298    /// acquiring both in opposite orders deadlock — which is not a hazard this
15299    /// comment is guessing at: adding the guard to the two debug-draw tests
15300    /// above their existing one did exactly that on 2026-09-01, and turned a
15301    /// 0.2 second suite into one that had not finished in ten minutes. It is
15302    /// invisible in a single-threaded run, where the same suite passes in a
15303    /// second, so `--test-threads=1` is not a check for it.
15304    ///
15305    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`]: fn@a_second_occlusion_blur_is_a_pass_the_frame_records
15306    pub(super) fn ssao_blur_switch() -> SsaoBlurSwitch {
15307        let guard = SSAO_BLUR_SWITCH
15308            .lock()
15309            .unwrap_or_else(std::sync::PoisonError::into_inner);
15310        let switch = SsaoBlurSwitch { _guard: guard };
15311        switch.set(1);
15312        switch
15313    }
15314
15315    /// What [`ssao_blur_switch`] hands back.
15316    pub(super) struct SsaoBlurSwitch {
15317        _guard: std::sync::MutexGuard<'static, ()>,
15318    }
15319
15320    impl SsaoBlurSwitch {
15321        /// Asks for `passes` of them.
15322        fn set(&self, passes: i64) {
15323            crate::ssao::r_ssao_blur_passes
15324                .set(&crcbl_console::Value::Int(passes))
15325                .expect("`r_ssao_blur_passes` is a writable int in range");
15326        }
15327    }
15328
15329    impl Drop for SsaoBlurSwitch {
15330        fn drop(&mut self) {
15331            // Back to the shipping count at both ends, so a check that panicked
15332            // mid-way does not hand the next holder a three-pass frame.
15333            self.set(1);
15334        }
15335    }
15336
15337    /// [`ssao_blur_switch`]'s lock.
15338    static SSAO_BLUR_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15339
15340    /// Takes `r_ssao_split` for this thread and puts it back when the guard
15341    /// drops.
15342    ///
15343    /// [`ssao_blur_switch`]'s shape exactly, for its reason. The seam is what
15344    /// makes the occlusion chain record its second march, so a test about the
15345    /// widest frame a renderer can produce has to hold this as well as the blur
15346    /// count — see `crate::ssao`'s `r_ssao_split`.
15347    pub(super) fn ssao_split_switch() -> SsaoSplitSwitch {
15348        let guard = SSAO_SPLIT_SWITCH
15349            .lock()
15350            .unwrap_or_else(std::sync::PoisonError::into_inner);
15351        let switch = SsaoSplitSwitch { _guard: guard };
15352        switch.set(0.0);
15353        switch
15354    }
15355
15356    /// What [`ssao_split_switch`] hands back.
15357    pub(super) struct SsaoSplitSwitch {
15358        _guard: std::sync::MutexGuard<'static, ()>,
15359    }
15360
15361    impl SsaoSplitSwitch {
15362        /// Asks for a seam at `at`, or for none at zero.
15363        fn set(&self, at: f32) {
15364            crate::ssao::r_ssao_split
15365                .set(&crcbl_console::Value::Float(at))
15366                .expect("`r_ssao_split` is a writable float in range");
15367        }
15368    }
15369
15370    impl Drop for SsaoSplitSwitch {
15371        fn drop(&mut self) {
15372            // Back to the default at both ends, so a check that panicked
15373            // mid-way does not hand the next holder a comparing frame.
15374            self.set(0.0);
15375        }
15376    }
15377
15378    /// [`ssao_split_switch`]'s lock.
15379    static SSAO_SPLIT_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15380
15381    /// Takes `r_shadow_filter` and `r_shadow_split` for this thread and puts
15382    /// them both back at their defaults when the guard drops.
15383    ///
15384    /// [`ssao_split_switch`]'s shape, with two variables under one lock because
15385    /// they are read into one row of one block — `crate::shadow::FILTER_SWITCH`
15386    /// is where that is argued, and why the lock lives there rather than beside
15387    /// this function: `crate::shadow`'s own tests move the same two.
15388    fn shadow_filter_switch() -> ShadowFilterSwitch {
15389        let guard = crate::shadow::FILTER_SWITCH
15390            .lock()
15391            .unwrap_or_else(std::sync::PoisonError::into_inner);
15392        let switch = ShadowFilterSwitch { _guard: guard };
15393        switch.reset();
15394        switch
15395    }
15396
15397    /// What [`shadow_filter_switch`] hands back.
15398    struct ShadowFilterSwitch {
15399        _guard: std::sync::MutexGuard<'static, ()>,
15400    }
15401
15402    impl ShadowFilterSwitch {
15403        /// Asks for `filter` on the near side of the seam.
15404        fn filter(&self, filter: shadow::Filter) {
15405            crate::shadow::r_shadow_filter
15406                .set(&crcbl_console::Value::Enum(filter.label()))
15407                .expect("`r_shadow_filter` is a writable enum in the set");
15408        }
15409
15410        /// Asks for a seam at `at`, or for none at zero.
15411        fn seam(&self, at: f32) {
15412            crate::shadow::r_shadow_split
15413                .set(&crcbl_console::Value::Float(at))
15414                .expect("`r_shadow_split` is a writable float in range");
15415        }
15416
15417        /// Asks for `texels` of constant bias.
15418        fn bias(&self, texels: f32) {
15419            crate::shadow::r_shadow_bias
15420                .set(&crcbl_console::Value::Float(texels))
15421                .expect("`r_shadow_bias` is a writable float in range");
15422        }
15423
15424        /// Asks for `texels` of normal offset.
15425        fn offset(&self, texels: f32) {
15426            crate::shadow::r_shadow_normal_offset
15427                .set(&crcbl_console::Value::Float(texels))
15428                .expect("`r_shadow_normal_offset` is a writable float in range");
15429        }
15430
15431        /// Back to the frame every golden was blessed as.
15432        fn reset(&self) {
15433            self.filter(shadow::shipped_filter());
15434            self.seam(0.0);
15435            self.bias(shipped_float(&crate::shadow::r_shadow_bias));
15436            self.offset(shipped_float(&crate::shadow::r_shadow_normal_offset));
15437        }
15438    }
15439
15440    /// The float `var` declares as its default — what a frame nobody typed at
15441    /// is drawn with, read off the variable rather than written down here.
15442    fn shipped_float(var: &crcbl_console::ConVar) -> f32 {
15443        match var.default() {
15444            crcbl_console::Value::Float(shipped) => *shipped,
15445            other => panic!("`{}` defaults to {other:?}, not to a float", var.name()),
15446        }
15447    }
15448
15449    impl Drop for ShadowFilterSwitch {
15450        fn drop(&mut self) {
15451            // Back to the defaults at both ends, so a check that panicked
15452            // mid-way does not hand the next holder a comparing frame.
15453            self.reset();
15454        }
15455    }
15456
15457    /// Takes `r_ssao_slices` for this thread and puts it back at its default
15458    /// when the guard drops.
15459    ///
15460    /// [`ssao_blur_switch`]'s shape exactly, for its reason: a plain
15461    /// `cargo test` run shares one process between tests, and a variable this
15462    /// one left moved is a frame the next test did not ask for.
15463    fn ssao_slice_switch() -> SsaoSliceSwitch {
15464        let guard = SSAO_SLICE_SWITCH
15465            .lock()
15466            .unwrap_or_else(std::sync::PoisonError::into_inner);
15467        let switch = SsaoSliceSwitch { _guard: guard };
15468        switch.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15469        switch
15470    }
15471
15472    /// What [`ssao_slice_switch`] hands back.
15473    struct SsaoSliceSwitch {
15474        _guard: std::sync::MutexGuard<'static, ()>,
15475    }
15476
15477    impl SsaoSliceSwitch {
15478        /// Asks each pixel for `slices` of them.
15479        fn set(&self, slices: i64) {
15480            crate::ssao::r_ssao_slices
15481                .set(&crcbl_console::Value::Int(slices))
15482                .expect("`r_ssao_slices` is a writable int in range");
15483        }
15484    }
15485
15486    impl Drop for SsaoSliceSwitch {
15487        fn drop(&mut self) {
15488            // Back to the shipping count at both ends, so a check that panicked
15489            // mid-way does not hand the next holder a four-slice frame — which
15490            // is a frame every golden in this workspace was blessed without.
15491            self.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15492        }
15493    }
15494
15495    /// [`ssao_slice_switch`]'s lock.
15496    static SSAO_SLICE_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15497
15498    /// Takes `r_ssao_technique` for this thread and puts it back at its default
15499    /// when the guard drops.
15500    ///
15501    /// [`ssao_blur_switch`]'s shape exactly, for its reason — and this one moves
15502    /// a **pipeline** rather than a lane of a uniform block, so a frame that
15503    /// picked it up from another thread's test gathers through a shader that
15504    /// test never selected.
15505    ///
15506    /// **Its lock lives in `crate::ssao`** rather than beside this function, and
15507    /// it is the one switch here whose does: `ssao`'s own
15508    /// `the_seams_other_side_is_the_technique_that_ships` moves the same
15509    /// variable, and a second mutex would serialise neither against the other.
15510    /// See `crate::ssao::TECHNIQUE_SWITCH` for where it sits in the order.
15511    fn ssao_technique_switch() -> SsaoTechniqueSwitch {
15512        let guard = crate::ssao::TECHNIQUE_SWITCH
15513            .lock()
15514            .unwrap_or_else(std::sync::PoisonError::into_inner);
15515        let switch = SsaoTechniqueSwitch { _guard: guard };
15516        switch.set(shipped_technique_name());
15517        switch
15518    }
15519
15520    /// The technique name the chain ships, and the one
15521    /// [`ssao_technique_switch`] restores.
15522    ///
15523    /// **Read off the variable rather than written down**, which is
15524    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
15525    /// rule about the slice count and for its reason: which value ships is a
15526    /// thing that moves, and a test naming the wrong one would be comparing the
15527    /// shipped configuration against itself.
15528    ///
15529    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
15530    fn shipped_technique_name() -> &'static str {
15531        match crate::ssao::r_ssao_technique.default() {
15532            crcbl_console::Value::Enum(name) => name,
15533            other => panic!("`r_ssao_technique` defaults to {other:?}, not to a technique name"),
15534        }
15535    }
15536
15537    /// A name from the variable's own set that is **not** the one it ships.
15538    ///
15539    /// [`shipped_technique_name`]'s clause from the other side: the tests below
15540    /// need a technique to move the console to, and picking it out of the
15541    /// declared set is what keeps them from naming one the variable does not
15542    /// offer — or, if a third arrived, from silently going on comparing the
15543    /// same two.
15544    fn other_technique_name() -> &'static str {
15545        let crcbl_console::Kind::Enum(names) = crate::ssao::r_ssao_technique.kind() else {
15546            panic!("`r_ssao_technique` is an enum variable");
15547        };
15548        let ships = shipped_technique_name();
15549        names
15550            .iter()
15551            .copied()
15552            .find(|name| *name != ships)
15553            .expect("`r_ssao_technique` offers a technique other than the one it ships")
15554    }
15555
15556    /// What [`ssao_technique_switch`] hands back.
15557    struct SsaoTechniqueSwitch {
15558        _guard: std::sync::MutexGuard<'static, ()>,
15559    }
15560
15561    impl SsaoTechniqueSwitch {
15562        /// Asks for the gather `name` selects.
15563        fn set(&self, name: &'static str) {
15564            crate::ssao::r_ssao_technique
15565                .set(&crcbl_console::Value::Enum(name))
15566                .expect("`r_ssao_technique` is a writable enum in the set");
15567        }
15568    }
15569
15570    impl Drop for SsaoTechniqueSwitch {
15571        fn drop(&mut self) {
15572            // Back to what ships at both ends, so a check that panicked mid-way
15573            // does not hand the next holder a frame gathered through the cheap
15574            // tier — which is a frame no golden in this workspace was blessed
15575            // on.
15576            self.set(shipped_technique_name());
15577        }
15578    }
15579
15580    /// Every draw the recorded stream holds, whichever call recorded it.
15581    ///
15582    /// Not scoped to a pass, unlike [`commands_in_pass`]: what
15583    /// [`ForwardRenderer::counters`] claims is a count over the *whole* frame, so
15584    /// the thing to compare it against is the whole frame.
15585    fn recorded_draws(recorder: &Recorder) -> usize {
15586        use crcbl_hal::null::Command;
15587
15588        recorder
15589            .commands()
15590            .into_iter()
15591            .filter(|command| {
15592                matches!(
15593                    command,
15594                    Command::Draw { .. }
15595                        | Command::DrawIndexed { .. }
15596                        | Command::DrawIndirect(_)
15597                        | Command::DrawIndexedIndirect(_)
15598                        | Command::DrawIndirectCount(_)
15599                        | Command::DrawIndexedIndirectCount(_)
15600                        | Command::DrawMeshTasks { .. }
15601                        | Command::DrawMeshTasksIndirect(_)
15602                )
15603            })
15604            .count()
15605    }
15606
15607    /// **The draw count is what the frame recorded, and the two GPU-side
15608    /// counters are `None` rather than a guess.**
15609    ///
15610    /// Both halves matter and both are checked here against something that
15611    /// moves. The draws are compared with the recorded stream, so a count that
15612    /// forgot the shadow pass's share or the tonemap's triangle fails. The
15613    /// instances are read before and after a pyramid is put in the pool, so a
15614    /// counter wired to a constant — or to the pool's *capacity*, which does not
15615    /// move — fails too.
15616    ///
15617    /// `drawn` and `triangles` are asserted [`None`] **on the frames this test
15618    /// runs**, which are inside [`CULL_STATS_FLOOR`]: nothing has come
15619    /// back off the GPU yet, and a `drawn` that was `Some` here would be a
15620    /// number invented before any readback landed. That is the assertion that
15621    /// catches the tempting version of this method: an instance count taken from
15622    /// the pool and reported as "drawn" would read as a culling win of exactly
15623    /// zero on every frame, which is the number the whole cull exists to change.
15624    /// What happens once the ring *has* come round is the test below.
15625    #[test]
15626    fn the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know() {
15627        let _blurs = ssao_blur_switch();
15628        let (recorder, device, queue) = open();
15629        let mut renderer =
15630            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15631
15632        // Before any frame: nothing recorded, and said as a known zero.
15633        assert_eq!(renderer.counters(), FrameCounters::default());
15634
15635        let first = frame(device.as_ref(), &mut renderer, queue);
15636        let counters = renderer.counters();
15637        assert_eq!(
15638            counters.draws,
15639            recorded_draws(&recorder) as u64,
15640            "the counter and the frame's recorded draws disagree",
15641        );
15642        // Derived from what the frame resolved rather than from a constant, so
15643        // this is still the every-effect frame's count and would follow a frame
15644        // that switched one off.
15645        let fullscreen = fullscreen_passes(
15646            renderer.effects(),
15647            TEST_EXTENT,
15648            false,
15649            renderer.frame_ssao_blurs,
15650        ) * FULLSCREEN_DRAWS;
15651        assert!(
15652            counters.draws > fullscreen,
15653            "a frame that recorded only its full-screen passes drew no scene",
15654        );
15655        assert_eq!(
15656            counters.instances,
15657            renderer.instances.len() as u64 + fullscreen,
15658        );
15659        assert_eq!(
15660            counters.drawn, None,
15661            "the ring has not come round, so there is no survivor count yet",
15662        );
15663        assert_eq!(counters.cull_frame, None, "and no frame to stamp it with");
15664        assert_eq!(counters.triangles, None);
15665        first.release(device.as_ref());
15666
15667        // A second scene: one more instance in the pool, and the counter moves
15668        // with it. The draws do not — one call per bucket whatever the scene
15669        // holds is what §3.3 is about, and this is where that shows.
15670        place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, Mat4::IDENTITY);
15671        recorder.clear();
15672        let second = frame(device.as_ref(), &mut renderer, queue);
15673        let richer = renderer.counters();
15674        assert_eq!(
15675            richer.instances,
15676            counters.instances + 1,
15677            "an instance added to the pool must move the counter",
15678        );
15679        assert_eq!(
15680            richer.draws, counters.draws,
15681            "the recorded call count is independent of what the scene holds",
15682        );
15683        assert_eq!(richer.draws, recorded_draws(&recorder) as u64);
15684
15685        second.finish(device.as_ref(), renderer);
15686    }
15687
15688    /// **Once the ring has come round, `drawn` is a number and it says which
15689    /// frame it is from.**
15690    ///
15691    /// The other half of the test above: `indirect` while the readback is in
15692    /// flight, a count afterwards, and a `cull_frame` naming a frame several
15693    /// behind the one just recorded. The null backend executes no copy, so the
15694    /// *value* here is the full-screen passes' own draws and nothing else — what the cull
15695    /// really kept is asserted against a real GPU, in the umbrella crate's
15696    /// `tests/draw_gen_e2e/`, where a scene is culled on purpose.
15697    ///
15698    /// The frame number is the assertion with teeth here: a ring that read the
15699    /// slot it had just written would report the frame it is on, and a
15700    /// `cull_frame` left at `None` would put a latent number on the panel with
15701    /// nothing to say how old it is.
15702    #[test]
15703    fn the_culling_counters_arrive_a_few_frames_late_and_say_which_frame() {
15704        let (_recorder, device, queue) = open();
15705        let mut renderer =
15706            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15707
15708        let mut frames = Vec::new();
15709        for _ in 0..CULL_STATS_FLOOR {
15710            frames.push(frame(device.as_ref(), &mut renderer, queue));
15711            assert_eq!(
15712                renderer.counters().drawn,
15713                None,
15714                "no readback has even been polled yet, so there is nothing back",
15715            );
15716        }
15717
15718        frames.push(frame(device.as_ref(), &mut renderer, queue));
15719        let counters = renderer.counters();
15720        assert_eq!(
15721            counters.drawn,
15722            Some(
15723                fullscreen_passes(
15724                    renderer.effects(),
15725                    TEST_EXTENT,
15726                    false,
15727                    renderer.frame_ssao_blurs,
15728                ) * FULLSCREEN_DRAWS,
15729            ),
15730            "the survivor count the null backend produced is zero, plus one instance per \
15731             full-screen pass — which is on both sides of the row",
15732        );
15733        assert_eq!(
15734            counters.cull_frame,
15735            Some(1),
15736            "the report is the frame whose copy answered, not the frame just recorded",
15737        );
15738        assert_eq!(renderer.cull_stats().expect("a readback answered").frame, 1,);
15739
15740        for frame in frames {
15741            frame.release(device.as_ref());
15742        }
15743        renderer.destroy(device.as_ref());
15744    }
15745
15746    /// The frames a culling counter cannot possibly have arrived in.
15747    ///
15748    /// Two: the copy is recorded on one frame and the readback for it requested
15749    /// on the next, so the earliest frame that can poll anything is the third.
15750    /// A device that answers its first poll — the null backend, and every native
15751    /// one — reports there; a browser answers later, which is why this is a
15752    /// floor rather than a latency. See [`crate::cull_stats`].
15753    const CULL_STATS_FLOOR: usize = 2;
15754
15755    /// **A light that takes a shadow tile moves the draw count**, because the
15756    /// shadow pass records one call per bucket per occupied view.
15757    ///
15758    /// The observable a `recorded_draws` comparison alone would miss: a
15759    /// `counters` that counted only the colour pass and the tonemap agrees with
15760    /// nothing here, and one that hard-coded the cascades agrees with the first
15761    /// frame and not the second.
15762    #[test]
15763    fn a_light_that_takes_a_shadow_tile_moves_the_draw_count() {
15764        let (recorder, device, queue) = open();
15765        let mut renderer =
15766            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15767
15768        let dark = frame(device.as_ref(), &mut renderer, queue);
15769        let without = renderer.counters().draws;
15770        assert_eq!(without, recorded_draws(&recorder) as u64);
15771        dark.release(device.as_ref());
15772
15773        renderer.set_lights(&[shadowable_spot(0.0)]);
15774        recorder.clear();
15775        let lit = frame(device.as_ref(), &mut renderer, queue);
15776        let with = renderer.counters().draws;
15777        assert!(
15778            with > without,
15779            "a shadow-casting light adds a view and therefore draws: {with} against {without}",
15780        );
15781        assert_eq!(
15782            with,
15783            recorded_draws(&recorder) as u64,
15784            "and the counter still matches the stream",
15785        );
15786        lit.finish(device.as_ref(), renderer);
15787    }
15788
15789    /// Opens a null device offering `optional` on top of the mesh path, and
15790    /// asserts it really selected that path.
15791    ///
15792    /// Asked for rather than merely reported, because a device grants what it
15793    /// enabled: leaving mesh shaders out of the optional set opens a device on
15794    /// an indirect tail and tests nothing.
15795    ///
15796    /// The adapter has [`Features::DRAW_INDEX`] too, which a device is granted
15797    /// only where `optional` asks for it — so a test that does not gets the
15798    /// mesh tail's call per bucket.
15799    fn open_mesh_path(recorder: &Recorder, optional: Features) -> (Box<dyn Device>, QueueHandle) {
15800        let caps = crcbl_hal::DeviceCaps {
15801            features: Features::GPU_DRIVEN
15802                | Features::MESH_SHADER
15803                | Features::TASK_SHADER
15804                | Features::DRAW_INDEX,
15805            limits: crcbl_hal::Limits::desktop(),
15806        };
15807        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
15808        let adapter = instance.adapters().remove(0);
15809        assert_eq!(
15810            instance
15811                .adapter_caps(adapter.id)
15812                .expect("the null backend describes its adapter")
15813                .geometry_path(),
15814            GeometryPath::MeshShader,
15815            "a device with mesh shaders selects them, which is the case this is about"
15816        );
15817        let device = instance
15818            .create_device(&DeviceDesc {
15819                label: None,
15820                adapter: adapter.id,
15821                required_features: Features::COMPUTE,
15822                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER | optional,
15823                compatible_surface: None,
15824            })
15825            .expect("the null backend always opens");
15826        assert_eq!(
15827            device.caps().geometry_path(),
15828            GeometryPath::MeshShader,
15829            "and the opened device still selects it"
15830        );
15831        let queue = device.queue(QueueKind::Graphics).expect("always present");
15832        (device, queue)
15833    }
15834
15835    /// **The four material pages are created with the format their contents
15836    /// call for, and it is only a *colour* that is sRGB.**
15837    ///
15838    /// Topic 44's rung 2 calls this the classic PBR bug and
15839    /// says why it survives review: a base-colour texel and an emissive one are
15840    /// sRGB-encoded *colours*, which is what glTF defines them as, and a normal
15841    /// texel and a packed occlusion-roughness-metallic one are *numbers* — so
15842    /// decoding either of those through the sRGB curve is wrong by a gamma and
15843    /// looks merely like a surface bumpier or shinier than the author drew.
15844    /// Nothing in a frame reports it, no golden comparison can name it, and the
15845    /// four constants sit a few lines apart with the wrong one compiling.
15846    ///
15847    /// So this is the whole guard, and it is three claims rather than one: that
15848    /// each constant is the one it should be, that
15849    /// [`PageKind::format`] — which is what the upload loop actually calls —
15850    /// answers with it, and, the half that would otherwise be a check that
15851    /// cannot fail, that the format each page is *created* with is the format
15852    /// its `ImportedImage` declares. A declaration naming a format the image is
15853    /// not in picks the wrong aspects in a barrier.
15854    #[test]
15855    fn the_page_formats_split_colour_from_number() {
15856        assert_eq!(BASE_COLOR_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15857        assert_eq!(EMISSIVE_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15858        assert_eq!(NORMAL_PAGE_FORMAT, Format::Rgba8Unorm);
15859        assert_eq!(MRO_PAGE_FORMAT, Format::Rgba8Unorm);
15860        // Through the dispatch the upload loop actually calls, rather than the
15861        // constants alone: one loop creates every image now, and a `format` arm
15862        // pointed at the wrong constant is the way that loop gets it wrong.
15863        assert_eq!(PageKind::BaseColor.format(), BASE_COLOR_PAGE_FORMAT);
15864        assert_eq!(PageKind::Normal.format(), NORMAL_PAGE_FORMAT);
15865        assert_eq!(
15866            PageKind::MetallicRoughnessOcclusion.format(),
15867            MRO_PAGE_FORMAT
15868        );
15869        assert_eq!(PageKind::Emissive.format(), EMISSIVE_PAGE_FORMAT);
15870        assert_ne!(
15871            BASE_COLOR_PAGE_FORMAT, NORMAL_PAGE_FORMAT,
15872            "a normal page created sRGB decodes every texel through a gamma it never had"
15873        );
15874        assert_ne!(
15875            EMISSIVE_PAGE_FORMAT, MRO_PAGE_FORMAT,
15876            "a packed roughness page created sRGB shades every surface smoother than authored"
15877        );
15878
15879        let (recorder, device, queue) = open();
15880        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15881            .expect("the forward renderer builds on the null backend");
15882        assert_eq!(
15883            renderer.base_color_page_import().format,
15884            BASE_COLOR_PAGE_FORMAT
15885        );
15886        assert_eq!(renderer.normal_page_import().format, NORMAL_PAGE_FORMAT);
15887        assert_eq!(renderer.mro_page_import().format, MRO_PAGE_FORMAT);
15888        assert_eq!(renderer.emissive_page_import().format, EMISSIVE_PAGE_FORMAT);
15889        // And they really are four images, not one bound four times — which is
15890        // the other way a page could be "linear" and still be sampled through
15891        // the sRGB one.
15892        let created = [
15893            renderer.base_color_page(),
15894            renderer.normal_page(),
15895            renderer.mro_page(),
15896            renderer.emissive_page(),
15897        ];
15898        for (at, page) in created.iter().enumerate() {
15899            for other in &created[at + 1..] {
15900                assert_ne!(page.image, other.image, "two page kinds share one image");
15901                assert_ne!(page.view, other.view, "two page kinds share one view");
15902            }
15903        }
15904        // The labels come off the recorder rather than off the handles, so this
15905        // is evidence about what the device was asked to create.
15906        let images: Vec<String> = recorder
15907            .events()
15908            .into_iter()
15909            .filter_map(|event| match event {
15910                Event::Created {
15911                    kind: ObjectKind::Image,
15912                    label: Some(label),
15913                } => Some(label),
15914                _ => None,
15915            })
15916            .collect();
15917        for kind in PageKind::ALL {
15918            let page = kind.upload_label();
15919            assert!(
15920                images.iter().any(|label| label == page),
15921                "no image was created for the {page} page, and it is {images:?} that were"
15922            );
15923        }
15924        renderer.destroy(device.as_ref());
15925    }
15926
15927    /// Compare native argument indices from the shipped entry points with the
15928    /// actual renderer layout. A shared fragment buffer must have the same index
15929    /// even when geometry introduces additional resources in another module.
15930    #[test]
15931    fn mesh_pipeline_buffers_match_native_shader_arguments() {
15932        for optional in [Features::TASK_SHADER, Features::empty()] {
15933            let recorder = Recorder::new();
15934            let (device, queue) = open_mesh_path(&recorder, optional);
15935            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15936                .expect("the mesh renderer builds");
15937            let (_, entries) = recorder
15938                .bind_group_layouts_created()
15939                .into_iter()
15940                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
15941                .expect("the actual mesh layout");
15942            let mut buffers: Vec<_> = entries
15943                .iter()
15944                .filter(|entry| {
15945                    matches!(
15946                        entry.kind,
15947                        BindingKind::UniformBuffer { .. } | BindingKind::StorageBuffer { .. }
15948                    )
15949                })
15950                .collect();
15951            buffers.sort_by_key(|entry| entry.binding);
15952            assert_eq!(buffers.len(), 20, "the native buffer budget is unchanged");
15953            for (source, shader, names) in [
15954                (
15955                    include_str!("../../crcbl-shaders/shaders/mesh.slang"),
15956                    &MESH,
15957                    &["fragmentMain"][..],
15958                ),
15959                (
15960                    include_str!("../../crcbl-shaders/shaders/mesh_cluster.slang"),
15961                    &MESH_CLUSTER,
15962                    &["meshMain", "taskMain", "amplifiedMeshMain"][..],
15963                ),
15964            ] {
15965                let declarations: Vec<_> = source.lines().collect();
15966                let bindings: Vec<_> = declarations
15967                    .windows(2)
15968                    .filter_map(|lines| {
15969                        let binding = lines[0]
15970                            .trim()
15971                            .strip_prefix("[[vk::binding(")?
15972                            .split(',')
15973                            .next()?
15974                            .parse::<u32>()
15975                            .ok()?;
15976                        // The name is the last word before the D3D12 register.
15977                        let name = lines[1]
15978                            .split(" D3D12_REGISTER(")
15979                            .next()?
15980                            .split_whitespace()
15981                            .last()?
15982                            .trim_end_matches(';');
15983                        Some((name, binding))
15984                    })
15985                    .collect();
15986                for name in names {
15987                    let signature = shader
15988                        .msl()
15989                        .expect("committed native shader")
15990                        .lines()
15991                        .find(|line| line.starts_with("[[") && line.contains(&format!(" {name}(")))
15992                        .expect("native entry signature");
15993                    let mut checked = 0;
15994                    for argument in signature.split(", ") {
15995                        let Some((declaration, tail)) = argument.split_once(" [[buffer(") else {
15996                            continue;
15997                        };
15998                        let native: usize = tail.split(')').next().unwrap().parse().unwrap();
15999                        let variable = declaration.split_whitespace().last().unwrap();
16000                        let variable = variable.rsplit_once('_').map_or(variable, |(base, _)| base);
16001                        let binding = bindings
16002                            .iter()
16003                            .find(|(candidate, _)| *candidate == variable)
16004                            .unwrap_or_else(|| panic!("unknown {name} buffer {variable}"))
16005                            .1;
16006                        let expected = buffers
16007                            .iter()
16008                            .position(|entry| entry.binding == binding)
16009                            .expect("shader binding exists in the renderer layout");
16010                        assert_eq!(
16011                            native, expected,
16012                            "{name}: {variable}, logical binding {binding}, native shader vs global layout"
16013                        );
16014                        checked += 1;
16015                    }
16016                    assert!(
16017                        checked >= 10,
16018                        "entry parsing must cover the complete buffer interface"
16019                    );
16020                }
16021            }
16022            renderer.destroy(device.as_ref());
16023        }
16024    }
16025
16026    #[test]
16027    fn the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage() {
16028        let mut declared: Vec<Vec<(u32, BindingKind)>> = Vec::new();
16029        for optional in [Features::TASK_SHADER, Features::empty()] {
16030            let recorder = Recorder::new();
16031            let (device, queue) = open_mesh_path(&recorder, optional);
16032            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16033                .expect("the forward renderer builds on both device shapes");
16034            assert_eq!(
16035                renderer.culls_clusters(),
16036                optional.contains(Features::TASK_SHADER),
16037                "the two arms must actually differ, or this compares a device with itself"
16038            );
16039            let (label, entries) = recorder
16040                .bind_group_layouts_created()
16041                .into_iter()
16042                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
16043                .expect("the mesh pass declares its layout by name");
16044            assert_eq!(label.as_deref(), Some(MESH_LAYOUT_LABEL));
16045            declared.push(
16046                entries
16047                    .iter()
16048                    .map(|entry| (entry.binding, entry.kind))
16049                    .collect(),
16050            );
16051        }
16052
16053        let [amplified, plain] = declared
16054            .try_into()
16055            .unwrap_or_else(|_| unreachable!("two arms were run"));
16056        assert_eq!(
16057            amplified, plain,
16058            "the mesh layout's bindings changed with the task stage, which moves every Metal \
16059             argument-table index above the difference"
16060        );
16061        // These mesh declarations remain present without a task stage.
16062        for binding in [
16063            CLUSTER_CULL_BINDING,
16064            CLUSTER_CULL_STATS_BINDING,
16065            CLUSTER_SELECT_BINDING,
16066            CLUSTER_SELECTION_BINDING,
16067            CLUSTER_GROUP_STATE_BINDING,
16068        ] {
16069            assert!(
16070                plain.iter().any(|(number, _)| *number == binding),
16071                "binding {binding} is declared by mesh_cluster.slang and must be in the layout"
16072            );
16073        }
16074        // Logical gaps consume no native slots. The complete shader union must
16075        // remain sorted, and every mesh-only buffer follows the fragment prefix.
16076        let numbers: Vec<u32> = plain.iter().map(|(binding, _)| *binding).collect();
16077        let expected: Vec<u32> = (0..=8).chain(15..=16).chain(20..=40).collect();
16078        assert_eq!(
16079            numbers, expected,
16080            "the complete sparse shader binding union"
16081        );
16082    }
16083
16084    /// **`Features::TASK_SHADER` is what decides whether §3.5's per-cluster cull
16085    /// is built, and a device without it still draws.**
16086    ///
16087    /// The two capabilities are separate, and the adapter above offers both — so
16088    /// asking for one and not the other is a device state a real driver has and
16089    /// this can reach. Neither arm is a skip:
16090    ///
16091    /// * With the task stage, the renderer builds the amplification stage and
16092    ///   [`ForwardRenderer::culls_clusters`] says so. The null backend refuses a
16093    ///   task stage on a device without the flag, so an arm that computed this
16094    ///   wrongly would fail to build rather than pass quietly. It records one
16095    ///   flat call per partition — [`flat_dispatch_calls`].
16096    /// * Without it, the renderer builds `meshMain` — the un-amplified entry
16097    ///   point — and draws every cluster of every surviving instance, one
16098    ///   indirect dispatch per bucket reading its own extents.
16099    #[test]
16100    fn the_task_stage_is_built_only_where_the_device_has_one() {
16101        use crcbl_hal::null::Command;
16102
16103        for (optional, expected) in [(Features::TASK_SHADER, true), (Features::empty(), false)] {
16104            let recorder = Recorder::new();
16105            let (device, queue) = open_mesh_path(&recorder, optional);
16106            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16107                .expect("the forward renderer builds on both device shapes");
16108            assert_eq!(
16109                device.caps().supports(Features::TASK_SHADER),
16110                expected,
16111                "the device must actually differ between the arms, or both test the same thing"
16112            );
16113            assert_eq!(
16114                renderer.culls_clusters(),
16115                expected,
16116                "the amplification stage is built exactly where the device has one"
16117            );
16118            assert_eq!(
16119                renderer.geometry_path(),
16120                GeometryPath::MeshShader,
16121                "both arms are the mesh path; only the stage in front of it differs"
16122            );
16123
16124            let frame = frame(device.as_ref(), &mut renderer, queue);
16125            // After the frame, because the buffer named is the slot the frame
16126            // rotated to — asking before it names the previous slot's ring
16127            // entry and the comparison is against a buffer nothing drew from.
16128            let expected = if expected {
16129                flat_dispatch_calls(&renderer, crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED).0
16130            } else {
16131                mesh_dispatch_calls(&renderer)
16132            };
16133
16134            let dispatched: Vec<DrawIndirect> = commands_in_pass(&recorder, "forward")
16135                .into_iter()
16136                .filter_map(|command| match command {
16137                    Command::DrawMeshTasksIndirect(draw) => Some(draw),
16138                    _ => None,
16139                })
16140                .collect();
16141            assert_eq!(
16142                dispatched, expected,
16143                "a flat call per partition behind the stage, and a dispatch per bucket reading \
16144                 its own extents without it"
16145            );
16146
16147            frame.finish(device.as_ref(), renderer);
16148        }
16149    }
16150
16151    /// The flat calls a pass splitting the bucket table by the material-mode
16152    /// bits `key` records behind a task stage, in region 0, in partition order
16153    /// — one per segment the table holds buckets of — and each segment's first
16154    /// bucket, whose block the call binds.
16155    ///
16156    /// The offsets from [`crcbl_shaders::draw_gen::flat_args_word`] over the
16157    /// camera generator's own region count rather than from
16158    /// `DrawGen::flat_args_offset`, for [`mesh_dispatch_calls`]' reason.
16159    fn flat_dispatch_calls(renderer: &ForwardRenderer, key: u32) -> (Vec<DrawIndirect>, Vec<u32>) {
16160        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
16161        let buckets = u32::try_from(renderer.bucket_constants.len()).expect("a few buckets");
16162        let regions = renderer.primary.draws.mode().regions();
16163        let segments = crcbl_shaders::draw_gen::flat_segments(&renderer.bucket_modes);
16164        let values: Vec<u32> = if key == crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED {
16165            vec![0, key]
16166        } else {
16167            DEPTH_MODES.to_vec()
16168        };
16169        values
16170            .into_iter()
16171            .filter(|value| {
16172                renderer
16173                    .bucket_modes
16174                    .iter()
16175                    .any(|mode| mode & key == *value)
16176            })
16177            .map(|value| {
16178                let segment = crcbl_shaders::draw_gen::flat_segment(key, value)
16179                    .expect("a split every pass makes");
16180                (
16181                    DrawIndirect {
16182                        args: renderer.primary.draws.mesh_args(renderer.frame),
16183                        offset: u64::from(crcbl_shaders::draw_gen::flat_args_word(
16184                            buckets, regions, 0, segment, 0,
16185                        )) * 4,
16186                        draw_count: 1,
16187                        stride,
16188                    },
16189                    segments[segment as usize].0,
16190                )
16191            })
16192            .unzip()
16193    }
16194
16195    /// The [`DrawIndirect`] the mesh path must record for each bucket, in bucket
16196    /// order.
16197    ///
16198    /// Built from the buffer the draw-argument pass writes and the stride the
16199    /// APIs fixed, so a test comparing against it is asserting that the call
16200    /// reads *this frame's* arguments at *this bucket's* offset — the two ways
16201    /// an indirect dispatch goes wrong while still dispatching something.
16202    ///
16203    /// **The offsets are multiplied out here rather than asked of
16204    /// [`DrawGen::mesh_args_offset`]**, which is the difference between a
16205    /// comparison and a tautology: an offset function that returned zero for
16206    /// every bucket would agree with itself, and three calls onto one structure
16207    /// is a frame that draws one bucket's geometry three times.
16208    fn mesh_dispatch_calls(renderer: &ForwardRenderer) -> Vec<DrawIndirect> {
16209        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
16210        // The extents share a buffer with the one draw count per bucket that
16211        // precedes them, so every offset is that far in. Written out from the
16212        // bucket count here rather than taken from `DrawGen::mesh_args_offset`,
16213        // for the reason above: a base of zero is exactly the mistake this
16214        // comparison exists to catch, and it would agree with itself.
16215        let counts_bytes = renderer.bucket_constants.len() as u64 * 4;
16216        (0..renderer.bucket_constants.len())
16217            .map(|bucket| DrawIndirect {
16218                args: renderer.primary.draws.mesh_args(renderer.frame),
16219                offset: counts_bytes + bucket as u64 * u64::from(stride),
16220                draw_count: 1,
16221                stride,
16222            })
16223            .collect()
16224    }
16225
16226    /// **A device selecting [`GeometryPath::MeshShader`] draws through a mesh
16227    /// pipeline, and records no indirect draw and no index-buffer bind at all.**
16228    ///
16229    /// The three halves are one claim. That it dispatched says the path is
16230    /// wired; that it recorded *no* `DrawIndexedIndirect` of either kind says it
16231    /// did not quietly fall through to a tail that draws the same picture; and
16232    /// that it bound no index buffer says the geometry really came out of the
16233    /// cluster records rather than out of the index pool. Until 2026-08 this
16234    /// device degraded and logged that it had, which is exactly the shape —
16235    /// "not implemented" arriving as a passing frame — the three together rule
16236    /// out.
16237    ///
16238    /// **The extents are not here to be checked, and that is the point.** They
16239    /// are three words the draw-argument pass writes, so what this can pin is
16240    /// the call reading *this* bucket's structure out of *this* frame's buffer
16241    /// — and the CPU-side half of the x extent, the per-bucket cluster table
16242    /// the host uploaded, which the null backend keeps the bytes of. What the
16243    /// GPU then makes of it needs a GPU: `crcbl-vk`'s
16244    /// `the_mesh_dispatch_extent_is_the_culled_instance_count` reads the
16245    /// arguments back.
16246    #[test]
16247    fn a_mesh_shader_device_draws_through_a_mesh_pipeline() {
16248        use crcbl_hal::null::Command;
16249
16250        let recorder = Recorder::new();
16251        let caps = crcbl_hal::DeviceCaps {
16252            features: Features::GPU_DRIVEN | Features::MESH_SHADER,
16253            limits: crcbl_hal::Limits::desktop(),
16254        };
16255        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
16256        let adapter = instance.adapters().remove(0);
16257        assert_eq!(
16258            instance
16259                .adapter_caps(adapter.id)
16260                .expect("the null backend describes its adapter")
16261                .geometry_path(),
16262            GeometryPath::MeshShader,
16263            "a device with mesh shaders selects them, which is the case this is about"
16264        );
16265        let device = instance
16266            .create_device(&DeviceDesc {
16267                label: None,
16268                adapter: adapter.id,
16269                required_features: Features::COMPUTE,
16270                // Asked for, because a device reports what it enabled: leaving
16271                // mesh shaders out of the optional set would open a device that
16272                // selects an indirect path outright and test nothing.
16273                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER,
16274                compatible_surface: None,
16275            })
16276            .expect("the null backend always opens");
16277        assert_eq!(
16278            device.caps().geometry_path(),
16279            GeometryPath::MeshShader,
16280            "and the opened device still selects it"
16281        );
16282        let queue = device.queue(QueueKind::Graphics).expect("always present");
16283        let mut renderer =
16284            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16285        assert_eq!(
16286            renderer.geometry_path(),
16287            GeometryPath::MeshShader,
16288            "the renderer must have *built* the mesh path, not merely been offered it"
16289        );
16290        let frame = frame(device.as_ref(), &mut renderer, queue);
16291        let expected = mesh_dispatch_calls(&renderer);
16292        // The table is written once at build, into a host-visible buffer the
16293        // null backend keeps the bytes of — so it is readable whether or not a
16294        // shader ever ran. It shares that buffer with the four other tables the
16295        // draw-argument pass reads, so the region has to be cut out at the
16296        // offset the renderer told the shader about rather than at zero.
16297        let table_bytes = recorder
16298            .buffer_bytes(renderer.primary.draws.tables())
16299            .expect("the table buffer is one of this recorder's buffers");
16300        let clusters_at = renderer.primary.draws.table_offsets().bucket_clusters_at as usize * 4;
16301        let clusters: Vec<u32> = table_bytes[clusters_at..]
16302            .as_chunks::<4>()
16303            .0
16304            .iter()
16305            .take(renderer.bucket_constants.len())
16306            .map(|word| u32::from_le_bytes(*word))
16307            .collect();
16308
16309        let mut dispatched = Vec::new();
16310        let mut index_binds = 0;
16311        for command in commands_in_pass(&recorder, "forward") {
16312            match command {
16313                Command::DrawMeshTasksIndirect(draw) => dispatched.push(draw),
16314                Command::DrawMeshTasks { .. } => panic!(
16315                    "the mesh path recorded a CPU-sized dispatch, which is the extent \
16316                     the instance cull is supposed to have taken over"
16317                ),
16318                Command::DrawIndexedIndirectCount(_) | Command::DrawIndexedIndirect(_) => {
16319                    panic!(
16320                        "the mesh path recorded an indirect draw, which is the silent \
16321                         fall-through this test exists to rule out"
16322                    )
16323                }
16324                Command::BindIndexBuffer { .. } => index_binds += 1,
16325                _ => {}
16326            }
16327        }
16328        assert_eq!(
16329            dispatched, expected,
16330            "one indirect dispatch per bucket, each reading its own argument structure \
16331             out of this frame's buffer"
16332        );
16333        assert_eq!(
16334            clusters.len(),
16335            renderer.bucket_constants.len(),
16336            "one x extent per bucket: {clusters:?}"
16337        );
16338        assert!(
16339            clusters.iter().all(|&count| count > 0),
16340            "a bucket with no clusters dispatches nothing, whatever the arguments say: \
16341             {clusters:?}"
16342        );
16343        // **The x extents are not all the same number**, which is what makes
16344        // the table a statement about each bucket's own mesh. Two
16345        // single-cluster meshes would let a table hard-coded to one cluster
16346        // pass; the open box is five, one per face.
16347        assert_eq!(
16348            clusters[DEMO_OPEN_BOX] as usize,
16349            crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
16350            "the open box dispatches one workgroup per face, and that is the only \
16351             resident whose cluster count is not one: {clusters:?}"
16352        );
16353        assert_eq!(
16354            index_binds, 0,
16355            "a mesh pipeline has no index buffer; binding one would mean the geometry \
16356             came from the index pool after all"
16357        );
16358
16359        frame.finish(device.as_ref(), renderer);
16360    }
16361
16362    /// **The cull pass is told the camera the frame is drawn with**, and how
16363    /// many array elements to walk.
16364    ///
16365    /// Both halves fail silently: a frustum from a different aspect ratio culls
16366    /// geometry that is on screen, and an instance count short of the pool's
16367    /// high-water mark stops testing the instances above a freed slot. Neither
16368    /// is visible in a picture until something disappears from an edge.
16369    #[test]
16370    fn the_cull_pass_gets_this_frame_s_camera_and_every_occupied_slot() {
16371        let (recorder, device, queue) = open();
16372        let mut renderer =
16373            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16374        // The cube first and the pyramid above it, because the second half of
16375        // this test frees the lower slot and asks what the walk still covers.
16376        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16377        place_demo(
16378            &mut renderer,
16379            DEMO_PYRAMID,
16380            DEMO_UNTINTED,
16381            Mat4::from_translation(Vec3::X),
16382        );
16383
16384        let camera = Camera {
16385            eye: Vec3::new(1.6, 1.2, 2.2),
16386            ..Camera::default()
16387        };
16388        let extent = (256u32, 192u32);
16389        renderer
16390            .begin_frame(
16391                device.as_ref(),
16392                &camera,
16393                &DirectionalLight::default(),
16394                extent,
16395            )
16396            .expect("write");
16397
16398        let aspect = extent.0 as f32 / extent.1 as f32;
16399        let expected = crate::cull::Frustum::from_view_projection(camera.view_projection(aspect));
16400        let written = recorder
16401            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16402            .expect("this frame's cull parameters are live");
16403        assert_eq!(
16404            &written[..crcbl_shaders::cull::PARAMS_SIZE],
16405            &crcbl_shaders::cull::Params {
16406                planes: expected.planes.map(|plane| plane.to_array()),
16407                instance_count: 2,
16408                capacity: scene::Capacities::default().instances,
16409                hidden_view: ViewId::PRIMARY.hidden_bit(),
16410                ..crcbl_shaders::cull::Params::default()
16411            }
16412            .to_bytes()[..],
16413            "the cull block must carry this frame's own frustum, the pool's whole \
16414             occupied range, and the visible list's capacity"
16415        );
16416
16417        // And the high-water mark is what is written, not the live count: remove
16418        // the cube and the pyramid above it still has to be tested.
16419        renderer.remove_instance(cube);
16420        renderer
16421            .begin_frame(
16422                device.as_ref(),
16423                &camera,
16424                &DirectionalLight::default(),
16425                extent,
16426            )
16427            .expect("write");
16428        let written = recorder
16429            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16430            .expect("live");
16431        assert_eq!(
16432            u32::from_le_bytes(written[96..100].try_into().expect("four bytes")),
16433            2,
16434            "one live instance, two occupied slots — a walk of one would never \
16435             reach the pyramid"
16436        );
16437
16438        renderer.destroy(device.as_ref());
16439        recorder.assert_valid();
16440    }
16441
16442    /// **Every counter both compute passes add to is zeroed by a pass of its
16443    /// own, before either of them runs.**
16444    ///
16445    /// The two shaders only ever increment, so a counter carrying the previous
16446    /// frame's total makes a bucket's argument structure claim more instances
16447    /// than its run holds — which draws whatever the run's stale tail happens to
16448    /// name.
16449    ///
16450    /// # This once read the bytes back, and no longer can
16451    ///
16452    /// It used to poison every counter with `0xAB` and assert `begin_frame`
16453    /// had written zeroes over them — the poison being the whole test, because
16454    /// the null backend runs no shader and a counter nothing wrote reads as the
16455    /// zero it was created with. The counters are device-local now, so nothing
16456    /// on the host writes them and [`Recorder::buffer_bytes`] holds nothing for
16457    /// them: the zero is a dispatch inside the frame, and a backend that runs no
16458    /// shader cannot observe it at all.
16459    ///
16460    /// So the poison moved to where a shader actually runs — `crcbl-vk`'s
16461    /// `draw_gen` end-to-end fills them with a sentinel and reads back the
16462    /// generated arguments — and what is checkable *here* is the schedule: that
16463    /// the frame contains the clearing pass, that it writes exactly those
16464    /// buffers, and that the graph orders the two accumulating passes after it.
16465    /// Each of the counts below goes red if a buffer is dropped from the
16466    /// clearing pass, and the pass list goes red if the pass leaves the frame.
16467    #[test]
16468    fn every_frame_starts_from_zeroed_counters() {
16469        let (recorder, device, queue) = open();
16470        let mut renderer =
16471            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16472        place_cube(&mut renderer, Mat4::IDENTITY);
16473        let imported = swapchain_image(device.as_ref());
16474        // Twice round the ring, because a slot cleared only on its first use is
16475        // exactly the failure this is about.
16476        for round in 0..FRAMES_IN_FLIGHT * 2 {
16477            renderer
16478                .begin_frame(
16479                    device.as_ref(),
16480                    &Camera::default(),
16481                    &DirectionalLight::default(),
16482                    (64, 48),
16483                )
16484                .expect("write");
16485            let mut graph = crate::RenderGraph::new(queue);
16486            let target = graph.import_image("target", imported);
16487            let pool = crate::TransientPool::new();
16488            renderer.add_passes(&mut graph, &pool, target, (64, 48));
16489            let compiled = graph.compile(&pool).expect("a legal frame");
16490
16491            let clear = &compiled.passes()[0];
16492            assert_eq!(
16493                clear.label(),
16494                "clear-counters",
16495                "round {round}: the zero has to be written before anything adds to it"
16496            );
16497            let barriers = &clear.barriers().buffers;
16498            assert_eq!(
16499                barriers.len(),
16500                3,
16501                "round {round}: the survivor count, the draw arguments, and the buffer \
16502                 holding both the draw counts and the mesh-dispatch arguments, and \
16503                 nothing else: {barriers:?}"
16504            );
16505            assert!(
16506                barriers
16507                    .iter()
16508                    .all(|barrier| barrier.to == ResourceState::ShaderReadWrite),
16509                "round {round}: every one of them is written by this pass: {barriers:?}"
16510            );
16511            // The ones the frame leaves as indirect arguments are the two a
16512            // driver reads; the survivor count rests in a shader read. That
16513            // split is what names them without a handle to compare.
16514            assert_eq!(
16515                barriers
16516                    .iter()
16517                    .filter(|barrier| barrier.from == ResourceState::IndirectArgument)
16518                    .count(),
16519                2,
16520                "round {round}: out of the state a draw read them in: {barriers:?}"
16521            );
16522
16523            let after = |label: &str| {
16524                compiled
16525                    .passes()
16526                    .iter()
16527                    .find(|pass| pass.label() == label)
16528                    .unwrap_or_else(|| panic!("round {round}: no `{label}` pass"))
16529                    .barriers()
16530                    .buffers
16531                    .iter()
16532                    .filter(|barrier| {
16533                        barrier.from == ResourceState::ShaderReadWrite
16534                            && barrier.to == ResourceState::ShaderReadWrite
16535                    })
16536                    .count()
16537            };
16538            assert_eq!(
16539                after("cull"),
16540                1,
16541                "round {round}: the survivor count reaches the cull pass's atomic behind a \
16542                 barrier on the write that zeroed it"
16543            );
16544            assert_eq!(
16545                after("draw-args"),
16546                4,
16547                "round {round}: and so do the draw arguments and the buffer holding the \
16548                 draw counts beside the mesh-dispatch arguments — plus the survivor list, \
16549                 which the cull pass has just written and this pass reads through the same \
16550                 descriptor it scatters the runs into, and `docs/notes/rendering.md`'s \
16551                 hysteresis state, which the clearing pass does *not* zero and which is \
16552                 behind the same kind of barrier for the opposite reason: it is the one \
16553                 buffer here carrying a value out of the previous frame, so what it needs \
16554                 ordering against is that frame rather than this one's clear"
16555            );
16556            // **And the prefix sum and the scatter behind barriers of their own**,
16557            // on every buffer the stage before them wrote. This is what orders
16558            // them on a device that runs undeclared commands in any order — see
16559            // `DrawGen::add_passes` — and what three dispatches in one pass
16560            // silently lacked.
16561            for label in ["draw-starts", "draw-scatter"] {
16562                assert_eq!(
16563                    after(label),
16564                    4,
16565                    "round {round}: `{label}` reads what the pass before it wrote, so every \
16566                     buffer they share is ordered behind a barrier"
16567                );
16568            }
16569
16570            // The compiled graph borrows the renderer's pass bodies, so it has
16571            // to go before the next frame borrows the renderer again.
16572            drop(compiled);
16573        }
16574        renderer.destroy(device.as_ref());
16575        device.destroy_image_view(imported.view);
16576        device.destroy_image(imported.image);
16577        recorder.assert_valid();
16578    }
16579
16580    /// **A frame with no instances leaves out every generator's cull and
16581    /// scatter passes**, and keeps the clear and the two stages that write each
16582    /// bucket's arguments.
16583    ///
16584    /// An empty pass is not a harmless no-op on Metal: the backend opens an
16585    /// encoder for every graph pass and strict validation rejects ending one
16586    /// with no work — see `DrawGen::add_passes`. Each count below goes red if
16587    /// an empty pass comes back, or if a pass a zero-draw frame needs drops out.
16588    #[test]
16589    fn a_frame_with_no_instances_omits_the_empty_draw_generation_passes() {
16590        let (recorder, device, queue) = open();
16591        let mut renderer =
16592            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16593        renderer
16594            .begin_frame(
16595                device.as_ref(),
16596                &Camera::default(),
16597                &DirectionalLight::default(),
16598                (64, 48),
16599            )
16600            .expect("write");
16601        let imported = swapchain_image(device.as_ref());
16602        let mut graph = crate::RenderGraph::new(queue);
16603        let target = graph.import_image("target", imported);
16604        let pool = crate::TransientPool::new();
16605        renderer.add_passes(&mut graph, &pool, target, (64, 48));
16606        let compiled = graph.compile(&pool).expect("a legal frame");
16607
16608        let count = |label: &str| {
16609            compiled
16610                .passes()
16611                .iter()
16612                .filter(|pass| pass.label() == label)
16613                .count()
16614        };
16615        // The camera's generator and one per shadow cascade.
16616        let generators = 1 + shadow::CASCADES;
16617        for label in ["clear-counters", "draw-args", "draw-starts"] {
16618            assert_eq!(
16619                count(label),
16620                generators,
16621                "`{label}` still has work with nothing to draw: the clear erases the \
16622                 previous frame's counts and the argument stages write zero draws"
16623            );
16624        }
16625        for label in ["cull", "draw-scatter"] {
16626            assert_eq!(
16627                count(label),
16628                0,
16629                "`{label}` has no workgroups to dispatch with no instances"
16630            );
16631        }
16632
16633        drop(compiled);
16634        renderer.destroy(device.as_ref());
16635        device.destroy_image_view(imported.view);
16636        device.destroy_image(imported.image);
16637        recorder.assert_valid();
16638    }
16639
16640    /// **The graph transitions the generated arguments into
16641    /// [`ResourceState::IndirectArgument`] before the draws read them**, and the
16642    /// runs into a shader read.
16643    ///
16644    /// The seam calls this the single most important barrier in a GPU-driven
16645    /// frame and says its absence produces "sometimes nothing draws" — which is
16646    /// exactly the failure a golden image on one driver would not catch. It is
16647    /// asserted on the compiled graph, which is pure and needs no device.
16648    #[test]
16649    fn the_graph_barriers_the_arguments_into_place_before_the_draws() {
16650        let _blurs = ssao_blur_switch();
16651        let (recorder, device, queue) = open();
16652        let mut renderer =
16653            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16654        place_cube(&mut renderer, Mat4::IDENTITY);
16655        renderer
16656            .begin_frame(
16657                device.as_ref(),
16658                &Camera::default(),
16659                &DirectionalLight::default(),
16660                (64, 48),
16661            )
16662            .expect("write");
16663
16664        let imported = swapchain_image(device.as_ref());
16665        let mut graph = crate::RenderGraph::new(queue);
16666        let target = graph.import_image("target", imported);
16667        let pool = crate::TransientPool::new();
16668        renderer.add_passes(&mut graph, &pool, target, (64, 48));
16669        let compiled = graph.compile(&pool).expect("a legal frame");
16670
16671        let passes: Vec<String> = compiled
16672            .passes()
16673            .iter()
16674            .map(|pass| pass.label().to_string())
16675            .collect();
16676        // The camera's five compute passes and topic 18's clustering dispatch,
16677        // then five per shadow cascade, then the depth-only pass they feed and
16678        // the colour pass that samples it.
16679        //
16680        // **The clustering pass is after the camera's clearing dispatch**, and
16681        // that is the ordering the overflow counter depends on: the clearing
16682        // pass zeroes the statistics word this one adds to, and both declare
16683        // the same buffer, so the graph is what puts the barrier between them.
16684        let mut expected: Vec<String> = Vec::new();
16685        for cascade in 0..=shadow::CASCADES {
16686            expected.extend(
16687                [
16688                    "clear-counters",
16689                    "cull",
16690                    "draw-args",
16691                    "draw-starts",
16692                    "draw-scatter",
16693                ]
16694                .into_iter()
16695                .map(str::to_string),
16696            );
16697            if cascade == 0 {
16698                expected.push("light-cluster".to_string());
16699            }
16700        }
16701        // And the culling-statistics copy **last**, after every pass that adds
16702        // to the buffer it reads — the cull dispatch, the clustering pass and
16703        // the amplification stage inside the colour pass.
16704        expected.extend(
16705            [
16706                "shadow",
16707                "depth-prepass",
16708                "ssao",
16709                "ssao-blur",
16710                // The reconstruction that ends the occlusion chain, between the
16711                // blur it reads and the pass that binds what it wrote — see
16712                // [`crate::ssao`]'s header on why the first two run smaller than
16713                // the frame and this one does not.
16714                "ssao-upsample",
16715                "forward",
16716                // The pyramid the march climbs, between the pass that wrote
16717                // level 0 and the pass that reads the chain. Two levels at this
16718                // extent, written out for the reason `crate::bloom`'s chain is
16719                // in the toggle test below: a table generated from
16720                // `crate::hiz::levels_for` could not fail.
16721                "hiz-1",
16722                "hiz-2",
16723                "ssr",
16724                "ssr-blur",
16725                "tonemap",
16726                // The resolve `RenderEffects::DEFAULT_STACK` carries, which is
16727                // CMAA2's three rather than FXAA's one —
16728                // `each_effect_toggle_removes_exactly_the_passes_it_owns` is
16729                // where the swap between the two tiers is pinned.
16730                "cmaa2-edges",
16731                "cmaa2-shapes",
16732                "cmaa2-apply",
16733                "cull-stats-readback",
16734            ]
16735            .into_iter()
16736            .map(str::to_string),
16737        );
16738        assert_eq!(
16739            passes, expected,
16740            "each cull's five compute passes come first, and in that order"
16741        );
16742
16743        // **The depth prepass, not the colour pass**, and that is what says the
16744        // prepass really is the first thing to draw from the camera's cull: it is
16745        // where the draw buffers leave the compute pass's writes. The colour pass
16746        // below then needs none of these, because they are already in the state it
16747        // wants — which is the assertion after it.
16748        let prepass = compiled
16749            .passes()
16750            .iter()
16751            .find(|pass| pass.label() == "depth-prepass")
16752            .expect("the pass list above");
16753        let into_indirect = prepass
16754            .barriers()
16755            .buffers
16756            .iter()
16757            .filter(|barrier| barrier.to == ResourceState::IndirectArgument)
16758            .count();
16759        assert_eq!(
16760            into_indirect,
16761            2,
16762            "the arguments and the count, out of the compute pass's writes and into \
16763             the state a draw reads them in: {:?}",
16764            prepass.barriers().buffers
16765        );
16766        assert!(
16767            prepass.barriers().buffers.iter().any(|barrier| {
16768                barrier.from == ResourceState::ShaderReadWrite
16769                    && barrier.to == ResourceState::ShaderRead
16770            }),
16771            "and the runs, which the vertex stage reads: {:?}",
16772            prepass.barriers().buffers
16773        );
16774
16775        let forward = compiled
16776            .passes()
16777            .iter()
16778            .find(|pass| pass.label() == "forward")
16779            .expect("the pass list above");
16780        assert!(
16781            forward
16782                .barriers()
16783                .buffers
16784                .iter()
16785                .all(|barrier| barrier.to != ResourceState::IndirectArgument),
16786            "the prepass draws from the same arguments, so the colour pass finds them \
16787             already in the state it wants — a barrier here would mean something between \
16788             the two put them back: {:?}",
16789            forward.barriers().buffers
16790        );
16791        // What the colour pass *does* still have to be given: the froxel grid,
16792        // which no earlier pass reads.
16793        assert!(
16794            forward.barriers().buffers.iter().any(|barrier| {
16795                barrier.from == ResourceState::ShaderReadWrite
16796                    && barrier.to == ResourceState::ShaderRead
16797            }),
16798            "and the froxel grid, which its fragment stage reads: {:?}",
16799            forward.barriers().buffers
16800        );
16801
16802        let draw_args = compiled
16803            .passes()
16804            .iter()
16805            .find(|pass| pass.label() == "draw-args")
16806            .expect("the pass list above");
16807        assert!(
16808            draw_args.barriers().buffers.iter().any(|barrier| {
16809                barrier.from == ResourceState::ShaderReadWrite
16810                    && barrier.to == ResourceState::ShaderRead
16811            }),
16812            "and the visible list is ordered after the cull pass wrote it: {:?}",
16813            draw_args.barriers().buffers
16814        );
16815
16816        // The compiled graph borrows the renderer's pass bodies, so it has to go
16817        // before the renderer does.
16818        drop(compiled);
16819        renderer.destroy(device.as_ref());
16820        device.destroy_image_view(imported.view);
16821        device.destroy_image(imported.image);
16822        recorder.assert_valid();
16823    }
16824
16825    /// One more frame than the uniform ring is deep, so at least one lap both
16826    /// reuses a slot and follows a lap that already sampled the atlas.
16827    const SHADOW_LAPS: usize = FRAMES_IN_FLIGHT + 1;
16828
16829    /// **Every frame's first barrier on the shadow atlas names what the previous
16830    /// frame left it in**, and the same for its placeholder.
16831    ///
16832    /// # Why this cannot be read off one frame
16833    ///
16834    /// The atlas is neither a transient nor a swapchain image. The pool never
16835    /// hands one out and has no description to size it from, and no acquire
16836    /// semaphore sits between one frame's use of it and the next — so
16837    /// [`ForwardRenderer::add_passes`] *declares* it, and the declaration is what
16838    /// makes the transition true.
16839    ///
16840    /// What it declares is [`imported_state`], the pool's record of what the
16841    /// last graph to *execute* left the image in, so [`InitialClaim::Tracked`]
16842    /// can only ever find the two agreeing for this one import — deliberately,
16843    /// because a declaration and an audit reading one value cannot drift apart
16844    /// the way a renderer-held copy of it could. The audit still has teeth
16845    /// elsewhere in this frame: `ssao-placeholder` and `probes` declare a
16846    /// constant, and `the_guard_still_catches_an_engine_import_that_lies` is
16847    /// what shows it fires on those.
16848    ///
16849    /// So neither mechanism says anything about the barriers on either side of
16850    /// the declaration — whether the frame that ran actually reached the state
16851    /// the ledger now claims, and whether the next frame's first barrier comes
16852    /// out of it — which is what the stream below is for.
16853    ///
16854    /// Declaring [`ResourceState::Undefined`] on a frame after the first is the
16855    /// failure this catches. It expands to `srcStageMask = NONE,
16856    /// srcAccessMask = NONE` (`crcbl_vk::conv::state_masks`), so the transition
16857    /// into the depth-only pass's attachment state orders against nothing — while
16858    /// the previous frame's colour pass is still sampling the very same image.
16859    /// Vulkan reports it as `SYNC-HAZARD-WRITE-AFTER-READ` with
16860    /// `read_barriers: 0`; every other backend resolves it however the driver
16861    /// likes.
16862    ///
16863    /// # Why the command stream is the observable
16864    ///
16865    /// Nothing above the seam can see a wrong declaration: the frame still
16866    /// renders, the golden still matches, and no state is ever read back. So this
16867    /// replays the recorded stream with a tracker, which is the same check a
16868    /// validation layer performs and needs no GPU at all — the shape
16869    /// `crcbl::screenshot`'s
16870    /// `every_readback_barrier_declares_the_state_the_image_is_actually_in` uses.
16871    /// One difference: `Undefined` is **not** waved through after the first
16872    /// touch. It is true for a swapchain image because the acquire's semaphore
16873    /// makes it true, and there is no such semaphore here.
16874    #[test]
16875    fn the_shadow_atlas_enters_each_frame_in_the_state_the_last_one_left_it() {
16876        use crcbl_hal::null::Command;
16877
16878        let (recorder, device, queue) = open();
16879        let device = device.as_ref();
16880        let mut renderer =
16881            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16882        let atlas = renderer.shadow_atlas();
16883        let placeholder = renderer.shadow_placeholder;
16884        let mut pool = crate::TransientPool::new();
16885        let imported = swapchain_image(device);
16886        let mut recorded = Vec::with_capacity(SHADOW_LAPS);
16887
16888        for lap in 0..SHADOW_LAPS {
16889            renderer
16890                .begin_frame(
16891                    device,
16892                    &Camera::default(),
16893                    // **A different sun each lap**, so every lap redraws the
16894                    // atlas: this is a test about the barrier a frame that
16895                    // writes the image declares, and a lap that cached would
16896                    // record no pass and no transition at all. See
16897                    // [`moving_sun`].
16898                    &moving_sun(u32::try_from(lap).expect("a handful of laps")),
16899                    (64, 48),
16900                )
16901                .expect("write");
16902            let mut graph = crate::RenderGraph::new(queue);
16903            let target = graph.import_image("target", imported);
16904            renderer.add_passes(&mut graph, &pool, target, (64, 48));
16905            let compiled = graph.compile(&pool).expect("a legal frame");
16906            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
16907                label: Some("shadow lap"),
16908                queue,
16909            });
16910            compiled
16911                .execute(device, &mut pool, encoder.as_mut(), None)
16912                .expect("the graph executed");
16913            recorded.push(encoder.finish().expect("recording succeeded"));
16914        }
16915
16916        // The two images the renderer owns across frames. A transient's state is
16917        // the pool's business and the fake swapchain image's is the acquire's, so
16918        // neither belongs in here.
16919        let mut tracked = [
16920            (atlas, ResourceState::Undefined),
16921            (placeholder, ResourceState::Undefined),
16922        ];
16923        let mut atlas_writes = 0usize;
16924        let mut named = 0usize;
16925        for command in recorder.commands() {
16926            let Command::Barrier { images, .. } = command else {
16927                continue;
16928            };
16929            for barrier in images {
16930                let Some((_, state)) = tracked
16931                    .iter_mut()
16932                    .find(|(handle, _)| *handle == barrier.image)
16933                else {
16934                    continue;
16935                };
16936                assert_eq!(
16937                    barrier.from, *state,
16938                    "a barrier declared {:?} -> {:?} on an image the frame before it left in \
16939                     {:?}. `Undefined` carries no source scope, so a transition declaring it \
16940                     orders against nothing and the previous frame's sampled read is still in \
16941                     flight underneath it.",
16942                    barrier.from, barrier.to, *state
16943                );
16944                if barrier.image == atlas && barrier.to == ResourceState::DepthStencilWrite {
16945                    atlas_writes += 1;
16946                }
16947                *state = barrier.to;
16948                named += 1;
16949            }
16950        }
16951
16952        // Both halves of the loop above are silent on an empty stream, so the
16953        // shape it walked is asserted rather than assumed: one transition into
16954        // the depth-only pass's attachment state per lap, the last one included.
16955        assert_eq!(
16956            atlas_writes, SHADOW_LAPS,
16957            "{named} barrier(s) named the atlas or its placeholder across {SHADOW_LAPS} laps, \
16958             {atlas_writes} of them taking the atlas into DepthStencilWrite — every lap moved \
16959             the sun, so every lap redraws the atlas, and anything else means the loop above \
16960             asserted on a stream that does not contain the transition it is about"
16961        );
16962        let (_, ended) = tracked[0];
16963        assert_eq!(
16964            ended,
16965            ResourceState::ShaderRead,
16966            "the import promises to hand the atlas back in the state the next frame declares"
16967        );
16968
16969        renderer.destroy(device);
16970        for commands in recorded {
16971            device.destroy_command_buffer(commands);
16972        }
16973        pool.destroy(device);
16974        device.destroy_image_view(imported.view);
16975        device.destroy_image(imported.image);
16976        recorder.assert_valid();
16977    }
16978
16979    /// A renderer with a shadowed spot beside the sun's cascades and a caster
16980    /// for both to draw, which is the smallest scene the atlas cache has
16981    /// anything to say about: without a light tile the only maps are the
16982    /// cascades, and without a caster every tile is a clear.
16983    fn shadow_cache_scene(
16984        device: &dyn Device,
16985        queue: QueueHandle,
16986    ) -> (ForwardRenderer, InstanceHandle) {
16987        let mut renderer =
16988            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16989        // Pinned, on `set_shadow_cadence`'s own terms: the console's two limits
16990        // are process-global and `the_console_moves_both_limits` holds them at
16991        // a four-frame hold and three faces a frame for the length of its
16992        // check. A cache test reading the console inside that window reports
16993        // "did not settle" — seen in the wild on 2026-09-04, and reproduced by
16994        // holding both limits at those values inside the arm's own process,
16995        // which the pin makes harmless.
16996        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
16997        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16998        renderer.set_lights(&[shadowable_spot(-1.0)]);
16999        (renderer, cube)
17000    }
17001
17002    /// Draws one frame and answers whether it drew the shadow atlas, **read two
17003    /// ways that have to agree**.
17004    ///
17005    /// [`ForwardRenderer::shadow_atlas_cached`] is the renderer's own claim and
17006    /// the recorded stream is what the device was actually told; either on its
17007    /// own would be satisfied by a renderer that reported one thing and did the
17008    /// other, which is precisely the failure a cache has. `seen` is the cursor
17009    /// into the cumulative recorder, so each call reads its own frame.
17010    fn drew_the_atlas(
17011        recorder: &Recorder,
17012        seen: &mut usize,
17013        device: &dyn Device,
17014        renderer: &mut ForwardRenderer,
17015        queue: QueueHandle,
17016        camera: &Camera,
17017        sun: &DirectionalLight,
17018    ) -> bool {
17019        let drawn = frame_seen_from(device, renderer, queue, camera, sun);
17020        let claimed = renderer.shadow_atlas_cached();
17021        let commands = recorder.commands();
17022        let opened = commands[*seen..].iter().any(|command| {
17023            command
17024                .opens_pass()
17025                .is_some_and(|(_, label)| label == Some("shadow"))
17026        });
17027        *seen = commands.len();
17028        drawn.release(device);
17029        assert_eq!(
17030            opened,
17031            !claimed,
17032            "the renderer reports cached = {claimed} and its frame {} a pass labelled `shadow`",
17033            if opened { "opened" } else { "opened no" }
17034        );
17035        opened
17036    }
17037
17038    #[test]
17039    fn shadow_preparation_retains_empty_scratch_after_redraw_and_cached_frames() {
17040        let (recorder, device, queue) = open();
17041        let device = device.as_ref();
17042        let (mut renderer, _) = shadow_cache_scene(device, queue);
17043        let camera = Camera::default();
17044        let sun = DirectionalLight::default();
17045        let mut seen = 0;
17046        assert!(drew_the_atlas(
17047            &recorder,
17048            &mut seen,
17049            device,
17050            &mut renderer,
17051            queue,
17052            &camera,
17053            &sun
17054        ));
17055        let capacity = (
17056            renderer.shadow_prepare_views.capacity(),
17057            renderer.shadow_prepare_culls.capacity(),
17058        );
17059        assert!(capacity.0 >= SHADOW_VIEWS && capacity.1 >= SHADOW_CULLS);
17060        assert!(renderer.shadow_prepare_views.is_empty());
17061        assert!(renderer.shadow_prepare_culls.is_empty());
17062        for _ in 0..FRAMES_IN_FLIGHT {
17063            assert!(!drew_the_atlas(
17064                &recorder,
17065                &mut seen,
17066                device,
17067                &mut renderer,
17068                queue,
17069                &camera,
17070                &sun
17071            ));
17072            assert!(renderer.shadow_prepare_views.is_empty());
17073            assert!(renderer.shadow_prepare_culls.is_empty());
17074            assert_eq!(
17075                (
17076                    renderer.shadow_prepare_views.capacity(),
17077                    renderer.shadow_prepare_culls.capacity()
17078                ),
17079                capacity
17080            );
17081        }
17082        for (step, view) in [0, 1, shadow_view(0, 0)].into_iter().enumerate() {
17083            // The spot moves for its own view and the camera for the cascades',
17084            // which are fitted to it: a moved spot alone is no input of theirs.
17085            renderer.set_lights(&[shadowable_spot(-2.0 - step as f32)]);
17086            let camera = Camera {
17087                eye: camera.eye + Vec3::X * 0.1 * (step + 1) as f32,
17088                ..camera
17089            };
17090            let slot = (renderer.frame + 1) % FRAMES_IN_FLIGHT;
17091            let short = device
17092                .create_buffer(&BufferDesc {
17093                    label: Some("refused shadow scratch test upload"),
17094                    size: std::mem::size_of::<f32>() as u64,
17095                    usage: BufferUsage::UNIFORM,
17096                    memory: MemoryLocation::HostUpload,
17097                })
17098                .unwrap();
17099            let original = std::mem::replace(&mut renderer.shadow_uniforms[slot][view], short);
17100            let before = recorder.buffer_bytes(short).unwrap();
17101            let result = renderer.begin_frame(device, &camera, &sun, TEST_EXTENT);
17102            renderer.shadow_uniforms[slot][view] = original;
17103            assert!(
17104                matches!(result, Err(HalError::InvalidDescriptor(ref cause)) if cause.contains("exceeds")),
17105                "observe a refused shadow uniform: {result:?}"
17106            );
17107            assert_eq!(recorder.buffer_bytes(short).unwrap(), before);
17108            assert!(!recorder.events().iter().any(
17109                |event| matches!(event, Event::BufferWritten { buffer, .. } if *buffer == short)
17110            ));
17111            assert!(renderer.shadow_prepare_views.is_empty());
17112            assert!(renderer.shadow_prepare_culls.is_empty());
17113            assert_eq!(
17114                (
17115                    renderer.shadow_prepare_views.capacity(),
17116                    renderer.shadow_prepare_culls.capacity()
17117                ),
17118                capacity
17119            );
17120            let refused_inputs = renderer.shadow_group_inputs.clone();
17121            device.destroy_buffer(short);
17122            recorder.assert_valid();
17123            assert!(drew_the_atlas(
17124                &recorder,
17125                &mut seen,
17126                device,
17127                &mut renderer,
17128                queue,
17129                &camera,
17130                &sun
17131            ));
17132            assert_eq!(renderer.shadow_group_inputs, refused_inputs);
17133            assert!(renderer.shadow_prepare_views.is_empty());
17134            assert!(renderer.shadow_prepare_culls.is_empty());
17135            assert_eq!(
17136                (
17137                    renderer.shadow_prepare_views.capacity(),
17138                    renderer.shadow_prepare_culls.capacity()
17139                ),
17140                capacity
17141            );
17142            assert!(!drew_the_atlas(
17143                &recorder,
17144                &mut seen,
17145                device,
17146                &mut renderer,
17147                queue,
17148                &camera,
17149                &sun
17150            ));
17151        }
17152        renderer.destroy(device);
17153        recorder.assert_valid();
17154        assert_eq!(recorder.total_live_objects(), 0);
17155    }
17156
17157    /// **A frame over a scene nothing moved in does not draw the shadow atlas
17158    /// again**, and what it saves is the whole of the atlas's work.
17159    ///
17160    /// Topic 45's static-caching rung, and the observable it
17161    /// otherwise has none for: the map a cached frame samples is byte for byte
17162    /// the map the frame before it sampled, so no golden image and no readback
17163    /// can tell the two frames apart. The recorded command stream can — and the
17164    /// dispatch count is the half that says the *culls* went with the pass,
17165    /// rather than the frame still paying for the draws it decided not to
17166    /// record.
17167    #[test]
17168    fn a_frame_over_a_still_scene_does_not_draw_the_shadow_atlas_again() {
17169        use crcbl_hal::null::Command;
17170
17171        // The blur count is a process-global console variable, and the frame's
17172        // draw count below includes the full-screen triangle each blur records
17173        // — so a concurrent test holding `r_ssao_blur_passes` at two would move
17174        // it under this one. Held rather than merely read, which is the
17175        // convention that variable's own test set.
17176        let _blurs = ssao_blur_switch();
17177        let (recorder, device, queue) = open();
17178        let device = device.as_ref();
17179        let (mut renderer, _) = shadow_cache_scene(device, queue);
17180        let camera = Camera::default();
17181        let sun = DirectionalLight::default();
17182
17183        let mut seen = 0usize;
17184        let dispatches = |recorder: &Recorder, from: usize| {
17185            recorder.commands()[from..]
17186                .iter()
17187                .filter(|command| matches!(command, Command::Dispatch { .. }))
17188                .count()
17189        };
17190
17191        let at = seen;
17192        assert!(
17193            drew_the_atlas(
17194                &recorder,
17195                &mut seen,
17196                device,
17197                &mut renderer,
17198                queue,
17199                &camera,
17200                &sun
17201            ),
17202            "the first frame of all has to draw the atlas: nothing has put anything in it"
17203        );
17204        let first = dispatches(&recorder, at);
17205        let drawing_draws = renderer.counters().draws;
17206        let buckets = renderer.bucket_constants.len() as u64;
17207        assert!(
17208            renderer.shadow_lights().base_of(0).is_some(),
17209            "the spot must hold a run for the count below to include a light slot's cull"
17210        );
17211        // The camera's own draw generation and topic 18's clustering dispatch,
17212        // plus a generation per cascade and one for the spot's slot.
17213        assert_eq!(
17214            first,
17215            DrawGen::DISPATCHES as usize * (2 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
17216            "the drawing frame did not record the culls this test is about skipping"
17217        );
17218
17219        for round in 0..3 {
17220            let at = seen;
17221            assert!(
17222                !drew_the_atlas(
17223                    &recorder,
17224                    &mut seen,
17225                    device,
17226                    &mut renderer,
17227                    queue,
17228                    &camera,
17229                    &sun
17230                ),
17231                "round {round} redrew an atlas nothing had changed"
17232            );
17233            assert_eq!(
17234                dispatches(&recorder, at),
17235                DrawGen::DISPATCHES as usize + 1 + RESOLVE_DISPATCHES,
17236                "round {round} kept a shadow cull it had no pass to feed"
17237            );
17238            assert_eq!(
17239                drawing_draws - renderer.counters().draws,
17240                (shadow::CASCADES + 1) as u64 * buckets,
17241                "round {round}: the frame's own draw count did not lose exactly the atlas's \
17242                 calls — one per bucket per cascade, and one per bucket for the spot's tile"
17243            );
17244        }
17245
17246        renderer.destroy(device);
17247        recorder.assert_valid();
17248    }
17249
17250    /// A cadence that holds every map one rung down for a frame, with the whole
17251    /// atlas's worth of tiles to spend.
17252    ///
17253    /// Pinned through [`ForwardRenderer::set_shadow_cadence`] rather than set on
17254    /// the console: [`shadow::r_shadow_cadence`] is process-global and the
17255    /// shadow pass is in every frame's pass list, so a test that moved it would
17256    /// change the frame every other test in this module draws.
17257    const HOLD_TWO: shadow::Cadence = shadow::Cadence {
17258        hold: 2,
17259        faces: shadow::TILES,
17260    };
17261
17262    /// How the shadow pass loaded its depth attachment, over the commands from
17263    /// `from` on, and [`None`] where the frame recorded no such pass.
17264    ///
17265    /// **The observable the tile clear otherwise has none for.** A frame that
17266    /// kept a tile and a frame that redrew every one of them sample maps that
17267    /// may be identical, so nothing in the picture separates them; this is the
17268    /// declaration that says which the device was told.
17269    fn shadow_pass_depth_load(recorder: &Recorder, from: usize) -> Option<LoadOp> {
17270        use crcbl_hal::null::Command;
17271
17272        recorder.commands()[from..].iter().find_map(|command| {
17273            let Command::BeginRenderPass {
17274                label,
17275                depth_stencil_attachment,
17276                ..
17277            } = command
17278            else {
17279                return None;
17280            };
17281            if label.as_deref() != Some("shadow") {
17282                return None;
17283            }
17284            depth_stencil_attachment
17285                .as_ref()
17286                .map(|attachment| attachment.depth_load)
17287        })
17288    }
17289
17290    /// Direct draws recorded inside the shadow pass, over the commands from
17291    /// `from` on — which is one per tile the pass reset itself, the atlas's
17292    /// geometry being drawn indirectly.
17293    fn tile_clears_in_the_shadow_pass(recorder: &Recorder, from: usize) -> usize {
17294        use crcbl_hal::null::Command;
17295
17296        let mut inside = false;
17297        let mut clears = 0;
17298        for command in &recorder.commands()[from..] {
17299            if let Some((_, label)) = command.opens_pass() {
17300                inside = label == Some("shadow");
17301                continue;
17302            }
17303            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
17304                inside = false;
17305                continue;
17306            }
17307            if inside && matches!(command, Command::Draw { .. }) {
17308                clears += 1;
17309            }
17310        }
17311        clears
17312    }
17313
17314    /// **The far cascade is redrawn every second frame and the near one every
17315    /// frame**, on a scene where the eye moves and so every map is out of date.
17316    ///
17317    /// Topic 45's cadence rung, and the observable it otherwise
17318    /// has none for: a held map draws a shadow one frame behind its caster,
17319    /// which is a plausible picture and one a golden accepts.
17320    ///
17321    /// The eye moves by a fraction of a cascade's own reach, so no frame is a
17322    /// reset — that is asserted rather than assumed, because a reset would make
17323    /// every frame redraw everything and this test would pass by having
17324    /// switched the cadence off.
17325    #[test]
17326    fn the_far_cascade_is_held_on_the_frames_between_its_turns() {
17327        let _blurs = ssao_blur_switch();
17328        let (recorder, device, queue) = open();
17329        let device = device.as_ref();
17330        let (mut renderer, _) = shadow_cache_scene(device, queue);
17331        let sun = DirectionalLight::default();
17332        renderer.set_shadow_cadence(Some(HOLD_TWO));
17333
17334        const FRAMES: usize = 8;
17335        let mut near = 0;
17336        let mut far = 0;
17337        for step in 0..FRAMES {
17338            #[expect(
17339                clippy::cast_precision_loss,
17340                reason = "a handful of frames, and the step is what is wanted"
17341            )]
17342            let camera = Camera {
17343                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17344                ..Camera::default()
17345            };
17346            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17347            assert_eq!(
17348                renderer.shadow_cadence_reset(),
17349                step == 0,
17350                "frame {step}: only the first frame has an atlas to lay out, and a reset \
17351                 after it would redraw everything and leave nothing for the cadence to hold"
17352            );
17353            near += usize::from(renderer.shadow_cascade_redrawn(0));
17354            far += usize::from(renderer.shadow_cascade_redrawn(1));
17355            drawn.release(device);
17356        }
17357        assert_eq!(
17358            near, FRAMES,
17359            "the near cascade is fitted to the eye and is on the top rung: every frame"
17360        );
17361        assert_eq!(
17362            far,
17363            FRAMES / 2,
17364            "the far cascade is one rung down, so every second frame"
17365        );
17366
17367        renderer.destroy(device);
17368        recorder.assert_valid();
17369    }
17370
17371    /// **A frame that keeps a tile loads the attachment and resets the tiles it
17372    /// redraws itself**, and a frame that keeps none clears it — which is what
17373    /// shipped.
17374    ///
17375    /// The half of the cadence a redraw count cannot see: holding a tile is only
17376    /// worth anything if the tile survives, and the one clear this seam has
17377    /// covers the whole image. A frame that loaded and reset nothing would draw
17378    /// into tiles still holding the last frame's depths, and under reversed-Z a
17379    /// caster that moved away would go on occluding.
17380    #[test]
17381    fn a_frame_that_keeps_a_tile_loads_the_attachment_and_resets_the_rest() {
17382        let _blurs = ssao_blur_switch();
17383        let (recorder, device, queue) = open();
17384        let device = device.as_ref();
17385        let (mut renderer, _) = shadow_cache_scene(device, queue);
17386        let sun = DirectionalLight::default();
17387
17388        // The first frame lays the atlas out, so it clears and redraws
17389        // everything whatever the console says.
17390        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17391        first.release(device);
17392        assert_eq!(
17393            shadow_pass_depth_load(&recorder, 0),
17394            Some(LoadOp::Clear),
17395            "the frame that lays the atlas out has nothing to keep"
17396        );
17397        assert_eq!(
17398            tile_clears_in_the_shadow_pass(&recorder, 0),
17399            0,
17400            "and so resets no tile of its own"
17401        );
17402
17403        renderer.set_shadow_cadence(Some(HOLD_TWO));
17404        let mut seen = recorder.commands().len();
17405        let mut loaded = 0;
17406        for step in 1..4 {
17407            #[expect(
17408                clippy::cast_precision_loss,
17409                reason = "a handful of frames, and the step is what is wanted"
17410            )]
17411            let camera = Camera {
17412                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17413                ..Camera::default()
17414            };
17415            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17416            let load = shadow_pass_depth_load(&recorder, seen).expect("a shadow pass");
17417            let clears = tile_clears_in_the_shadow_pass(&recorder, seen);
17418            let faces = renderer.shadow_faces_redrawn() as usize;
17419            if load == LoadOp::Load {
17420                loaded += 1;
17421                assert_eq!(
17422                    clears, faces,
17423                    "frame {step} loaded the attachment and reset {clears} of the {faces} \
17424                     tiles it redrew"
17425                );
17426                assert!(
17427                    faces < shadow::TILES,
17428                    "frame {step} loaded an attachment while redrawing every tile"
17429                );
17430            } else {
17431                assert_eq!(
17432                    clears, 0,
17433                    "frame {step} cleared the attachment and reset {clears} tiles again"
17434                );
17435            }
17436            seen = recorder.commands().len();
17437            drawn.release(device);
17438        }
17439        assert!(
17440            loaded > 0,
17441            "no frame kept a tile, so nothing here is about the load path"
17442        );
17443
17444        renderer.destroy(device);
17445        recorder.assert_valid();
17446    }
17447
17448    /// A point light costs the budget every face it draws, not one.
17449    ///
17450    /// **The half of the budget its name is about.** `shadow_faces_redrawn` is
17451    /// a sum over the groups a frame redrew of the maps each of them owns, and
17452    /// a point light owns [`shadow::POINT_FACES`] of them. Every other check
17453    /// here is built on the sun and a spot, which own one map each — so a face
17454    /// count that answered `1` for every group would satisfy all of them, and
17455    /// did: collapsing it passed the whole of `crcbl-render` and the mesh e2e
17456    /// suite. This is what binds on the difference.
17457    #[test]
17458    fn a_point_light_costs_the_budget_every_face_it_draws() {
17459        let _blurs = ssao_blur_switch();
17460        let (_recorder, device, queue) = open();
17461        let device = device.as_ref();
17462        let mut renderer =
17463            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17464        let _cube = place_cube(&mut renderer, Mat4::IDENTITY);
17465        renderer.set_lights(&[shadowable_point(-1.0)]);
17466        let sun = DirectionalLight::default();
17467
17468        // Every group is forced on the first frame — the image has held none of
17469        // them — so this counts what a full redraw actually costs.
17470        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
17471        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17472        first.release(device);
17473        let point_faces = u32::try_from(shadow::POINT_FACES).expect("a handful of faces");
17474        assert!(
17475            renderer.shadow_lights().base_of(0).is_some(),
17476            "the point must hold a run of tiles, or there is no multi-face group to count"
17477        );
17478        assert!(
17479            renderer.shadow_faces_redrawn() >= point_faces,
17480            "a frame that redrew a point light's whole cube reported {} faces, fewer than the \
17481             {point_faces} it owns — so the budget is counting groups rather than the maps they \
17482             draw, and a cube would slip past a budget of one",
17483            renderer.shadow_faces_redrawn()
17484        );
17485    }
17486
17487    /// **A frame never redraws more tiles than the budget allows**, and every
17488    /// map still gets its turn.
17489    ///
17490    /// The starvation half is what makes this more than an inequality: a
17491    /// schedule that spent the budget on the same maps every frame would satisfy
17492    /// the bound and never draw the rest at all.
17493    #[test]
17494    fn the_face_budget_bounds_a_frame_and_starves_no_map() {
17495        let _blurs = ssao_blur_switch();
17496        let (recorder, device, queue) = open();
17497        let device = device.as_ref();
17498        let (mut renderer, _) = shadow_cache_scene(device, queue);
17499        let sun = DirectionalLight::default();
17500
17501        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17502        first.release(device);
17503        assert!(
17504            renderer.shadow_lights().base_of(0).is_some(),
17505            "the spot must hold a run, or the budget has only the cascades to bind on"
17506        );
17507
17508        // One tile a frame: the two cascades and the spot's map cannot all fit,
17509        // so something is held on every frame of the run below.
17510        const BUDGET: u32 = 1;
17511        renderer.set_shadow_cadence(Some(shadow::Cadence {
17512            hold: 1,
17513            faces: BUDGET as usize,
17514        }));
17515        const FRAMES: usize = 12;
17516        let mut drew = [0usize; 3];
17517        for step in 1..=FRAMES {
17518            #[expect(
17519                clippy::cast_precision_loss,
17520                reason = "a handful of frames, and the step is what is wanted"
17521            )]
17522            let camera = Camera {
17523                eye: Camera::default().eye + Vec3::X * 0.02 * step as f32,
17524                ..Camera::default()
17525            };
17526            // The spot drifts too: its map is not fitted to the camera, so a
17527            // moving eye alone leaves it up to date and asking for nothing.
17528            #[expect(
17529                clippy::cast_precision_loss,
17530                reason = "a handful of frames, and the step is what is wanted"
17531            )]
17532            renderer.set_lights(&[shadowable_spot(-1.0 + 0.01 * step as f32)]);
17533            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17534            assert!(
17535                renderer.shadow_faces_redrawn() <= BUDGET,
17536                "frame {step} redrew {} tiles against a budget of {BUDGET}",
17537                renderer.shadow_faces_redrawn()
17538            );
17539            drew[0] += usize::from(renderer.shadow_cascade_redrawn(0));
17540            drew[1] += usize::from(renderer.shadow_cascade_redrawn(1));
17541            drew[2] += usize::from(renderer.shadow_slot_redrawn(0));
17542            drawn.release(device);
17543        }
17544        for (map, count) in drew.iter().enumerate() {
17545            assert!(
17546                *count > 0,
17547                "map {map} was never redrawn in {FRAMES} frames under a budget of \
17548                 {BUDGET}: {drew:?}"
17549            );
17550        }
17551
17552        renderer.destroy(device);
17553        recorder.assert_valid();
17554    }
17555
17556    /// **A light that jumps further than its own radius resets the cadence**,
17557    /// and one that drifts inside it does not.
17558    ///
17559    /// Topic 45's "a moving light or camera cut resets it",
17560    /// made precise: a map whose centre has moved past the map's own reach is
17561    /// not a frame out of date, it is about somewhere else — so it is redrawn on
17562    /// the frame that notices rather than when its turn comes round. Both arms,
17563    /// because a reset that fired on every move would be the cadence switched
17564    /// off.
17565    #[test]
17566    fn a_light_that_jumps_past_its_own_radius_resets_the_cadence() {
17567        let _blurs = ssao_blur_switch();
17568        let (recorder, device, queue) = open();
17569        let device = device.as_ref();
17570        let (mut renderer, _) = shadow_cache_scene(device, queue);
17571        let sun = DirectionalLight::default();
17572        let camera = Camera::default();
17573        // The coarsest hold there is, so a redraw of the spot's map on the
17574        // frames below is the reset and not its turn.
17575        renderer.set_shadow_cadence(Some(shadow::Cadence {
17576            hold: 8,
17577            faces: shadow::TILES,
17578        }));
17579
17580        let mut settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17581        settle.release(device);
17582        for _ in 0..2 {
17583            settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17584            settle.release(device);
17585        }
17586        assert!(
17587            !renderer.shadow_cadence_reset(),
17588            "the scene has settled, so nothing is about somewhere else"
17589        );
17590
17591        // A drift well inside the light's own radius: out of date, not moved.
17592        renderer.set_lights(&[shadowable_spot(-1.0 + 0.5)]);
17593        let drifted = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17594        drifted.release(device);
17595        assert!(
17596            !renderer.shadow_cadence_reset(),
17597            "a light that moved a sixteenth of its radius is a map a frame out of date"
17598        );
17599
17600        // And a jump past it. `shadowable_spot`'s radius is what the reach is
17601        // taken from, so this is a light standing where its own map says
17602        // nothing.
17603        renderer.set_lights(&[shadowable_spot(-1.0 + 40.0)]);
17604        let jumped = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17605        jumped.release(device);
17606        assert!(
17607            renderer.shadow_cadence_reset(),
17608            "a light that jumped five times its own radius must not hold its map"
17609        );
17610        assert!(
17611            renderer.shadow_slot_redrawn(0),
17612            "and the reset is only a reset if the map is actually redrawn"
17613        );
17614
17615        renderer.destroy(device);
17616        recorder.assert_valid();
17617    }
17618
17619    /// **A console knob about *sampling* the atlas does not redraw it.**
17620    ///
17621    /// `r_shadow_filter` and `r_shadow_split` decide how the colour pass reads
17622    /// a map, and `r_shadow_bias` and `r_shadow_normal_offset` how far from a
17623    /// receiver it reads — and not one byte of what the depth pass writes into
17624    /// it is any of theirs. Yet the
17625    /// shadow views' blocks are the frame's block spread, and the cache record
17626    /// is those blocks' bytes — so until the views zeroed the row, a person
17627    /// typing `r_shadow_filter box` redrew every map in the atlas for nothing,
17628    /// and in this crate's own test process the filter tests moving that cell
17629    /// redrew the atlas under `each_thing_the_atlas_is_drawn_from_redraws_it`
17630    /// once in every five or six workspace runs on 2026-09-04. Holding the lock
17631    /// here is what makes the move below the only one in flight.
17632    #[test]
17633    fn a_moved_shadow_filter_leaves_a_still_atlas_alone() {
17634        let switch = shadow_filter_switch();
17635        let (recorder, device, queue) = open();
17636        let device = device.as_ref();
17637        let (mut renderer, _) = shadow_cache_scene(device, queue);
17638        let camera = Camera::default();
17639        let sun = DirectionalLight::default();
17640        let mut seen = 0usize;
17641        assert!(
17642            drew_the_atlas(
17643                &recorder,
17644                &mut seen,
17645                device,
17646                &mut renderer,
17647                queue,
17648                &camera,
17649                &sun
17650            ),
17651            "the first frame of all draws the atlas"
17652        );
17653        assert!(
17654            !drew_the_atlas(
17655                &recorder,
17656                &mut seen,
17657                device,
17658                &mut renderer,
17659                queue,
17660                &camera,
17661                &sun
17662            ),
17663            "a still second frame has to hold it, or the move below proves nothing"
17664        );
17665
17666        switch.filter(shadow::Filter::Box);
17667        switch.seam(0.5);
17668        assert!(
17669            !drew_the_atlas(
17670                &recorder,
17671                &mut seen,
17672                device,
17673                &mut renderer,
17674                queue,
17675                &camera,
17676                &sun
17677            ),
17678            "`r_shadow_filter` and `r_shadow_split` moved and the atlas was drawn again: a \
17679             sampling knob reached the record of what the maps were drawn from"
17680        );
17681
17682        // The bias pair sits in a different row of the same block, and the
17683        // second row it reaches is `Cascades::params`, which is rebuilt every
17684        // frame — so this is the arm that says the *whole* row is kept out of
17685        // the record rather than the one lane the filter is in.
17686        switch.bias(8.0);
17687        switch.offset(8.0);
17688        assert!(
17689            !drew_the_atlas(
17690                &recorder,
17691                &mut seen,
17692                device,
17693                &mut renderer,
17694                queue,
17695                &camera,
17696                &sun
17697            ),
17698            "`r_shadow_bias` and `r_shadow_normal_offset` moved and the atlas was drawn again: \
17699             the bias row reached the record of what the maps were drawn from"
17700        );
17701
17702        renderer.destroy(device);
17703        recorder.assert_valid();
17704    }
17705
17706    /// **Every input the atlas is drawn from redraws it**, one at a time.
17707    ///
17708    /// The half that stops "cached everything, for ever" from passing every
17709    /// assertion above. Each arm moves exactly one thing and asserts the next
17710    /// frame draws again — and then holds still and asserts it stops, so an arm
17711    /// cannot pass by having broken the cache outright.
17712    ///
17713    /// The camera is in here because it is not obvious: a shadow map is drawn
17714    /// from a light, not from the eye. But a cascade is fitted to the camera's
17715    /// own frustum, and every shadow cull selects a DAG's detail at the camera's
17716    /// pixels — `SHADOW_LOD_BIAS` — so a moved eye is a different cascade, and a
17717    /// different light map wherever a DAG is in the light's cull.
17718    /// `shadow_reach`'s tests are the other half: what a moved eye or a moved
17719    /// caster must *not* redraw.
17720    ///
17721    /// `settles` is how many still frames it takes to go quiet again, and it is
17722    /// two for exactly one arm: `InstancePool`'s carry-forward puts a moved
17723    /// instance's `previous_transform` back at rest on the frame *after* the
17724    /// move, and that is a write, which is a change this record cannot tell
17725    /// from any other. See `InstancePool::take_written`, which says so.
17726    #[test]
17727    fn each_thing_the_atlas_is_drawn_from_redraws_it() {
17728        let camera = Camera::default();
17729        let sun = DirectionalLight::default();
17730        let moved_camera = Camera {
17731            eye: camera.eye + Vec3::X * 4.0,
17732            ..camera
17733        };
17734        type Change = fn(&mut ForwardRenderer, InstanceHandle);
17735        let arms: [(&str, Change, &Camera, &DirectionalLight, usize); 4] = [
17736            (
17737                "a caster moved",
17738                |renderer, cube| {
17739                    renderer.set_instance(
17740                        cube,
17741                        &InstanceDesc {
17742                            mesh: DEMO_CUBE,
17743                            material: DEMO_UNTINTED,
17744                            transform: Mat4::from_translation(Vec3::X),
17745                        },
17746                    );
17747                },
17748                &camera,
17749                &sun,
17750                2,
17751            ),
17752            (
17753                "a caster removed",
17754                |renderer, cube| renderer.remove_instance(cube),
17755                &camera,
17756                &sun,
17757                1,
17758            ),
17759            (
17760                "the light moved",
17761                |renderer, _| renderer.set_lights(&[shadowable_spot(1.5)]),
17762                &camera,
17763                &sun,
17764                1,
17765            ),
17766            ("the camera moved", |_, _| {}, &moved_camera, &sun, 1),
17767        ];
17768
17769        for (what, change, camera, sun, settles) in arms {
17770            let (recorder, device, queue) = open();
17771            let device = device.as_ref();
17772            let (mut renderer, cube) = shadow_cache_scene(device, queue);
17773            let mut seen = 0usize;
17774            // Two frames, so the atlas is drawn and then held: the arm's own
17775            // assertion is about a frame that would otherwise have cached.
17776            for round in 0..2 {
17777                let drew = drew_the_atlas(
17778                    &recorder,
17779                    &mut seen,
17780                    device,
17781                    &mut renderer,
17782                    queue,
17783                    &Camera::default(),
17784                    &DirectionalLight::default(),
17785                );
17786                assert_eq!(
17787                    drew,
17788                    round == 0,
17789                    "{what}: the still frames before the change did not settle"
17790                );
17791            }
17792
17793            change(&mut renderer, cube);
17794            assert!(
17795                drew_the_atlas(
17796                    &recorder,
17797                    &mut seen,
17798                    device,
17799                    &mut renderer,
17800                    queue,
17801                    camera,
17802                    sun
17803                ),
17804                "{what} and the atlas was not drawn again"
17805            );
17806            // And it goes quiet again in exactly `settles` frames, so the arm
17807            // cannot pass by having broken the cache rather than by having
17808            // invalidated it — and a change that started redrawing for ever
17809            // fails here rather than going unnoticed.
17810            for round in 0..settles {
17811                assert_eq!(
17812                    drew_the_atlas(
17813                        &recorder,
17814                        &mut seen,
17815                        device,
17816                        &mut renderer,
17817                        queue,
17818                        camera,
17819                        sun
17820                    ),
17821                    round + 1 < settles,
17822                    "{what}: the still frames after the change did not settle in {settles}"
17823                );
17824            }
17825
17826            renderer.destroy(device);
17827            recorder.assert_valid();
17828        }
17829    }
17830
17831    /// **A frame with a skinned object in it always redraws the atlas**, and
17832    /// that is a limit written down rather than a gap.
17833    ///
17834    /// A skinned caster's vertices are produced by a compute dispatch into the
17835    /// pool, so there is nothing on the host to compare: the palette a caller
17836    /// hands over is not the geometry, and the geometry is never read back. The
17837    /// honest answer is to redraw, and the dishonest one is a map of a pose the
17838    /// character has left.
17839    #[test]
17840    fn a_frame_with_a_skinned_object_never_caches_the_atlas() {
17841        let (recorder, device, queue) = open();
17842        let device = device.as_ref();
17843        let mut fixture = SkinnedFixture::build(device, queue);
17844        fixture.renderer.set_lights(&[shadowable_spot(-1.0)]);
17845        let imported = swapchain_image_at(device, TEST_EXTENT);
17846        let mut pool = crate::TransientPool::new();
17847
17848        // The same palette and the same plan every lap, so nothing a host-side
17849        // comparison could see has moved.
17850        for lap in 0..3 {
17851            fixture.begin(device);
17852            let mut graph = crate::RenderGraph::new(queue);
17853            let target = graph.import_image("target", imported);
17854            fixture.renderer.add_skinned_passes(
17855                &mut graph,
17856                &pool,
17857                target,
17858                TEST_EXTENT,
17859                &fixture.skinning,
17860            );
17861            let compiled = graph.compile(&pool).expect("a legal frame");
17862            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17863                label: Some("skinned lap"),
17864                queue,
17865            });
17866            compiled
17867                .execute(device, &mut pool, encoder.as_mut(), None)
17868                .expect("the graph executed");
17869            device.destroy_command_buffer(encoder.finish().expect("recording succeeded"));
17870            assert!(
17871                !fixture.renderer.shadow_atlas_cached(),
17872                "lap {lap} held a shadow map of a pose no host-side comparison can vouch for"
17873            );
17874        }
17875
17876        fixture.destroy(device);
17877        pool.destroy(device);
17878        device.destroy_image_view(imported.view);
17879        device.destroy_image(imported.image);
17880        recorder.assert_valid();
17881    }
17882
17883    /// **Switching the shadows off clears the atlas once, and then holds the
17884    /// clear**, which is the same cache answering a frame that draws nothing.
17885    ///
17886    /// The switched-off frame is not itself a cached frame: the pass has to run
17887    /// to write the reversed-Z clear that makes every comparison come back lit,
17888    /// and the image holds the last drawn maps until it does. What *is* cached
17889    /// is every frame after it, and the record for a switched-off frame is
17890    /// deliberately blind to the camera and the casters, because nothing about
17891    /// them reaches an atlas nothing draws into.
17892    #[test]
17893    fn switching_the_shadows_off_clears_the_atlas_once_and_then_holds_it() {
17894        let (recorder, device, queue) = open();
17895        let device = device.as_ref();
17896        let (mut renderer, cube) = shadow_cache_scene(device, queue);
17897        let camera = Camera::default();
17898        let sun = DirectionalLight::default();
17899        let mut seen = 0usize;
17900
17901        assert!(
17902            drew_the_atlas(
17903                &recorder,
17904                &mut seen,
17905                device,
17906                &mut renderer,
17907                queue,
17908                &camera,
17909                &sun
17910            ),
17911            "the first frame draws the maps"
17912        );
17913        renderer.set_effect_request(EffectRequest {
17914            programmatic: EffectOverride::none().force(RenderEffects::SHADOWS, Some(false)),
17915            ..EffectRequest::default()
17916        });
17917        assert!(
17918            drew_the_atlas(
17919                &recorder,
17920                &mut seen,
17921                device,
17922                &mut renderer,
17923                queue,
17924                &camera,
17925                &sun
17926            ),
17927            "the frame that switched the shadows off has to run the pass that clears the maps \
17928             out of the image"
17929        );
17930        assert!(
17931            !drew_the_atlas(
17932                &recorder,
17933                &mut seen,
17934                device,
17935                &mut renderer,
17936                queue,
17937                &camera,
17938                &sun
17939            ),
17940            "a second switched-off frame cleared an atlas that was already clear"
17941        );
17942        // And nothing about the scene reaches a frame that draws no map: the
17943        // caster moves and the atlas is still the clear it was.
17944        renderer.set_instance(
17945            cube,
17946            &InstanceDesc {
17947                mesh: DEMO_CUBE,
17948                material: DEMO_UNTINTED,
17949                transform: Mat4::from_translation(Vec3::X),
17950            },
17951        );
17952        assert!(
17953            !drew_the_atlas(
17954                &recorder,
17955                &mut seen,
17956                device,
17957                &mut renderer,
17958                queue,
17959                &camera,
17960                &sun
17961            ),
17962            "a caster moved with the shadows off, and the frame cleared the atlas over again"
17963        );
17964
17965        renderer.set_effect_request(EffectRequest::default());
17966        assert!(
17967            drew_the_atlas(
17968                &recorder,
17969                &mut seen,
17970                device,
17971                &mut renderer,
17972                queue,
17973                &camera,
17974                &sun
17975            ),
17976            "switching the shadows back on has to draw the maps the clear replaced"
17977        );
17978
17979        renderer.destroy(device);
17980        recorder.assert_valid();
17981    }
17982
17983    /// **A frame the graph refuses leaves the shadow atlas where it was.**
17984    ///
17985    /// [`RenderGraph::compile`] returns a [`Result`], so a frame can be
17986    /// described in full and then thrown away, and
17987    /// [`CompiledGraph::execute`](crate::CompiledGraph::execute) — the only
17988    /// thing that writes the pool's ledger — never runs. That is the case a
17989    /// renderer-held `ResourceState`, stepped forward while the passes were
17990    /// declared, gets wrong: it would already say [`ResourceState::ShaderRead`]
17991    /// for an image no barrier has touched, and [`InitialClaim::Tracked`] cannot
17992    /// object, because with nothing recorded there is nothing to contradict. The
17993    /// guard would be silent on precisely the drift it exists to find, which is
17994    /// why [`imported_state`] reads the ledger instead of a second copy of it.
17995    ///
17996    /// The observable is the first barrier the *next* frame records on the
17997    /// atlas. `Undefined -> DepthStencilWrite` is the transition an image
17998    /// nothing has written needs; `ShaderRead -> DepthStencilWrite` names an old
17999    /// layout the image was never in, which is a layout mismatch on every
18000    /// backend and a discarded image on some.
18001    #[test]
18002    fn a_refused_frame_leaves_the_shadow_atlas_where_it_was() {
18003        use crcbl_hal::null::Command;
18004
18005        let (recorder, device, queue) = open();
18006        let device = device.as_ref();
18007        let mut renderer =
18008            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18009        let atlas = renderer.shadow_atlas();
18010        let placeholder = renderer.shadow_placeholder;
18011        let mut pool = crate::TransientPool::new();
18012        let imported = swapchain_image(device);
18013
18014        // The refused frame: every pass a real frame declares, and beside them
18015        // one transient nothing reads or writes. `compile` answers
18016        // `UnusedTransient` and the whole description — the shadow atlas's
18017        // import included — is dropped without a command being recorded.
18018        renderer
18019            .begin_frame(
18020                device,
18021                &Camera::default(),
18022                &DirectionalLight::default(),
18023                (64, 48),
18024            )
18025            .expect("write");
18026        {
18027            let mut graph = crate::RenderGraph::new(queue);
18028            let target = graph.import_image("target", imported);
18029            renderer.add_passes(&mut graph, &pool, target, (64, 48));
18030            graph.create_image("orphan", crate::targets::scene_color((64, 48)));
18031            let refused = graph
18032                .compile(&pool)
18033                .expect_err("a transient no pass declares");
18034            assert!(
18035                matches!(refused, crate::GraphError::UnusedTransient { .. }),
18036                "the frame has to be refused for the reason this test is about — a graph that \
18037                 compiled would go on to execute and the ledger would be written after all: \
18038                 {refused:?}"
18039            );
18040        }
18041        assert_eq!(
18042            pool.imported_image_use(atlas),
18043            None,
18044            "nothing executed, so the ledger has nothing to say about the atlas — this is the \
18045             emptiness `InitialClaim::Tracked` cannot check against"
18046        );
18047
18048        // And the frame after it, which does run.
18049        renderer
18050            .begin_frame(
18051                device,
18052                &Camera::default(),
18053                &DirectionalLight::default(),
18054                (64, 48),
18055            )
18056            .expect("write");
18057        let mut graph = crate::RenderGraph::new(queue);
18058        let target = graph.import_image("target", imported);
18059        renderer.add_passes(&mut graph, &pool, target, (64, 48));
18060        let compiled = graph.compile(&pool).expect("a legal frame");
18061        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
18062            label: Some("frame after a refusal"),
18063            queue,
18064        });
18065        compiled
18066            .execute(device, &mut pool, encoder.as_mut(), None)
18067            .expect("the graph executed");
18068        let commands = encoder.finish().expect("recording succeeded");
18069
18070        // The first barrier each of the two images gets. Only the refused frame
18071        // ran before this one and it recorded nothing, so these are the frame's
18072        // opening transitions.
18073        let mut opened: Vec<(crcbl_hal::ImageHandle, ResourceState, ResourceState)> = Vec::new();
18074        for command in recorder.commands() {
18075            let Command::Barrier { images, .. } = command else {
18076                continue;
18077            };
18078            for barrier in images {
18079                if barrier.image != atlas && barrier.image != placeholder {
18080                    continue;
18081                }
18082                if opened.iter().any(|(image, _, _)| *image == barrier.image) {
18083                    continue;
18084                }
18085                opened.push((barrier.image, barrier.from, barrier.to));
18086            }
18087        }
18088        for (image, from, to) in &opened {
18089            assert_eq!(
18090                *from,
18091                ResourceState::Undefined,
18092                "a barrier declared {from:?} -> {to:?} on an image the refused frame never gave a \
18093                 layout to. The declaration is what makes the transition true, so one that has \
18094                 moved on without an executed frame behind it names a source scope and an old \
18095                 layout the image was never in — and the ledger is empty, so nothing refuses it \
18096                 either. Image {image:?}"
18097            );
18098        }
18099        // The loop above is silent on an empty list and on a short one, and a
18100        // wrong declaration shortens it: an image declared in the state it is
18101        // wanted in needs no transition, so it drops out of the stream
18102        // altogether rather than appearing with the wrong source.
18103        assert_eq!(
18104            opened.len(),
18105            2,
18106            "the atlas and its placeholder are both imported every frame and both are wanted in a \
18107             state they are not in, so both have to be barriered: {opened:?}"
18108        );
18109        assert!(
18110            opened
18111                .iter()
18112                .any(|(image, _, to)| *image == atlas && *to == ResourceState::DepthStencilWrite),
18113            "and the atlas's is the shadow pass taking it as a depth attachment: {opened:?}"
18114        );
18115
18116        renderer.destroy(device);
18117        device.destroy_command_buffer(commands);
18118        pool.destroy(device);
18119        device.destroy_image_view(imported.view);
18120        device.destroy_image(imported.image);
18121        recorder.assert_valid();
18122    }
18123
18124    /// **The import audit still refuses an engine site whose declaration is
18125    /// wrong**, now that the shadow atlas's is read out of the same ledger it is
18126    /// checked against.
18127    ///
18128    /// That pair is deliberately circular and this test is what keeps it from
18129    /// swallowing the guard whole: `shadow-atlas` and `shadow-placeholder` say
18130    /// what [`imported_state`] just read, so [`InitialClaim::Tracked`] can only
18131    /// ever find them agreeing — their safety comes from there being one answer
18132    /// rather than from the check. Every *other* import in the frame declares a
18133    /// constant, and `ssao-placeholder` is the one this drives a ledger entry
18134    /// away from: uploaded into [`ResourceState::ShaderRead`] at build and
18135    /// declared so on every frame, so a graph that leaves it somewhere else is a
18136    /// declaration the next `compile` has to refuse.
18137    #[test]
18138    fn the_guard_still_catches_an_engine_import_that_lies() {
18139        let (recorder, device, queue) = open();
18140        let device = device.as_ref();
18141        let mut renderer =
18142            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18143        let mut pool = crate::TransientPool::new();
18144        let imported = swapchain_image(device);
18145        let occlusion = renderer.ambient_occlusion_placeholder.image;
18146
18147        // A graph of this test's own, which moves the renderer's occlusion
18148        // placeholder somewhere `add_passes` does not expect. Same image handle,
18149        // so the entry it leaves in the ledger is the one the next `compile`
18150        // reads for `ssao-placeholder`.
18151        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
18152            label: Some("move the placeholder"),
18153            queue,
18154        });
18155        {
18156            let mut graph = crate::RenderGraph::new(queue);
18157            let moved = graph.import_image(
18158                "moved-placeholder",
18159                ImportedImage {
18160                    image: occlusion,
18161                    view: renderer.ambient_occlusion_placeholder.view,
18162                    format: Format::Rgba8Unorm,
18163                    extent: (1, 1),
18164                    initial: ResourceState::ShaderRead,
18165                    claim: InitialClaim::Tracked,
18166                    final_state: ResourceState::TransferSrc,
18167                },
18168            );
18169            graph
18170                .add_copy_pass("read the placeholder")
18171                .use_image(moved, ResourceState::TransferSrc)
18172                .execute(|_| {});
18173            graph
18174                .compile(&pool)
18175                .expect("a legal frame")
18176                .execute(device, &mut pool, encoder.as_mut(), None)
18177                .expect("the graph executed");
18178        }
18179        let commands = encoder.finish().expect("recording succeeded");
18180        assert_eq!(
18181            pool.imported_image_use(occlusion),
18182            Some(ResourceState::TransferSrc),
18183            "the ledger has to have moved for the frame below to have anything to disagree with"
18184        );
18185
18186        renderer
18187            .begin_frame(
18188                device,
18189                &Camera::default(),
18190                &DirectionalLight::default(),
18191                (64, 48),
18192            )
18193            .expect("write");
18194        let mut graph = crate::RenderGraph::new(queue);
18195        let target = graph.import_image("target", imported);
18196        renderer.add_passes(&mut graph, &pool, target, (64, 48));
18197        let refused = graph
18198            .compile(&pool)
18199            .expect_err("`ssao-placeholder` declares a constant the ledger no longer agrees with");
18200        let crate::GraphError::ImportStateMismatch {
18201            resource,
18202            declared,
18203            left,
18204        } = &refused
18205        else {
18206            panic!("the audit has to name the import it refused, not merely fail: {refused:?}");
18207        };
18208        assert_eq!(resource, "ssao-placeholder");
18209        assert_eq!(*declared, ResourceState::ShaderRead);
18210        assert_eq!(*left, ResourceState::TransferSrc);
18211
18212        renderer.destroy(device);
18213        device.destroy_command_buffer(commands);
18214        pool.destroy(device);
18215        device.destroy_image_view(imported.view);
18216        device.destroy_image(imported.image);
18217        recorder.assert_valid();
18218    }
18219
18220    /// Compiles one frame and names the passes it turned out to be, in order.
18221    ///
18222    /// Compiled and not executed: what a pass costs is not the question here,
18223    /// only which of them the frame declared. Names rather than a count since
18224    /// the toggles landed — a count says a frame lost two passes and a list says
18225    /// *which* two, which is the difference between "the switch did something"
18226    /// and "the switch did the thing it is for".
18227    fn passes_in_a_frame(
18228        device: &dyn Device,
18229        queue: QueueHandle,
18230        renderer: &mut ForwardRenderer,
18231        imported: ImportedImage,
18232        pool: &crate::TransientPool,
18233        extent: (u32, u32),
18234    ) -> Vec<String> {
18235        renderer
18236            .begin_frame(
18237                device,
18238                &Camera::default(),
18239                &DirectionalLight::default(),
18240                extent,
18241            )
18242            .expect("write");
18243        let mut graph = crate::RenderGraph::new(queue);
18244        let target = graph.import_image("target", imported);
18245        renderer.add_passes(&mut graph, pool, target, extent);
18246        graph
18247            .compile(pool)
18248            .expect("a legal frame")
18249            .passes()
18250            .iter()
18251            .map(|pass| pass.label().to_string())
18252            .collect()
18253    }
18254
18255    /// A spot at `x` that [`shadow::Selection`] will give a tile: finite, a
18256    /// radius, a direction and a cone well inside the widest one allowed.
18257    /// A shadowed point light, which is [`shadow::POINT_FACES`] maps rather
18258    /// than one.
18259    ///
18260    /// The spot beside it is one tile and one face, so a scene built only from
18261    /// spots cannot tell a budget counting **faces** from one counting groups —
18262    /// which is what this exists to give a check something to bind on.
18263    fn shadowable_point(x: f32) -> Light {
18264        Light::Point(crate::light::PointLight {
18265            position: Vec3::new(x, 2.0, 0.0),
18266            radius: 8.0,
18267            color: Vec3::ONE,
18268            fill: false,
18269        })
18270    }
18271
18272    fn shadowable_spot(x: f32) -> Light {
18273        Light::Spot(crate::light::SpotLight {
18274            position: Vec3::new(x, 2.0, 0.0),
18275            radius: 8.0,
18276            color: Vec3::ONE,
18277            direction: -Vec3::Y,
18278            inner_angle: 0.3,
18279            outer_angle: 0.6,
18280            fill: false,
18281        })
18282    }
18283
18284    /// The page's anisotropy is the plan's default clamped to the device, and
18285    /// one on a device that was not granted the feature — whatever its limit
18286    /// says.
18287    ///
18288    /// The last arm is the one worth having: `gate_limits_on_features` narrows
18289    /// a declined feature's limit on `crcbl-vk`, but a backend that did not
18290    /// would report sixteen beside an absent feature, and a clamp that read the
18291    /// limit alone would ask for a sampler the device refuses.
18292    #[test]
18293    fn the_anisotropy_is_the_default_clamped_to_what_the_device_granted() {
18294        let caps = |features: Features, max_sampler_anisotropy: f32| DeviceCaps {
18295            features,
18296            limits: crcbl_hal::Limits {
18297                max_sampler_anisotropy,
18298                ..crcbl_hal::Limits::desktop()
18299            },
18300        };
18301        let granted = Features::SAMPLER_ANISOTROPY;
18302        assert!(
18303            (ForwardRenderer::anisotropy_for(&caps(granted, 16.0)) - DEFAULT_ANISOTROPY).abs()
18304                < f32::EPSILON,
18305            "a device above the default gets the default"
18306        );
18307        assert!(
18308            (ForwardRenderer::anisotropy_for(&caps(granted, 4.0)) - 4.0).abs() < f32::EPSILON,
18309            "a device below the default gets its own limit"
18310        );
18311        assert!(
18312            (ForwardRenderer::anisotropy_for(&caps(Features::empty(), 16.0)) - 1.0).abs()
18313                < f32::EPSILON,
18314            "a device that was not granted the feature gets one, whatever its limit says"
18315        );
18316    }
18317
18318    /// A new anisotropy is a new sampler, and every slot moves onto it at its
18319    /// own frame — the old one living until the last slot has left it.
18320    ///
18321    /// Counted on the null recorder rather than looked at: the sampler count
18322    /// rises by one at the call, holds through every slot's frame but the
18323    /// last, and falls back there, while the live group count never moves at
18324    /// all — every rebuilt group replaced one. A rebuild that leaked, one that
18325    /// destroyed a group a slot in flight still held, and one that never
18326    /// happened each move one of those counts; a second lap of the ring
18327    /// creating any group at all would be a rebuild that did not know it was
18328    /// done.
18329    #[test]
18330    fn a_new_anisotropy_moves_each_slot_at_its_own_frame_and_retires_the_old() {
18331        let (recorder, device, queue) =
18332            open_with(Features::GPU_DRIVEN.union(Features::SAMPLER_ANISOTROPY));
18333        let device = device.as_ref();
18334        let mut renderer =
18335            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18336        assert!(
18337            (renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON,
18338            "a renderer nobody has called the setter on samples at the default"
18339        );
18340        let samplers = recorder.live_objects(ObjectKind::Sampler);
18341        let groups = recorder.live_objects(ObjectKind::BindGroup);
18342        let groups_created = || {
18343            recorder
18344                .events()
18345                .iter()
18346                .filter(|event| {
18347                    matches!(
18348                        event,
18349                        Event::Created {
18350                            kind: ObjectKind::BindGroup,
18351                            ..
18352                        }
18353                    )
18354                })
18355                .count()
18356        };
18357
18358        renderer
18359            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18360            .expect("the device allows it");
18361        assert_eq!(
18362            recorder.live_objects(ObjectKind::Sampler),
18363            samplers,
18364            "the value in force creates nothing"
18365        );
18366
18367        renderer
18368            .set_anisotropy(device, 4.0)
18369            .expect("the device allows it");
18370        assert!((renderer.anisotropy() - 4.0).abs() < f32::EPSILON);
18371        assert_eq!(
18372            recorder.live_objects(ObjectKind::Sampler),
18373            samplers + 1,
18374            "the new sampler stands beside the one every slot still names"
18375        );
18376        assert_eq!(
18377            recorder.live_objects(ObjectKind::BindGroup),
18378            groups,
18379            "no group moves until its slot's frame"
18380        );
18381
18382        for round in 0..FRAMES_IN_FLIGHT {
18383            renderer
18384                .begin_frame(
18385                    device,
18386                    &Camera::default(),
18387                    &DirectionalLight::default(),
18388                    (64, 48),
18389                )
18390                .expect("write");
18391            let expected = if round + 1 < FRAMES_IN_FLIGHT {
18392                samplers + 1
18393            } else {
18394                samplers
18395            };
18396            assert_eq!(
18397                recorder.live_objects(ObjectKind::Sampler),
18398                expected,
18399                "round {round}: the replaced sampler lives until the last slot has left it"
18400            );
18401            assert_eq!(
18402                recorder.live_objects(ObjectKind::BindGroup),
18403                groups,
18404                "round {round}: every rebuilt group replaced one"
18405            );
18406        }
18407        let created = groups_created();
18408        for _ in 0..FRAMES_IN_FLIGHT {
18409            renderer
18410                .begin_frame(
18411                    device,
18412                    &Camera::default(),
18413                    &DirectionalLight::default(),
18414                    (64, 48),
18415                )
18416                .expect("write");
18417        }
18418        assert_eq!(
18419            groups_created(),
18420            created,
18421            "a slot already on the sampler in force rebuilds nothing"
18422        );
18423
18424        // The clamp: the device's ceiling above it, off below one, the default
18425        // for a value that is not a number.
18426        let ceiling = device.caps().limits.max_sampler_anisotropy;
18427        renderer
18428            .set_anisotropy(device, ceiling * 4.0)
18429            .expect("clamped to what the device allows");
18430        assert!((renderer.anisotropy() - ceiling).abs() < f32::EPSILON);
18431        renderer
18432            .set_anisotropy(device, 0.0)
18433            .expect("one is the value that turns it off");
18434        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18435        renderer
18436            .set_anisotropy(device, f32::NAN)
18437            .expect("the default is a sampler the device allows");
18438        assert!((renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON);
18439
18440        recorder.assert_valid();
18441        renderer.destroy(device);
18442        assert_eq!(
18443            recorder.live_objects(ObjectKind::Sampler),
18444            0,
18445            "the samplers no slot ever adopted went with the renderer"
18446        );
18447    }
18448
18449    /// A device without the feature samples isotropically whatever is asked:
18450    /// the ceiling is one, so the clamp lands on the value already in force and
18451    /// no sampler is created that `create_sampler` would refuse.
18452    #[test]
18453    fn a_device_without_the_feature_keeps_the_page_isotropic_whatever_is_asked() {
18454        let (recorder, device, queue) = open();
18455        let device = device.as_ref();
18456        assert!(
18457            !device
18458                .caps()
18459                .features
18460                .contains(Features::SAMPLER_ANISOTROPY),
18461            "the default request does not name the feature"
18462        );
18463        let mut renderer =
18464            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18465        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18466        let samplers = recorder.live_objects(ObjectKind::Sampler);
18467
18468        renderer
18469            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18470            .expect("asks for nothing the device lacks");
18471        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18472        assert_eq!(recorder.live_objects(ObjectKind::Sampler), samplers);
18473        renderer.destroy(device);
18474    }
18475
18476    /// The knob clamps to the range it documents, in both directions and on a
18477    /// value that is neither.
18478    ///
18479    /// **The `NaN` arm is the one worth having.** A slider that divided by a
18480    /// zero, or a settings file that carried a nonsense string, reaches this
18481    /// with a value that fails every comparison it is put through — so a naive
18482    /// `clamp` would keep it, `internal_extent` would multiply by it, and the
18483    /// `as u32` below would produce a zero extent and a device error a long way
18484    /// from here.
18485    #[test]
18486    fn the_render_scale_is_clamped_to_the_range_it_documents() {
18487        let (recorder, device, queue) = open();
18488        let device = device.as_ref();
18489        let mut renderer =
18490            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18491
18492        assert!(
18493            (renderer.render_scale() - 1.0).abs() < f32::EPSILON,
18494            "a renderer nobody has called the setter on draws at full scale"
18495        );
18496
18497        renderer.set_render_scale(0.5);
18498        assert!((renderer.render_scale() - 0.5).abs() < f32::EPSILON);
18499
18500        // Above one is supersampling, which this filter is the wrong one for.
18501        renderer.set_render_scale(2.0);
18502        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18503
18504        renderer.set_render_scale(0.01);
18505        assert!((renderer.render_scale() - MIN_RENDER_SCALE).abs() < f32::EPSILON);
18506
18507        renderer.set_render_scale(f32::NAN);
18508        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18509        renderer.set_render_scale(f32::INFINITY);
18510        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18511
18512        renderer.destroy(device);
18513        recorder.assert_valid();
18514    }
18515
18516    /// The internal extent is the target rounded, never zero, and is the target
18517    /// itself at full scale.
18518    ///
18519    /// **The floor is not decoration.** A transient image of zero extent is a
18520    /// device error rather than a small frame, and a 4×3 target at the minimum
18521    /// scale is exactly the arithmetic that would produce one.
18522    #[test]
18523    fn the_internal_extent_rounds_and_never_reaches_zero() {
18524        let (recorder, device, queue) = open();
18525        let device = device.as_ref();
18526        let mut renderer =
18527            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18528
18529        assert_eq!(
18530            renderer.internal_extent((1920, 1080)),
18531            (1920, 1080),
18532            "full scale is the absence of the feature, not a resize by one"
18533        );
18534
18535        renderer.set_render_scale(0.5);
18536        assert_eq!(renderer.internal_extent((1920, 1080)), (960, 540));
18537
18538        // Rounds rather than truncating: 1920 * 0.7 is 1344, and 1080 * 0.7 is
18539        // 756 — both exact — so a target that does *not* divide evenly is what
18540        // shows the rounding. 1281 * 0.7 = 896.7.
18541        renderer.set_render_scale(0.7);
18542        assert_eq!(renderer.internal_extent((1281, 1080)), (897, 756));
18543
18544        renderer.set_render_scale(MIN_RENDER_SCALE);
18545        assert_eq!(renderer.internal_extent((4, 3)), (1, 1));
18546        assert_eq!(
18547            renderer.internal_extent((0, 0)),
18548            (1, 1),
18549            "a minimised window is the caller's zero extent, and this may not \
18550             pass it through as one"
18551        );
18552
18553        renderer.destroy(device);
18554        recorder.assert_valid();
18555    }
18556
18557    /// **The upscale is a pass below full scale and is not there above it**, and
18558    /// the frame is otherwise the same list.
18559    ///
18560    /// This is the observable the knob is: everything else about it — the
18561    /// clamps, the rounding — is arithmetic that could be right while the frame
18562    /// went on being drawn at the caller's extent. What says the feature works
18563    /// is that the pass appears, that it appears **last**, and that switching it
18564    /// off leaves the frame that was there before it existed.
18565    #[test]
18566    fn the_upscale_is_the_last_pass_and_only_below_full_scale() {
18567        let _blurs = ssao_blur_switch();
18568        let (recorder, device, queue) = open();
18569        let device = device.as_ref();
18570        let mut renderer =
18571            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18572        let imported = swapchain_image_at(device, TEST_EXTENT);
18573        let pool = crate::TransientPool::new();
18574
18575        let full = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18576        assert!(
18577            !full.contains(&"upscale".to_string()),
18578            "a frame at full scale has no upscale in it: {full:?}"
18579        );
18580
18581        renderer.set_render_scale(0.5);
18582        let scaled = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18583        assert_eq!(
18584            scaled.iter().filter(|label| *label == "upscale").count(),
18585            1,
18586            "a scaled frame records exactly one upscale: {scaled:?}"
18587        );
18588        // Last of the passes that draw. The statistics copy is genuinely after
18589        // it and says so — see the comment on `add_copy_pass`'s placement.
18590        let upscale = scaled
18591            .iter()
18592            .position(|label| label == "upscale")
18593            .expect("the assertion above");
18594        let tonemap = scaled
18595            .iter()
18596            .position(|label| label == "tonemap")
18597            .expect("every frame tonemaps");
18598        assert!(
18599            upscale > tonemap,
18600            "the upscale carries what the post chain ended with: {scaled:?}"
18601        );
18602
18603        // **The pyramid gets shorter, and that is the evidence the rest of the
18604        // frame really is smaller.** Everything above this is about the last
18605        // pass; a knob that added an upscale while going on rendering at the
18606        // caller's extent would pass every one of those assertions and save
18607        // nothing. `crate::hiz`'s chain is as long as the extent allows, so the
18608        // level count is a number read out of the frame that can only be the
18609        // internal extent's.
18610        let levels = |passes: &[String]| {
18611            passes
18612                .iter()
18613                .filter(|label| label.starts_with("hiz-"))
18614                .count()
18615        };
18616        let internal = renderer.internal_extent(TEST_EXTENT);
18617        assert_eq!(levels(&full), crate::hiz::levels_for(TEST_EXTENT) as usize);
18618        assert_eq!(levels(&scaled), crate::hiz::levels_for(internal) as usize);
18619        assert!(
18620            levels(&scaled) < levels(&full),
18621            "at this extent the halved frame has to lose a level, or this \
18622             assertion is not looking at anything: {scaled:?}"
18623        );
18624
18625        // And nothing else moved: an upscale is a pass added to the frame, not a
18626        // frame rebuilt around one. The pyramid is the one part that is a
18627        // function of the extent, so it is compared by the count above and
18628        // dropped from the list here.
18629        let without_hiz = |passes: &[String]| -> Vec<String> {
18630            passes
18631                .iter()
18632                .filter(|label| !label.starts_with("hiz-") && *label != "upscale")
18633                .cloned()
18634                .collect()
18635        };
18636        assert_eq!(
18637            without_hiz(&scaled),
18638            without_hiz(&full),
18639            "the scaled frame is the full-scale frame, one pass longer and one \
18640             pyramid shorter"
18641        );
18642
18643        renderer.set_render_scale(1.0);
18644        let back = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18645        assert_eq!(
18646            back, full,
18647            "the knob goes back, which is what a settings slider does"
18648        );
18649
18650        renderer.destroy(device);
18651        device.destroy_image_view(imported.view);
18652        device.destroy_image(imported.image);
18653        recorder.assert_valid();
18654    }
18655
18656    /// **A skinned-frame overlay receives the display and depth images at the
18657    /// internal extent, before either resolve reconstructs the target.**
18658    ///
18659    /// The callback's own pass attaches the display and depth it received. That
18660    /// makes matching dimensions a graph invariant rather than a comparison of
18661    /// numbers the callback could have been handed without ever using the
18662    /// images; changing either id to a target-sized image makes compilation
18663    /// refuse the mismatched attachments.
18664    #[test]
18665    fn an_overlay_uses_the_internal_display_and_depth_before_the_resolves() {
18666        let (recorder, device, queue) = open();
18667        let device = device.as_ref();
18668        let mut fixture = SkinnedFixture::build(device, queue);
18669        fixture.renderer.set_render_scale(0.5);
18670        fixture.renderer.set_effect_request(EffectRequest {
18671            antialiasing: Some(Antialiasing::Fxaa),
18672            ..EffectRequest::default()
18673        });
18674        fixture.begin(device);
18675        let internal_extent = fixture.renderer.internal_extent(TEST_EXTENT);
18676
18677        let imported = swapchain_image_at(device, TEST_EXTENT);
18678        let mut pool = crate::TransientPool::new();
18679        {
18680            let mut graph = crate::RenderGraph::new(queue);
18681            let target = graph.import_image("target", imported);
18682            let mut received = None;
18683            fixture.renderer.add_skinned_passes_with_overlay(
18684                &mut graph,
18685                &pool,
18686                target,
18687                TEST_EXTENT,
18688                &fixture.skinning,
18689                |graph, targets| {
18690                    received = Some(targets);
18691                    graph
18692                        .add_render_pass("overlay-probe")
18693                        .color(
18694                            targets.display,
18695                            LoadOp::Load,
18696                            StoreOp::Store,
18697                            crcbl_hal::ClearValue::default(),
18698                        )
18699                        .depth_read(targets.depth)
18700                        .execute(|_| {});
18701                },
18702            );
18703            let received = received.expect("the overlay callback runs while the frame is built");
18704            assert_eq!(
18705                received.internal_extent, internal_extent,
18706                "the overlay receives the extent its display and depth attachments have"
18707            );
18708
18709            let compiled = graph.compile(&pool).expect("the shared attachments match");
18710            let labels: Vec<&str> = compiled.passes().iter().map(|pass| pass.label()).collect();
18711            let overlay = labels
18712                .iter()
18713                .position(|label| *label == "overlay-probe")
18714                .expect("the callback's pass is part of the frame");
18715            let fxaa = labels
18716                .iter()
18717                .position(|label| *label == "fxaa")
18718                .expect("the requested resolve is part of the frame");
18719            let upscale = labels
18720                .iter()
18721                .position(|label| *label == "upscale")
18722                .expect("the half-scale frame reconstructs its target");
18723            assert!(
18724                overlay < fxaa && overlay < upscale,
18725                "the overlay must write display before its resolve and upscale: {labels:?}"
18726            );
18727        }
18728
18729        fixture.destroy(device);
18730        pool.destroy(device);
18731        device.destroy_image_view(imported.view);
18732        device.destroy_image(imported.image);
18733        recorder.assert_valid();
18734    }
18735
18736    /// **[`ForwardRenderer::MAX_PASSES`] bounds the frame, and lands on it.**
18737    ///
18738    /// It is what a caller sizes [`PassTimers`](crate::PassTimers) with, so both
18739    /// halves matter: a bound under the widest frame times part of it and drops
18740    /// the rest, and a bound well over it buys query sets nothing ever writes.
18741    /// A shadowable spot per light slot fills every one of them, which is the
18742    /// most culls a frame can run and so the widest frame there is — it must land
18743    /// exactly on the constant, and the frame with no shadowed light at all must
18744    /// be short of it by exactly the culls those slots would have added.
18745    ///
18746    /// The ground grid is switched on for **both** frames, because the widest
18747    /// frame is the one that has it: it is off by default and not a
18748    /// [`RenderEffects`] bit, so nothing else here would put its pass in. The
18749    /// debug draw layer is on for both frames for the same reason, and it needs
18750    /// a segment appended before each rather than one switch, because
18751    /// [`begin_frame`](ForwardRenderer::begin_frame) clears its buffer.
18752    ///
18753    /// **And the frames are drawn at [`WIDEST_EXTENT`] rather than at
18754    /// [`TEST_EXTENT`], with every effect forced on and the render scale off
18755    /// full.** The bloom chain's length is a function of the extent the frame is
18756    /// drawn at — see [`crate::bloom`] — so the widest frame this renderer
18757    /// records is a *large* one, and a bound checked against a 64×48 frame would
18758    /// sit six passes above what that frame runs and this assertion would have
18759    /// to be a `<=`. It is an `==` on purpose: a bound well over the widest
18760    /// frame buys query sets nothing writes, and only an exact comparison
18761    /// notices.
18762    ///
18763    /// **The render scale is what makes those two requirements compose.** The
18764    /// upscale is a pass only below full scale, and below full scale the chain
18765    /// runs at the *internal* extent — so a frame with both is one whose
18766    /// internal extent is the longest chain's, and whose target is larger than
18767    /// that. Halving a target of 2048×1024 is what arranges it, and the two
18768    /// assertions below check the arrangement rather than trusting it.
18769    ///
18770    /// [`WIDEST_EXTENT`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
18771    #[test]
18772    fn the_pass_bound_is_the_widest_frame_the_renderer_records() {
18773        /// The extent whose bloom chain is the longest [`crate::bloom`] will
18774        /// build: six halvings of 512 leave sixteen by eight, which is still at
18775        /// or above that module's floor. The widest frame is drawn at this,
18776        /// which is why it is the internal one and not the target.
18777        const WIDEST_INTERNAL: (u32, u32) = (1024, 512);
18778        /// Half, so the frame records an upscale and draws at
18779        /// [`WIDEST_INTERNAL`].
18780        const WIDEST_SCALE: f32 = 0.5;
18781        /// The caller's extent: twice [`WIDEST_INTERNAL`] in each dimension.
18782        const WIDEST_EXTENT: (u32, u32) = (WIDEST_INTERNAL.0 * 2, WIDEST_INTERNAL.1 * 2);
18783
18784        let (recorder, device, queue) = open();
18785        let device = device.as_ref();
18786        // **A scene whose probes ask to be updated**, because the widest frame
18787        // is the one with every pass in it and
18788        // the irradiance probes' two are recorded by a volume
18789        // rather than by an effect bit — the ground grid's argument exactly. A
18790        // renderer built on the demo's empty grid records neither, and the bound
18791        // would then be checked against a frame that could not reach it.
18792        let mut scene = scene::demo();
18793        scene.capacities.probes = 1;
18794        scene.probes = scene::ProbeGrid {
18795            volume: crcbl_shaders::probe::ProbeVolume {
18796                origin: [0.0; 3],
18797                inv_spacing: [1.0; 3],
18798                counts: [1, 1, 1],
18799                levels: 1,
18800                steps: crcbl_shaders::probe::ProbeSteps::default(),
18801            },
18802            probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
18803            update: ProbeUpdate::EveryFrame,
18804        };
18805        let mut renderer =
18806            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
18807                .expect("built");
18808        // A maximum-width graph must include actual instances to cull.
18809        place_cube(&mut renderer, Mat4::IDENTITY);
18810        renderer
18811            .set_ground_grid(device, Some(GridStyle::default()))
18812            .expect("the null backend builds every pipeline");
18813        // **And the occlusion cull**, whose late prepass, farthest pyramid and
18814        // three late compute passes are the ground grid's kind of pass: off
18815        // unless a caller asks, and in the widest frame when one does.
18816        renderer.set_occlusion_culling(OcclusionCulling {
18817            occlusion: true,
18818            small_feature_pixels: None,
18819        });
18820        // **A body of water**, on the ground grid's terms: content rather than
18821        // an effect bit, so the widest frame is one a caller gave water to, and
18822        // `Water::PASSES` is in the bound for it.
18823        renderer
18824            .set_water(&[crcbl_water::WaterBody {
18825                outline: vec![[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]],
18826                level: 0.0,
18827                medium: crcbl_water::Medium {
18828                    absorption: [0.4, 0.1, 0.05],
18829                    scattering: [0.01, 0.01, 0.01],
18830                },
18831            }])
18832            .expect("a square meshes");
18833        // **A field of grass**, on the water body's terms exactly: content
18834        // rather than an effect bit, so the widest frame is one a caller gave a
18835        // field to and `Grass::PASSES` is in the bound for it.
18836        renderer
18837            .set_grass(
18838                device,
18839                queue,
18840                Some(
18841                    &crate::grass::GrassField::new(
18842                        [1, 1],
18843                        4.0,
18844                        [-2.0, -2.0],
18845                        50.0,
18846                        crate::grass::Heightfield {
18847                            texels: [4, 4],
18848                            metres_per_texel: 1.0,
18849                            origin: [-2.0, -2.0],
18850                            heights: vec![0.0; 16],
18851                        },
18852                        crate::grass::CoverMap {
18853                            texels: [4, 4],
18854                            metres_per_texel: 1.0,
18855                            origin: [-2.0, -2.0],
18856                            cover: vec![[255, 0]; 16],
18857                        },
18858                        // A shell row and a mesh blade row, so the widest
18859                        // frame records every look's draw the grass pass has.
18860                        [
18861                            crate::grass::BladeLook::Shells,
18862                            crate::grass::BladeLook::Blades,
18863                        ]
18864                        .map(|look| crate::grass::BladeType {
18865                            root_color: [0.05, 0.1, 0.02],
18866                            tip_color: [0.3, 0.5, 0.1],
18867                            height: 0.3,
18868                            half_width: 0.03,
18869                            height_spread: 0.3,
18870                            width_spread: 0.2,
18871                            look,
18872                            style: crate::grass::BladeStyle::PLAIN,
18873                            shape: crate::grass::BladeShape::STRAIGHT,
18874                            clumping: crate::grass::Clumping::NONE,
18875                        })
18876                        .to_vec(),
18877                    )
18878                    .expect("a real field"),
18879                ),
18880            )
18881            .expect("the null backend uploads every map");
18882        renderer.set_render_scale(WIDEST_SCALE);
18883        assert_eq!(
18884            renderer.internal_extent(WIDEST_EXTENT),
18885            WIDEST_INTERNAL,
18886            "the scale has to take the target to the extent whose chain is the \
18887             longest one, or the bound below is checked against a frame that \
18888             could not reach it"
18889        );
18890        // **Both post effects forced on.** Neither is in the default camera
18891        // stack — see [`RenderEffects::DEFAULT_STACK`], which leaves the lens out
18892        // for one reason and the resolve out for another — and the widest frame
18893        // is the one that has every effect in it, the ground grid's argument
18894        // exactly.
18895        renderer.set_effect_request(EffectRequest {
18896            programmatic: EffectOverride::none().force(OUTSIDE_THE_DEFAULT, Some(true)),
18897            ..EffectRequest::default()
18898        });
18899        let imported = swapchain_image_at(device, WIDEST_EXTENT);
18900        let mut pool = crate::TransientPool::new();
18901
18902        // The debug draw layer on for both frames below, because it is a pass
18903        // the bound counts and no effect bit switches on — the ground grid's
18904        // argument again. A segment before each, since `begin_frame` clears the
18905        // buffer: the layer is immediate mode.
18906        let switch = debug_draw_switch();
18907        switch.set(true);
18908        // And the occlusion pair's second blur, for exactly that reason: it is a
18909        // pass [`Ssao::MAX_PASSES`] counts and no effect bit switches on, so a
18910        // frame at the shipping count comes one short of the bound and this test
18911        // would be asserting the bound against a frame that could not reach it.
18912        let blurs = ssao_blur_switch();
18913        blurs.set(i64::from(Ssao::MAX_BLUR_PASSES));
18914        // And the comparison seam, which is the occlusion chain's other
18915        // conditional pass — see `crate::ssao`'s `r_ssao_split`. Held for the
18916        // same reason the blur count is: the bound counts a frame that compares,
18917        // so a frame that does not could never reach it.
18918        let split = ssao_split_switch();
18919        split.set(0.5);
18920        renderer
18921            .debug_draw()
18922            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18923        let bare =
18924            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18925        assert_eq!(
18926            crate::bloom::mips_for(WIDEST_INTERNAL),
18927            crate::bloom::MAX_MIPS,
18928            "the widest frame has to be one whose chain is the longest one there \
18929             is, or the bound below is checked against a frame that could not \
18930             reach it"
18931        );
18932        assert!(
18933            bare < ForwardRenderer::MAX_PASSES as usize,
18934            "a frame with no shadowed light runs {bare} passes, which is already the \
18935             bound of {} — then the bound does not cover the slots this scene left free",
18936            ForwardRenderer::MAX_PASSES
18937        );
18938
18939        // One spot per slot, spaced so no two of them share an influence — the
18940        // list has to fill every slot or the bound below is checked against a
18941        // frame that could not reach it.
18942        #[expect(
18943            clippy::cast_precision_loss,
18944            reason = "a handful of slots, and the value is only a position"
18945        )]
18946        let spots: Vec<Light> = (0..shadow::LIGHT_SLOTS)
18947            .map(|slot| shadowable_spot(1.0 + slot as f32))
18948            .collect();
18949        renderer.set_lights(&spots);
18950        renderer
18951            .debug_draw()
18952            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18953        let widest =
18954            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18955        assert_eq!(
18956            renderer.shadow_lights.slots().iter().flatten().count(),
18957            shadow::LIGHT_SLOTS,
18958            "the spots must actually hold every slot, or this is the bare frame again \
18959             under another name"
18960        );
18961        assert_eq!(
18962            widest,
18963            ForwardRenderer::MAX_PASSES as usize,
18964            "the widest frame is what the bound is for"
18965        );
18966        assert_eq!(
18967            widest - bare,
18968            DrawGen::MAX_PASSES as usize * shadow::LIGHT_SLOTS,
18969            "a filled slot costs a cull's passes and nothing else"
18970        );
18971
18972        renderer.destroy(device);
18973        pool.destroy(device);
18974        device.destroy_image_view(imported.view);
18975        device.destroy_image(imported.image);
18976        recorder.assert_valid();
18977    }
18978
18979    /// **A toggle reaches the recorded frame, and takes exactly its own passes
18980    /// with it.**
18981    ///
18982    /// The observable is the compiled pass list, because the thing that could
18983    /// otherwise be true is that the switch is stored and read by nothing: a
18984    /// renderer holding `SHADOWS` clear and recording every shadow cull anyway
18985    /// draws a frame that looks right, reports the right effect set, and has not
18986    /// switched anything off.
18987    ///
18988    /// So each arm compares the whole list rather than its length. Two passes
18989    /// fewer is satisfied by removing the wrong two, and it is satisfied by a
18990    /// frame that lost its tonemap.
18991    ///
18992    /// The shadow arm is the one that cannot be written by name — a cascade's
18993    /// cull passes are labelled exactly as the camera's are — so it is written as
18994    /// its two halves instead: the count moves by a cull's worth per cascade and
18995    /// per filled light slot, and everything from the `shadow` pass onwards is
18996    /// unchanged. The `shadow` pass itself **stays**, because it is what writes
18997    /// the clear that reads as "fully lit".
18998    #[test]
18999    fn each_effect_toggle_removes_exactly_the_passes_it_owns() {
19000        let _blurs = ssao_blur_switch();
19001        let (recorder, device, queue) = open();
19002        let device = device.as_ref();
19003        let mut renderer =
19004            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19005        place_cube(&mut renderer, Mat4::IDENTITY);
19006        // One shadowed light beside the cascades, so the shadow arm below covers
19007        // a light slot's cull as well as a cascade's.
19008        renderer.set_lights(&[shadowable_spot(-1.0)]);
19009        let imported = swapchain_image(device);
19010        let mut pool = crate::TransientPool::new();
19011
19012        // [`OUTSIDE_THE_DEFAULT`] forced on and then `off` forced off, on
19013        // [`frame_switching_off`]'s terms exactly: the default camera stack
19014        // leaves both of them out — see [`RenderEffects::DEFAULT_STACK`] — so a
19015        // control built on the default alone would have nothing for their arms
19016        // to remove. `force` clears the other side, so an arm whose `off` is one
19017        // of them still resolves to off.
19018        //
19019        // [`frame_switching_off`]: fn@frame_switching_off
19020        let without = |renderer: &mut ForwardRenderer, off: RenderEffects| {
19021            renderer.set_effect_request(EffectRequest {
19022                programmatic: EffectOverride::none()
19023                    .force(OUTSIDE_THE_DEFAULT, Some(true))
19024                    .force(off, Some(false)),
19025                ..EffectRequest::default()
19026            });
19027            passes_in_a_frame(device, queue, renderer, imported, &pool, TEST_EXTENT)
19028        };
19029
19030        let all_on = without(&mut renderer, RenderEffects::empty());
19031        assert_eq!(
19032            renderer.effects(),
19033            RenderEffects::all(),
19034            "the control frame has to be the every-effect one"
19035        );
19036        assert_eq!(
19037            renderer.shadow_lights.slots().iter().flatten().count(),
19038            1,
19039            "the spot must actually hold a slot, or the shadow arm below is only about cascades"
19040        );
19041
19042        // **None of the three leaves anything behind it**, and for the same
19043        // reason: nothing reads what it would have written. The occlusion pair's
19044        // reader binds the 1×1 white placeholder instead — `mesh.slang` clamps
19045        // its `Load` into it — and the reflection pair's and the chain's readers
19046        // both tonemap whatever image they would have read anyway.
19047        //
19048        // The chain's labels are written out rather than built from
19049        // `crate::bloom`'s arithmetic, because a table generated from the code
19050        // under test cannot fail: it is `TEST_EXTENT`'s two levels — two
19051        // downsamples, the one upsample between them, and the composite — and if
19052        // that extent moves this is the assertion that says so.
19053        for (off, gone) in [
19054            (
19055                RenderEffects::AMBIENT_OCCLUSION,
19056                ["ssao", "ssao-blur", "ssao-upsample"].as_slice(),
19057            ),
19058            (
19059                RenderEffects::CONTACT_SHADOWS,
19060                // One pass and no blur — `crate::contact_shadows`'s header says
19061                // why the occlusion pair's second pass has no counterpart here.
19062                ["contact-shadows"].as_slice(),
19063            ),
19064            (
19065                RenderEffects::REFLECTIONS,
19066                // **The pyramid goes with the march**, which is the whole of
19067                // what makes it an optimisation rather than a resource: it is
19068                // recorded on the frames that reflect and on no others. Two
19069                // levels at `TEST_EXTENT`, written out on the chain's terms
19070                // above.
19071                ["hiz-1", "hiz-2", "ssr", "ssr-blur"].as_slice(),
19072            ),
19073            (
19074                RenderEffects::BLOOM,
19075                [
19076                    "bloom-down-1",
19077                    "bloom-down-2",
19078                    "bloom-up-1",
19079                    "bloom-composite",
19080                ]
19081                .as_slice(),
19082            ),
19083            (
19084                RenderEffects::AUTO_EXPOSURE,
19085                // All three go together and the tonemap stays: the pass reads
19086                // the measurement only when the block says to, and the block
19087                // says so on exactly the frames these three ran on.
19088                ["exposure-clear", "exposure-histogram", "exposure-reduce"].as_slice(),
19089            ),
19090        ] {
19091            let labels = without(&mut renderer, off);
19092            assert_eq!(
19093                renderer.effects(),
19094                RenderEffects::all().difference(off),
19095                "{off:?}: the frame must have resolved to the set the request asked for"
19096            );
19097            // **The control frame has to contain what this arm removes**, and
19098            // that is not a restatement of the comparison below: the comparison
19099            // builds `expected` by filtering `gone` out of `all_on`, so an arm
19100            // naming a pass the control never recorded filters nothing, matches,
19101            // and passes whether the effect draws anything or not. Removing the
19102            // resolve pass entirely left this loop green until this assertion
19103            // existed.
19104            for label in gone {
19105                assert!(
19106                    all_on.iter().any(|recorded| recorded == label),
19107                    "{off:?}: the every-effect frame does not record `{label}`, so removing it \
19108                     below proves nothing: {all_on:#?}"
19109                );
19110            }
19111            let expected: Vec<String> = all_on
19112                .iter()
19113                .filter(|label| !gone.contains(&label.as_str()))
19114                .cloned()
19115                .collect();
19116            assert_eq!(
19117                labels, expected,
19118                "{off:?}: the frame must lose {gone:?}, gain nothing in their place, and keep \
19119                 every other pass"
19120            );
19121        }
19122
19123        // **The two antialiasing tiers share one resolve slot**, so neither is
19124        // a plain removal and neither belongs in the loop above: switching
19125        // CMAA2 off while FXAA stays on swaps three passes for one rather than
19126        // losing three, and the loop's "gain nothing in their place" comparison
19127        // is exactly what that violates. Three frames say it instead.
19128        let both = all_on.clone();
19129        let cheap = without(&mut renderer, RenderEffects::CMAA2);
19130        let neither = without(
19131            &mut renderer,
19132            RenderEffects::CMAA2.union(RenderEffects::ANTIALIASING),
19133        );
19134        const CMAA2_PASSES: [&str; 3] = ["cmaa2-edges", "cmaa2-shapes", "cmaa2-apply"];
19135        let resolve_of = |labels: &[String]| -> Vec<String> {
19136            labels
19137                .iter()
19138                .filter(|label| *label == "fxaa" || CMAA2_PASSES.contains(&label.as_str()))
19139                .cloned()
19140                .collect()
19141        };
19142        let without_resolve = |labels: &[String]| -> Vec<String> {
19143            labels
19144                .iter()
19145                .filter(|label| *label != "fxaa" && !CMAA2_PASSES.contains(&label.as_str()))
19146                .cloned()
19147                .collect()
19148        };
19149        assert_eq!(
19150            resolve_of(&both),
19151            CMAA2_PASSES.map(str::to_string).to_vec(),
19152            "with both bits set the higher tier takes the slot and the cheap one \
19153             records nothing"
19154        );
19155        assert_eq!(
19156            resolve_of(&cheap),
19157            vec!["fxaa".to_string()],
19158            "with only the cheap bit set the slot is FXAA's"
19159        );
19160        assert!(
19161            resolve_of(&neither).is_empty(),
19162            "with neither bit set the frame has no resolve at all: {neither:#?}"
19163        );
19164        // And nothing else moved: the tiers swap in one slot rather than
19165        // rebuilding the frame around themselves.
19166        assert_eq!(without_resolve(&both), without_resolve(&cheap));
19167        assert_eq!(without_resolve(&both), without_resolve(&neither));
19168        // The slot is where the ordering argument puts it — directly after the
19169        // last pass that writes the display image, which at this extent is the
19170        // tonemap.
19171        for labels in [&both, &cheap] {
19172            let at = labels
19173                .iter()
19174                .position(|label| label == "tonemap")
19175                .expect("a frame has to reach the swapchain");
19176            assert_eq!(
19177                &labels[at + 1..=at + resolve_of(labels).len()],
19178                resolve_of(labels).as_slice(),
19179                "the resolve must follow the tonemap: {labels:#?}"
19180            );
19181        }
19182
19183        let no_shadows = without(&mut renderer, RenderEffects::SHADOWS);
19184        assert_eq!(
19185            renderer.effects(),
19186            RenderEffects::all().difference(RenderEffects::SHADOWS),
19187        );
19188        assert_eq!(
19189            all_on.len() - no_shadows.len(),
19190            DrawGen::MAX_PASSES as usize * (shadow::CASCADES + 1),
19191            "shadows off must drop a cull's passes per cascade and per filled slot"
19192        );
19193        let from_the_atlas = |labels: &[String]| {
19194            let at = labels
19195                .iter()
19196                .position(|label| label == "shadow")
19197                .expect("the atlas pass is recorded whether or not anything draws into it");
19198            labels[at..].to_vec()
19199        };
19200        assert_eq!(
19201            from_the_atlas(&no_shadows),
19202            from_the_atlas(&all_on),
19203            "only the culls go: the atlas pass and everything after it are unchanged"
19204        );
19205
19206        renderer.destroy(device);
19207        pool.destroy(device);
19208        device.destroy_image_view(imported.view);
19209        device.destroy_image(imported.image);
19210        recorder.assert_valid();
19211    }
19212
19213    /// **The contact march is a pass a frame records only when it was asked
19214    /// for, and the mask it writes is what the forward pass then reads.**
19215    ///
19216    /// Two observables, because either alone is satisfied by a mistake the other
19217    /// one catches:
19218    ///
19219    /// * **The compiled pass list.** `contact-shadows` appears between the
19220    ///   prepass whose depth it marches and the forward pass that binds it, and
19221    ///   appears at all only on the frame that asked. The toggle test above
19222    ///   already says a frame loses this pass and nothing else; what is added
19223    ///   here is *where* it sits, which is the half a set comparison cannot see
19224    ///   — a march recorded after the pass that reads it compiles and draws a
19225    ///   mask nothing ever looks at.
19226    /// * **The forward pass's own barriers.** On the frame that marched, one
19227    ///   more image is transitioned into [`ResourceState::ShaderRead`] before
19228    ///   the forward pass opens than on the frame that did not — which is the
19229    ///   mask leaving the colour attachment it was written as. That is what says
19230    ///   the pass's output reaches the shading, rather than being written into a
19231    ///   transient and dropped while the shader goes on reading the 1×1
19232    ///   placeholder. The placeholder is imported in `ShaderRead` already and
19233    ///   needs no transition, so it contributes nothing to this count and the
19234    ///   difference is exactly the mask.
19235    ///
19236    /// [`RenderEffects::CONTACT_SHADOWS`] is out of the default camera stack
19237    /// while its re-bless is pending — see that constant — so the `on` frame has
19238    /// to force it and the `off` frame is what a view saying nothing draws.
19239    #[test]
19240    fn the_contact_march_is_recorded_only_when_asked_and_its_mask_reaches_the_forward_pass() {
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
19248        let frame = |renderer: &mut ForwardRenderer, on: bool| -> (Vec<String>, usize) {
19249            renderer.set_effect_request(EffectRequest {
19250                programmatic: EffectOverride::none()
19251                    .force(RenderEffects::CONTACT_SHADOWS, Some(on)),
19252                ..EffectRequest::default()
19253            });
19254            renderer
19255                .begin_frame(
19256                    device,
19257                    &Camera::default(),
19258                    &DirectionalLight::default(),
19259                    TEST_EXTENT,
19260                )
19261                .expect("write");
19262            let mut graph = crate::RenderGraph::new(queue);
19263            let target = graph.import_image("target", imported);
19264            renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19265            let compiled = graph.compile(&pool).expect("a legal frame");
19266            let labels: Vec<String> = compiled
19267                .passes()
19268                .iter()
19269                .map(|pass| pass.label().to_string())
19270                .collect();
19271            let readable = compiled
19272                .passes()
19273                .iter()
19274                .find(|pass| pass.label() == "forward")
19275                .expect("every frame draws its geometry")
19276                .barriers()
19277                .images
19278                .iter()
19279                .filter(|barrier| barrier.to == ResourceState::ShaderRead)
19280                .count();
19281            (labels, readable)
19282        };
19283
19284        let (marched, marched_reads) = frame(&mut renderer, true);
19285        assert!(
19286            renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19287            "the forced frame has to have resolved with the bit set"
19288        );
19289        let (bare, bare_reads) = frame(&mut renderer, false);
19290        assert!(
19291            !renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19292            "and the control frame without it"
19293        );
19294
19295        assert!(
19296            !bare.iter().any(|label| label == "contact-shadows"),
19297            "a frame that did not ask must record no march at all: {bare:#?}"
19298        );
19299        let at = |labels: &[String], wanted: &str| {
19300            labels
19301                .iter()
19302                .position(|label| label == wanted)
19303                .unwrap_or_else(|| panic!("no `{wanted}` pass in {labels:#?}"))
19304        };
19305        let march = at(&marched, "contact-shadows");
19306        assert!(
19307            march > at(&marched, "depth-prepass"),
19308            "the march reads the prepass's depth, so it cannot precede it: {marched:#?}"
19309        );
19310        assert!(
19311            march < at(&marched, "forward"),
19312            "and the forward pass binds what it wrote, so it cannot follow it: {marched:#?}"
19313        );
19314
19315        assert_eq!(
19316            marched_reads,
19317            bare_reads + 1,
19318            "the forward pass has to take one more image into `ShaderRead` on the frame that \
19319             marched — the mask. Equal counts mean the pass wrote a transient the shading \
19320             never reads."
19321        );
19322
19323        renderer.destroy(device);
19324        pool.destroy(device);
19325        device.destroy_image_view(imported.view);
19326        device.destroy_image(imported.image);
19327        recorder.assert_valid();
19328    }
19329
19330    /// **The ground grid is off until a caller asks, and then it is the last
19331    /// pass of the frame — after the tonemap.**
19332    ///
19333    /// Three claims and each is a separate way to get this wrong. Off by default
19334    /// is what keeps every sample and every golden image where they were. *After
19335    /// the tonemap* is the placement decision: added a line earlier it would
19336    /// draw into the HDR scene colour and be tonemapped like geometry, which
19337    /// compiles, draws a grid, and gives it a colour that moves with the
19338    /// exposure. And switching it off again has to remove the pass, not merely
19339    /// stop reporting it.
19340    ///
19341    /// The whole list is compared rather than its length, for the reason the
19342    /// effect-toggle test gives: one more pass is satisfied by gaining the wrong
19343    /// one.
19344    #[test]
19345    fn the_ground_grid_is_opt_in_and_lands_after_the_tonemap() {
19346        let _blurs = ssao_blur_switch();
19347        let (recorder, device, queue) = open();
19348        let device = device.as_ref();
19349        let mut renderer =
19350            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19351        let imported = swapchain_image(device);
19352        let mut pool = crate::TransientPool::new();
19353
19354        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19355        assert!(
19356            renderer.ground_grid().is_none(),
19357            "a renderer nobody asked has no grid"
19358        );
19359        assert!(
19360            !off.contains(&"grid".to_string()),
19361            "the grid must not be in a frame nobody asked for it in: {off:#?}"
19362        );
19363
19364        renderer
19365            .set_ground_grid(device, Some(GridStyle::default()))
19366            .expect("the null backend builds every pipeline");
19367        assert_eq!(renderer.ground_grid(), Some(&GridStyle::default()));
19368        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19369
19370        let mut expected = off.clone();
19371        // The statistics copy is added after every render pass and stays last —
19372        // see `add_passes`. So the grid goes in front of it, which is directly
19373        // after the tonemap.
19374        let tonemap = expected
19375            .iter()
19376            .position(|label| label == "tonemap")
19377            .expect("a frame has to reach the swapchain");
19378        expected.insert(tonemap + 1, "grid".to_string());
19379        assert_eq!(
19380            on, expected,
19381            "the grid must be the one pass gained, and it must sit after the tonemap"
19382        );
19383
19384        renderer
19385            .set_ground_grid(device, None)
19386            .expect("switching off builds nothing");
19387        assert!(renderer.ground_grid().is_none());
19388        assert_eq!(
19389            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
19390            off,
19391            "switching the grid off has to remove its pass, not just stop reporting it"
19392        );
19393
19394        renderer.destroy(device);
19395        pool.destroy(device);
19396        device.destroy_image_view(imported.view);
19397        device.destroy_image(imported.image);
19398        recorder.assert_valid();
19399    }
19400
19401    /// **A second occlusion blur is a pass the frame records, an image it takes
19402    /// out of the pool, and a triangle its counter reports** — or it is a switch
19403    /// that does nothing.
19404    ///
19405    /// `crcbl`'s `forward_e2e::occlusion` measures what the second blur is worth
19406    /// by driving the pipelines itself, so nothing there would notice that a
19407    /// real frame never records it. The three things below are what a frame has
19408    /// to do differently, and each of them fails silently on its own: a missing
19409    /// pass draws a slightly rougher picture, a missing image is a bind of the
19410    /// wrong one, and a counter short by one is a number nobody reads until it
19411    /// is quoted.
19412    ///
19413    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19414    /// [`ssao_blur_switch`] and for [`debug_draw_switch`]'s reason.
19415    /// The id [`Ssao::add_passes`] hands back is the reconstruction's target,
19416    /// whichever blur ran into it.
19417    ///
19418    /// **The one thing about that chain no other check can see.** The pass list
19419    /// is identical either way, the graph accepts a written-and-never-read
19420    /// transient without complaint, and every golden is at one blur where the
19421    /// two blur answers coincide — so a frame bound to the wrong image draws
19422    /// something nobody would question, which is exactly what the function's
19423    /// own doc warns about. Verified 2026-08-31 by returning `blurred` from the
19424    /// two-blur arm: `crcbl-render`'s unit tests, the forward and mesh e2e
19425    /// suites and lantern's golden all stayed green.
19426    ///
19427    /// **Since the halving it is a second silent failure and a louder one.**
19428    /// Every working image is [`crate::ssao::half_extent`] of the frame, so a
19429    /// returned working id is not merely a rougher channel — it is an image a
19430    /// quarter of the size bound where `mesh.slang` reads at `SV_Position`,
19431    /// which its clamp turns into occlusion smeared over the top-left quarter of
19432    /// the frame rather than into an error.
19433    #[test]
19434    fn the_occlusion_id_handed_back_is_the_reconstruction_target() {
19435        let (_recorder, device, queue) = open();
19436        let device = device.as_ref();
19437        let mut ssao = Ssao::new(device, 1, ForwardRenderer::build_fullscreen).expect("built");
19438        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19439
19440        let one = {
19441            let mut graph = crate::RenderGraph::new(queue);
19442            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19443            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19444            let blurred =
19445                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19446            let upsampled = graph.create_image(
19447                "ssao-upsampled",
19448                crate::targets::ambient_occlusion(TEST_EXTENT),
19449            );
19450            let got = ssao.add_passes(
19451                &mut graph,
19452                0,
19453                TEST_EXTENT,
19454                depth,
19455                crate::ssao::OcclusionImages {
19456                    raw,
19457                    blurred,
19458                    again: None,
19459                    upsampled,
19460                },
19461            );
19462            (got == upsampled, got == blurred || got == raw)
19463        };
19464        assert!(one.0, "one blur finishes in the reconstruction's image");
19465        assert!(
19466            !one.1,
19467            "and never in one of the half-extent images the chain worked in"
19468        );
19469
19470        let two = {
19471            let mut graph = crate::RenderGraph::new(queue);
19472            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19473            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19474            let blurred =
19475                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19476            let again = graph.create_image(
19477                "ssao-blurred-2",
19478                crate::targets::ambient_occlusion(gathered),
19479            );
19480            let upsampled = graph.create_image(
19481                "ssao-upsampled",
19482                crate::targets::ambient_occlusion(TEST_EXTENT),
19483            );
19484            let got = ssao.add_passes(
19485                &mut graph,
19486                0,
19487                TEST_EXTENT,
19488                depth,
19489                crate::ssao::OcclusionImages {
19490                    raw,
19491                    blurred,
19492                    again: Some(again),
19493                    upsampled,
19494                },
19495            );
19496            (got == upsampled, got == again || got == blurred)
19497        };
19498        assert!(
19499            two.0,
19500            "two blurs finish in the reconstruction's image as well, which is the id the forward \
19501             pass binds"
19502        );
19503        assert!(
19504            !two.1,
19505            "and not in a blur's own image -- a frame bound to one of those is a frame nobody \
19506             would question"
19507        );
19508    }
19509
19510    /// **The gather runs at half the frame and the reconstruction runs at all
19511    /// of it** — or the halving is a description nobody rendered into.
19512    ///
19513    /// The pass list cannot see this: three passes with the right labels in the
19514    /// right order is exactly what a chain that halved nothing would record. The
19515    /// **render area** is where the halving is observable, and the graph derives
19516    /// it from each pass's colour attachment — so this is the check that the
19517    /// transients [`ForwardRenderer::add_passes`] created are the ones
19518    /// [`crate::ssao::half_extent`] sized, and that the reconstruction was given
19519    /// the frame-sized one.
19520    ///
19521    /// Neither mistake is an error anywhere else. Working images at the frame's
19522    /// extent are four times the march and a reconstruction reading the corner
19523    /// of its input; a frame-sized image handed to the march and a half-sized
19524    /// one to the forward pass is occlusion smeared over a quarter of the
19525    /// picture by `mesh.slang`'s clamp. Both are pictures.
19526    ///
19527    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19528    /// [`ssao_blur_switch`] and for that function's second reason: it looks the
19529    /// occlusion chain's passes up by name, and a second blur arriving from
19530    /// another thread's switch is a pass this frame did not ask for.
19531    #[test]
19532    fn the_occlusion_chain_gathers_at_half_the_frame_and_reconstructs_at_all_of_it() {
19533        let _switch = ssao_blur_switch();
19534
19535        let (recorder, device, queue) = open();
19536        let device = device.as_ref();
19537        let mut renderer =
19538            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19539        let imported = swapchain_image(device);
19540        let mut pool = crate::TransientPool::new();
19541        renderer
19542            .begin_frame(
19543                device,
19544                &Camera::default(),
19545                &DirectionalLight::default(),
19546                TEST_EXTENT,
19547            )
19548            .expect("write");
19549        let mut graph = crate::RenderGraph::new(queue);
19550        let target = graph.import_image("target", imported);
19551        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19552        let compiled = graph.compile(&pool).expect("a legal frame");
19553        let area_of = |label: &str| {
19554            let pass = compiled
19555                .passes()
19556                .iter()
19557                .find(|pass| pass.label() == label)
19558                .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
19559            let area = pass.render_area();
19560            (area.width, area.height)
19561        };
19562
19563        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19564        assert_ne!(
19565            gathered, TEST_EXTENT,
19566            "the fixture extent has to halve to something else, or every assertion below holds \
19567             of a chain that halved nothing"
19568        );
19569        assert_eq!(
19570            area_of("ssao"),
19571            gathered,
19572            "the march has to run over the gather extent"
19573        );
19574        assert_eq!(
19575            area_of("ssao-blur"),
19576            gathered,
19577            "and so does the blur over what the march wrote"
19578        );
19579        assert_eq!(
19580            area_of("ssao-upsample"),
19581            TEST_EXTENT,
19582            "the reconstruction writes the channel `mesh.slang` reads at `SV_Position`, so it \
19583             runs at the frame's own extent"
19584        );
19585
19586        drop(compiled);
19587        renderer.destroy(device);
19588        pool.destroy(device);
19589        device.destroy_image_view(imported.view);
19590        device.destroy_image(imported.image);
19591        recorder.assert_valid();
19592    }
19593
19594    /// [`ssr_resolution_switch`]'s lock.
19595    static SSR_RESOLUTION_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
19596
19597    /// Takes `r_ssr_resolution` for this thread and puts full resolution back
19598    /// when the guard drops, on [`ssao_blur_switch`]'s terms.
19599    fn ssr_resolution_switch() -> std::sync::MutexGuard<'static, ()> {
19600        SSR_RESOLUTION_SWITCH
19601            .lock()
19602            .unwrap_or_else(std::sync::PoisonError::into_inner)
19603    }
19604
19605    /// **The reflection march runs at its share of the frame and the composite
19606    /// at all of it**, at every share a quality tier writes.
19607    ///
19608    /// On the occlusion chain's terms just above: the pass list is the same at
19609    /// every share, so the **render area** is where the scale is observable. A
19610    /// march image left at the frame's extent would be a march that saved
19611    /// nothing, and a composite at the march's extent would tonemap a truncated
19612    /// frame.
19613    #[test]
19614    fn the_reflection_march_runs_at_its_share_and_composites_at_the_frame() {
19615        let _switch = ssr_resolution_switch();
19616
19617        let (recorder, device, queue) = open();
19618        let device = device.as_ref();
19619        let mut renderer =
19620            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19621        let imported = swapchain_image(device);
19622        let mut pool = crate::TransientPool::new();
19623        for share in [1.0, 0.75, 0.5, 0.25] {
19624            crate::ssr::r_ssr_resolution
19625                .set(&crcbl_console::Value::Float(share))
19626                .expect("every tier's share is in the variable's range");
19627            renderer
19628                .begin_frame(
19629                    device,
19630                    &Camera::default(),
19631                    &DirectionalLight::default(),
19632                    TEST_EXTENT,
19633                )
19634                .expect("write");
19635            let mut graph = crate::RenderGraph::new(queue);
19636            let target = graph.import_image("target", imported);
19637            renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19638            let compiled = graph.compile(&pool).expect("a legal frame");
19639            let area_of = |label: &str| {
19640                let pass = compiled
19641                    .passes()
19642                    .iter()
19643                    .find(|pass| pass.label() == label)
19644                    .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
19645                let area = pass.render_area();
19646                (area.width, area.height)
19647            };
19648            let marched = crate::ssr::march_extent(TEST_EXTENT, share);
19649            assert_eq!(
19650                area_of("ssr"),
19651                marched,
19652                "at {share} the march has to run over its own share of the frame"
19653            );
19654            assert_eq!(
19655                area_of("ssr-blur"),
19656                TEST_EXTENT,
19657                "at {share} the composite replaces the scene colour, so it runs at the frame's \
19658                 own extent"
19659            );
19660            drop(compiled);
19661        }
19662        crate::ssr::r_ssr_resolution
19663            .set(&crcbl_console::Value::Float(1.0))
19664            .expect("full resolution is in range");
19665
19666        renderer.destroy(device);
19667        pool.destroy(device);
19668        device.destroy_image_view(imported.view);
19669        device.destroy_image(imported.image);
19670        recorder.assert_valid();
19671    }
19672
19673    /// **The comparison seam records a second march, scissored to the columns
19674    /// the first one was kept off.**
19675    ///
19676    /// `crate::split`'s geometry, read off the encoder rather than off the code
19677    /// that drove it: two passes, and two `SetScissor` rectangles that tile the
19678    /// gather extent between them.
19679    ///
19680    /// **What this cannot see is which block each march bound.** The reference
19681    /// backend records a bind group as a handle and a layout, not as the
19682    /// resources behind it, so pointing both marches at one buffer leaves this
19683    /// test green — measured, by doing exactly that. The group inequality below
19684    /// is kept because it is free and would catch the two marches sharing a
19685    /// cache, which is a different fault; what covers the blocks is
19686    /// `crate::ssao`'s `the_seams_other_side_is_what_the_chain_ships`, and what
19687    /// is not covered at all is the wiring between them. `docs/backlog.md`
19688    /// carries that gap.
19689    ///
19690    /// **The control is the same frame without a seam**, and it is what makes
19691    /// the assertions mean anything: a chain that scissored unconditionally
19692    /// would satisfy every claim below and change every golden in the workspace,
19693    /// so the frame nobody asked to compare has to record one march and set no
19694    /// rectangle at all.
19695    ///
19696    /// Holds [`ssao_split_switch`] for [`ssao_blur_switch`]'s reason: the seam
19697    /// is process-wide state and a frame that picked one up from another
19698    /// thread's test is a frame with a pass this one did not ask for.
19699    #[test]
19700    fn the_comparison_seam_marches_twice_over_columns_that_tile_the_gather() {
19701        use crcbl_hal::null::Command;
19702
19703        let _blurs = ssao_blur_switch();
19704        let split = ssao_split_switch();
19705        // Third, after the two above: the only other test that takes this one
19706        // takes it alone, so this is the whole order and there is no cycle in
19707        // it. Moved below, because two blocks holding the same scalars are
19708        // equal whatever the seam did.
19709        let slices = ssao_slice_switch();
19710        // The count the seam's far side reads, and one that is not it. Read off
19711        // the variable rather than written down: which end of the range ships
19712        // has changed once already, and a test naming the wrong end would be
19713        // comparing the shipped configuration against itself.
19714        let ships = match crate::ssao::r_ssao_slices.default() {
19715            crcbl_console::Value::Int(count) => *count,
19716            other => panic!("`r_ssao_slices` defaults to {other:?}, which is not a count"),
19717        };
19718        let moved = if ships == i64::from(ssao::SLICE_COUNT_MAX) {
19719            i64::from(ssao::SLICE_COUNT_DEFAULT)
19720        } else {
19721            i64::from(ssao::SLICE_COUNT_MAX)
19722        };
19723        assert_ne!(
19724            ships, moved,
19725            "the two slice counts this compares are one count, so the blocks below would differ \
19726             by nothing whatever the seam did"
19727        );
19728        slices.set(ships);
19729
19730        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19731        // One entry per march the frame recorded: the last rectangle that pass
19732        // left the scissor at, and the group it bound.
19733        //
19734        // **The last and not the only one.** The graph opens every pass with a
19735        // scissor over the whole render area, so a march that sets none of its
19736        // own still records one — which is why "did it scissor at all" is not
19737        // the question and "what did it end up cropped to" is.
19738        let marches = |recorder: &Recorder, from: usize| {
19739            let mut inside = false;
19740            let mut found: Vec<(crcbl_hal::Rect2d, crcbl_hal::BindGroupHandle)> = Vec::new();
19741            let mut rect = None;
19742            let mut group = None;
19743            for command in &recorder.commands()[from..] {
19744                if let Some((_, label)) = command.opens_pass() {
19745                    inside = matches!(label, Some("ssao" | "ssao-shipped"));
19746                    (rect, group) = (None, None);
19747                    continue;
19748                }
19749                if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19750                    if let (true, Some(rect), Some(group)) = (inside, rect, group) {
19751                        found.push((rect, group));
19752                    }
19753                    inside = false;
19754                    continue;
19755                }
19756                if !inside {
19757                    continue;
19758                }
19759                match command {
19760                    Command::SetScissor(at) => rect = Some(*at),
19761                    Command::BindGroup { group: bound, .. } => group = Some(*bound),
19762                    _ => {}
19763                }
19764            }
19765            found
19766        };
19767
19768        let (recorder, device, queue) = open();
19769        let device = device.as_ref();
19770        let mut renderer =
19771            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19772
19773        split.set(0.0);
19774        let alone = frame_seen_from(
19775            device,
19776            &mut renderer,
19777            queue,
19778            &Camera::default(),
19779            &DirectionalLight::default(),
19780        );
19781        let plain = marches(&recorder, 0);
19782        let after = recorder.commands().len();
19783        let (console, shipped) = renderer
19784            .primary
19785            .ssao
19786            .as_ref()
19787            .expect("the default stack builds the occlusion pair")
19788            .blocks(renderer.frame);
19789        let (uncompared_console, uncompared_shipped) = (
19790            recorder.buffer_bytes(console).expect("the console's block"),
19791            recorder.buffer_bytes(shipped).expect("the seam's block"),
19792        );
19793        alone.release(device);
19794
19795        split.set(0.5);
19796        slices.set(moved);
19797        let frame = frame_seen_from(
19798            device,
19799            &mut renderer,
19800            queue,
19801            &Camera::default(),
19802            &DirectionalLight::default(),
19803        );
19804        let compared = marches(&recorder, after);
19805        let (console, shipped) = renderer
19806            .primary
19807            .ssao
19808            .as_ref()
19809            .expect("the default stack builds the occlusion pair")
19810            .blocks(renderer.frame);
19811        let (compared_console, compared_shipped) = (
19812            recorder.buffer_bytes(console).expect("the console's block"),
19813            recorder.buffer_bytes(shipped).expect("the seam's block"),
19814        );
19815        frame.finish(device, renderer);
19816
19817        assert_eq!(
19818            plain.len(),
19819            1,
19820            "a frame comparing nothing recorded {} march(es); the seam is off, so there is one",
19821            plain.len()
19822        );
19823        assert_eq!(
19824            (
19825                plain[0].0.x,
19826                plain[0].0.y,
19827                plain[0].0.width,
19828                plain[0].0.height
19829            ),
19830            (0, 0, gathered.0, gathered.1),
19831            "a frame comparing nothing left its march cropped to something other than the whole \
19832             gather extent {gathered:?} — so the chain crops whether or not anybody asked it to, \
19833             and every golden in this workspace was blessed on a frame that does not"
19834        );
19835
19836        assert_eq!(
19837            compared.len(),
19838            2,
19839            "a frame comparing two configurations recorded {} march(es)",
19840            compared.len()
19841        );
19842        let (left, right) = (compared[0].0, compared[1].0);
19843        assert_eq!(
19844            (left.x, left.y, right.y),
19845            (0, 0, 0),
19846            "both halves start at the top and the left one at the edge"
19847        );
19848        assert_eq!(
19849            i64::from(right.x),
19850            i64::from(left.width),
19851            "the second march starts where the first one ended, or a column is drawn twice"
19852        );
19853        assert_eq!(
19854            (left.width + right.width, left.height, right.height),
19855            (gathered.0, gathered.1, gathered.1),
19856            "the two rectangles have to cover the gather extent {gathered:?} exactly"
19857        );
19858        assert!(
19859            left.width < gathered.0 && right.width < gathered.0,
19860            "one half covers the whole extent, so the other draws over it and the seam is a \
19861             rectangle that crops nothing"
19862        );
19863        assert_ne!(
19864            compared[0].1, compared[1].1,
19865            "the two marches bound one group, so they cannot be reading two blocks"
19866        );
19867
19868        // How far the reference backend can follow the far side. It will say
19869        // what bytes a buffer holds and it will not say which buffer a group
19870        // names, so the two together are "there are two blocks, and they differ
19871        // by the knob that was moved" — not "the right march read the right
19872        // one". Pointing both marches at one buffer still passes; see this
19873        // module's entry in `docs/backlog.md`.
19874        assert_eq!(
19875            uncompared_console, uncompared_shipped,
19876            "the console sat at its defaults and the two blocks still differ, so the seam's far \
19877             side is not this frame with the shipped scalars — it is another frame"
19878        );
19879        assert_ne!(
19880            compared_console, compared_shipped,
19881            "one slice count was moved off the shipped one and both blocks still hold the same \
19882             bytes, so a comparison shows the same picture twice"
19883        );
19884
19885        recorder.assert_valid();
19886    }
19887
19888    /// Every gather pipeline the frame bound, in the order the marches ran.
19889    ///
19890    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
19891    /// `marches` closure asking the other question of the same stream: that one
19892    /// reads the scissor and the group, and this one reads the pipeline. Only
19893    /// the `ssao` and `ssao-shipped` passes are looked at, because every other
19894    /// pass in the chain binds a pipeline too and a filter over the whole stream
19895    /// would be counting blurs.
19896    ///
19897    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
19898    fn gathers_bound(recorder: &Recorder, from: usize) -> Vec<crcbl_hal::GraphicsPipelineHandle> {
19899        use crcbl_hal::null::Command;
19900
19901        let mut inside = false;
19902        let mut found = Vec::new();
19903        for command in &recorder.commands()[from..] {
19904            if let Some((_, label)) = command.opens_pass() {
19905                inside = matches!(label, Some("ssao" | "ssao-shipped"));
19906                continue;
19907            }
19908            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19909                inside = false;
19910                continue;
19911            }
19912            if let (true, Command::BindGraphicsPipeline(pipeline)) = (inside, command) {
19913                found.push(*pipeline);
19914            }
19915        }
19916        found
19917    }
19918
19919    /// **`r_ssao_technique` decides which shader the gather runs**, read off the
19920    /// pipeline the `ssao` pass bound.
19921    ///
19922    /// The observable `docs/backlog.md` says the uniform block cannot have. The
19923    /// reference backend records a bind group as a handle and a layout rather
19924    /// than as the resources behind it, so nothing can ask which *block* a march
19925    /// read — but a pipeline is recorded as itself, so which *technique* a march
19926    /// ran is a question this backend answers. `Ssao::gathers` is what names the
19927    /// two, so this is an equality against the pipeline built from each shader
19928    /// rather than an inequality that any two handles would satisfy.
19929    ///
19930    /// **The default arm is the load-bearing half.** A selector that read the
19931    /// wrong variable, or a `pipeline_for` whose arms were swapped, would still
19932    /// change the frame when the console moved; what would go with it is every
19933    /// golden in this workspace, which is blessed on the technique that ships.
19934    ///
19935    /// Holds [`ssao_blur_switch`] for its own reason and
19936    /// [`ssao_technique_switch`] third, after it and [`ssao_split_switch`] —
19937    /// see `crate::ssao::TECHNIQUE_SWITCH` on the order.
19938    #[test]
19939    fn the_occlusion_technique_picks_the_gathers_pipeline() {
19940        let _blurs = ssao_blur_switch();
19941        let _seam = ssao_split_switch();
19942        let technique = ssao_technique_switch();
19943        // The name to move to, taken out of the variable's own set — see
19944        // `other_technique_name`.
19945        let other = other_technique_name();
19946
19947        let (recorder, device, queue) = open();
19948        let device = device.as_ref();
19949        let mut renderer =
19950            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19951        let (ships, cheap) = renderer
19952            .primary
19953            .ssao
19954            .as_ref()
19955            .expect("the default stack builds the occlusion pair")
19956            .gathers();
19957        assert_ne!(
19958            ships, cheap,
19959            "the renderer built one gather pipeline for both techniques, so nothing below can \
19960             tell them apart"
19961        );
19962
19963        let shipped = frame_seen_from(
19964            device,
19965            &mut renderer,
19966            queue,
19967            &Camera::default(),
19968            &DirectionalLight::default(),
19969        );
19970        let by_default = gathers_bound(&recorder, 0);
19971        let after = recorder.commands().len();
19972        shipped.release(device);
19973
19974        technique.set(other);
19975        let moved_frame = frame_seen_from(
19976            device,
19977            &mut renderer,
19978            queue,
19979            &Camera::default(),
19980            &DirectionalLight::default(),
19981        );
19982        let moved = gathers_bound(&recorder, after);
19983        moved_frame.finish(device, renderer);
19984
19985        assert_eq!(
19986            by_default,
19987            vec![ships],
19988            "a frame nobody has touched the console on gathered through something other than \
19989             `ssao.slang`'s pipeline, which is what every golden in this workspace was blessed on"
19990        );
19991        assert_eq!(
19992            moved,
19993            vec![cheap],
19994            "`r_ssao_technique {other}` left the frame gathering through the pipeline \
19995             it gathered through before, so the selector reaches nothing"
19996        );
19997        recorder.assert_valid();
19998    }
19999
20000    /// **The comparison seam's two marches run two techniques**, which is what
20001    /// the seam was built for.
20002    ///
20003    /// Alcove's second milestone is SSAO and GTAO in
20004    /// one frame, and this is that claim as a pair of pipeline handles: with the
20005    /// technique moved the near side runs the cheap tier and the far side the
20006    /// one that ships, and with it at its default both marches run the same
20007    /// shader and the seam separates nothing.
20008    ///
20009    /// **The control is the frame at the default**, and it is what makes the
20010    /// first half mean anything: a far side that always ran `ssao.slang` would
20011    /// satisfy the inequality below whatever `shipped_technique` did, and a
20012    /// chain that had simply forgotten to pass the far side a pipeline of its
20013    /// own would too.
20014    #[test]
20015    fn the_comparison_seam_marches_through_two_techniques() {
20016        let _blurs = ssao_blur_switch();
20017        let seam = ssao_split_switch();
20018        let technique = ssao_technique_switch();
20019        let other = other_technique_name();
20020
20021        let (recorder, device, queue) = open();
20022        let device = device.as_ref();
20023        let mut renderer =
20024            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20025        let (ships, cheap) = renderer
20026            .primary
20027            .ssao
20028            .as_ref()
20029            .expect("the default stack builds the occlusion pair")
20030            .gathers();
20031
20032        seam.set(0.5);
20033        let compared = frame_seen_from(
20034            device,
20035            &mut renderer,
20036            queue,
20037            &Camera::default(),
20038            &DirectionalLight::default(),
20039        );
20040        let one_technique = gathers_bound(&recorder, 0);
20041        let after = recorder.commands().len();
20042        compared.release(device);
20043
20044        technique.set(other);
20045        let frame = frame_seen_from(
20046            device,
20047            &mut renderer,
20048            queue,
20049            &Camera::default(),
20050            &DirectionalLight::default(),
20051        );
20052        let two_techniques = gathers_bound(&recorder, after);
20053        frame.finish(device, renderer);
20054
20055        assert_eq!(
20056            one_technique,
20057            vec![ships, ships],
20058            "a seam with the technique at its default has to march the shipped gather twice — \
20059             both sides read `shipped`'s configuration, and the picture is one technique either \
20060             side of a line"
20061        );
20062        assert_eq!(
20063            two_techniques,
20064            vec![cheap, ships],
20065            "with `r_ssao_technique {other}` the near side has to run the cheap tier \
20066             and the far side what ships; the far side follows the variable's *default*, exactly \
20067             as the four scalars do"
20068        );
20069        recorder.assert_valid();
20070    }
20071
20072    /// **The frame block carries the console's shadow filter on the near side
20073    /// of the seam, the shipped one on the far side, and the column
20074    /// [`crate::split::halves`] counted.**
20075    ///
20076    /// [`the_comparison_seam_marches_through_two_techniques`]'s claim for the
20077    /// other seam, and it has to be a claim about *bytes* rather than about
20078    /// pass handles: the occlusion chain compares two pipelines and this
20079    /// compares two arms of one, so there is nothing in the pass list to look
20080    /// at. What a person sees is decided entirely by the row this asserts.
20081    ///
20082    /// **The frame at the default is the control**, and it is what makes the
20083    /// rest mean anything: a block that always wrote the shipped filter into
20084    /// both lanes would satisfy the third case's far side whatever
20085    /// `shipped_filter` did, and one that copied the near lane into the far one
20086    /// would satisfy the first two.
20087    ///
20088    /// The column is compared against `halves`' own answer rather than against
20089    /// a number written here, which is the seam module's whole point: a test
20090    /// that multiplied the fraction by the width itself would be a second
20091    /// opinion about the rounding, and the floor is exactly what that module's
20092    /// `the_seam_takes_the_floor_of_the_column_it_asks_for` exists to pin.
20093    ///
20094    /// [`the_comparison_seam_marches_through_two_techniques`]: fn@the_comparison_seam_marches_through_two_techniques
20095    #[test]
20096    fn the_frame_block_carries_a_shadow_filter_for_each_side_of_the_seam() {
20097        let switch = shadow_filter_switch();
20098
20099        let (recorder, device, queue) = open();
20100        let device = device.as_ref();
20101        let mut renderer =
20102            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20103
20104        // The seam is counted over the extent the scene is *drawn* at, which is
20105        // what `SV_Position.x` is denominated in — not the caller's window.
20106        let internal = renderer.internal_extent(TEST_EXTENT);
20107        let (left, _) = crate::split::halves(internal, 0.5).expect("a seam down the middle");
20108        assert!(
20109            left.width > 0,
20110            "a seam with no columns on one side would make every assertion below hold of a \
20111             frame that compares nothing"
20112        );
20113
20114        let ships = shadow::shipped_filter();
20115        let other = shadow::Filter::Box;
20116        assert_ne!(
20117            other.mode(),
20118            ships.mode(),
20119            "the filter this test moves the console to is the one that ships, so the seam it \
20120             asks for compares one kernel against itself"
20121        );
20122
20123        let draw = |renderer: &mut ForwardRenderer| {
20124            renderer
20125                .begin_frame(
20126                    device,
20127                    &Camera::default(),
20128                    &DirectionalLight::default(),
20129                    TEST_EXTENT,
20130                )
20131                .expect("write");
20132            let bytes = recorder
20133                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
20134                .expect("this frame's uniform block is live");
20135            let at = mesh::FRAME_UNIFORMS_SIZE - 16;
20136            core::array::from_fn(|lane| {
20137                u32::from_le_bytes(
20138                    bytes[at + lane * 4..at + lane * 4 + 4]
20139                        .try_into()
20140                        .expect("four bytes"),
20141                )
20142            })
20143        };
20144
20145        let shipped: [u32; 4] = draw(&mut renderer);
20146        assert_eq!(
20147            shipped,
20148            [ships.mode(), ships.mode(), 0, 0],
20149            "a frame nobody has touched the console on must carry the shipped filter in both \
20150             lanes and no column, which is the row every golden in this workspace was blessed \
20151             under"
20152        );
20153
20154        switch.filter(other);
20155        let unsplit: [u32; 4] = draw(&mut renderer);
20156        assert_eq!(
20157            unsplit,
20158            [other.mode(), other.mode(), 0, 0],
20159            "`r_shadow_filter {}` with no seam has to reach every pixel, so both lanes carry it",
20160            other.label()
20161        );
20162
20163        switch.seam(0.5);
20164        let compared: [u32; 4] = draw(&mut renderer);
20165        assert_eq!(
20166            compared,
20167            [other.mode(), ships.mode(), left.width, 0],
20168            "a seam at 0.5 has to put the console's filter left of `halves`' column and the \
20169             shipped one right of it; the far side follows the variable's *default*, exactly \
20170             as the occlusion chain's does"
20171        );
20172
20173        renderer.destroy(device);
20174        recorder.assert_valid();
20175    }
20176
20177    #[test]
20178    fn a_second_occlusion_blur_is_a_pass_the_frame_records() {
20179        let switch = ssao_blur_switch();
20180
20181        let (recorder, device, queue) = open();
20182        let device = device.as_ref();
20183        let mut renderer =
20184            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20185        let imported = swapchain_image(device);
20186        let pool = crate::TransientPool::new();
20187
20188        let once = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20189        let counted_once = renderer.counters().instances;
20190        assert!(
20191            once.contains(&"ssao-blur".to_string()),
20192            "the shipping frame has to blur once, or the arm below is about a frame with no \
20193             occlusion in it at all: {once:#?}"
20194        );
20195        assert!(
20196            !once.contains(&"ssao-blur-2".to_string()),
20197            "a frame nobody moved the switch for must record one blur: {once:#?}"
20198        );
20199
20200        switch.set(2);
20201        let twice = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20202        let counted_twice = renderer.counters().instances;
20203        assert!(
20204            twice.contains(&"ssao-blur-2".to_string()),
20205            "`r_ssao_blur_passes 2` must put a second blur in the frame: {twice:#?}"
20206        );
20207        assert_eq!(
20208            twice.len(),
20209            once.len() + 1,
20210            "the second blur is the only pass that may join the frame: {twice:#?}"
20211        );
20212        assert_eq!(
20213            counted_twice,
20214            counted_once + FULLSCREEN_DRAWS,
20215            "the frame recorded a full-screen triangle its counter did not report"
20216        );
20217
20218        // The pass has to write somewhere the forward pass then reads, and the
20219        // graph is what would refuse a frame that bound an image nothing wrote.
20220        // `passes_in_a_frame` compiles rather than executes, so this is the
20221        // check that the third transient was requested at all.
20222        assert!(
20223            twice.iter().any(|pass| pass == "forward"),
20224            "the frame still has to reach its forward pass: {twice:#?}"
20225        );
20226        recorder.assert_valid();
20227    }
20228
20229    /// Every host-written buffer at the end of a whole ring of frames, keyed by
20230    /// the handle written and holding what that handle last held.
20231    ///
20232    /// A whole ring rather than one frame, because the blocks a frame writes are
20233    /// themselves rings — a buffer per frame in flight, [`Ssao`]'s among them —
20234    /// so one frame touches one slot of each and two single-frame batches would
20235    /// be comparing different buffers. A ring writes every slot, so two batches'
20236    /// keys line up and a difference between them is a difference in *bytes*.
20237    ///
20238    /// Only the events this call appends are read, so a caller can take one
20239    /// batch after another off the same recorder.
20240    fn host_buffers_over_a_ring(
20241        recorder: &Recorder,
20242        device: &dyn Device,
20243        renderer: &mut ForwardRenderer,
20244        queue: QueueHandle,
20245    ) -> std::collections::BTreeMap<u64, Vec<u8>> {
20246        let from = recorder.events().len();
20247        for _ in 0..FRAMES_IN_FLIGHT {
20248            frame(device, renderer, queue).release(device);
20249        }
20250        recorder.events()[from..]
20251            .iter()
20252            .filter_map(|event| match event {
20253                Event::BufferWritten { buffer, .. } => Some(*buffer),
20254                _ => None,
20255            })
20256            .map(|buffer| {
20257                let bytes = recorder
20258                    .buffer_bytes(buffer)
20259                    .expect("the stream only names buffers this recorder created");
20260                (buffer.to_bits(), bytes)
20261            })
20262            .collect()
20263    }
20264
20265    /// **`r_ssao_slices` reaches the block `ssao.slang` reads, on every frame of
20266    /// the ring, and moves nothing else in the frame.**
20267    ///
20268    /// The device test drives the two occlusion pipelines directly and
20269    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] moves the *blur*
20270    /// count, so until this the slice count was a variable with a `get_i64` and
20271    /// no evidence that a rendered frame ever carried it: `slice_count` could
20272    /// have returned its default unconditionally and every check in this
20273    /// workspace would still be green.
20274    ///
20275    /// So the observable is the bytes, taken off the null recorder's write log
20276    /// after a whole ring of frames at each setting and compared **by handle**.
20277    /// Two claims come out of that comparison and both are load-bearing:
20278    ///
20279    /// * **Some block moved** — every ring slot, in fact, which is what says the
20280    ///   count reaches the frame at all rather than only the slot the last frame
20281    ///   happened to land in.
20282    /// * **Every block that moved, moved only there.** A frame is a few dozen
20283    ///   host writes and the slice count has business with exactly one word of
20284    ///   one of them; a setting that perturbed a matrix, an instance or a shadow
20285    ///   view would be drawing a different frame for a reason nobody asked for,
20286    ///   and the "at least one differs" half alone would pass on it happily.
20287    ///
20288    /// **Holds every switch whose row is in a block it compares**, in the lock
20289    /// order: the two batches are compared byte for byte over every host
20290    /// buffer the frame writes, so any console row another test moves between
20291    /// them — the blur count, the seam, the technique, the shadow filter, or
20292    /// `crate::ssao`'s own mover of the params block — reads here as "some
20293    /// other write moving". [`ssao_technique_switch`] is the one that
20294    /// serialises against that mover.
20295    #[test]
20296    fn four_slices_reach_the_frame_the_shader_reads() {
20297        let _blurs = ssao_blur_switch();
20298        let _seam = ssao_split_switch();
20299        let switch = ssao_slice_switch();
20300        let _technique = ssao_technique_switch();
20301        let _filter = shadow_filter_switch();
20302
20303        let (recorder, device, queue) = open();
20304        let device = device.as_ref();
20305        let mut renderer =
20306            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20307
20308        // A ring rendered before either batch is taken, because the two below
20309        // are compared by handle and the renderer's opening frame writes blocks
20310        // no later frame writes again: it fills a cold shadow atlas, so the
20311        // shadow views' uniform blocks and the draw-generation blocks of the
20312        // cascades that were drawn are written once and never again while the
20313        // cache holds. Those would be in the first batch and missing from the
20314        // second, and a key that is only in one of them is a difference this
20315        // test cannot say anything about.
20316        for _ in 0..FRAMES_IN_FLIGHT {
20317            frame(device, &mut renderer, queue).release(device);
20318        }
20319        let shipping = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
20320        switch.set(i64::from(ssao::SLICE_COUNT_MAX));
20321        let asked = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
20322        assert_eq!(
20323            shipping.keys().collect::<Vec<_>>(),
20324            asked.keys().collect::<Vec<_>>(),
20325            "the two batches must write the same buffers, or they are not comparable",
20326        );
20327
20328        // Which bytes moving the count alone is allowed to move, asked of
20329        // `SsaoParams::to_bytes` rather than written here as an offset: the
20330        // block's layout is `crcbl_shaders::ssao`'s, and a field inserted ahead
20331        // of the count would leave a number spelled here pointing at the radius.
20332        let block_of = |slices| {
20333            ssao::SsaoParams {
20334                inv_proj: [0.0; 16],
20335                proj: [0.0; 16],
20336                inv_view: [0.0; 16],
20337                radius: 0.0,
20338                slices,
20339                intensity: ssao::INTENSITY_DEFAULT,
20340                bent_normals: crate::ssao::bent_normals(),
20341            }
20342            .to_bytes()
20343        };
20344        let at_shipping = block_of(ssao::SLICE_COUNT_DEFAULT);
20345        let at_max = block_of(ssao::SLICE_COUNT_MAX);
20346        let count_word: Vec<usize> = (0..ssao::PARAMS_SIZE)
20347            .filter(|at| at_shipping[*at] != at_max[*at])
20348            .collect();
20349
20350        let mut moved = 0;
20351        for (handle, before) in &shipping {
20352            let after = &asked[handle];
20353            if before == after {
20354                continue;
20355            }
20356            moved += 1;
20357            let mut only_the_count = before.clone();
20358            for at in &count_word {
20359                assert_eq!(
20360                    before[*at], at_shipping[*at],
20361                    "buffer {handle} differs between the batches but did not go in holding the \
20362                     shipping slice count, so this is some other write moving",
20363                );
20364                only_the_count[*at] = at_max[*at];
20365            }
20366            assert_eq!(
20367                after, &only_the_count,
20368                "buffer {handle} moved somewhere other than the slice count's word: the setting \
20369                 is perturbing a block it has no business in",
20370            );
20371        }
20372        assert_eq!(
20373            moved, FRAMES_IN_FLIGHT,
20374            "`r_ssao_slices 4` must reach every slot of the occlusion ring; a count that moved \
20375             none of them is a console variable no rendered frame reads",
20376        );
20377
20378        renderer.destroy(device);
20379        recorder.assert_valid();
20380    }
20381
20382    /// **The debug draw layer costs a frame nothing until something is appended
20383    /// *and* the console switch is on, and then it is the pass immediately
20384    /// before the tonemap.**
20385    ///
20386    /// Four claims, and each is a separate way to get this wrong.
20387    ///
20388    /// * **Off by default** is what keeps every golden image in the workspace
20389    ///   where it was blessed.
20390    /// * **A segment appended while the switch is off records nothing**, so a
20391    ///   system may append unconditionally.
20392    /// * **The switch on with an empty buffer records nothing either** — this is
20393    ///   the "costs nothing when empty" claim as a check rather than a sentence:
20394    ///   the compiled pass list is compared whole against the frame drawn before
20395    ///   the layer was switched on, so a pass that clears, blits or barriers
20396    ///   anything would show up here.
20397    /// * **Before the tonemap**, which is
20398    ///   `docs/plan/18-render-features.md`'s interaction rule and the opposite of
20399    ///   the ground grid above. Recorded a line later it would draw into the
20400    ///   display-space target and be free of the exposure, which compiles and
20401    ///   draws lines and is the wrong picture.
20402    ///
20403    /// And the fifth, which is what "immediate mode" means: the frame *after*
20404    /// the one that appended records nothing again, because
20405    /// [`ForwardRenderer::begin_frame`] cleared the buffer.
20406    ///
20407    /// The whole list is compared rather than its length, for the ground grid
20408    /// test's reason: one more pass is satisfied by gaining the wrong one.
20409    ///
20410    /// **This test owns `r_debug_draw` for its duration**, through
20411    /// [`debug_draw_switch`]: a plain `cargo test` run shares one process
20412    /// between tests, so the two checks here that move it have to take turns.
20413    /// `cargo nextest`, which CI runs, gives each a process of its own and needs
20414    /// none of it.
20415    #[test]
20416    fn the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap() {
20417        let switch = debug_draw_switch();
20418        let _blurs = ssao_blur_switch();
20419
20420        let (recorder, device, queue) = open();
20421        let device = device.as_ref();
20422        let mut renderer =
20423            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20424        let imported = swapchain_image(device);
20425        let mut pool = crate::TransientPool::new();
20426
20427        assert!(
20428            !crate::DebugDraw::enabled(),
20429            "the layer must be off before anything switches it on, or every claim below is \
20430             about a different default"
20431        );
20432        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20433        assert!(
20434            !off.contains(&"debug-draw".to_string()),
20435            "the layer must not be in a frame nobody switched it on for: {off:#?}"
20436        );
20437
20438        renderer
20439            .debug_draw()
20440            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20441        assert_eq!(
20442            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20443            off,
20444            "a segment appended while the switch is off must record no pass"
20445        );
20446
20447        switch.set(true);
20448        assert_eq!(
20449            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20450            off,
20451            "the switch on with an empty buffer must record the frame the layer's absence would"
20452        );
20453
20454        renderer
20455            .debug_draw()
20456            .aabb(-Vec3::ONE, Vec3::ONE, [0.0, 1.0, 0.0, 1.0]);
20457        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20458        let mut expected = off.clone();
20459        let tonemap = expected
20460            .iter()
20461            .position(|label| label == "tonemap")
20462            .expect("a frame has to reach the swapchain");
20463        expected.insert(tonemap, "debug-draw".to_string());
20464        assert_eq!(
20465            on, expected,
20466            "the layer must be the one pass gained, and it must sit before the tonemap"
20467        );
20468
20469        assert_eq!(
20470            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20471            off,
20472            "the buffer is immediate mode: the frame after the one that appended must record \
20473             nothing"
20474        );
20475
20476        switch.set(false);
20477        renderer.destroy(device);
20478        pool.destroy(device);
20479        device.destroy_image_view(imported.view);
20480        device.destroy_image(imported.image);
20481        recorder.assert_valid();
20482    }
20483
20484    /// **The debug draw layer's own call is counted in the frame's draws.**
20485    ///
20486    /// [`ForwardRenderer::counters`]' draw count is compared against the
20487    /// commands the null backend actually recorded, which is the same instrument
20488    /// `the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know`
20489    /// uses — so a layer whose line list was recorded and not counted fails here
20490    /// rather than quietly making every panel's draw row one short.
20491    ///
20492    /// Both directions are asserted: the frame that drew a segment records one
20493    /// more draw than the frame before it, *and* the counter moved by the same
20494    /// one. A count wired to a constant satisfies neither.
20495    ///
20496    /// It owns `r_debug_draw` for its duration, on
20497    /// `the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap`'s
20498    /// terms.
20499    #[test]
20500    fn the_debug_draw_layers_call_is_counted_in_the_frames_draws() {
20501        let switch = debug_draw_switch();
20502        let _blurs = ssao_blur_switch();
20503
20504        let (recorder, device, queue) = open();
20505        let device = device.as_ref();
20506        let mut renderer =
20507            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20508
20509        // A different sun in each of the two frames, so both of them redraw the
20510        // shadow atlas: the claim below is that the layer's own call is the one
20511        // draw the second frame gained, and a second frame that cached its
20512        // atlas would have lost the atlas's draws at the same time. See
20513        // [`moving_sun`].
20514        let quiet = frame_moving_the_sun(device, &mut renderer, queue, 0);
20515        let without = renderer.counters().draws;
20516        assert_eq!(
20517            without,
20518            recorded_draws(&recorder) as u64,
20519            "the counter and the frame's recorded draws disagree before the layer draws at all"
20520        );
20521        quiet.release(device);
20522
20523        switch.set(true);
20524        renderer
20525            .debug_draw()
20526            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20527        let drawn = frame_moving_the_sun(device, &mut renderer, queue, 1);
20528        let with = renderer.counters().draws;
20529        assert_eq!(
20530            with,
20531            without + 1,
20532            "the layer records one draw, so the count has to move by one"
20533        );
20534        assert_eq!(
20535            recorded_draws(&recorder) as u64,
20536            without + with,
20537            "the two frames' recorded draws and the two counts disagree, so the layer's call is \
20538             counted somewhere it was not recorded or recorded somewhere it was not counted"
20539        );
20540
20541        switch.set(false);
20542        drawn.finish(device, renderer);
20543        recorder.assert_valid();
20544    }
20545
20546    /// **The depth-only passes run the depth-only entry point, and the colour
20547    /// pass does not.**
20548    ///
20549    /// Topic 43 §2 split the vertex pool so a pass
20550    /// that wants a clip position and no more could fetch stream 0 alone, and
20551    /// [`MeshModules::depth_pipeline`] naming `mesh.slang`'s `depthVertexMain`
20552    /// is the whole of how that split is spent. **Nothing else in the tree sees
20553    /// it.** `crcbl_shaders::mesh`'s
20554    /// `the_depth_entry_point_fetches_the_position_stream_alone` reads the
20555    /// compiled artifact and would pass with the entry point built and unused;
20556    /// no golden moves, because the two stages compute the same clip position on
20557    /// purpose; the render graph records a legal frame either way; and the
20558    /// measured price says nothing — pointing this pipeline back at `vertexMain`
20559    /// cost the depth prepass about a tenth more on lavapipe and nothing to
20560    /// three figures on an RX 7900 XTX, measured 2026-08-31. So the wiring is
20561    /// asserted here, against the reference backend, which records the entry
20562    /// point a pipeline names precisely so this question has an answer.
20563    ///
20564    /// **Both halves, so the check is shown to discriminate.** A lookup that
20565    /// answered `depthVertexMain` for every pipeline would satisfy the first
20566    /// assertion alone, and the colour pipeline is the one that must *not* have
20567    /// moved. The labels are the descriptors' own and are what the two are told
20568    /// apart by, so a renamed pipeline fails at the `expect` rather than
20569    /// silently matching nothing.
20570    #[test]
20571    fn the_depth_pipeline_names_the_depth_only_vertex_stage_and_the_colour_one_does_not() {
20572        let (recorder, device, queue) = open();
20573        let device = device.as_ref();
20574        // A masked row, so the build compiles the cutout shape the third
20575        // assertion reads — a scene that masks nothing gets none.
20576        let mut scene = scene::demo();
20577        scene.materials[DEMO_UNTINTED].flags = mesh::GpuMaterial::ALPHA_MODE_MASK;
20578        let renderer = ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
20579            .expect("built");
20580        // A mesh stage has no vertex entry point to name, and this whole rung is
20581        // about the raster arm — see [`MeshModules::depth_pipeline`]. The null
20582        // preset reports no `Features::MESH_SHADER`, so this is what it built;
20583        // asserted rather than assumed, because a preset that grew the feature
20584        // would leave every assertion below looking for pipelines that do not
20585        // exist.
20586        assert_ne!(
20587            renderer.geometry_path(),
20588            crcbl_hal::GeometryPath::MeshShader,
20589            "this device built a mesh-shader path, whose geometry stage names no vertex \
20590             entry point at all"
20591        );
20592
20593        let pipelines = recorder.graphics_pipeline_vertex_entries();
20594        let entry_of = |label: &str| -> String {
20595            let found: Vec<&str> = pipelines
20596                .iter()
20597                .filter(|(name, _)| name.as_deref() == Some(label))
20598                .map(|(_, entry)| entry.as_str())
20599                .collect();
20600            assert_eq!(
20601                found.len(),
20602                1,
20603                "the renderer built {} pipeline(s) labelled `{label}`, out of {pipelines:?}",
20604                found.len()
20605            );
20606            found[0].to_owned()
20607        };
20608
20609        assert_eq!(
20610            entry_of("shadow cascade"),
20611            "depthVertexMain",
20612            "the shadow atlas and the depth prepass share this pipeline, and it is the one \
20613             that reads the position stream alone"
20614        );
20615        assert_eq!(
20616            entry_of("forward mesh"),
20617            "vertexMain",
20618            "the colour pass needs every attribute the depth pass skips, so it is the entry \
20619             point that reads a whole vertex"
20620        );
20621        assert_eq!(
20622            entry_of("shadow cascade masked"),
20623            "vertexMain",
20624            "the cutout twin has to read a whole vertex: the UV it samples the mask from lives \
20625             in the attribute region `depthVertexMain` exists not to read"
20626        );
20627
20628        renderer.destroy(device);
20629        recorder.assert_valid();
20630    }
20631
20632    /// **A masked material moves that mesh's depth draws onto the cutout
20633    /// pipeline, and moves nothing else.**
20634    ///
20635    /// The mechanism is which pipeline handle the recorded stream binds and
20636    /// which buckets' indirect calls follow each bind — the wireframe test's
20637    /// observable, for the same reason: a field saying a mode was read would
20638    /// prove the flag was read, not that the frame changed.
20639    ///
20640    /// Four claims, and each rules out a different way of passing wrongly:
20641    ///
20642    /// * a scene with nothing masked binds the vertex-only pipeline and
20643    ///   **never** the cutout one, which is the "an opaque frame costs what it
20644    ///   always did" claim at the level a null device can see it;
20645    /// * a scene with one masked row binds **both** in the depth prepass and
20646    ///   both in the shadow atlas — a per-frame choice binds one or the other,
20647    ///   never the pair;
20648    /// * the calls following each bind are exactly that mode's buckets, in
20649    ///   bucket order, read off the argument offsets the draws name. A split
20650    ///   that bound both pipelines and drew every bucket under each would
20651    ///   satisfy the claim above and double the frame's draws;
20652    /// * and folding the two handles together — then collapsing the runs of
20653    ///   equal binds the fold creates — leaves the two frames' bind streams
20654    ///   **equal**, so the colour pass, the tile clears and the reflective
20655    ///   shadow map are all where they were. A change that had also moved the
20656    ///   colour pass would satisfy the first three and fail this.
20657    ///
20658    /// The two scenes differ in one flags word and nothing else.
20659    #[test]
20660    fn a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline() {
20661        use crcbl_hal::null::Command;
20662
20663        // The occlusion blur count is a process-global console variable and a
20664        // frame binds one pipeline per blur, so a concurrent test moving it
20665        // would put a bind in one of these frames and not the other — the
20666        // wireframe test's hazard exactly.
20667        let _blurs = ssao_blur_switch();
20668
20669        let masked_scene = {
20670            let mut scene = crate::scene::demo();
20671            scene.materials[DEMO_UNTINTED].flags =
20672                crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
20673            scene
20674        };
20675
20676        /// What one scene's frame reveals: the bucket count and each bucket's
20677        /// mode, how often each depth pipeline was bound, the (pipeline, bucket)
20678        /// pairs the depth prepass and the shadow atlas recorded, and the whole
20679        /// bind stream with the two depth handles folded into one.
20680        struct Recorded {
20681            modes: Vec<u32>,
20682            cutouts: usize,
20683            plains: usize,
20684            prepass: Vec<(bool, u32)>,
20685            atlas: Vec<(bool, u32)>,
20686            folded: Vec<String>,
20687        }
20688
20689        // One frame each, from two renderers rather than two frames from one:
20690        // a bucket table is fixed at build, and two builds keep the frames'
20691        // shadow-atlas state identical — both are a first frame.
20692        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20693            let (recorder, device, queue) = open();
20694            let device = device.as_ref();
20695            let mut renderer =
20696                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20697                    .expect("the null backend accepts the demo description");
20698            place_cube(&mut renderer, Mat4::IDENTITY);
20699            let imported = swapchain_image(device);
20700            let mut pool = crate::TransientPool::new();
20701            renderer
20702                .begin_frame(
20703                    device,
20704                    &Camera::default(),
20705                    &DirectionalLight::default(),
20706                    (64, 48),
20707                )
20708                .expect("write");
20709            let mut graph = crate::RenderGraph::new(queue);
20710            let target = graph.import_image("target", imported);
20711            renderer.add_passes(&mut graph, &pool, target, (64, 48));
20712            let compiled = graph.compile(&pool).expect("a legal frame");
20713            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20714                label: Some("alpha mask lap"),
20715                queue,
20716            });
20717            compiled
20718                .execute(device, &mut pool, encoder.as_mut(), None)
20719                .expect("the graph executed");
20720            encoder.finish().expect("recording succeeded");
20721            let plain = renderer.shadow_pipeline.single;
20722            // `None` for the opaque scene, which builds no cutout shape at all
20723            // and so can bind none — the comparisons below read it as such.
20724            let cutout = renderer.depth_masked_pipeline.map(|masked| masked.single);
20725            assert_ne!(
20726                Some(plain),
20727                cutout,
20728                "the two depth pipelines have to be two objects, or nothing below discriminates"
20729            );
20730            // Which bucket a draw is, recovered from the argument offset it
20731            // names — the offsets are the renderer's own accessor, so a call
20732            // pointing at the wrong bucket has no entry here at all.
20733            let bucket_of = |args_offset: u64| -> u32 {
20734                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
20735                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
20736                    .unwrap_or_else(|| {
20737                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
20738                    })
20739            };
20740            // Per depth pass: the pipeline in force at each indirect call and
20741            // the bucket that call drew, in the order they were recorded.
20742            let pass_calls = |label: &str| -> Vec<(bool, u32)> {
20743                let mut current = None;
20744                let mut out = Vec::new();
20745                for command in commands_in_pass(&recorder, label) {
20746                    match command {
20747                        Command::BindGraphicsPipeline(handle) => current = Some(handle),
20748                        Command::DrawIndexedIndirectCount(draw) => {
20749                            let handle = current.expect("a draw follows a pipeline bind");
20750                            assert!(
20751                                handle == plain || Some(handle) == cutout,
20752                                "a depth pass drew under a pipeline that is neither depth one"
20753                            );
20754                            out.push((Some(handle) == cutout, bucket_of(draw.args_offset)));
20755                        }
20756                        _ => {}
20757                    }
20758                }
20759                out
20760            };
20761            let prepass = pass_calls("depth-prepass");
20762            let atlas = pass_calls("shadow");
20763            let binds: Vec<GraphicsPipelineHandle> = recorder
20764                .commands()
20765                .iter()
20766                .filter_map(|command| match command {
20767                    Command::BindGraphicsPipeline(handle) => Some(*handle),
20768                    _ => None,
20769                })
20770                .collect();
20771            let cutouts = binds
20772                .iter()
20773                .filter(|handle| Some(**handle) == cutout)
20774                .count();
20775            let plains = binds.iter().filter(|handle| **handle == plain).count();
20776            let labels = graphics_pipeline_labels(&recorder);
20777            let mut folded: Vec<String> = Vec::with_capacity(binds.len());
20778            for handle in binds {
20779                let handle = if Some(handle) == cutout {
20780                    plain
20781                } else {
20782                    handle
20783                };
20784                let handle = labels[handle.index() as usize].clone();
20785                // The fold turns the masked frame's `plain, cutout` pair into
20786                // `plain, plain`; collapsing a run of equal binds is what makes
20787                // the two streams comparable without hiding a bind of anything
20788                // else, since no pass in either frame binds two *different*
20789                // pipelines that the fold could bring together.
20790                if folded.last() != Some(&handle) {
20791                    folded.push(handle);
20792                }
20793            }
20794            let modes = renderer.bucket_modes.clone();
20795            renderer.destroy(device);
20796            recorder.assert_valid();
20797            Recorded {
20798                modes,
20799                cutouts,
20800                plains,
20801                prepass,
20802                atlas,
20803                folded,
20804            }
20805        };
20806
20807        let opaque = bound(&crate::scene::demo());
20808        let masked = bound(&masked_scene);
20809
20810        assert_eq!(
20811            opaque.cutouts, 0,
20812            "a scene with nothing masked must never bind the cutout pipeline"
20813        );
20814        assert!(
20815            opaque.plains > 0,
20816            "a scene with nothing masked must bind the vertex-only pipeline, or the assertion \
20817             above is about a frame with no depth pass in it"
20818        );
20819        assert!(
20820            opaque.modes.iter().all(|mode| *mode == 0),
20821            "and every one of its buckets is opaque: {:?}",
20822            opaque.modes
20823        );
20824        assert_eq!(
20825            opaque.prepass.iter().filter(|(cutout, _)| *cutout).count(),
20826            0,
20827            "so no opaque draw is recorded under the cutout pipeline"
20828        );
20829
20830        assert!(
20831            masked.cutouts > 0 && masked.plains > 0,
20832            "a masked scene must bind **both** depth pipelines — {} cutout and {} plain — or \
20833             the choice is still per frame",
20834            masked.cutouts,
20835            masked.plains
20836        );
20837        // What each depth pass should have recorded: every opaque bucket under
20838        // the plain pipeline in bucket order, then every masked one under the
20839        // cutout, which is the partition order `depth_partitions` lays down.
20840        let want: Vec<(bool, u32)> = [false, true]
20841            .into_iter()
20842            .flat_map(|cutout| {
20843                masked
20844                    .modes
20845                    .iter()
20846                    .enumerate()
20847                    .filter(move |(_, mode)| {
20848                        (**mode == crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK) == cutout
20849                    })
20850                    .map(move |(bucket, _)| (cutout, u32::try_from(bucket).expect("a few buckets")))
20851            })
20852            .collect();
20853        assert!(
20854            want.iter().any(|(cutout, _)| *cutout) && want.iter().any(|(cutout, _)| !*cutout),
20855            "the masked demo has to hold buckets of both modes, or this compares one partition \
20856             against itself: {:?}",
20857            masked.modes
20858        );
20859        assert_eq!(
20860            masked.prepass, want,
20861            "the depth prepass must record each bucket once, under the pipeline its own mode \
20862             asked for"
20863        );
20864        // The atlas draws every bucket once per occupied view, and the
20865        // partition is **outside** the view loop — one pipeline bind covers
20866        // every view of that mode — so its stream is each partition's bucket
20867        // list repeated once per view.
20868        let views = masked.atlas.len() / want.len();
20869        assert!(
20870            views > 0 && masked.atlas.len() % want.len() == 0,
20871            "the shadow atlas recorded {} calls over {} buckets, which is not a whole number \
20872             of views",
20873            masked.atlas.len(),
20874            want.len()
20875        );
20876        let mut atlas_want: Vec<(bool, u32)> = Vec::with_capacity(masked.atlas.len());
20877        for cutout in [false, true] {
20878            let partition: Vec<(bool, u32)> = want
20879                .iter()
20880                .copied()
20881                .filter(|(mode, _)| *mode == cutout)
20882                .collect();
20883            for _ in 0..views {
20884                atlas_want.extend_from_slice(&partition);
20885            }
20886        }
20887        assert_eq!(
20888            masked.atlas, atlas_want,
20889            "and every shadow view draws both partitions, each under its own pipeline"
20890        );
20891
20892        assert_eq!(
20893            masked.folded, opaque.folded,
20894            "the frame gained or lost a pipeline bind beyond the cutout twin beside a plain one"
20895        );
20896    }
20897
20898    /// **A double-sided material moves every pass's draws for its own buckets
20899    /// onto the `CullMode::None` twins, and moves nothing else.**
20900    ///
20901    /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]'s
20902    /// claim for glTF's other mode, and it is wider by construction: an alpha
20903    /// mask is cut inside a fragment stage, so only the two depth-only passes
20904    /// route around it, while a cull mode is a pipeline state and **every** pass
20905    /// that draws the surface has to route around it — the colour pass, both
20906    /// depth passes and the two reflective shadow maps.
20907    ///
20908    /// So this walks the whole recorded stream rather than two named passes:
20909    /// every render pass that recorded an indirect draw is read back as the
20910    /// (side, bucket) pairs it recorded, and each of the four claims below is
20911    /// about all of them at once.
20912    ///
20913    /// * a scene with nothing double-sided binds **no** cull-none twin
20914    ///   anywhere, which is the "an all-single-sided frame costs what it always
20915    ///   did" claim at the level a null device can see it;
20916    /// * a scene with one double-sided row binds a twin in every pass that
20917    ///   draws — a frame that had only routed the colour pass would satisfy
20918    ///   nothing below, and one that had only routed the depth passes would
20919    ///   draw a surface the prepass wrote no depth for;
20920    /// * the calls following each bind are exactly that side's buckets, in
20921    ///   bucket order. A split that bound both pipelines and drew every bucket
20922    ///   under each would satisfy the claim above and double the frame's draws;
20923    /// * and folding each twin onto the pipeline it is a twin of — then
20924    ///   collapsing the runs of equal binds the fold creates — leaves the two
20925    ///   frames' bind streams **equal**, so nothing else in the frame moved.
20926    ///
20927    /// The two scenes differ in one flags word and nothing else.
20928    ///
20929    /// [`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
20930    #[test]
20931    fn a_double_sided_material_moves_every_passs_draws_onto_the_cull_none_twins() {
20932        use crcbl_hal::null::Command;
20933
20934        // The occlusion blur count is a process-global console variable and a
20935        // frame binds one pipeline per blur — the masked test's hazard exactly.
20936        let _blurs = ssao_blur_switch();
20937
20938        // **A scene whose probes ask to be updated**, because the reflective
20939        // shadow maps are recorded by a volume rather than by an effect bit —
20940        // and they are two of the five passes this claim is about. The demo's
20941        // empty grid records neither, which would leave the widest half of the
20942        // routing unchecked.
20943        let scene_with_probes = || {
20944            let mut scene = crate::scene::demo();
20945            scene.capacities.probes = 1;
20946            scene.probes = crate::scene::ProbeGrid {
20947                volume: crcbl_shaders::probe::ProbeVolume {
20948                    origin: [0.0; 3],
20949                    inv_spacing: [1.0; 3],
20950                    counts: [1, 1, 1],
20951                    levels: 1,
20952                    steps: crcbl_shaders::probe::ProbeSteps::default(),
20953                },
20954                probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
20955                update: ProbeUpdate::EveryFrame,
20956            };
20957            scene
20958        };
20959        let single_scene = scene_with_probes();
20960        let double_scene = {
20961            let mut scene = scene_with_probes();
20962            scene.materials[DEMO_UNTINTED].flags = crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED;
20963            scene
20964        };
20965
20966        /// What one scene's frame reveals: each bucket's mode, how often a
20967        /// cull-none twin was bound at all, every drawing pass's (side, bucket)
20968        /// pairs in record order, and the whole bind stream with each twin
20969        /// folded onto the pipeline it twins.
20970        struct Recorded {
20971            modes: Vec<u32>,
20972            twins_bound: usize,
20973            passes: Vec<(String, Vec<(bool, u32)>)>,
20974            folded: Vec<String>,
20975        }
20976
20977        // One frame each, from two renderers rather than two frames from one, on
20978        // the masked test's terms: a bucket table is fixed at build, and two
20979        // builds keep both frames a first frame.
20980        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20981            let (recorder, device, queue) = open();
20982            let device = device.as_ref();
20983            let mut renderer =
20984                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20985                    .expect("the null backend accepts the demo description");
20986            assert!(
20987                !renderer.emit.is_mesh(),
20988                "this preset built a mesh-shader path, whose draws carry no argument offset to \
20989                 recover a bucket from"
20990            );
20991            place_cube(&mut renderer, Mat4::IDENTITY);
20992            // **One shadowed spot**, so the punctual reflective shadow map has a
20993            // face to draw into: the pass is recorded on every frame but its
20994            // view loop is empty without one, and an empty loop records no draw
20995            // for the claim below to be about.
20996            renderer.set_lights(&[crate::Light::Spot(crate::SpotLight {
20997                position: Vec3::new(0.0, 2.0, 0.0),
20998                radius: 8.0,
20999                color: Vec3::splat(4.0),
21000                direction: Vec3::NEG_Y,
21001                inner_angle: 0.3,
21002                outer_angle: 0.6,
21003                fill: false,
21004            })]);
21005            let imported = swapchain_image(device);
21006            let mut pool = crate::TransientPool::new();
21007            renderer
21008                .begin_frame(
21009                    device,
21010                    &Camera::default(),
21011                    &DirectionalLight::default(),
21012                    (64, 48),
21013                )
21014                .expect("write");
21015            let mut graph = crate::RenderGraph::new(queue);
21016            let target = graph.import_image("target", imported);
21017            renderer.add_passes(&mut graph, &pool, target, (64, 48));
21018            let compiled = graph.compile(&pool).expect("a legal frame");
21019            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21020                label: Some("double sided lap"),
21021                queue,
21022            });
21023            compiled
21024                .execute(device, &mut pool, encoder.as_mut(), None)
21025                .expect("the graph executed");
21026            encoder.finish().expect("recording succeeded");
21027
21028            // Every twin and the pipeline it twins, so a bind can be reported as
21029            // a side and folded back. Asserted distinct, or nothing here
21030            // discriminates.
21031            // The scene masks nothing, so it built no cutout shape to twin.
21032            assert_eq!(renderer.depth_masked_pipeline, None);
21033            let sided: Vec<SidedPipelines> = [
21034                Some(renderer.mesh_pipeline),
21035                Some(renderer.shadow_pipeline),
21036                renderer.rsm_pipeline,
21037            ]
21038            .into_iter()
21039            .flatten()
21040            .collect();
21041            for pair in &sided {
21042                assert_ne!(
21043                    Some(pair.single),
21044                    pair.double,
21045                    "a pipeline and its cull-none twin have to be two objects"
21046                );
21047            }
21048            let twin_of = |handle: GraphicsPipelineHandle| -> Option<GraphicsPipelineHandle> {
21049                sided
21050                    .iter()
21051                    .find(|pair| pair.double == Some(handle))
21052                    .map(|pair| pair.single)
21053            };
21054            let bucket_of = |args_offset: u64| -> u32 {
21055                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
21056                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
21057                    .unwrap_or_else(|| {
21058                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
21059                    })
21060            };
21061
21062            let mut passes: Vec<(String, Vec<(bool, u32)>)> = Vec::new();
21063            let labels = graphics_pipeline_labels(&recorder);
21064            let mut folded: Vec<String> = Vec::new();
21065            let mut twins_bound = 0usize;
21066            let mut current: Option<GraphicsPipelineHandle> = None;
21067            let mut label: Option<String> = None;
21068            let mut calls: Vec<(bool, u32)> = Vec::new();
21069            let commands = recorder.commands();
21070            for command in &commands {
21071                match command {
21072                    Command::BeginRenderPass { label: name, .. } => {
21073                        label = name.clone();
21074                        calls = Vec::new();
21075                    }
21076                    Command::EndRenderPass => {
21077                        if !calls.is_empty() {
21078                            passes.push((
21079                                label.clone().expect("every pass here is labelled"),
21080                                std::mem::take(&mut calls),
21081                            ));
21082                        }
21083                    }
21084                    Command::BindGraphicsPipeline(handle) => {
21085                        current = Some(*handle);
21086                        if twin_of(*handle).is_some() {
21087                            twins_bound += 1;
21088                        }
21089                        // The fold turns a `single, double` pair into
21090                        // `single, single`; collapsing a run of equal binds is
21091                        // what makes the two streams comparable without hiding
21092                        // a bind of anything else.
21093                        let folded_handle = twin_of(*handle).unwrap_or(*handle);
21094                        let folded_label = &labels[folded_handle.index() as usize];
21095                        if folded.last() != Some(folded_label) {
21096                            folded.push(folded_label.clone());
21097                        }
21098                    }
21099                    Command::DrawIndexedIndirectCount(draw) => {
21100                        let handle = current.expect("a draw follows a pipeline bind");
21101                        calls.push((twin_of(handle).is_some(), bucket_of(draw.args_offset)));
21102                    }
21103                    Command::DrawIndexedIndirect(draw) => {
21104                        let handle = current.expect("a draw follows a pipeline bind");
21105                        calls.push((twin_of(handle).is_some(), bucket_of(draw.offset)));
21106                    }
21107                    _ => {}
21108                }
21109            }
21110            let modes = renderer.bucket_modes.clone();
21111            renderer.destroy(device);
21112            pool.destroy(device);
21113            device.destroy_image_view(imported.view);
21114            device.destroy_image(imported.image);
21115            recorder.assert_valid();
21116            Recorded {
21117                modes,
21118                twins_bound,
21119                passes,
21120                folded,
21121            }
21122        };
21123
21124        let single = bound(&single_scene);
21125        let double = bound(&double_scene);
21126
21127        assert_eq!(
21128            single.twins_bound, 0,
21129            "a scene with nothing double-sided must never bind a cull-none twin"
21130        );
21131        // Named rather than counted, because the claim is that **every** pass
21132        // that draws the surface routes: a frame that had quietly stopped
21133        // recording one of them would satisfy a count and leave that pass's
21134        // routing unchecked for ever.
21135        let drawing: Vec<&str> = single
21136            .passes
21137            .iter()
21138            .map(|(name, _)| name.as_str())
21139            .collect();
21140        for pass in ["shadow", "depth-prepass", "forward", "rsm", "rsm-punctual"] {
21141            assert!(
21142                drawing.contains(&pass),
21143                "`{pass}` drew nothing in this frame, so its routing is unchecked: {drawing:?}"
21144            );
21145        }
21146        assert!(
21147            double.twins_bound > 0,
21148            "a double-sided scene must bind the cull-none twins"
21149        );
21150        assert_eq!(
21151            double
21152                .passes
21153                .iter()
21154                .map(|(name, _)| name)
21155                .collect::<Vec<_>>(),
21156            single
21157                .passes
21158                .iter()
21159                .map(|(name, _)| name)
21160                .collect::<Vec<_>>(),
21161            "the two frames must draw in the same passes, or they are not comparable"
21162        );
21163
21164        // What each drawing pass should have recorded: every single-sided bucket
21165        // under the plain pipeline in bucket order, then every double-sided one
21166        // under the twin — the partition order `sided_partitions` lays down —
21167        // repeated once per view for a pass that draws several.
21168        let want: Vec<(bool, u32)> = [false, true]
21169            .into_iter()
21170            .flat_map(|twin| {
21171                double
21172                    .modes
21173                    .iter()
21174                    .enumerate()
21175                    .filter(move |(_, mode)| {
21176                        (**mode & crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED != 0) == twin
21177                    })
21178                    .map(move |(bucket, _)| (twin, u32::try_from(bucket).expect("a few buckets")))
21179            })
21180            .collect();
21181        assert!(
21182            want.iter().any(|(twin, _)| *twin) && want.iter().any(|(twin, _)| !*twin),
21183            "the double-sided demo has to hold buckets of both sides, or this compares one \
21184             partition against itself: {:?}",
21185            double.modes
21186        );
21187        for (name, calls) in &double.passes {
21188            let views = calls.len() / want.len();
21189            assert!(
21190                views > 0 && calls.len() % want.len() == 0,
21191                "`{name}` recorded {} call(s) over {} bucket(s), which is not a whole number of \
21192                 views",
21193                calls.len(),
21194                want.len()
21195            );
21196            // The partition is **outside** any view loop — one pipeline bind
21197            // covers every view of that side — so the stream is each partition's
21198            // bucket list repeated once per view.
21199            let mut expected: Vec<(bool, u32)> = Vec::with_capacity(calls.len());
21200            for twin in [false, true] {
21201                let partition: Vec<(bool, u32)> = want
21202                    .iter()
21203                    .copied()
21204                    .filter(|(side, _)| *side == twin)
21205                    .collect();
21206                for _ in 0..views {
21207                    expected.extend_from_slice(&partition);
21208                }
21209            }
21210            assert_eq!(
21211                *calls, expected,
21212                "`{name}` must record each bucket once per view, under the pipeline its own \
21213                 side asked for"
21214            );
21215        }
21216
21217        assert_eq!(
21218            double.folded, single.folded,
21219            "the frame gained or lost a pipeline bind beyond a cull-none twin beside the \
21220             pipeline it twins"
21221        );
21222    }
21223
21224    /// **The wireframe view swaps the colour pass's pipeline and nothing else.**
21225    ///
21226    /// The mechanism, at the level a null device can observe it: which pipeline
21227    /// handle each pass of the recorded stream binds. A field on the renderer
21228    /// would say only that a flag moved — this says the *frame* moved, and says
21229    /// which part of it did.
21230    ///
21231    /// Four claims, and each rules out a different way of passing wrongly:
21232    ///
21233    /// * the filled pipeline is bound on a frame nobody asked, and the wireframe
21234    ///   one does not exist;
21235    /// * switching on **removes** the filled pipeline from the stream — a second
21236    ///   pipeline that was built and never bound would still leave it there;
21237    /// * every other pipeline the frame binds is unchanged, so the depth prepass
21238    ///   and the shadow cascades are still filling triangles;
21239    /// * and switching off puts the stream back exactly, so the view is a toggle
21240    ///   rather than a one-way door.
21241    #[test]
21242    fn the_wireframe_view_swaps_the_colour_passs_pipeline_and_no_other() {
21243        use crcbl_hal::null::Command;
21244
21245        // The pipelines a frame binds include one per occlusion blur, and the
21246        // blur count is a process-global console variable — so a concurrent
21247        // test holding `r_ssao_blur_passes` at two adds a bind to one of the
21248        // frames below and not to the others. It reddened this assertion on
21249        // 2026-08-31 under a workspace `cargo test`.
21250        let _blurs = ssao_blur_switch();
21251        let (recorder, device, queue) =
21252            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
21253        let device = device.as_ref();
21254        assert!(
21255            ForwardRenderer::supports_wireframe(device),
21256            "this test needs the line fill mode, and asked the device for it",
21257        );
21258        let mut renderer =
21259            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21260        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
21261        let imported = swapchain_image(device);
21262        let mut pool = crate::TransientPool::new();
21263
21264        // The pipelines one frame binds, in record order. Cumulative recorder,
21265        // so each call takes the tail its own frame added.
21266        let mut seen = 0usize;
21267        // A different sun each lap, so the shadow atlas is redrawn in every one
21268        // of them: the comparison below is "which pipelines did this frame
21269        // bind", and a lap that cached its atlas would bind the depth-only
21270        // pipeline one fewer time for a reason that has nothing to do with the
21271        // wireframe. See [`moving_sun`].
21272        let mut lap = 0u32;
21273        let mut pipelines_in_a_frame = |renderer: &mut ForwardRenderer, pool: &mut _| {
21274            lap += 1;
21275            renderer
21276                .begin_frame(device, &Camera::default(), &moving_sun(lap), (64, 48))
21277                .expect("write");
21278            let mut graph = crate::RenderGraph::new(queue);
21279            let target = graph.import_image("target", imported);
21280            renderer.add_passes(&mut graph, pool, target, (64, 48));
21281            let compiled = graph.compile(pool).expect("a legal frame");
21282            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21283                label: Some("wireframe lap"),
21284                queue,
21285            });
21286            compiled
21287                .execute(device, pool, encoder.as_mut(), None)
21288                .expect("the graph executed");
21289            encoder.finish().expect("recording succeeded");
21290            let commands = recorder.commands();
21291            let bound: Vec<GraphicsPipelineHandle> = commands[seen..]
21292                .iter()
21293                .filter_map(|command| match command {
21294                    Command::BindGraphicsPipeline(handle) => Some(*handle),
21295                    _ => None,
21296                })
21297                .collect();
21298            seen = commands.len();
21299            bound
21300        };
21301
21302        let filled = renderer.mesh_pipeline.single;
21303        let off = pipelines_in_a_frame(&mut renderer, &mut pool);
21304        assert!(
21305            off.contains(&filled),
21306            "a frame nobody asked has to bind the filled pipeline: {off:?}",
21307        );
21308        assert!(!renderer.wireframe());
21309        assert!(
21310            renderer.wireframe_pipeline.is_none(),
21311            "the wireframe pipeline must not be built until it is asked for",
21312        );
21313
21314        renderer
21315            .set_wireframe(device, true)
21316            .expect("a device with the line fill mode builds it");
21317        assert!(renderer.wireframe());
21318        let lines = renderer
21319            .wireframe_pipeline
21320            .expect("switching on is what builds it")
21321            .single;
21322        let on = pipelines_in_a_frame(&mut renderer, &mut pool);
21323        assert!(
21324            !on.contains(&filled),
21325            "the colour pass still bound the filled pipeline: {on:?}",
21326        );
21327        assert_eq!(
21328            on.iter().filter(|handle| **handle == lines).count(),
21329            1,
21330            "the wireframe pipeline has to be bound exactly once — by the colour pass: {on:?}",
21331        );
21332        let substituted: Vec<GraphicsPipelineHandle> = on
21333            .iter()
21334            .map(|handle| if *handle == lines { filled } else { *handle })
21335            .collect();
21336        assert_eq!(
21337            substituted, off,
21338            "the frame gained or lost a pipeline bind beyond the colour pass's: {on:?} against \
21339             {off:?}",
21340        );
21341
21342        renderer
21343            .set_wireframe(device, false)
21344            .expect("switching off builds nothing");
21345        assert!(!renderer.wireframe());
21346        assert_eq!(
21347            pipelines_in_a_frame(&mut renderer, &mut pool),
21348            off,
21349            "switching the view off has to put the filled pipeline back, not just stop reporting \
21350             it",
21351        );
21352
21353        renderer.destroy(device);
21354        pool.destroy(device);
21355        device.destroy_image_view(imported.view);
21356        device.destroy_image(imported.image);
21357        recorder.assert_valid();
21358    }
21359
21360    /// **The colour pass tests against the prepass's depth instead of clearing
21361    /// and rewriting it, so each pixel is shaded once** — and a wireframe frame
21362    /// does the opposite, because lines do not reproduce a filled prepass.
21363    ///
21364    /// Both halves have to hold together or the frame is wrong in one of two
21365    /// ways, so both are asserted here. The attachment alone read-only while the
21366    /// pipeline still wrote would be a pipeline writing to a read-only
21367    /// attachment; the pipeline alone on `GreaterOrEqual` against an attachment
21368    /// this pass had just *cleared* would reject every fragment and draw a black
21369    /// frame. Neither shows up as an error — the first is a validation message
21370    /// on one backend and undefined behaviour on the rest, the second is a
21371    /// picture — which is why the observable is read off the compiled graph and
21372    /// off the pipeline state rather than off a screenshot.
21373    #[test]
21374    fn the_colour_pass_shades_once_per_pixel_against_the_prepasss_depth() {
21375        let (recorder, device, queue) =
21376            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
21377        let device = device.as_ref();
21378        let mut renderer =
21379            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21380        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
21381        let imported = swapchain_image(device);
21382        let mut pool = crate::TransientPool::new();
21383
21384        // Each pass's depth attachment, off the graph's own dump: the label it
21385        // was declared under, and the `load`/`store`/`write` triple the backend
21386        // is handed. A pass with no depth attachment contributes nothing, which
21387        // is what makes the lookup below a search rather than an index.
21388        let depth_of = |renderer: &mut ForwardRenderer, pool: &mut _, label: &str| {
21389            renderer
21390                .begin_frame(
21391                    device,
21392                    &Camera::default(),
21393                    &DirectionalLight::default(),
21394                    (64, 48),
21395                )
21396                .expect("write");
21397            let mut graph = crate::RenderGraph::new(queue);
21398            let target = graph.import_image("target", imported);
21399            renderer.add_passes(&mut graph, pool, target, (64, 48));
21400            let dump = graph.compile(pool).expect("a legal frame").dump();
21401            let mut pass = String::new();
21402            let mut found = None;
21403            for line in dump.lines() {
21404                if let Some(rest) = line.split(" pass \"").nth(1) {
21405                    pass = rest.trim_end_matches('"').to_string();
21406                    if let Some((name, _)) = pass.split_once('"') {
21407                        pass = name.to_string();
21408                    }
21409                }
21410                if pass == label
21411                    && let Some(at) = line.find("depth load=")
21412                {
21413                    // Without the slot note the dump appends: which physical
21414                    // image the transient landed on is aliasing's business, not
21415                    // this assertion's.
21416                    let role = &line[at..];
21417                    let role = role.split_once(" [").map_or(role, |(head, _)| head);
21418                    found = Some(role.trim().to_string());
21419                }
21420            }
21421            found.unwrap_or_else(|| panic!("no depth attachment on `{label}`:\n{dump}"))
21422        };
21423
21424        assert_eq!(
21425            depth_of(&mut renderer, &mut pool, "depth-prepass"),
21426            "depth load=Clear store=Store write=yes",
21427            "the prepass is what puts the depth there, so it clears, writes and keeps it",
21428        );
21429        assert_eq!(
21430            depth_of(&mut renderer, &mut pool, "forward"),
21431            "depth load=Load store=Store write=no",
21432            "and the colour pass reads it: a clear here would throw away the prepass and \
21433             pay for the overdraw again, and a write would be a second pass writing the \
21434             same values",
21435        );
21436        assert_eq!(
21437            MeshModules::color_depth_stencil(PolygonMode::Fill),
21438            Some(DepthStencilState {
21439                format: Format::D32Float,
21440                depth_write: false,
21441                depth_compare: CompareOp::GreaterOrEqual,
21442                stencil: None,
21443                bias: DepthBias::default(),
21444            }),
21445            "and the pipeline agrees with the attachment: equality against the prepass, \
21446             reachable only through the `OrEqual` under reversed-Z",
21447        );
21448
21449        renderer
21450            .set_wireframe(device, true)
21451            .expect("this device was asked for the line fill mode");
21452        assert_eq!(
21453            depth_of(&mut renderer, &mut pool, "forward"),
21454            "depth load=Clear store=Store write=yes",
21455            "a wireframe frame keeps the old shape: `PolygonMode::Line` interpolates depth \
21456             along the edge rather than across the face, so testing it against a filled \
21457             prepass rejects most of the wireframe — and *loading* that depth under the \
21458             writing default's `Greater` would reject all of it",
21459        );
21460        assert_eq!(
21461            MeshModules::color_depth_stencil(PolygonMode::Line),
21462            MeshModules::depth_stencil(),
21463            "which is the writing default, the same state the depth-only twin uses",
21464        );
21465
21466        renderer.destroy(device);
21467        pool.destroy(device);
21468        device.destroy_image_view(imported.view);
21469        device.destroy_image(imported.image);
21470        recorder.assert_valid();
21471    }
21472
21473    /// **A device with no line fill mode is refused, not quietly filled.**
21474    ///
21475    /// The failure this rules out is the silent one: a caller who binds a key to
21476    /// this, presses it, and gets the solid frame back with nothing anywhere
21477    /// saying why — which on a model whose silhouette hides its interior is
21478    /// indistinguishable from a wireframe that worked. WebGPU is the real device
21479    /// this happens on; `open`'s null device stands in for it, because
21480    /// [`DeviceDesc::for_adapter`] asks for
21481    /// [`Features::GPU_DRIVEN`] and nothing else.
21482    #[test]
21483    fn a_device_without_the_line_fill_mode_refuses_the_wireframe_rather_than_filling_it() {
21484        let (recorder, device, queue) = open();
21485        let device = device.as_ref();
21486        assert!(
21487            !ForwardRenderer::supports_wireframe(device),
21488            "this device was not asked for the line fill mode, so it must not report it",
21489        );
21490        let mut renderer =
21491            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21492
21493        let refused = renderer
21494            .set_wireframe(device, true)
21495            .expect_err("a device without the feature has to say so");
21496        assert!(
21497            matches!(
21498                refused,
21499                HalError::UnsupportedFeatures { missing } if missing == Features::POLYGON_MODE_LINE
21500            ),
21501            "the refusal has to name the feature to go and look up, and is {refused:?}",
21502        );
21503        assert!(
21504            !renderer.wireframe(),
21505            "a refused request must leave the view off rather than half on",
21506        );
21507        assert!(
21508            renderer.wireframe_pipeline.is_none(),
21509            "nothing may be left behind by a refusal",
21510        );
21511        // And switching *off* is still fine on such a device: it builds nothing.
21512        renderer
21513            .set_wireframe(device, false)
21514            .expect("switching off asks the device for nothing");
21515
21516        renderer.destroy(device);
21517        recorder.assert_valid();
21518    }
21519
21520    /// The grid's own full-screen triangle is counted as submitted, and only
21521    /// while it is on.
21522    ///
21523    /// [`FrameCounters::instances`] is the "submitted" half of the debug panel's
21524    /// row, and every full-screen pass in the frame contributes one — so a grid
21525    /// that drew and was not counted makes that row disagree with the frame by
21526    /// exactly one triangle, silently.
21527    #[test]
21528    fn the_grids_triangle_is_counted_only_while_it_is_on() {
21529        let _blurs = ssao_blur_switch();
21530        let (recorder, device, queue) = open();
21531        let device = device.as_ref();
21532        let mut renderer =
21533            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21534        let imported = swapchain_image(device);
21535        let mut pool = crate::TransientPool::new();
21536
21537        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21538        let off = renderer.counters();
21539
21540        renderer
21541            .set_ground_grid(device, Some(GridStyle::default()))
21542            .expect("the null backend builds every pipeline");
21543        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21544        let on = renderer.counters();
21545
21546        assert_eq!(
21547            on.draws - off.draws,
21548            FULLSCREEN_DRAWS,
21549            "the grid records exactly one draw"
21550        );
21551        assert_eq!(
21552            on.instances - off.instances,
21553            FULLSCREEN_DRAWS,
21554            "and exactly one submitted instance"
21555        );
21556
21557        renderer.destroy(device);
21558        pool.destroy(device);
21559        device.destroy_image_view(imported.view);
21560        device.destroy_image(imported.image);
21561        recorder.assert_valid();
21562    }
21563
21564    /// One frame on a device of its own, under an override switching `off`.
21565    ///
21566    /// **A device of its own per arm**, because a [`Recorder`] accumulates for a
21567    /// device's whole life: asking "did the atlas pass draw" of a recorder that
21568    /// has seen two frames answers about both of them, and the arm that matters
21569    /// most here is the one whose answer must be zero.
21570    ///
21571    /// Returns what the frame reported and what its atlas pass actually drew.
21572    fn frame_switching_off(off: RenderEffects) -> (FrameCounters, u64, usize) {
21573        use crcbl_hal::null::Command;
21574
21575        let recorder = Recorder::new();
21576        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21577        let adapter = instance.adapters().remove(0);
21578        let opened = instance
21579            .create_device(&DeviceDesc::for_adapter(adapter.id))
21580            .expect("the null backend always opens");
21581        let device = opened.as_ref();
21582        let queue = opened.queue(QueueKind::Graphics).expect("always present");
21583        let mut renderer =
21584            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21585        // A shadowed light beside the cascades, so the atlas pass has draws to
21586        // lose rather than being empty either way.
21587        renderer.set_lights(&[shadowable_spot(-1.0)]);
21588        // **[`OUTSIDE_THE_DEFAULT`] forced on, then `off` forced off.** The default
21589        // camera stack leaves both of them out — see
21590        // [`RenderEffects::DEFAULT_STACK`] — so a control frame built on the
21591        // default alone would be measuring three effects and calling it five,
21592        // and their arms below would be switching off something already off.
21593        // `force` clears the other side, so an arm whose `off` is one of them
21594        // still resolves to off.
21595        renderer.set_effect_request(EffectRequest {
21596            programmatic: EffectOverride::none()
21597                .force(OUTSIDE_THE_DEFAULT, Some(true))
21598                .force(off, Some(false)),
21599            ..EffectRequest::default()
21600        });
21601
21602        let recorded = frame(device, &mut renderer, queue);
21603        assert_eq!(
21604            renderer.effects(),
21605            RenderEffects::all().difference(off),
21606            "the frame must have resolved to the set the request asked for"
21607        );
21608        let counters = renderer.counters();
21609        let instances = renderer.instances.len() as u64;
21610        let atlas_draws = commands_in_pass(&recorder, "shadow")
21611            .into_iter()
21612            .filter(|command| {
21613                matches!(
21614                    command,
21615                    Command::DrawIndexedIndirect(_)
21616                        | Command::DrawIndexedIndirectCount(_)
21617                        | Command::DrawMeshTasksIndirect(_)
21618                )
21619            })
21620            .count();
21621        assert_eq!(
21622            counters.draws,
21623            recorded_draws(&recorder) as u64,
21624            "the counter and the frame's own recorded stream must agree, whatever is switched off"
21625        );
21626        recorded.finish(device, renderer);
21627        recorder.assert_valid();
21628        (counters, instances, atlas_draws)
21629    }
21630
21631    /// **A switched-off effect is work the frame did not record**, and a frame
21632    /// that still executes with the placeholder bound in place of what it lost.
21633    ///
21634    /// The other half of the pass-list test above, and the half a pass list
21635    /// cannot make: the `shadow` pass is still *there* with shadows off, so the
21636    /// question is whether it drew. That answer comes off the recorded command
21637    /// stream, which is a different instrument from `recorded_draws` — the number
21638    /// under test.
21639    ///
21640    /// Executed rather than only compiled, because the occlusion switch changes
21641    /// which image the forward pass has bound. A frame that declared a read of a
21642    /// transient it never created, or bound a view the graph never realised,
21643    /// fails here and compiles perfectly.
21644    #[test]
21645    fn a_switched_off_effect_is_work_the_frame_did_not_record() {
21646        let _blurs = ssao_blur_switch();
21647        let (control, instances, atlas_draws) = frame_switching_off(RenderEffects::empty());
21648        assert!(
21649            atlas_draws > 0,
21650            "with shadows on the atlas pass has to draw something, or turning it off means \
21651             nothing"
21652        );
21653        assert_eq!(
21654            control.instances,
21655            instances
21656                + fullscreen_passes(
21657                    RenderEffects::all(),
21658                    TEST_EXTENT,
21659                    false,
21660                    crate::ssao::blur_passes(),
21661                ) * FULLSCREEN_DRAWS,
21662            "the control frame submits one triangle per full-screen pass"
21663        );
21664
21665        // Each pair is one full-screen triangle per pass, and the atlas is
21666        // untouched by either.
21667        for (off, fewer) in [
21668            (
21669                RenderEffects::AMBIENT_OCCLUSION,
21670                u64::from(Ssao::passes(crate::ssao::blur_passes())),
21671            ),
21672            // The contact march's one pass, and a constant rather than a
21673            // function of anything: it has no blur behind it and no chain.
21674            (
21675                RenderEffects::CONTACT_SHADOWS,
21676                u64::from(ContactShadows::PASSES),
21677            ),
21678            // The march's two passes and the reductions that feed them, which
21679            // is what makes this arm's number a function of the extent the way
21680            // the chain's below is.
21681            (
21682                RenderEffects::REFLECTIONS,
21683                u64::from(Ssr::PASSES) + u64::from(crate::hiz::levels_for(TEST_EXTENT)),
21684            ),
21685            // Not a constant, unlike the occlusion pair above: the chain's
21686            // length is a function of the extent, and this is what it is at
21687            // `TEST_EXTENT`.
21688            (
21689                RenderEffects::BLOOM,
21690                u64::from(Bloom::passes_for(TEST_EXTENT)),
21691            ),
21692        ] {
21693            let (counters, instances, atlas) = frame_switching_off(off);
21694            assert_eq!(
21695                counters.draws,
21696                control.draws - fewer * FULLSCREEN_DRAWS,
21697                "{off:?}: the frame must record one draw fewer per pass it did not add"
21698            );
21699            assert_eq!(
21700                counters.instances,
21701                instances
21702                    + fullscreen_passes(
21703                        RenderEffects::all().difference(off),
21704                        TEST_EXTENT,
21705                        false,
21706                        crate::ssao::blur_passes(),
21707                    ) * FULLSCREEN_DRAWS,
21708                "{off:?}: and must not report as submitted a triangle it never submitted"
21709            );
21710            assert_eq!(
21711                atlas, atlas_draws,
21712                "{off:?}: a screen-space effect must not touch the shadow atlas"
21713            );
21714        }
21715
21716        // Shadows: the atlas pass survives and draws nothing at all, which is
21717        // the mechanism — a cleared reversed-Z atlas reads as fully lit.
21718        let (counters, _, atlas) = frame_switching_off(RenderEffects::SHADOWS);
21719        assert_eq!(
21720            atlas, 0,
21721            "with shadows off the atlas pass must record its clear and no draw"
21722        );
21723        assert_eq!(
21724            counters.draws,
21725            control.draws - atlas_draws as u64,
21726            "and the frame must record exactly the atlas pass's draws fewer"
21727        );
21728    }
21729
21730    /// **Every pass the frame records gets a row in the report, except the ones
21731    /// that open no scope.**
21732    ///
21733    /// The observable the bound exists for: the samples' hand-picked capacity
21734    /// timed the first eight passes of a fourteen-pass frame and reported eight
21735    /// rows, which reads exactly like a frame that has eight passes. Sized from
21736    /// [`MAX_TIMED_PASSES`](crate::MAX_TIMED_PASSES), the report names every
21737    /// pass the graph compiled, in order — so a bound one short of the frame
21738    /// makes this list short too.
21739    ///
21740    /// A [`PassKind::Copy`](crate::graph::PassKind::Copy) is filtered out of the
21741    /// expectation rather than expected to be missing by accident. The seam
21742    /// takes a timestamp only where a pass opens and closes and a copy opens
21743    /// nothing, so `PassTimers` gives it no query pair and no row — a row
21744    /// reading 0.000 ms would be a measurement nobody made.
21745    #[test]
21746    fn every_pass_of_the_frame_gets_a_timing_row() {
21747        let _blurs = ssao_blur_switch();
21748        // And the comparison seam, so the frame this checks carries the
21749        // occlusion chain's second march: `docs/plan/ROADMAP.md`'s S4D row asks
21750        // for a *per-technique* cost, and what makes that true is this test's
21751        // own claim — every pass that opens a scope gets a row — applied to a
21752        // frame that compares. See `crate::ssao`'s `r_ssao_split`.
21753        let split = ssao_split_switch();
21754        split.set(0.5);
21755        let recorder = Recorder::new();
21756        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21757        let adapter = instance.adapters().remove(0);
21758        // `TIMESTAMP_QUERY` is not part of `GPU_DRIVEN` — topic 10's browsers
21759        // may lack it — so a device that wants timers has to ask for it, and
21760        // `open` above, which uses `DeviceDesc::for_adapter`, does not.
21761        let opened = instance
21762            .create_device(&DeviceDesc {
21763                label: Some("timed frame"),
21764                adapter: adapter.id,
21765                required_features: Features::GPU_DRIVEN,
21766                optional_features: Features::TIMESTAMP_QUERY,
21767                compatible_surface: None,
21768            })
21769            .expect("the null backend always opens");
21770        let queue = opened.queue(QueueKind::Graphics).expect("always present");
21771        let device = opened.as_ref();
21772        let mut renderer =
21773            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21774        renderer.set_lights(&[shadowable_spot(-1.0), shadowable_spot(1.0)]);
21775        let mut timers = crate::PassTimers::new(device, FRAMES_IN_FLIGHT, crate::MAX_TIMED_PASSES)
21776            .expect("the tier A null adapter has timestamp queries");
21777        let imported = swapchain_image(device);
21778        let mut pool = crate::TransientPool::new();
21779        let mut recorded = Vec::new();
21780        let mut compiled_labels = Vec::new();
21781
21782        // The ring is one slot longer than the frames in flight and resolves a
21783        // slot only when it comes round again, so the first frame's report is
21784        // that many frames behind it — see the [`timing`](crate::timing) docs.
21785        for _ in 0..FRAMES_IN_FLIGHT + 2 {
21786            renderer
21787                .begin_frame(
21788                    device,
21789                    &Camera::default(),
21790                    &DirectionalLight::default(),
21791                    (64, 48),
21792                )
21793                .expect("write");
21794            let mut graph = crate::RenderGraph::new(queue);
21795            let target = graph.import_image("target", imported);
21796            renderer.add_passes(&mut graph, &pool, target, (64, 48));
21797            let compiled = graph.compile(&pool).expect("a legal frame");
21798            if compiled_labels.is_empty() {
21799                compiled_labels = compiled
21800                    .passes()
21801                    .iter()
21802                    .filter(|pass| pass.kind() != crate::graph::PassKind::Copy)
21803                    .map(|pass| pass.label().to_string())
21804                    .collect();
21805            }
21806            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21807                label: Some("timed frame"),
21808                queue,
21809            });
21810            compiled
21811                .execute(device, &mut pool, encoder.as_mut(), Some(&mut timers))
21812                .expect("the graph executed");
21813            recorded.push(encoder.finish().expect("recording succeeded"));
21814        }
21815
21816        let reported: Vec<&str> = timers
21817            .latest()
21818            .passes
21819            .iter()
21820            .map(|timing| timing.label.as_str())
21821            .collect();
21822        // Anti-vacuity for the seam held above: a frame that did not compare
21823        // would satisfy the equality below and say nothing about a
21824        // per-technique cost, because there would be one technique in it.
21825        for label in ["ssao", "ssao-shipped"] {
21826            assert!(
21827                compiled_labels.iter().any(|pass| pass == label),
21828                "the frame compiled no `{label}` pass, so the seam did not reach it and this \
21829                 test says nothing about a comparison having a cost per side. Its passes: \
21830                 {compiled_labels:?}"
21831            );
21832        }
21833        assert_eq!(
21834            reported,
21835            compiled_labels,
21836            "the report must name every pass the frame compiled that opens a scope, in order \
21837             — {} of {} timed with a capacity of {}",
21838            reported.len(),
21839            compiled_labels.len(),
21840            timers.capacity()
21841        );
21842
21843        timers.destroy(device);
21844        renderer.destroy(device);
21845        for commands in recorded {
21846            device.destroy_command_buffer(commands);
21847        }
21848        pool.destroy(device);
21849        device.destroy_image_view(imported.view);
21850        device.destroy_image(imported.image);
21851        recorder.assert_valid();
21852    }
21853
21854    /// One mesh-table entry, decoded from the bytes that reached the device.
21855    fn mesh_entry(
21856        recorder: &Recorder,
21857        renderer: &ForwardRenderer,
21858        id: u32,
21859    ) -> crcbl_shaders::mesh::GpuMesh {
21860        let table = recorder
21861            .buffer_bytes(renderer.pool.table_buffer())
21862            .expect("the table is live");
21863        let at = id as usize * crcbl_shaders::mesh::MESH_ENTRY_STRIDE;
21864        crcbl_shaders::mesh::GpuMesh::from_bytes(
21865            table[at..at + crcbl_shaders::mesh::MESH_ENTRY_STRIDE]
21866                .try_into()
21867                .expect("one whole entry"),
21868        )
21869    }
21870
21871    // --- skinning: the seam a caller draws a skinned mesh through -----------
21872
21873    /// A renderer with [`scene::demo`]'s cube reserved for skinning, and a
21874    /// [`Skinning`] built against that renderer's own vertex pool.
21875    struct SkinnedFixture {
21876        renderer: ForwardRenderer,
21877        skinning: Skinning,
21878        skinned: SkinnedMesh,
21879        palette: Vec<Mat4>,
21880        bindings: Vec<crcbl_shaders::skinning::SkinBinding>,
21881    }
21882
21883    impl SkinnedFixture {
21884        fn build(device: &dyn Device, queue: QueueHandle) -> Self {
21885            let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
21886                .expect("the null backend accepts every descriptor");
21887            let skinned = renderer
21888                .reserve_skinned(DEMO_CUBE)
21889                .expect("a default pool has room for two halves of a cube");
21890            let skinning = Skinning::new(
21891                device,
21892                &crate::skinning::SkinningDesc {
21893                    label: Some("skinned fixture"),
21894                    frames: FRAMES_IN_FLIGHT,
21895                    ranges: 1,
21896                    joints: 1,
21897                    bindings: skinned.vertex_count(),
21898                    // The renderer's own pool, which is the whole of what makes
21899                    // the dispatch's output reachable by its draws.
21900                    vertices: renderer.vertex_buffer(),
21901                    attribute_base: renderer.attribute_base(),
21902                },
21903            )
21904            .expect("the null backend accepts every descriptor");
21905            let bindings = vec![
21906                crcbl_shaders::skinning::SkinBinding {
21907                    joints: [0; crcbl_shaders::skinning::JOINTS_PER_VERTEX],
21908                    weights: [1.0, 0.0, 0.0, 0.0],
21909                };
21910                skinned.vertex_count() as usize
21911            ];
21912            Self {
21913                renderer,
21914                skinning,
21915                skinned,
21916                palette: vec![Mat4::IDENTITY],
21917                bindings,
21918            }
21919        }
21920
21921        /// One skinned frame's `begin_skinned_frame`, with this fixture's single
21922        /// range.
21923        fn begin(&mut self, device: &dyn Device) {
21924            let range = self.skinned.skin_range(&self.palette, &self.bindings);
21925            self.renderer
21926                .begin_skinned_frame(
21927                    device,
21928                    &mut self.skinning,
21929                    &[range],
21930                    &Camera::default(),
21931                    &DirectionalLight::default(),
21932                    TEST_EXTENT,
21933                )
21934                .expect("a legal skinning plan");
21935        }
21936
21937        fn destroy(mut self, device: &dyn Device) {
21938            self.renderer.release_skinned(self.skinned);
21939            self.skinning.destroy(device);
21940            self.renderer.destroy(device);
21941        }
21942    }
21943
21944    /// How many times the host wrote the mesh-table entry `id` names.
21945    fn table_writes(recorder: &Recorder, renderer: &ForwardRenderer, id: u32) -> usize {
21946        let table = renderer.pool.table_buffer();
21947        let at = u64::from(id) * crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u64;
21948        recorder
21949            .events()
21950            .into_iter()
21951            .filter(|event| {
21952                matches!(
21953                    event,
21954                    crcbl_hal::null::Event::BufferWritten { buffer, offset, .. }
21955                        if *buffer == table && *offset == at
21956                )
21957            })
21958            .count()
21959    }
21960
21961    /// The record `handle` names, out of the ring buffer **this frame draws
21962    /// from** rather than out of the pool's host mirror.
21963    ///
21964    /// A mirror and a buffer that disagree is exactly the defect a re-pointing
21965    /// design can have, so every claim about a skinned instance's bases is read
21966    /// off the bytes a shader would.
21967    fn instance_record(
21968        recorder: &Recorder,
21969        renderer: &ForwardRenderer,
21970        handle: InstanceHandle,
21971    ) -> mesh::GpuInstance {
21972        let buffer = renderer.instances.buffers()[renderer.frame()];
21973        let bytes = recorder.buffer_bytes(buffer).expect("the ring is live");
21974        let index = renderer
21975            .instances
21976            .index(handle)
21977            .expect("the object is live") as usize;
21978        let at = index * mesh::INSTANCE_STRIDE;
21979        mesh::GpuInstance::from_bytes(
21980            bytes[at..at + mesh::INSTANCE_STRIDE]
21981                .try_into()
21982                .expect("one whole instance"),
21983        )
21984    }
21985
21986    /// **A skinned primitive takes no mesh-table entry of its own, and nothing
21987    /// rewrites the one it draws through.**
21988    ///
21989    /// [`crate::mesh_pool`]'s table is one host-visible buffer rather than a ring
21990    /// precisely because nothing rewrites an entry between frames, so a design
21991    /// that re-pointed an entry at the half a frame writes would be wrong only
21992    /// on the frames that overlap — which is to say invisibly. What alternates
21993    /// instead is a field of the *instance*, and instances go through a ring.
21994    ///
21995    /// So a skinned object draws through the source mesh's own entry: the same
21996    /// id [`add_instance`](ForwardRenderer::add_instance) would give it, still
21997    /// carrying the bind pose's base vertex, still written exactly once after
21998    /// four skinned frames. That shared entry is also what lets one mesh be
21999    /// drawn skinned and unskinned in the same frame.
22000    #[test]
22001    fn a_skinned_mesh_takes_no_table_entry_and_rewrites_none() {
22002        let (recorder, device, queue) = open();
22003        let device = device.as_ref();
22004        let mut fixture = SkinnedFixture::build(device, queue);
22005
22006        let bind_pose_id = fixture.renderer.mesh_ids[DEMO_CUBE];
22007        assert_eq!(
22008            fixture.skinned.mesh_id(),
22009            bind_pose_id,
22010            "a skinned instance names the mesh it was deformed from, so the bucket, the level \
22011             tables and the bounding box all resolve as the bind pose's"
22012        );
22013
22014        let bind_pose = mesh_entry(&recorder, &fixture.renderer, bind_pose_id);
22015        assert_eq!(
22016            bind_pose.base_vertex,
22017            fixture.skinned.input_base(),
22018            "the entry goes on naming the bind pose the dispatch reads, not either half it \
22019             writes"
22020        );
22021        for parity in 0..2 {
22022            assert_ne!(
22023                fixture.skinned.region().base(parity),
22024                bind_pose.base_vertex,
22025                "half {parity} must not be the bind pose, which the kernel reads while it \
22026                 writes them"
22027            );
22028        }
22029        assert_ne!(
22030            fixture.skinned.region().base(0),
22031            fixture.skinned.region().base(1),
22032            "the two halves are separate reservations, or the ping-pong is one buffer"
22033        );
22034
22035        // Counted before the frames rather than compared against a literal:
22036        // `MeshPool::new` clears the whole table with one write at offset zero,
22037        // which lands on this entry too, so the number here is the pool's
22038        // start-up and not this test's business. What the loop below has to
22039        // leave alone is whatever it is.
22040        let writes_before = table_writes(&recorder, &fixture.renderer, bind_pose_id);
22041        assert!(
22042            writes_before > 0,
22043            "the entry was written at least once before any frame ran, or the counter below \
22044             is counting nothing and the comparison after the frames is vacuous"
22045        );
22046
22047        // Four frames, which is two of each parity: enough that a design
22048        // rewriting an entry per frame would have written four more times.
22049        let imported = swapchain_image_at(device, TEST_EXTENT);
22050        let mut pool = crate::TransientPool::new();
22051        for _ in 0..4 {
22052            fixture.begin(device);
22053            let mut graph = crate::RenderGraph::new(queue);
22054            let target = graph.import_image("target", imported);
22055            fixture.renderer.add_skinned_passes(
22056                &mut graph,
22057                &pool,
22058                target,
22059                TEST_EXTENT,
22060                &fixture.skinning,
22061            );
22062            graph.compile(&pool).expect("a legal frame");
22063        }
22064
22065        assert_eq!(
22066            table_writes(&recorder, &fixture.renderer, bind_pose_id),
22067            writes_before,
22068            "entry {bind_pose_id} was written again by a skinned frame; the whole reason this \
22069             table is one buffer rather than a ring is that nothing rewrites an entry between \
22070             frames"
22071        );
22072
22073        fixture.destroy(device);
22074        pool.destroy(device);
22075        device.destroy_image_view(imported.view);
22076        device.destroy_image(imported.image);
22077        recorder.assert_valid();
22078    }
22079
22080    /// **A skinned object's recorded base vertex follows the parity of the frame
22081    /// it is drawn in**, and it carries the bit that makes a shader read it.
22082    ///
22083    /// The other half of the design: the table entry never moves, so what has to
22084    /// alternate is a field of the *instance* — and it has to alternate in the
22085    /// buffer the frame actually draws from, which is why this reads the
22086    /// instance ring's bytes rather than the host's mirror.
22087    ///
22088    /// Three claims, and the last two are what stop the first being vacuous. The
22089    /// base must be the one this frame's parity names; the record must carry
22090    /// [`GpuInstance::BASE_VERTEX_OVERRIDE`](mesh::GpuInstance::BASE_VERTEX_OVERRIDE),
22091    /// without which the raster stages read the mesh entry and the field is
22092    /// decoration; and two consecutive frames must have named **different**
22093    /// halves, without which a renderer ignoring the parity entirely would pass.
22094    #[test]
22095    fn a_skinned_draw_carries_the_base_the_frames_dispatch_filled() {
22096        let (recorder, device, queue) = open();
22097        let device = device.as_ref();
22098        let mut fixture = SkinnedFixture::build(device, queue);
22099        let handle = fixture
22100            .renderer
22101            .add_skinned_instance(&SkinnedInstanceDesc {
22102                mesh: &fixture.skinned,
22103                material: DEMO_UNTINTED,
22104                transform: Mat4::IDENTITY,
22105            })
22106            .expect("a pool of thousands has room for one object");
22107
22108        let mut carried = Vec::new();
22109        for _ in 0..2 {
22110            fixture.begin(device);
22111            let parity = fixture.skinning.parity();
22112            let instance = instance_record(&recorder, &fixture.renderer, handle);
22113            assert_eq!(
22114                instance.base_vertex,
22115                fixture.skinned.region().base(parity),
22116                "the buffer this frame draws from must carry the base parity {parity} writes"
22117            );
22118            assert_eq!(
22119                instance.flags & mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
22120                mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
22121                "without the bit the raster stages resolve the mesh entry's base and this \
22122                 field is never read"
22123            );
22124            assert_eq!(
22125                instance.mesh, fixture.renderer.mesh_ids[DEMO_CUBE],
22126                "and the record still names the source mesh, which is what its bucket, its \
22127                 levels and its bounding box resolve through"
22128            );
22129            carried.push(instance.base_vertex);
22130        }
22131        assert_ne!(
22132            carried[0], carried[1],
22133            "two consecutive frames must have drawn different halves, or a renderer that \
22134             ignored the parity entirely would pass this"
22135        );
22136
22137        fixture.destroy(device);
22138        recorder.assert_valid();
22139    }
22140
22141    /// **A skinned object's record names the half the frame before it filled**,
22142    /// and it starts at rest.
22143    ///
22144    /// The other half of a skinned motion vector. The base above is where a
22145    /// fragment *is*; this is where it *was*, and without it the geometry stages
22146    /// put the previous transform through this frame's deformed vertex — so a
22147    /// limb that swung reports the motion of the body it hangs off. See
22148    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
22149    ///
22150    /// Four claims, and the first and last are what stop the middle two being a
22151    /// restatement of the parity:
22152    ///
22153    /// * the **first** frame of a fresh object writes the base it draws out of,
22154    ///   because the other half holds whatever its reservation came with and a
22155    ///   motion vector against undefined vertices is worse than no motion;
22156    /// * the frames after it write
22157    ///   [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base),
22158    ///   which must also **differ** from the base they draw out of — a renderer
22159    ///   that wrote the current base into both lanes would satisfy every "it is
22160    ///   a legal base" reading of this and leave every skinned instance at rest;
22161    /// * and moving the object onto a **different region** puts it back at rest
22162    ///   for one frame, because the halves it now names are two runs it has
22163    ///   never been drawn out of.
22164    #[test]
22165    fn a_skinned_draw_carries_the_previous_half_and_starts_at_rest() {
22166        let (recorder, device, queue) = open();
22167        let device = device.as_ref();
22168        let mut fixture = SkinnedFixture::build(device, queue);
22169        let handle = fixture
22170            .renderer
22171            .add_skinned_instance(&SkinnedInstanceDesc {
22172                mesh: &fixture.skinned,
22173                material: DEMO_UNTINTED,
22174                transform: Mat4::IDENTITY,
22175            })
22176            .expect("a pool of thousands has room for one object");
22177
22178        for frame in 1..=3u32 {
22179            fixture.begin(device);
22180            let parity = fixture.skinning.parity();
22181            let instance = instance_record(&recorder, &fixture.renderer, handle);
22182            assert_eq!(
22183                instance.base_vertex,
22184                fixture.skinned.region().base(parity),
22185                "frame {frame} must draw out of the half parity {parity} fills"
22186            );
22187            if frame == 1 {
22188                assert_eq!(
22189                    instance.previous_base_vertex, instance.base_vertex,
22190                    "a fresh object has no previous deformation, so its first frame owes rest \
22191                     rather than a half no dispatch has written"
22192                );
22193            } else {
22194                assert_eq!(
22195                    instance.previous_base_vertex,
22196                    fixture.skinned.region().previous_base(parity),
22197                    "frame {frame} must subtract against the half the frame before it filled"
22198                );
22199                assert_ne!(
22200                    instance.previous_base_vertex, instance.base_vertex,
22201                    "frame {frame} named one half twice, which is every skinned fragment at \
22202                     rest however far its surface moved"
22203                );
22204            }
22205        }
22206
22207        // The same object, moved onto a region it has never been drawn out of:
22208        // both halves are runs no dispatch of this object's has filled, so the
22209        // rule that put the first frame at rest applies again.
22210        let second = fixture
22211            .renderer
22212            .reserve_skinned(DEMO_CUBE)
22213            .expect("a default pool has room for two more halves of a cube");
22214        assert_ne!(
22215            second.region().base(0),
22216            fixture.skinned.region().base(0),
22217            "the second reservation is the same two runs as the first, so nothing below is \
22218             about a change of region at all"
22219        );
22220        fixture.renderer.set_skinned_instance(
22221            handle,
22222            &SkinnedInstanceDesc {
22223                mesh: &second,
22224                material: DEMO_UNTINTED,
22225                transform: Mat4::IDENTITY,
22226            },
22227        );
22228
22229        for frame in 1..=2u32 {
22230            fixture.begin(device);
22231            let parity = fixture.skinning.parity();
22232            let instance = instance_record(&recorder, &fixture.renderer, handle);
22233            assert_eq!(
22234                instance.base_vertex,
22235                second.region().base(parity),
22236                "frame {frame} after the move must draw out of the new region"
22237            );
22238            if frame == 1 {
22239                assert_eq!(
22240                    instance.previous_base_vertex, instance.base_vertex,
22241                    "the first frame on a new region owes rest, exactly as a fresh object does"
22242                );
22243            } else {
22244                assert_eq!(
22245                    instance.previous_base_vertex,
22246                    second.region().previous_base(parity),
22247                    "and the frame after it is subtracting against the new region's other half"
22248                );
22249            }
22250        }
22251
22252        fixture.renderer.release_skinned(second);
22253        fixture.destroy(device);
22254        recorder.assert_valid();
22255    }
22256
22257    /// **A skinned object that moves carries the transform it moved from**, and
22258    /// the frame after it is back at rest.
22259    ///
22260    /// The transform half of a skinned motion vector, and the half the
22261    /// per-frame re-point used to erase: it rewrote the record through
22262    /// [`InstancePool::set`], which fills the previous transform out of the
22263    /// record it overwrites — and that record already held this frame's
22264    /// transform, because
22265    /// [`set_skinned_instance`](ForwardRenderer::set_skinned_instance) had put
22266    /// it there. Every skinned instance then read `previous_transform ==
22267    /// transform` on every frame, so a character that walked contributed
22268    /// nothing to the motion target from the walk, only from its deformation.
22269    /// [`InstancePool::set_bases`] is what the re-point goes through instead.
22270    ///
22271    /// Both frames are the claim. Without the second, a re-point that wrote
22272    /// some *other* stale transform into the field would pass; and the second
22273    /// is the pool's own rest rule reaching a skinned object at all, which a
22274    /// re-point that kept enrolling the element every frame would suppress
22275    /// for ever.
22276    ///
22277    /// Read out of the ring buffer the frame draws from, on
22278    /// [`instance_record`]'s terms.
22279    #[test]
22280    fn a_skinned_instance_that_moves_carries_the_transform_it_moved_from() {
22281        let (recorder, device, queue) = open();
22282        let device = device.as_ref();
22283        let mut fixture = SkinnedFixture::build(device, queue);
22284        let handle = fixture
22285            .renderer
22286            .add_skinned_instance(&SkinnedInstanceDesc {
22287                mesh: &fixture.skinned,
22288                material: DEMO_UNTINTED,
22289                transform: Mat4::IDENTITY,
22290            })
22291            .expect("a pool of thousands has room for one object");
22292
22293        // Two frames standing still, so the history the move is measured
22294        // against is a settled record rather than a fresh one.
22295        fixture.begin(device);
22296        fixture.begin(device);
22297
22298        let moved = Mat4::from_translation(Vec3::new(5.0, 0.0, 0.0));
22299        fixture.renderer.set_skinned_instance(
22300            handle,
22301            &SkinnedInstanceDesc {
22302                mesh: &fixture.skinned,
22303                material: DEMO_UNTINTED,
22304                transform: moved,
22305            },
22306        );
22307        fixture.begin(device);
22308        let instance = instance_record(&recorder, &fixture.renderer, handle);
22309        assert_eq!(
22310            instance.transform,
22311            moved.to_cols_array(),
22312            "the frame that moved the object must draw it where it arrived"
22313        );
22314        assert_eq!(
22315            instance.previous_transform,
22316            Mat4::IDENTITY.to_cols_array(),
22317            "and it must say where from — a previous transform equal to the current one is \
22318             the re-point having overwritten the move"
22319        );
22320
22321        fixture.begin(device);
22322        let settled = instance_record(&recorder, &fixture.renderer, handle);
22323        assert_eq!(
22324            settled.transform,
22325            moved.to_cols_array(),
22326            "nothing moved it again"
22327        );
22328        assert_eq!(
22329            settled.previous_transform, settled.transform,
22330            "so the frame after the move owes rest; a re-point that enrolled the element \
22331             every frame would keep it reporting the move for ever"
22332        );
22333
22334        fixture.destroy(device);
22335        recorder.assert_valid();
22336    }
22337
22338    /// **The graph barriers the skinning dispatch's write before every pass that
22339    /// pulls vertices**, and it does so because `add_skinned_passes` added the
22340    /// dispatch itself rather than trusting a caller to.
22341    ///
22342    /// Pass order alone would not settle it — a dispatch that ran first and was
22343    /// never barriered is the exact defect, and it produces a correct-looking
22344    /// frame on a desktop driver. So the transition out of
22345    /// [`ResourceState::ShaderReadWrite`] is named: there must be exactly one,
22346    /// it must sit after the dispatch, and it must sit at or before the first of
22347    /// the three passes that draw.
22348    #[test]
22349    fn the_skinning_dispatch_is_barriered_before_every_pass_that_draws() {
22350        let (recorder, device, queue) = open();
22351        let device = device.as_ref();
22352        let mut fixture = SkinnedFixture::build(device, queue);
22353        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
22354        fixture
22355            .renderer
22356            .add_skinned_instance(&SkinnedInstanceDesc {
22357                mesh: &fixture.skinned,
22358                material: DEMO_UNTINTED,
22359                transform: Mat4::IDENTITY,
22360            })
22361            .expect("room for one object");
22362        fixture.begin(device);
22363
22364        let imported = swapchain_image_at(device, TEST_EXTENT);
22365        let mut pool = crate::TransientPool::new();
22366        let mut graph = crate::RenderGraph::new(queue);
22367        let target = graph.import_image("target", imported);
22368        // The same node `Skinning::add_pass` imports — one handle is one node —
22369        // so the barriers below can be named rather than guessed at.
22370        let vertices = graph.import_buffer(
22371            "vertex-pool",
22372            ImportedBuffer {
22373                buffer: fixture.renderer.vertex_buffer(),
22374                initial: ResourceState::ShaderRead,
22375                final_state: ResourceState::ShaderRead,
22376            },
22377        );
22378        fixture.renderer.add_skinned_passes(
22379            &mut graph,
22380            &pool,
22381            target,
22382            TEST_EXTENT,
22383            &fixture.skinning,
22384        );
22385        let compiled = graph.compile(&pool).expect("a legal frame");
22386        let labels: Vec<&str> = compiled
22387            .passes()
22388            .iter()
22389            .map(crate::graph::CompiledPass::label)
22390            .collect();
22391
22392        let dispatch = labels
22393            .iter()
22394            .position(|label| *label == "skinning")
22395            .expect("add_skinned_passes adds the dispatch itself");
22396        let drawing: Vec<usize> = ["shadow", "depth-prepass", "forward"]
22397            .into_iter()
22398            .map(|wanted| {
22399                labels
22400                    .iter()
22401                    .position(|label| *label == wanted)
22402                    .unwrap_or_else(|| panic!("the frame draws through {wanted}: {labels:?}"))
22403            })
22404            .collect();
22405        for (label, at) in ["shadow", "depth-prepass", "forward"]
22406            .into_iter()
22407            .zip(&drawing)
22408        {
22409            assert!(
22410                dispatch < *at,
22411                "the dispatch is at {dispatch} and {label} at {at}: {labels:?}"
22412            );
22413        }
22414
22415        // Each drawing pass declares the read for itself, and this is asserted
22416        // per pass rather than left to the single barrier below. The graph
22417        // transitions the region once, before the first reader, and a later
22418        // pass that never declared the read finds it already in the state it
22419        // wanted — so dropping the declaration from `forward` alone changes no
22420        // barrier and moves no label, and every assertion in this test still
22421        // passes. What it does drop is that pass's *dependency* on the
22422        // dispatch, which is the only thing keeping the two in this order.
22423        for (label, at) in ["shadow", "depth-prepass", "forward"]
22424            .into_iter()
22425            .zip(&drawing)
22426        {
22427            assert!(
22428                compiled.passes()[*at].reads_buffer(vertices),
22429                "{label} draws skinned vertices and must declare that it reads them, or \
22430                 nothing but declaration order keeps it after the dispatch"
22431            );
22432        }
22433
22434        let released: Vec<usize> = compiled
22435            .passes()
22436            .iter()
22437            .enumerate()
22438            .filter(|(_, pass)| {
22439                pass.barriers().buffers.iter().any(|barrier| {
22440                    barrier.buffer == vertices
22441                        && barrier.from == ResourceState::ShaderReadWrite
22442                        && barrier.to == ResourceState::ShaderRead
22443                })
22444            })
22445            .map(|(at, _)| at)
22446            .collect();
22447        assert_eq!(
22448            released.len(),
22449            1,
22450            "exactly one transition out of the dispatch's write: {released:?} in {labels:?}"
22451        );
22452        let barrier = released[0];
22453        let first_draw = *drawing.iter().min().expect("three passes");
22454        assert!(
22455            dispatch < barrier && barrier <= first_draw,
22456            "the barrier is at {barrier}, the dispatch at {dispatch} and the first pass that \
22457             draws at {first_draw} — a draw that reads the region before the write is made \
22458             visible is the whole defect this seam exists to prevent"
22459        );
22460
22461        drop(compiled);
22462        fixture.destroy(device);
22463        pool.destroy(device);
22464        device.destroy_image_view(imported.view);
22465        device.destroy_image(imported.image);
22466        recorder.assert_valid();
22467    }
22468
22469    /// A frame with nothing to skin adds no dispatch and declares no read, and
22470    /// is the frame [`ForwardRenderer::add_passes`] would have built.
22471    #[test]
22472    fn a_frame_with_no_skinned_range_is_the_frame_add_passes_builds() {
22473        let _blurs = ssao_blur_switch();
22474        let (recorder, device, queue) = open();
22475        let device = device.as_ref();
22476        let mut fixture = SkinnedFixture::build(device, queue);
22477        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
22478
22479        let imported = swapchain_image_at(device, TEST_EXTENT);
22480        let pool = crate::TransientPool::new();
22481        let mut skinned_labels = Vec::new();
22482        for _ in 0..1 {
22483            fixture
22484                .renderer
22485                .begin_skinned_frame(
22486                    device,
22487                    &mut fixture.skinning,
22488                    &[],
22489                    &Camera::default(),
22490                    &DirectionalLight::default(),
22491                    TEST_EXTENT,
22492                )
22493                .expect("an empty plan is a legal one");
22494            let mut graph = crate::RenderGraph::new(queue);
22495            let target = graph.import_image("target", imported);
22496            fixture.renderer.add_skinned_passes(
22497                &mut graph,
22498                &pool,
22499                target,
22500                TEST_EXTENT,
22501                &fixture.skinning,
22502            );
22503            skinned_labels = graph
22504                .compile(&pool)
22505                .expect("a legal frame")
22506                .passes()
22507                .iter()
22508                .map(|pass| pass.label().to_string())
22509                .collect();
22510        }
22511        let plain = passes_in_a_frame(
22512            device,
22513            queue,
22514            &mut fixture.renderer,
22515            imported,
22516            &pool,
22517            TEST_EXTENT,
22518        );
22519        assert_eq!(
22520            skinned_labels, plain,
22521            "a frame with nothing to skin must cost the vertex pool no barrier at all"
22522        );
22523
22524        fixture.destroy(device);
22525        let mut pool = pool;
22526        pool.destroy(device);
22527        device.destroy_image_view(imported.view);
22528        device.destroy_image(imported.image);
22529        recorder.assert_valid();
22530    }
22531
22532    /// One frame recorded end to end: `begin_frame`, the graph, and an encoder
22533    /// the commands land in.
22534    ///
22535    /// Returned rather than cleaned up here because the caller reads the
22536    /// recorder afterwards, and everything below must outlive that.
22537    struct Frame {
22538        imported: ImportedImage,
22539        pool: crate::TransientPool,
22540        commands: crcbl_hal::CommandBufferHandle,
22541    }
22542
22543    impl Frame {
22544        /// Releases the frame and the image it drew into, leaving the renderer
22545        /// alive for another one.
22546        fn release(self, device: &dyn Device) {
22547            device.destroy_command_buffer(self.commands);
22548            let mut pool = self.pool;
22549            pool.destroy(device);
22550            device.destroy_image_view(self.imported.view);
22551            device.destroy_image(self.imported.image);
22552        }
22553
22554        /// Releases the frame, the renderer and the image it drew into.
22555        fn finish(self, device: &dyn Device, renderer: ForwardRenderer) {
22556            self.release(device);
22557            renderer.destroy(device);
22558        }
22559    }
22560
22561    /// Everything one labelled pass recorded, and nothing any other pass did.
22562    ///
22563    /// **Every draw assertion below is scoped through this**, and the reason is
22564    /// topic 18: the frame now records the same indirect call the colour pass
22565    /// records once per shadow cascade as well, out of that cascade's own
22566    /// arguments. A test filtering the whole stream for `DrawIndexedIndirect`
22567    /// would see one per cascade as well as the colour pass's, and could not
22568    /// say which pass any of them belonged to — so "the forward pass records one
22569    /// call per bucket" would become a claim about a total, which a shadow pass
22570    /// recording the wrong thing could satisfy.
22571    /// The compute dispatches a default frame's **resolve** records, which
22572    /// every dispatch count in this module sees and none of them is about.
22573    ///
22574    /// `RenderEffects::DEFAULT_STACK` carries `CMAA2`, whose edge detect and
22575    /// shape classification are dispatches; its apply is a draw and does not
22576    /// count here. `each_effect_toggle_removes_exactly_the_passes_it_owns` is
22577    /// what pins the resolve's pass list itself, so a tier that grew a dispatch
22578    /// fails there first and arrives here as a second red rather than as a
22579    /// silent skew.
22580    const RESOLVE_DISPATCHES: usize = 2;
22581
22582    fn commands_in_pass(
22583        recorder: &crcbl_hal::null::Recorder,
22584        label: &str,
22585    ) -> Vec<crcbl_hal::null::Command> {
22586        use crcbl_hal::null::Command;
22587
22588        let mut inside = false;
22589        let mut out = Vec::new();
22590        for command in recorder.commands() {
22591            if let Some((_, recorded)) = command.opens_pass() {
22592                inside = recorded == Some(label);
22593                continue;
22594            }
22595            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
22596                inside = false;
22597                continue;
22598            }
22599            if inside {
22600                out.push(command);
22601            }
22602        }
22603        assert!(!out.is_empty(), "no pass labelled `{label}` recorded work");
22604        out
22605    }
22606
22607    /// The extent every helper frame in this module is drawn at.
22608    ///
22609    /// Named since the bloom chain, whose length is a function of it — see
22610    /// [`crate::bloom`] — so a test comparing a pass count against
22611    /// [`fullscreen_passes`] has to ask about the same size the frame was drawn
22612    /// at. Small on purpose: two chain levels is enough for every arm here, and
22613    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`] is the one
22614    /// test that needs a frame large enough for six.
22615    ///
22616    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
22617    const TEST_EXTENT: (u32, u32) = (64, 48);
22618
22619    /// The effects a caller has to ask for, because the default stack leaves
22620    /// them out — see [`RenderEffects::DEFAULT_STACK`].
22621    ///
22622    /// Named rather than written out at each of the three sites that force them
22623    /// on, because the point of those sites is "every effect there is" and the
22624    /// bug they exist to catch is a new effect joining the set and one site
22625    /// still measuring the old one while calling it the whole stack. They are
22626    /// held out of the default for different reasons — [`crate::effects`] gives
22627    /// each, and [`RenderEffects::CONTACT_SHADOWS`]'s is the only one that is a
22628    /// pending re-bless rather than a decision — and share only that a test
22629    /// wanting the widest frame must ask.
22630    ///
22631    /// **Named for what it is rather than for what most of it is**: the set held
22632    /// four post passes and a resolve when it was `POST_EFFECTS`, and the contact
22633    /// march is neither.
22634    const OUTSIDE_THE_DEFAULT: RenderEffects = RenderEffects::BLOOM
22635        .union(RenderEffects::ANTIALIASING)
22636        .union(RenderEffects::VOLUMETRIC_FOG)
22637        .union(RenderEffects::AUTO_EXPOSURE)
22638        .union(RenderEffects::CMAA2)
22639        .union(RenderEffects::CONTACT_SHADOWS);
22640
22641    /// Every effect this renderer draws is either in the default stack or in
22642    /// [`OUTSIDE_THE_DEFAULT`].
22643    ///
22644    /// The guard on the three sites above: they force [`OUTSIDE_THE_DEFAULT`] on and
22645    /// call the result "every effect", which is only true while nothing else is
22646    /// held out. An effect added outside the default stack and not added
22647    /// here makes this red before it makes a pass-list assertion red — which is
22648    /// the useful order, since a pass list going red says a label moved and this
22649    /// says what actually happened.
22650    #[test]
22651    fn forcing_the_post_effects_on_reaches_every_effect_there_is() {
22652        assert_eq!(
22653            RenderEffects::DEFAULT_STACK.union(OUTSIDE_THE_DEFAULT),
22654            RenderEffects::all(),
22655            "an effect outside the default stack that no test forces on is an effect \
22656             the every-effect frames below have never drawn"
22657        );
22658    }
22659
22660    /// The default sun, turned a little further round for each `lap`.
22661    ///
22662    /// Topic 45's static-caching rung means a second frame over
22663    /// a scene nothing moved in records **no shadow pass at all** — see
22664    /// [`ForwardRenderer::shadow_atlas_cached`]. That is the feature, and it is
22665    /// a difference that every A/B drawing two frames from one renderer would
22666    /// otherwise be measuring on top of the one it is about. Turning the sun is
22667    /// the smallest input the atlas depends on: the cascades are refitted, so
22668    /// the atlas is redrawn, and no pass, pipeline or draw of the frame moves
22669    /// with it.
22670    ///
22671    /// Lap zero is [`DirectionalLight::default`] exactly, so a test whose first
22672    /// frame is the ordinary one keeps the frame every other test draws.
22673    fn moving_sun(lap: u32) -> DirectionalLight {
22674        let sun = DirectionalLight::default();
22675        // A degree a lap, about the axis the default direction is not parallel
22676        // to. Small enough that every cascade still sees the scene, and large
22677        // enough that the snapped cascade origin actually moves.
22678        let turn = Mat4::from_rotation_y(
22679            f32::from(u16::try_from(lap).expect("a handful of laps")) * std::f32::consts::PI
22680                / 180.0,
22681        );
22682        DirectionalLight {
22683            direction: turn.transform_vector3(sun.direction).normalize(),
22684            ..sun
22685        }
22686    }
22687
22688    /// [`frame`] drawn under [`moving_sun`], so this frame's shadow atlas is
22689    /// not the one the lap before it left in the image.
22690    fn frame_moving_the_sun(
22691        device: &dyn Device,
22692        renderer: &mut ForwardRenderer,
22693        queue: QueueHandle,
22694        lap: u32,
22695    ) -> Frame {
22696        frame_lit_by(device, renderer, queue, &moving_sun(lap))
22697    }
22698
22699    fn frame(device: &dyn Device, renderer: &mut ForwardRenderer, queue: QueueHandle) -> Frame {
22700        frame_lit_by(device, renderer, queue, &DirectionalLight::default())
22701    }
22702
22703    fn frame_lit_by(
22704        device: &dyn Device,
22705        renderer: &mut ForwardRenderer,
22706        queue: QueueHandle,
22707        sun: &DirectionalLight,
22708    ) -> Frame {
22709        frame_seen_from(device, renderer, queue, &Camera::default(), sun)
22710    }
22711
22712    fn frame_seen_from(
22713        device: &dyn Device,
22714        renderer: &mut ForwardRenderer,
22715        queue: QueueHandle,
22716        camera: &Camera,
22717        sun: &DirectionalLight,
22718    ) -> Frame {
22719        renderer
22720            .begin_frame(device, camera, sun, TEST_EXTENT)
22721            .expect("write");
22722        let imported = swapchain_image(device);
22723        let mut graph = crate::RenderGraph::new(queue);
22724        let target = graph.import_image("target", imported);
22725        let mut pool = crate::TransientPool::new();
22726        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
22727        let compiled = graph.compile(&pool).expect("a legal frame");
22728        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
22729            label: Some("forward frame"),
22730            queue,
22731        });
22732        compiled
22733            .execute(device, &mut pool, encoder.as_mut(), None)
22734            .expect("the graph executed");
22735        let commands = encoder.finish().expect("recording succeeded");
22736        Frame {
22737            imported,
22738            pool,
22739            commands,
22740        }
22741    }
22742
22743    /// A stand-in for the acquired swapchain image the frame normally ends in,
22744    /// at [`TEST_EXTENT`].
22745    fn swapchain_image(device: &dyn Device) -> ImportedImage {
22746        swapchain_image_at(device, TEST_EXTENT)
22747    }
22748
22749    /// The same, at an extent of the caller's choosing.
22750    ///
22751    /// A frame's attachments must all be one size — the graph refuses a pass
22752    /// whose colour target and depth disagree — so a test drawing at anything
22753    /// but [`TEST_EXTENT`] has to import a target of that size too.
22754    pub(super) fn swapchain_image_at(device: &dyn Device, extent: (u32, u32)) -> ImportedImage {
22755        let format = Format::Rgba8UnormSrgb;
22756        let image = device
22757            .create_image(&crcbl_hal::ImageDesc {
22758                label: Some("fake swapchain image"),
22759                image_type: crcbl_hal::ImageType::D2,
22760                extent: crcbl_hal::Extent3d::d2(extent.0, extent.1),
22761                format,
22762                mip_levels: 1,
22763                samples: 1,
22764                usage: crcbl_hal::ImageUsage::COLOR_ATTACHMENT | crcbl_hal::ImageUsage::PRESENT,
22765            })
22766            .expect("an image");
22767        let view = device
22768            .create_image_view(&crcbl_hal::ImageViewDesc {
22769                label: Some("fake swapchain view"),
22770                image,
22771                view_type: crcbl_hal::ImageViewType::D2,
22772                format,
22773                range: crcbl_hal::ImageSubresourceRange::all(format),
22774            })
22775            .expect("a view");
22776        ForwardRenderer::present_target(image, view, format, extent)
22777    }
22778
22779    /// The spin is a rotation: no scale, no shear, so the cube neither grows
22780    /// nor mirrors as it turns, and every mesh golden blessed at a `spin` is a
22781    /// picture of one cube.
22782    ///
22783    /// That is also what keeps those goldens insensitive to `mesh.slang`'s
22784    /// `normal_basis`. A matrix with orthonormal rows and a positive
22785    /// determinant is its own cofactor matrix, to within a rounding step, so
22786    /// the vertex stage writes the normals it wrote when it multiplied by the
22787    /// bare 3×3 — see [`crcbl_shaders::mesh::GpuInstance::transform`], which no
22788    /// longer requires a caller to be rigid at all.
22789    #[test]
22790    fn the_spin_matrix_stays_rigid() {
22791        for seconds in [0.0f32, 0.5, 3.25, 100.0] {
22792            let model = ForwardRenderer::spin(seconds);
22793            let basis = glam::Mat3::from_mat4(model);
22794            let product = basis * basis.transpose();
22795            for (row, expected) in [
22796                (product.x_axis, Vec3::X),
22797                (product.y_axis, Vec3::Y),
22798                (product.z_axis, Vec3::Z),
22799            ] {
22800                assert!(
22801                    (row - expected).length() < 1e-5,
22802                    "the spin at {seconds}s is not orthonormal: {product:?}"
22803                );
22804            }
22805            assert!((model.determinant() - 1.0).abs() < 1e-5, "at {seconds}s");
22806        }
22807        // And it actually moves.
22808        assert_ne!(ForwardRenderer::spin(0.0), ForwardRenderer::spin(1.0));
22809    }
22810
22811    /// The swapchain import says what a swapchain image actually needs, which is
22812    /// the knowledge the hand-written barriers used to carry.
22813    #[test]
22814    fn the_present_target_starts_undefined_and_ends_presentable() {
22815        let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
22816        let image = pool.insert(0).cast();
22817        let view = pool.insert(0).cast();
22818        let imported =
22819            ForwardRenderer::present_target(image, view, Format::Bgra8UnormSrgb, (1280, 720));
22820        assert_eq!(imported.initial, ResourceState::Undefined);
22821        assert_eq!(imported.final_state, ResourceState::Present);
22822        assert_eq!(imported.extent, (1280, 720));
22823    }
22824
22825    /// The scene target is `Rgba16Float`, and the depth target is the
22826    /// reversed-Z format. Both are locked decisions and both are cheap to pin.
22827    #[test]
22828    fn the_scene_targets_are_hdr_and_reversed_z() {
22829        let color = crate::targets::scene_color((64, 48));
22830        assert_eq!(color.format, Format::Rgba16Float);
22831        assert!(color.format.is_hdr_capable());
22832        assert!(color.usage.contains(crcbl_hal::ImageUsage::SAMPLED));
22833
22834        let depth = crate::targets::scene_depth((64, 48));
22835        assert_eq!(depth.format, Format::D32Float);
22836        assert_eq!(
22837            DepthStencilState::default().depth_compare,
22838            crcbl_hal::CompareOp::Greater
22839        );
22840    }
22841
22842    /// A sun ten degrees or so above the horizon, and one further round: two
22843    /// atmospheres whose LUTs are nowhere near each other, so a comparison
22844    /// between them cannot pass by the two skies being alike.
22845    ///
22846    /// Spelled as directions rather than as angles for
22847    /// `crcbl_shaders::atmosphere`'s reason — nothing here takes a `sin` of its
22848    /// own — and normalised by `Atmosphere::parameters` on the way in.
22849    const MOVED_SUN: Atmosphere = Atmosphere {
22850        sun_direction: Vec3::new(1.0, 0.2, 0.0),
22851        ..Atmosphere::NOON
22852    };
22853
22854    /// [`MOVED_SUN`] again, further round and lower.
22855    const MOVED_AGAIN: Atmosphere = Atmosphere {
22856        sun_direction: Vec3::new(1.0, 0.05, 0.5),
22857        ..Atmosphere::NOON
22858    };
22859
22860    /// Frames the striped march takes to cross the LUT.
22861    const MARCH_FRAMES: usize = crcbl_shaders::atmosphere::SKY_VIEW_HEIGHT / SKY_VIEW_BUILD_ROWS;
22862
22863    /// The bytes the most recent sky-view LUT upload put on the device.
22864    ///
22865    /// `crate::sky_pass` writes the whole buffer at offset zero on every frame
22866    /// that has an atmosphere, into the slot that frame is using — so the last
22867    /// write to any of the ring's buffers is the LUT the frame just recorded
22868    /// would draw. That is the only place the presented LUT is observable: the
22869    /// renderer's own copy is what a test could assert about instead, and it
22870    /// would then be asserting about the thing rather than about what reached
22871    /// the device.
22872    fn presented_lut(recorder: &Recorder, luts: &[BufferHandle]) -> Vec<u8> {
22873        recorder
22874            .events()
22875            .into_iter()
22876            .rev()
22877            .find_map(|event| match event {
22878                crcbl_hal::null::Event::BufferWritten { buffer, .. } if luts.contains(&buffer) => {
22879                    recorder.buffer_bytes(buffer)
22880                }
22881                _ => None,
22882            })
22883            .expect("a frame with an atmosphere uploads a sky-view LUT")
22884    }
22885
22886    /// A renderer with an atmosphere set and its first LUT marched, and the
22887    /// buffers that LUT reaches the device through.
22888    ///
22889    /// The three tests below all start here: the first march is synchronous, so
22890    /// one frame is what it takes to have a sky to be stale about.
22891    fn with_marched_atmosphere(
22892        device: &dyn Device,
22893        queue: QueueHandle,
22894        atmosphere: Atmosphere,
22895    ) -> (ForwardRenderer, Vec<BufferHandle>) {
22896        let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
22897            .expect("the null backend builds a renderer");
22898        let luts = renderer.primary.sky_pass.luts().to_vec();
22899        renderer.set_atmosphere(Some(atmosphere));
22900        atmosphere_frame(&mut renderer, device);
22901        (renderer, luts)
22902    }
22903
22904    /// One frame of the atmosphere tests: nothing is drawn, and `begin_frame`
22905    /// is what writes the blocks and steps the march.
22906    fn atmosphere_frame(renderer: &mut ForwardRenderer, device: &dyn Device) {
22907        renderer
22908            .begin_frame(
22909                device,
22910                &Camera::default(),
22911                &DirectionalLight::default(),
22912                (64, 48),
22913            )
22914            .expect("the frame's blocks are written");
22915    }
22916
22917    /// A sun that moved is marched a stripe per frame, and every frame until it
22918    /// is finished still uploads the LUT of the sun before it.
22919    ///
22920    /// **The amortisation, from the device's side.** Before this, one
22921    /// `begin_frame` marched the whole LUT, so a scene that swept its sun paid
22922    /// tens of milliseconds of CPU in every frame. The claim now is three
22923    /// things at once, and only the middle one is about performance: the march
22924    /// advances by `SKY_VIEW_BUILD_ROWS` per frame, the bytes reaching the
22925    /// device meanwhile are the *previous* sun's rather than a half-marched
22926    /// sky, and the new sun's LUT arrives whole on the frame the march ends.
22927    ///
22928    /// **And the aerial-perspective LUT keeps the same pace**: it rides the
22929    /// same stripes, so it too uploads the previous sun's air on every frame
22930    /// of the march and the new sun's on the frame that ends it — the lag
22931    /// behind a moving sun is [`MARCH_FRAMES`] for both, and the two never
22932    /// reach the device a sun apart.
22933    #[test]
22934    fn a_moving_sun_is_marched_a_stripe_per_frame() {
22935        let (recorder, device, queue) = open();
22936        let (mut renderer, luts) =
22937            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22938        let aerials = renderer.primary.sky_pass.aerials().to_vec();
22939
22940        let before_view = SkyView::build(&Atmosphere::NOON.parameters());
22941        let after_view = SkyView::build(&MOVED_SUN.parameters());
22942        let before = before_view.rows();
22943        let after = after_view.rows();
22944        let (air_before, air_after) = (before_view.aerial().rows(), after_view.aerial().rows());
22945        assert_ne!(
22946            before, after,
22947            "the two suns march to the same LUT, so nothing below distinguishes them"
22948        );
22949        assert_ne!(
22950            air_before, air_after,
22951            "the two suns march to the same air, so nothing below distinguishes them"
22952        );
22953        assert!(
22954            renderer.sky_view_build.is_none(),
22955            "the first march is synchronous, so no build is left in flight"
22956        );
22957        assert_eq!(
22958            presented_lut(&recorder, &luts),
22959            before,
22960            "the frame after `set_atmosphere` did not upload that sun's LUT"
22961        );
22962        assert_eq!(
22963            presented_lut(&recorder, &aerials),
22964            air_before,
22965            "the frame after `set_atmosphere` did not upload that sun's air"
22966        );
22967
22968        renderer.set_atmosphere(Some(MOVED_SUN));
22969        for step in 1..MARCH_FRAMES {
22970            atmosphere_frame(&mut renderer, device.as_ref());
22971            assert_eq!(
22972                renderer
22973                    .sky_view_build
22974                    .as_ref()
22975                    .map(SkyViewBuild::rows_done),
22976                Some(step * SKY_VIEW_BUILD_ROWS),
22977                "frame {step} of the march is not a stripe further along than frame {} was",
22978                step - 1
22979            );
22980            assert_eq!(
22981                presented_lut(&recorder, &luts),
22982                before,
22983                "frame {step} of the march uploaded something other than the sky it is still \
22984                 drawing"
22985            );
22986            assert_eq!(
22987                presented_lut(&recorder, &aerials),
22988                air_before,
22989                "frame {step} of the march uploaded air other than the sky it is still drawing's"
22990            );
22991        }
22992
22993        atmosphere_frame(&mut renderer, device.as_ref());
22994        assert!(
22995            renderer.sky_view_build.is_none(),
22996            "the march did not finish in the frames its own stripe says it takes"
22997        );
22998        assert_eq!(
22999            presented_lut(&recorder, &luts),
23000            after,
23001            "the frame that finished the march did not upload the new sun's LUT"
23002        );
23003        assert_eq!(
23004            presented_lut(&recorder, &aerials),
23005            air_after,
23006            "the frame that finished the march did not upload the new sun's air"
23007        );
23008    }
23009
23010    /// An atmosphere adds the composite for its air whether or not the fog
23011    /// effect is on, and the block tells the composite which halves to read.
23012    ///
23013    /// **The seam between the two volumes, on the renderer's side.** Three
23014    /// frames of one renderer: no atmosphere and the default stack, which has
23015    /// no fog effect in it — no composite at all, the frame drawn before the
23016    /// air existed; an atmosphere and the same stack — the composite and
23017    /// nothing of the column, and a block saying so; and an atmosphere with
23018    /// the fog effect forced on — all three passes, and a block saying both.
23019    /// The counters are held to the frame on the second: the composite is a
23020    /// full-screen triangle, and a frame that drew it and did not count it
23021    /// makes the debug panel's row disagree with the frame by one.
23022    #[test]
23023    fn an_atmosphere_composites_its_air_with_or_without_the_fog_effect() {
23024        let _blurs = ssao_blur_switch();
23025        let (recorder, device, queue) = open();
23026        let device = device.as_ref();
23027        let mut renderer =
23028            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
23029        let blocks: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
23030            .map(|frame| renderer.primary.volumetric.buffers(frame).params)
23031            .collect();
23032        let imported = swapchain_image(device);
23033        let mut pool = crate::TransientPool::new();
23034        let block = |recorder: &Recorder| {
23035            let bytes: [u8; crcbl_shaders::volumetric::PARAMS_SIZE] =
23036                presented_lut(recorder, &blocks)
23037                    .try_into()
23038                    .expect("the block is its own size");
23039            crcbl_shaders::volumetric::VolumetricParams::from_bytes(&bytes)
23040        };
23041        let column = ["volumetric-scatter", "volumetric-integrate"];
23042
23043        let bare = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
23044        let before = renderer.counters();
23045        assert!(
23046            !bare.iter().any(|pass| pass.starts_with("volumetric")),
23047            "a frame with neither fog nor an atmosphere records {bare:?}"
23048        );
23049        let off = block(&recorder);
23050        assert_eq!(
23051            off.aerial_params,
23052            [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
23053            "a frame with no atmosphere writes something into the aerial row"
23054        );
23055
23056        renderer.set_atmosphere(Some(Atmosphere::NOON));
23057        let air = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
23058        assert!(
23059            air.iter().any(|pass| pass == "volumetric-composite")
23060                && !air.iter().any(|pass| column.contains(&pass.as_str())),
23061            "an atmosphere with the fog effect off records {air:?}, where it should composite its \
23062             air and run nothing of the column"
23063        );
23064        let after = renderer.counters();
23065        assert_eq!(
23066            after.draws - before.draws,
23067            (SkyPass::PASSES + u64::from(Volumetric::COMPOSITE_PASSES)) * FULLSCREEN_DRAWS,
23068            "the atmosphere's two full-screen passes — the sky and the air — are not both counted"
23069        );
23070        let aerial_only = block(&recorder);
23071        let sun = Atmosphere::NOON.parameters().sun_direction;
23072        assert_eq!(
23073            aerial_only.aerial_params,
23074            [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON],
23075            "the aerial row does not carry the atmosphere's sun and its switch"
23076        );
23077        assert_eq!(
23078            aerial_only.fog_params[3],
23079            crcbl_shaders::volumetric::LOCAL_COLUMN_OFF,
23080            "the block tells the composite to read a column no pass filled"
23081        );
23082
23083        renderer.set_effect_request(EffectRequest {
23084            programmatic: EffectOverride::none().force(RenderEffects::VOLUMETRIC_FOG, Some(true)),
23085            ..EffectRequest::default()
23086        });
23087        let both = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
23088        assert!(
23089            column
23090                .iter()
23091                .chain(&["volumetric-composite"])
23092                .all(|name| both.iter().any(|pass| pass == name)),
23093            "an atmosphere with the fog effect on records {both:?}"
23094        );
23095        assert_eq!(
23096            block(&recorder).fog_params[3],
23097            crcbl_shaders::volumetric::LOCAL_COLUMN_ON,
23098            "the block tells the composite to skip a column the frame filled"
23099        );
23100
23101        renderer.destroy(device);
23102        pool.destroy(device);
23103        device.destroy_image_view(imported.view);
23104        device.destroy_image(imported.image);
23105        recorder.assert_valid();
23106    }
23107
23108    /// A sun that moves while a march is in flight restarts it from row zero.
23109    ///
23110    /// **The decision `refresh_sky_view` writes down**, and the reason a sun
23111    /// that moves every frame shows a frozen sky rather than a stuttering one:
23112    /// finishing a march for a sun that has already moved would swap in a LUT
23113    /// that is wrong on arrival. What is observable is the progress counter —
23114    /// a build that kept its rows would be two stripes along here rather than
23115    /// one — and the sun the build in flight names.
23116    #[test]
23117    fn a_sun_that_moves_mid_march_restarts_it() {
23118        let (recorder, device, queue) = open();
23119        let (mut renderer, luts) =
23120            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
23121        let before = SkyView::build(&Atmosphere::NOON.parameters()).rows();
23122
23123        renderer.set_atmosphere(Some(MOVED_SUN));
23124        atmosphere_frame(&mut renderer, device.as_ref());
23125        atmosphere_frame(&mut renderer, device.as_ref());
23126        assert_eq!(
23127            renderer
23128                .sky_view_build
23129                .as_ref()
23130                .map(SkyViewBuild::rows_done),
23131            Some(2 * SKY_VIEW_BUILD_ROWS),
23132            "two frames of marching did not leave two stripes marched"
23133        );
23134
23135        renderer.set_atmosphere(Some(MOVED_AGAIN));
23136        atmosphere_frame(&mut renderer, device.as_ref());
23137        assert_eq!(
23138            renderer
23139                .sky_view_build
23140                .as_ref()
23141                .map(SkyViewBuild::rows_done),
23142            Some(SKY_VIEW_BUILD_ROWS),
23143            "the march kept the rows it had marched for a sun that has since moved"
23144        );
23145        assert_eq!(
23146            renderer
23147                .sky_view_build
23148                .as_ref()
23149                .map(SkyViewBuild::atmosphere),
23150            Some(MOVED_AGAIN.parameters()),
23151            "the build in flight is marching a sun the caller has moved away from"
23152        );
23153        assert_eq!(
23154            presented_lut(&recorder, &luts),
23155            before,
23156            "a restart uploaded something other than the last LUT that finished"
23157        );
23158    }
23159
23160    /// A frame whose sun has not moved marches nothing and re-takes neither
23161    /// projection.
23162    ///
23163    /// **What `PresentedSky` is for.** `gradient_fit` and `irradiance` used to
23164    /// be taken from the LUT in every `begin_frame`, which is host work a still
23165    /// sun has no reason to pay. Both are now taken once, where the march
23166    /// finishes — so a sentinel written over the cached gradient survives a
23167    /// frame if and only if that frame took neither the march nor the
23168    /// projection again, and the same sentinel's bytes turn up in what the
23169    /// frame wrote, which is what says the cache is the thing being read.
23170    #[test]
23171    fn a_still_sun_marches_nothing_and_reprojects_nothing() {
23172        let (recorder, device, queue) = open();
23173        let (mut renderer, _luts) =
23174            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
23175
23176        let sentinel = crcbl_shaders::sky::SkyGradient {
23177            zenith: [0.125, 0.25, 0.375],
23178            horizon: [0.5, 0.625, 0.75],
23179            ground: [0.875, 1.125, 1.375],
23180        };
23181        let presented = renderer
23182            .sky_view
23183            .as_mut()
23184            .expect("the first frame marched a LUT");
23185        assert_ne!(
23186            presented.gradient, sentinel,
23187            "the sentinel is what the real projection already returns, so it proves nothing"
23188        );
23189        presented.gradient = sentinel;
23190
23191        let before = recorder.events().len();
23192        atmosphere_frame(&mut renderer, device.as_ref());
23193        assert_eq!(
23194            renderer
23195                .sky_view
23196                .as_ref()
23197                .map(|presented| presented.gradient),
23198            Some(sentinel),
23199            "a frame under a sun that has not moved re-took the projections"
23200        );
23201        assert!(
23202            renderer.sky_view_build.is_none(),
23203            "a frame under a sun that has not moved started a march"
23204        );
23205
23206        let wanted: Vec<u8> = sentinel
23207            .rows()
23208            .iter()
23209            .flatten()
23210            .flat_map(|value| value.to_le_bytes())
23211            .collect();
23212        let used = recorder
23213            .events()
23214            .into_iter()
23215            .skip(before)
23216            .filter_map(|event| match event {
23217                crcbl_hal::null::Event::BufferWritten { buffer, .. } => {
23218                    recorder.buffer_bytes(buffer)
23219                }
23220                _ => None,
23221            })
23222            .any(|bytes| {
23223                bytes
23224                    .windows(wanted.len())
23225                    .any(|window| window == wanted.as_slice())
23226            });
23227        assert!(
23228            used,
23229            "the cached gradient reached no block this frame wrote, so the frame is not reading \
23230             the cache at all"
23231        );
23232    }
23233
23234    /// **The frame block's ambient rows carry the marched LUT's own L1
23235    /// projection**, and not the three-band fit's.
23236    ///
23237    /// `begin_frame` writes [`PresentedSky::irradiance`] into
23238    /// [`FrameUniforms::sky_sh_r`] and the two rows beside it, and until this
23239    /// test nothing read them back. The only reader of those rows is arithmetic
23240    /// in `mesh.slang`'s fragment stage, and no frame in the tree draws a
23241    /// surface under an atmosphere — `crcbl`'s
23242    /// `an_atmosphere_frame_is_the_host_lut` puts no geometry in its scene at
23243    /// all — so `PresentedSky::new` handed `view.gradient_fit().irradiance()`
23244    /// instead, the three-band fit's projection rather than the LUT's, was a
23245    /// swap `docs/backlog.md` recorded passing every suite in the tree on
23246    /// 2026-09-06.
23247    ///
23248    /// **Both halves are needed and the second is the sabotage's.** The rows
23249    /// equalling the LUT's projection is the wiring; the rows *differing* from
23250    /// the fit's is what makes the equality a claim about which projection
23251    /// arrived rather than about two numbers that happen to agree. The
23252    /// `assert_ne` above them is the anti-vacuity: a sun for which the two
23253    /// projections coincide would make this test pass under the swap.
23254    ///
23255    /// [`FrameUniforms::sky_sh_r`]: crcbl_shaders::mesh::FrameUniforms::sky_sh_r
23256    #[test]
23257    fn an_atmosphere_writes_the_luts_own_ambient_term() {
23258        /// The three rows, as the little-endian bytes `FrameUniforms::to_bytes`
23259        /// puts in the block.
23260        fn rows(probe: &crcbl_shaders::probe::GpuProbe) -> Vec<u8> {
23261            [probe.sh_r, probe.sh_g, probe.sh_b]
23262                .iter()
23263                .flatten()
23264                .flat_map(|value| value.to_le_bytes())
23265                .collect()
23266        }
23267
23268        let (recorder, device, queue) = open();
23269        let (renderer, _luts) = with_marched_atmosphere(device.as_ref(), queue, MOVED_SUN);
23270
23271        let view = SkyView::build(&MOVED_SUN.parameters());
23272        let marched = rows(&view.irradiance());
23273        let fitted = rows(&view.gradient_fit().irradiance());
23274        assert_ne!(
23275            marched, fitted,
23276            "this sun's LUT and its three-band fit project to the same rows, so a block \
23277             carrying either would satisfy the check below and the swap it exists for would \
23278             pass"
23279        );
23280
23281        let block = recorder
23282            .buffer_bytes(renderer.primary.uniforms[renderer.frame])
23283            .expect("a frame with an atmosphere writes its uniform block");
23284        let at = mesh::SKY_SH_R_OFFSET;
23285        assert_eq!(
23286            &block[at..at + marched.len()],
23287            marched.as_slice(),
23288            "the frame block's sky rows are not `SkyView::irradiance` of the LUT this frame \
23289             marched, so the ambient term the fragment stage evaluates comes from somewhere \
23290             else"
23291        );
23292        assert_ne!(
23293            &block[at..at + fitted.len()],
23294            fitted.as_slice(),
23295            "the frame block's sky rows are the gradient fit's projection — the LUT was \
23296             marched and then thrown away for the three-band approximation of it"
23297        );
23298
23299        renderer.destroy(device.as_ref());
23300    }
23301}