crcbl_render/forward.rs
1//! The frame milestones 3, 4 and 5 draw: a lit mesh into an HDR target, then a
2//! tonemap into whatever the caller is presenting to.
3//!
4//! ```text
5//! ┌ cull ───────────┐ ┌ draw-args ──────┐ ┌ forward ──────────┐ ┌ tonemap ──────┐
6//! │ instances ─────▶│ │ visible ───────▶│ │ scene-color Clear │ │ reads it │
7//! │ visible list │ │ per-bucket runs │ │ scene-depth Clear │ │ writes the │
8//! │ + a GPU count │ │ + indirect args │ │ one indirect call │ │ target │
9//! │ │ │ + a draw count │ │ per bucket │ │ │
10//! └─────────────────┘ └─────────────────┘ └───────────────────┘ └───────────────┘
11//! ```
12//!
13//! Two passes and one graph. Everything that makes them ordered, everything that
14//! transitions `scene-color` from a colour attachment into a sampled texture,
15//! and everything that returns the target to [`ResourceState::Present`] is
16//! computed by [`crate::graph`] — **there is not one hand-written barrier in
17//! this file, or anywhere above the seam.**
18//!
19//! # Scope
20//!
21//! Stage 2's ladder rungs 3–5, and nothing beyond:
22//!
23//! * **3** — depth-tested spinning mesh, perspective camera in a uniform buffer.
24//! * **4** — one directional light (in `mesh.slang`). The rung's own wording is
25//! "Lambert+Blinn"; what shipped is Lambert plus a Cook-Torrance GGX lobe over
26//! a glTF metallic-roughness row, which is that rung's "real material model"
27//! arriving early rather than a different rung.
28//! * **5** — orthographic mode, which is [`Camera::projection`] and *nothing
29//! else*: no second pipeline, no branch in this file, no shader permutation.
30//!
31//! Explicitly not here: bindless at scale (P3), shadows and real post (P7),
32//! material authoring (topic 37), asset loading (P9). The mesh is a constant in
33//! `crcbl-shaders` because rung 3 says "hardcoded cube/sphere".
34//!
35//! What *is* here since 2026-08 is [`crate::material_table`]: §3.2's material
36//! table, holding **both** halves of "texture indices + factors", with
37//! [`mesh::GpuInstance::material`] selecting a row. Three rows are resident and
38//! two of them exist to be seen: [`scene::DEMO_TINTED`] differs from the default
39//! row in its factor and its roughness, and [`scene::DEMO_TEXTURED`] in its
40//! base-colour page layer alone. Which rows those are is [`crate::scene::demo`]'s
41//! to say, and so is why the shading factor rides on that row rather than on a
42//! fourth.
43//!
44//! The page is the texture side, and it is one `D2Array` image rather than an
45//! array of descriptors — `BindingModel::ArrayPages` rather than `Bindless`.
46//! That is the whole of the binding-model decision §3.2 leaves open, taken
47//! here because a layer index needs nothing of a device where a descriptor
48//! array needs `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws. So
49//! there is one lookup, one layout and one artifact rather than a permutation,
50//! and a device that reports the feature runs the same declaration. What
51//! bindless buys later is capacity, not a second path — see [`crate::scene::PageDesc`]
52//! and the layout entry for binding 7.
53//!
54//! What *was* on that list until 2026-08 is GPU culling and the indirect draw
55//! count, and both are here now: [`crate::draw_gen`] runs `cull.slang` and
56//! `draw_gen.slang` in front of this pass, and the draws below come out of the
57//! arguments they wrote. See that module for what a bucket is and why the
58//! arguments are per bucket rather than per surviving instance.
59//!
60//! # The CPU records a fixed number of draws
61//!
62//! One per bucket, whatever the scene holds — topic 03's
63//! headline goal, "10 objects and 10,000 objects record roughly the same
64//! commands". Adding an object is an instance in the pool and nothing else;
65//! removing one is [`InstancePool::remove`] and nothing else. Neither changes a
66//! single command this file records, because what varies — how many instances a
67//! bucket draws, and which — is written by a compute pass into a buffer the
68//! draw reads.
69//!
70//! Which *call* those draws are is the one branch: [`GeometryPath::IndirectCount`]
71//! takes the count from GPU memory too, and [`GeometryPath::IndirectPerBatch`] —
72//! Metal, whose API has multi-draw-indirect and no GPU-side count — reads each
73//! bucket's one argument structure unconditionally and leans on its instance
74//! count being zero.
75//!
76//! What *is* here, since 2026-08, is [`crate::mesh_pool`]: the cube is the first
77//! resident of the global vertex and index pools rather than owning two buffers
78//! of its own, so it is `{base_vertex, base_index, index_count}` like everything
79//! P7 will draw. Same geometry, different residence.
80//!
81//! And since the same month, [`crate::instance_pool`]: the cube's model matrix
82//! is a `GpuInstance` in a storage buffer rather than a field of the frame's
83//! uniform block, uploaded by delta. It holds the same matrix `begin_frame` used
84//! to write into the uniform, which is why the golden images did not move.
85//!
86//! # A second resident, and how it finds its own vertices
87//!
88//! A pool whose only mesh is at base vertex 0 cannot tell a base vertex that
89//! works from one that is silently cancelled out, and `mesh.slang`'s header
90//! shows the four targets disagreeing about exactly that: the SPIR-V subtracts
91//! `BaseVertex` back out of `SV_VertexID`, so the pool's base — passed through
92//! `draw_indexed`'s own argument — reached the shader as zero, while WGSL and
93//! MSL kept it. The same disagreement covers `SV_InstanceID`, which is what
94//! [`crate::sprite_pass`] paid for first.
95//!
96//! So **every draw this pass records passes zero for both of its bases**, and
97//! the real ones arrive as data. The base vertex comes from
98//! [`MeshPool`]'s mesh table, indexed by the drawn instance's
99//! [`mesh::GpuInstance::mesh`] — so it is resolved per instance, by the GPU,
100//! and one draw could cover instances of different meshes. The instance comes
101//! from the bucket's run of survivors, walked with `SV_InstanceID`, which counts
102//! from zero on every target *because* the first instance is zero. All a draw
103//! says for itself is which word holds its run's start — the start is the GPU's,
104//! per frame — in a [`mesh::DrawConstants`] block reached through a dynamic
105//! offset: one block per bucket, written once at build.
106//!
107//! That is what makes the pool's *second* resident,
108//! [`mesh::pyramid_vertices`], draw its own geometry rather than the cube's.
109//!
110//! The pyramid is in the pools from `new` but has no *instance* until a caller
111//! places one with [`ForwardRenderer::add_instance`] — an instance in the pool
112//! is an object in the scene now that culling decides what draws. The frame the
113//! samples draw is still the cube alone, which is why their golden images did
114//! not move either.
115//!
116//! # A third resident, and how it finds its own clusters
117//!
118//! The same argument one layer down. A mesh that fits **one** cluster cannot
119//! tell a per-cluster offset that works from one that is lost, and the cube and
120//! the pyramid fit one each — 24 and 16 vertices against a bound of 64. So the
121//! pool's third resident is [`mesh::open_box_vertices`], five clusters of one
122//! flat face each, four of them at a `Meshlet::vertex_offset` that is not zero.
123//! It is [`crate::cluster_pool`]'s counterpart to what the pyramid is for
124//! [`crate::mesh_pool`], and it is what §3.5's per-cluster culling will need
125//! before a surviving-cluster count can mean anything.
126//!
127//! It arrives on the pyramid's terms exactly: resident from `new`, in the scene
128//! only when a caller places it, so no golden moved for it either.
129//!
130//! # Uniforms are a ring, and they have to be
131//!
132//! The camera spins, so the uniform block is rewritten every frame — and the
133//! previous frame may still be reading it. One buffer would be a
134//! read-after-write hazard *across* submissions, which is precisely what
135//! `CRCBL_VK_SYNC_VALIDATION=1` exists to find and precisely what
136//! stage 2 called its headline risk. So there
137//! is one uniform buffer and one bind group per frame in flight, and
138//! [`ForwardRenderer::begin_frame`] rotates them.
139
140use crcbl_hal::{
141 BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
142 BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
143 BufferUsage, ColorTargetState, CompareOp, CullMode, DepthBias, DepthStencilState, Device,
144 DeviceCaps, Features, FilterMode, Format, GeometryPath, GraphicsPipelineDesc,
145 GraphicsPipelineHandle, HalError, ImageDesc, ImageHandle, ImageSubresourceRange, ImageType,
146 ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
147 MeshPipelineDesc, MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PolygonMode,
148 PrimitiveState, QueueHandle, Rect2d, ResourceState, SampleType, SamplerAddressMode,
149 SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc, ShaderModuleHandle, ShaderStages,
150 StoreOp, Viewport, check_portable_storage_buffers,
151};
152use crcbl_shaders::meshlet::MeshClusters;
153use crcbl_shaders::probe_gather::PunctualProducer;
154use crcbl_shaders::{
155 MESH, MESH_CLUSTER, Stage, TONEMAP, contact_shadows, dfg, level_select, ltc, mesh, ssao, ssr,
156 tonemap,
157};
158use glam::{Mat4, Quat, Vec3};
159use std::sync::Arc;
160use std::sync::atomic::{AtomicU64, Ordering};
161
162use crate::camera::{Atmosphere, Camera, DirectionalLight, Fog, Sky};
163use crate::cluster_pool::{ClusterPool, ClusterRange, PooledMesh};
164use crate::contact_shadows::ContactShadows;
165use crate::counters::FrameCounters;
166use crate::cull::Frustum;
167use crate::cull_stats::CullStatsRing;
168use crate::debug_draw::DebugDraw;
169use crate::draw_gen::{DrawGen, DrawGenDesc, FrameCull, GeneratedDraws};
170use crate::effects::{EffectRequest, RenderEffects};
171use crate::graph::{
172 BufferId, ImageId, ImportedBuffer, ImportedImage, InitialClaim, PassBuilder, RenderGraph,
173};
174// Renamed on the way in, because [`crate::light_grid::Grid`] already holds the
175// bare name here and means the froxel grid — the collision [`crate::grid`]'s
176// header predicted.
177use crate::atlas_view::AtlasView;
178use crate::bloom::Bloom;
179use crate::cmaa2::Cmaa2;
180use crate::exposure::{Exposure, ExposureAdaptation, ExposureBuffers};
181use crate::fxaa::Fxaa;
182use crate::grass::{Grass, GrassFrame, GrassScene};
183use crate::grid::{Grid as GroundGrid, GridStyle};
184use crate::hiz::Hiz;
185use crate::instance_pool::{InstanceHandle, InstancePool, InstancePoolDesc, InstancePoolError};
186use crate::light::{Light, sun_row};
187use crate::light_grid::{FROXEL_CAPACITY, FrameView, Grid, LightGrid, LightGridDesc};
188use crate::material_table::{MaterialTable, MaterialTableDesc};
189use crate::mesh_pool::{MeshHandle, MeshPool, MeshPoolDesc, MeshPoolError, MeshUpload};
190use crate::occlusion_cull::{OcclusionCulling, OcclusionPyramid};
191use crate::probe::{ProbeTable, ProbeTableDesc};
192use crate::probe_gather::{ProbeGather, ProbeGatherDesc, RsmImages, RsmTargets};
193use crate::rsm;
194use crate::scene::{self, Geometry, InstanceDesc, PageKind, ProbeUpdate, SceneDesc};
195use crate::shadow::{self, Cascades};
196use crate::skinning::{SkinRange, SkinnedMesh, Skinning, SkinningError};
197use crate::sky_pass::SkyPass;
198use crate::ssao::{Ssao, cached_group};
199use crate::ssr::{Ssr, SsrEnvironment, SsrImages};
200use crate::stack::CameraStack;
201use crate::texture::{
202 UploadedTexture, upload_texture, upload_texture_layers, upload_texture_mip_layers,
203};
204use crate::transient::TransientPool;
205use crate::upscale::Upscale;
206use crate::volumetric::{FroxelBuffers, Medium, Volumetric, VolumetricImages, VolumetricReads};
207use crate::water::{Water, WaterBodies, WaterFrame, WaterImages, WaterInputs};
208use crcbl_shaders::atmosphere::{SKY_VIEW_BUILD_ROWS, SkyView, SkyViewBuild};
209
210mod bucket_draws;
211mod frame_prepare;
212mod pages;
213mod shadow_inputs;
214mod view;
215
216use pages::{PageBindings, RetiredPage, upload_page};
217
218pub use shadow_inputs::{FRAME_UNIFORMS_READERS, UniformsField, UniformsReader};
219
220use bucket_draws::{BucketDraws, EmitTail, RegionStep};
221
222use view::{FramePasses, Overlays, TonemapPipeline, View, ViewInputs, ViewOutput};
223pub use view::{
224 FrameTargets, MAX_VIEWS, ViewBackground, ViewDesc, ViewId, ViewLighting, ViewMask, ViewTarget,
225};
226
227/// The clear behind the mesh, in **linear** light.
228///
229/// The scene target is `Rgba16Float`, so this is a linear value and the tonemap
230/// pass plus the swapchain's sRGB encode are what turn it into pixels. Writing a
231/// display-referred colour here would come out visibly paler, which is the
232/// classic HDR-pipeline mistake and worth a sentence rather than a surprise.
233pub const SCENE_CLEAR: [f32; 4] = [0.012, 0.016, 0.030, 1.0];
234
235/// How many frames of uniform buffers to keep. Matches the frame loop's
236/// frames-in-flight.
237pub const FRAMES_IN_FLIGHT: usize = 2;
238
239// The UI pass this renderer draws its HUD through keeps a ring of its own,
240// built at `crcbl_frame`'s default depth; held equal here, where both are in
241// scope, so the HUD cannot fall a frame behind the ring it shares a submit with.
242const _: () = assert!(crcbl_frame::ui_pass::FRAMES_IN_FLIGHT == FRAMES_IN_FLIGHT);
243
244/// The darkest exposure [`ForwardRenderer::set_exposure`] will accept: **five
245/// stops below** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`].
246///
247/// The floor exists so that the control cannot be driven somewhere it cannot be
248/// driven back from. The operator clamps its own *output* to `[0, 1]`, so an
249/// unclamped input has two dead ends: far enough down and every pixel rounds to
250/// the same black byte, far enough up and every pixel saturates to white — and
251/// in both the picture stops carrying the information a user would need to see
252/// which way to go. Five stops is well inside either: it is a sixteenth of the
253/// scene's brightness, dark but plainly still a picture, and it is the range a
254/// camera's exposure-compensation dial covers.
255pub const EXPOSURE_MIN: f32 = 1.0 / 32.0;
256
257/// The brightest exposure [`ForwardRenderer::set_exposure`] will accept: **five
258/// stops above** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`], for
259/// [`EXPOSURE_MIN`]'s reason.
260pub const EXPOSURE_MAX: f32 = 32.0;
261
262/// The default has to be reachable from both ends of the range, or a control
263/// that steps by a ratio starts somewhere it can only leave in one direction.
264const _: () = assert!(
265 EXPOSURE_MIN > 0.0
266 && EXPOSURE_MIN < crcbl_shaders::tonemap::DEFAULT_EXPOSURE
267 && EXPOSURE_MAX > crcbl_shaders::tonemap::DEFAULT_EXPOSURE
268);
269
270/// The format the frame's depth buffer is created with, taken from the
271/// description that creates it rather than written down a second time.
272///
273/// Read by [`ForwardRenderer::set_ground_grid`], whose pipeline is built for a
274/// depth attachment before there is a frame to ask. The extent is irrelevant to
275/// a format, which is why any is passed.
276pub(crate) const SCENE_DEPTH_FORMAT: Format = crate::targets::scene_depth((1, 1)).format;
277
278/// The format the frame's HDR scene target is created with, taken from the
279/// description that creates it rather than written down a second time.
280///
281/// Read by [`crate::debug_draw`], whose pipeline blends into whichever image the
282/// chain of HDR passes ended with — every one of them is a
283/// [`crate::targets::scene_color`]. The extent is irrelevant to a format,
284/// which is why any is passed.
285pub(crate) const SCENE_COLOR_FORMAT: Format = crate::targets::scene_color((1, 1)).format;
286
287/// The format §3.2's base-colour page is created with.
288///
289/// **`Rgba8UnormSrgb`, and that is the colour-space decision** — the argument
290/// for it is at the `upload_texture_mip_layers` call inside
291/// [`ForwardRenderer::with_scene`]. Named rather than spelled twice because
292/// [`ForwardRenderer::base_color_page_import`] has to declare the same format
293/// the image was created with, and a barrier naming a format the image is not in
294/// picks the wrong aspects.
295const BASE_COLOR_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
296
297/// The format topic 43 §2's **normal** page is
298/// created with.
299///
300/// **`Rgba8Unorm`, and the missing `Srgb` is the whole decision.**
301/// Topic 44's rung 2 argues it: a base-colour texel is a
302/// colour and glTF defines it as sRGB-encoded, so the format above is what makes
303/// the sampler decode it; a normal texel is a *number* — three components of a
304/// direction, stored as `n * 0.5 + 0.5` — and pushing it through the sRGB
305/// transfer curve is wrong by a gamma. What that looks like is not an error but
306/// a surface that leans further off vertical than the author drew, which is why
307/// the mistake survives review everywhere it is made.
308///
309/// `the_page_formats_split_colour_from_number` is the whole guard, and it is
310/// worth having because the four constants sit a few lines apart and the wrong
311/// one compiles.
312const NORMAL_PAGE_FORMAT: Format = Format::Rgba8Unorm;
313
314/// The format topic 43 §2's **metallic-roughness-
315/// occlusion** page is created with.
316///
317/// **`Rgba8Unorm`, and the missing `Srgb` is the same decision
318/// [`NORMAL_PAGE_FORMAT`] argues.** An occlusion, a roughness and a metalness
319/// are numbers rather than colours — glTF 2.0 §3.9.2 and §3.9.5 define them as
320/// linear factors — and a surface shaded through an sRGB decode of them is
321/// smoother and shinier than the author drew, which is a failure that survives
322/// review because it looks like a choice.
323///
324/// A separate constant from [`NORMAL_PAGE_FORMAT`] rather than a reuse of it,
325/// for [`LTC_SIZE_U32`]'s reason: the two stand for different facts, and a day
326/// one of them wanted a different format should be an edit here rather than a
327/// search for which callers of a shared name meant which page.
328const MRO_PAGE_FORMAT: Format = Format::Rgba8Unorm;
329
330/// The format topic 43 §2's **emissive** page is
331/// created with.
332///
333/// **`Rgba8UnormSrgb`, and it is the base-colour page's decision rather than
334/// the normal page's.** An emissive texel is a colour: glTF 2.0 §3.9.4 defines
335/// `emissiveTexture` as sRGB-encoded exactly as it defines `baseColorTexture`,
336/// and `GpuMaterial::emissive` beside it is a linear radiance, so the format is
337/// what puts the two in one space before they are multiplied.
338///
339/// A separate constant from [`BASE_COLOR_PAGE_FORMAT`] for the reason above it,
340/// and `the_page_formats_split_colour_from_number` is the guard that the four
341/// do not drift into one another.
342const EMISSIVE_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
343
344/// What the renderer needs of a [`PageKind`] to create and fill its image.
345///
346/// Written here rather than in [`crate::scene`] because the two answers are the
347/// device's: the format is the one [`base_color_page_import`] and
348/// [`normal_page_import`] have to declare, and the filter is the one
349/// [`crate::mip`] builds the chain with. A kind added by
350/// topic 43 §2's rung 3 is a new arm in each.
351///
352/// [`base_color_page_import`]: ForwardRenderer::base_color_page_import
353/// [`normal_page_import`]: ForwardRenderer::normal_page_import
354impl PageKind {
355 /// The format this kind's image is created with.
356 ///
357 /// The sRGB in one and its absence in the other is the whole colour-space
358 /// decision — see [`BASE_COLOR_PAGE_FORMAT`] and [`NORMAL_PAGE_FORMAT`],
359 /// which is where each is argued.
360 const fn format(self) -> Format {
361 match self {
362 Self::BaseColor => BASE_COLOR_PAGE_FORMAT,
363 Self::Normal => NORMAL_PAGE_FORMAT,
364 Self::MetallicRoughnessOcclusion => MRO_PAGE_FORMAT,
365 Self::Emissive => EMISSIVE_PAGE_FORMAT,
366 }
367 }
368
369 /// Every mip level below `level0`, built on the host with this kind's own
370 /// filter.
371 ///
372 /// [`crate::mip::normal_chain`] averages the decoded vectors plainly and
373 /// renormalises, where [`crate::mip::chain`] decodes an sRGB curve and
374 /// weights by alpha. A normal map mipped through the colour filter leans
375 /// further off vertical at every level than the map it was built from, and
376 /// nothing in a frame reports it.
377 fn chain(self, level0: &[u8], extent: u32) -> Vec<Vec<u8>> {
378 match self {
379 Self::BaseColor | Self::Emissive => crate::mip::chain(level0, extent),
380 Self::Normal => crate::mip::normal_chain(level0, extent),
381 Self::MetallicRoughnessOcclusion => crate::mip::linear_chain(level0, extent),
382 }
383 }
384
385 /// The device label this kind's image is created under.
386 const fn upload_label(self) -> &'static str {
387 match self {
388 Self::BaseColor => "material base colour",
389 Self::Normal => "material normals",
390 Self::MetallicRoughnessOcclusion => "material metallic-roughness-occlusion",
391 Self::Emissive => "material emissive",
392 }
393 }
394}
395
396/// The one texel a page **nothing names** is created with.
397///
398/// [`crate::texture::upload_texture_mip_layers`] refuses a zero-layer image, and
399/// every bind group of the mesh layout has to fill both page bindings whether or
400/// not the description carried either page — so a [`PageKind`] with no layers
401/// gets a 1×1 single-layer image in its own format instead of an `extent²` one
402/// nobody samples. That is the whole of what row (d) bought back:
403/// `apps/alcove`, `apps/sundial` and `apps/quarry` name no page at all, and
404/// every scene in the tree that has no normal map used to carry a full neutral
405/// layer and a third again for its chain.
406///
407/// **Magenta, and it is never sampled for its value.** A material naming no page
408/// carries [`GpuMaterial::NO_PAGE`](mesh::GpuMaterial::NO_PAGE):
409/// `mesh.slang`'s `base_color_texel` discards the fetch with a select and
410/// returns the literal `1.0`, and `shading_normal_of` returns before it fetches
411/// at all. So nothing should ever read this — and the value is chosen so that if
412/// something does, the frame says so in a colour no lit surface in this engine
413/// produces. White would blend into every untextured surface and black would
414/// read as a shadow; both are failures a golden could pass.
415const PAGE_PLACEHOLDER_TEXEL: [u8; 4] = [0xFF, 0x00, 0xFF, 0xFF];
416
417/// The format the motion-vector target is created with: two channels of half
418/// float, topic 43 §9's third colour attachment.
419///
420/// **Named here rather than in [`crate::targets::motion`]**, on
421/// [`crate::graph`]'s other format-owning descriptions' terms: the description
422/// and
423/// [`MeshModules::COLOR_TARGETS`] have to agree, and the pass that builds the
424/// pipeline is the one that owns the answer.
425///
426/// # The convention the target holds, so a consumer never has to guess it
427///
428/// **Current minus previous, in texture coordinates, `+y` down.** A pass
429/// holding the previous frame reads its history at `uv - motion`, and a surface
430/// travelling right and down the screen has both components positive.
431/// `mesh.slang`'s `motion_vector` is where the mapping is written out and this
432/// is the same sentence on the host side, because the first consumer will read
433/// one of the two and not both.
434///
435/// # Two channels and half float
436///
437/// A motion vector is a screen-space offset and has no third component. Half
438/// float rather than a normalised integer because the value is signed and
439/// unbounded — an object crossing the frame in one frame is a motion past `1.0`
440/// — and because the interesting magnitudes are small: a surface moving a
441/// tenth of a pixel is the case a temporal filter is most sensitive to, and
442/// eight or even sixteen unsigned bits over a `-1..1` range would quantise it
443/// into rest. It is also the format `crcbl_hal::Format::Rg16Float`'s own doc
444/// names motion vectors as the use for.
445pub(crate) const MOTION_FORMAT: Format = Format::Rg16Float;
446
447/// Which picture the colour pass draws instead of the shaded one.
448///
449/// The engine's debug views, as one value rather than as independent booleans,
450/// because they are not independent: every one of them rides in a single lane of
451/// the frame's uniform block and the shaders test the thresholds outermost
452/// first, so a renderer with two of them set draws exactly one.
453/// [`ForwardRenderer::debug_view`] is where that order lives, and this is what it
454/// answers with — so a menu row, a debug panel and the picture cannot disagree
455/// about which view is on.
456///
457/// **The declaration order is not the precedence** — each view was appended as
458/// it arrived, and [`ForwardRenderer::debug_view`] is the one place the order is
459/// decided. The sentinels in
460/// [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) ascend with it, though:
461/// see its `HEATMAP_VIEW_ON`, and the shaders test the outermost threshold
462/// first.
463#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
464pub enum DebugView {
465 /// The lit picture. What every frame draws unless a caller asked otherwise.
466 #[default]
467 Shaded,
468 /// Each cluster shaded by the projected screen-space error the LOD
469 /// selection judged it on — [`ForwardRenderer::set_heatmap`].
470 Heatmap,
471 /// Each cluster tinted by the DAG level it was decimated to —
472 /// [`ForwardRenderer::set_lod_view`].
473 LodTint,
474 /// World-space surface normals — [`ForwardRenderer::set_normals_view`].
475 Normals,
476 /// The ambient-occlusion channel alone, as grey —
477 /// [`ForwardRenderer::set_occlusion_view`].
478 AmbientOcclusion,
479 /// The motion vector each fragment wrote, stretched and centred on grey —
480 /// [`ForwardRenderer::set_motion_view`].
481 Motion,
482 /// The bent direction the occlusion channel carries beside its scalar, as
483 /// `n * 0.5 + 0.5` — [`ForwardRenderer::set_bent_normal_view`]. **Wins over
484 /// every other view.**
485 BentNormal,
486 /// The sun's cascades and the lit tiles beside them — the `D32Float` shadow
487 /// atlas itself, letterboxed over the finished frame with a border round
488 /// every occupied slot — [`ForwardRenderer::set_atlas_view`].
489 ///
490 /// **The one view that is a pass rather than a branch in `mesh.slang`**, and
491 /// therefore the one whose lane is the off sentinel: the colour pass draws
492 /// the shaded picture exactly as it always did and `crate::atlas_view`
493 /// replaces it afterwards. That module's header is where the placement is
494 /// argued.
495 ///
496 /// It resolves **below every view above and above [`Self::Cascades`]** — see
497 /// [`ForwardRenderer::debug_view`].
498 ShadowAtlas,
499 /// The shaded picture tinted by the cascade each sun-lit fragment's shadow
500 /// was sampled from, with the cross-fade band drawn as the blend of the two
501 /// — [`ForwardRenderer::set_cascade_view`].
502 ///
503 /// **Loses to every other view**, and it is the only one that does. The views
504 /// above draw something *instead of* the shaded picture; this one draws the
505 /// shaded picture and multiplies it, so there is nothing left for it to
506 /// modulate as soon as one of them is on. See
507 /// [`ForwardRenderer::debug_view`].
508 Cascades,
509}
510
511impl DebugView {
512 /// What a panel row or a summary line calls it.
513 #[must_use]
514 pub const fn label(self) -> &'static str {
515 match self {
516 Self::Shaded => "shaded",
517 Self::Heatmap => "heatmap",
518 Self::LodTint => "lod tint",
519 Self::Normals => "normals",
520 Self::AmbientOcclusion => "ambient occlusion",
521 Self::Motion => "motion",
522 Self::BentNormal => "bent normal",
523 Self::ShadowAtlas => "shadow atlas",
524 Self::Cascades => "cascades",
525 }
526 }
527}
528
529// Mesh-only resources follow the complete common fragment binding range.
530// Metal assigns dense native indices by resource-table order, so inserting a
531// mesh-only buffer before lights/probes would shift the layout away from the
532// independently compiled fragment stage. Sparse logical bindings cost no slots.
533const CLUSTERS_BINDING: u32 = 32;
534const CLUSTER_VERTICES_BINDING: u32 = 33;
535const CLUSTER_CORNERS_BINDING: u32 = 34;
536const CLUSTER_DRAW_ARGS_BINDING: u32 = 35;
537const CLUSTER_CULL_BINDING: u32 = 36;
538const CLUSTER_CULL_STATS_BINDING: u32 = 37;
539const CLUSTER_SELECT_BINDING: u32 = 38;
540const CLUSTER_SELECTION_BINDING: u32 = 39;
541const CLUSTER_GROUP_STATE_BINDING: u32 = 40;
542
543/// The shared fragment shader's shadow atlas slot. Historical logical gaps
544/// remain reserved so the raster shader bindings stay unchanged.
545const SHADOW_ATLAS_BINDING: u32 = 15;
546
547/// The bind-group slot the shadow atlas's **comparison** sampler is bound to.
548const SHADOW_SAMPLER_BINDING: u32 = 16;
549
550/// The bind-group slot the base-colour page is bound to.
551///
552/// Named because [`ForwardRenderer::replace_page`] rewrites it in every group
553/// of the mesh layout, as it does each page's binding — see
554/// `pages::page_binding`.
555const BASE_COLOR_PAGE_BINDING: u32 = 7;
556
557/// The bind-group slot the base-colour page's sampler is bound to.
558///
559/// Named because it is an entry [`ForwardRenderer::set_anisotropy`] rewrites
560/// in every group of the mesh layout: a sampler is a resource a group holds by
561/// handle, so a new sampler is a new group, and the rebuild finds the entry by
562/// this number.
563const PAGE_SAMPLER_BINDING: u32 = 8;
564
565/// The shared fragment shader's light list. Both shader modules declare it
566/// before mesh-only buffers so native buffer index 7 is common to both stages.
567const LIGHT_LIST_BINDING: u32 = 20;
568
569/// The bind-group slot the froxel grid is read through.
570const LIGHT_GRID_BINDING: u32 = 21;
571
572/// The fragment shader's screen-space occlusion texture. Mesh-only additions
573/// are buffers, so this resource does not shift their native argument table.
574const AMBIENT_OCCLUSION_BINDING: u32 = 22;
575
576/// The shared irradiance probe table, native buffer 9 in both shader modules.
577/// `mesh_cluster.slang` mirrors it before its own buffers to preserve the prefix.
578const PROBE_TABLE_BINDING: u32 = 23;
579
580/// The mesh path's packed `DrawGen` table, read for the screen-error heatmap.
581/// Its logical binding stays 24; after the shared fragment buffer prefix it is
582/// native buffer 10. The raster path does not declare this storage buffer.
583const LEVEL_GROUP_TABLE_BINDING: u32 = 24;
584
585/// The bind-group slot the split-sum `DFG` table is fetched through — how much
586/// of the light arriving at a GGX lobe that lobe hands back.
587///
588/// No mirror is needed in `mesh_cluster.slang`: that module adds only buffers
589/// after the shared prefix. The fragment shader's `specular_dfg` remains at
590/// native texture 3, following `ambient_occlusion` at texture 2.
591///
592/// **An image rather than a storage buffer, and that is forced.** The table is
593/// 4096 pairs and a buffer would carry it exactly; but the raster path's layout
594/// is at the WebGPU storage-buffer ceiling in its *vertex* stage, and Slang's
595/// Metal backend materialises every global into every entry point — so a row
596/// bound to the fragment stage alone would be a global the vertex stage names
597/// and nothing fills. See [`crcbl_hal::check_portable_storage_buffers`] and
598/// binding 7's `geometry` visibility.
599const SPECULAR_DFG_BINDING: u32 = 25;
600
601/// The bind-group slot §2's normal page is sampled through.
602///
603/// **Appended past [`SPECULAR_DFG_BINDING`], never inserted**, for
604/// [`PROBE_TABLE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
605/// next index in its Metal argument table by counting the same-table entries of
606/// this layout, and Slang numbers a stage's arguments by declaration order, so
607/// the two agree only while both ascend. No mirror is needed in
608/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
609///
610/// **No sampler of its own.** The page is read through
611/// [`PAGE_SAMPLER_BINDING`]'s sampler, the same trilinear anisotropic one the
612/// base-colour page uses, because it is sampled at the same UV over an image of
613/// the same extent. A second sampler would be a second layout entry, a second
614/// index in Metal's sampler argument table, and a second thing
615/// [`ForwardRenderer::set_anisotropy`] has to rebuild — for a filter that would
616/// be identical.
617const NORMAL_PAGE_BINDING: u32 = 26;
618
619/// The bind-group slot topic 44's rung 5 reads its linearly
620/// transformed cosine table through.
621///
622/// **Appended past [`NORMAL_PAGE_BINDING`], never inserted**, for that
623/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
624/// Metal argument table by counting the same-table entries of this layout, and
625/// Slang numbers a stage's arguments by declaration order, so the two agree only
626/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
627/// needs no mirror there and no index anything already owns moves.
628///
629/// **No sampler**, like the table two rows below it: four `Load`s and a bilinear
630/// blend written out in the shader, because a hardware filter's weights are
631/// fixed-function arithmetic four rasterisers compute independently and these
632/// goldens are compared across all four.
633const LTC_TABLE_BINDING: u32 = 27;
634
635/// The bind-group slot topic 45's contact-shadow channel is
636/// read through.
637///
638/// **Appended past [`LTC_TABLE_BINDING`], never inserted**, for that constant's
639/// reason exactly: `crcbl-mtl` gives a resource the next index in its Metal
640/// argument table by counting the same-table entries of this layout, and Slang
641/// numbers a stage's arguments by declaration order, so the two agree only while
642/// both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it needs
643/// no mirror there and no index anything already owns moves.
644///
645/// **No sampler**, like the occlusion channel: `mesh.slang`'s `contact_at` is a
646/// clamped `Load` at `SV_Position.xy`, and the channel is exactly the size of
647/// the frame on every pass that computed one.
648const CONTACT_SHADOW_BINDING: u32 = 28;
649
650/// The bind-group slot the irradiance probes' per-probe
651/// visibility maps are read through: one `Rg32Float` layer per probe.
652///
653/// **Appended past [`CONTACT_SHADOW_BINDING`], never inserted**, for that
654/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
655/// Metal argument table by counting the same-table entries of this layout, and
656/// Slang numbers a stage's arguments by declaration order, so the two agree only
657/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
658/// needs no mirror there and no index anything already owns moves —
659/// `msl/mesh.metal` puts it at `texture(7)`, the next free index of that table.
660///
661/// **A texture rather than a storage buffer, and that is forced**: the raster
662/// path's vertex stage is already at every storage buffer a WebGPU device
663/// guarantees, which is the same reason [`SPECULAR_DFG_BINDING`] is an image.
664///
665/// **No sampler**, like the occlusion channel and both cooked tables:
666/// `mesh.slang`'s `probe_moments` is four clamped `Load`s and a blend written
667/// out, because a hardware filter's weights are fixed-function arithmetic four
668/// rasterisers compute independently — and because `Rg32Float` is not a
669/// filterable format on WebGPU without an optional feature.
670const PROBE_VISIBILITY_BINDING: u32 = 29;
671
672/// The bind-group slot topic 43 §2's packed
673/// **metallic-roughness-occlusion** page is sampled through.
674///
675/// **Appended past [`PROBE_VISIBILITY_BINDING`], never inserted**, for
676/// [`NORMAL_PAGE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
677/// next index in its Metal argument table by counting the same-table entries of
678/// this layout, and Slang numbers a stage's arguments by declaration order, so
679/// the two agree only while both ascend. No mirror is needed in
680/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
681///
682/// **No sampler of its own**, for [`NORMAL_PAGE_BINDING`]'s reason: the page is
683/// read at the same UV over an image of the same shape as the base-colour one,
684/// so it goes through [`PAGE_SAMPLER_BINDING`]'s sampler and adds no entry to
685/// Metal's sampler argument table.
686const MRO_PAGE_BINDING: u32 = 30;
687
688/// The bind-group slot topic 43 §2's **emissive**
689/// page is sampled through.
690///
691/// **Appended past [`MRO_PAGE_BINDING`], never inserted**, for that constant's
692/// reason exactly, and it shares [`PAGE_SAMPLER_BINDING`]'s sampler on the same
693/// terms. `mesh_cluster.slang` adds only buffers after these textures, so it needs no
694/// mirror there and no index anything already owns moves.
695const EMISSIVE_PAGE_BINDING: u32 = 31;
696
697/// [`crcbl_shaders::dfg::DFG_SIZE`] as an image extent.
698///
699/// The table is square, and its size is a compile-time constant, so the
700/// conversion belongs here rather than as a fallible one at the upload.
701const DFG_SIZE_U32: u32 = dfg::DFG_SIZE as u32;
702
703/// [`crcbl_shaders::ltc::LTC_SIZE`] as an image extent.
704///
705/// The same number as [`DFG_SIZE_U32`], and a separate constant rather than a
706/// reuse of it: `crcbl_shaders::ltc`'s `the_grid_is_the_dfg_table_s_grid` is
707/// what says the two tables are the same square, and each upload naming its own
708/// module is what would make a day they were not into a compile error here
709/// rather than a stretched image.
710const LTC_SIZE_U32: u32 = ltc::LTC_SIZE as u32;
711
712/// The `Rgba8Unorm` texel that occludes nothing and steers nothing.
713///
714/// What [`ForwardRenderer::ambient_occlusion_placeholder`] holds, and therefore
715/// what `mesh.slang` reads on a frame drawing without
716/// [`RenderEffects::AMBIENT_OCCLUSION`].
717///
718/// **`r` is `0xFF`, which is `1.0`**: the shading multiplies its ambient by
719/// this and the term is untouched. Any other value would be a silent global
720/// ambient scale.
721///
722/// **`gba` are [`ssao::BENT_NORMAL_NONE`], which decodes to a zero-length
723/// direction** — the sentinel the occlusion chain writes wherever it has no
724/// bent direction to report, and which `mesh.slang`'s `bent_normal_at` answers
725/// with the fragment's own shading normal. So "no occlusion pass ran" and "no
726/// direction at this pixel" are one case with one answer, and a frame drawn
727/// with the effect off is the frame this renderer drew before the channel was
728/// widened. Encoding a direction here instead would tilt every ambient term in
729/// such a frame towards one world axis.
730const AMBIENT_OCCLUSION_NONE: [u8; 4] = [
731 0xFF,
732 ssao::BENT_NORMAL_NONE,
733 ssao::BENT_NORMAL_NONE,
734 ssao::BENT_NORMAL_NONE,
735];
736
737/// The `R8Unorm` texel the sun reaches unobstructed: `1.0`, which is `0xFF`.
738///
739/// What [`ForwardRenderer::contact_shadow_placeholder`] holds, and therefore
740/// what `mesh.slang` reads on a frame drawing without
741/// [`RenderEffects::CONTACT_SHADOWS`] — it multiplies `sun_visibility` by this
742/// and the cascades have the last word alone. Any other value would be a silent
743/// global scale on the sun.
744///
745/// The same byte as [`AMBIENT_OCCLUSION_NONE`]'s first and a constant of its
746/// own, for the reason [`LTC_SIZE_U32`] is not [`DFG_SIZE_U32`]: the two
747/// placeholders stand for different facts, and a day one of them wanted a
748/// different value should be an edit here rather than a search for which
749/// callers of a shared name meant which thing.
750const CONTACT_SHADOW_NONE: u8 = 0xFF;
751
752/// The one `Rg32Float` texel that occludes nothing: a mean distance of
753/// [`probe_visibility::FAR`](crcbl_shaders::probe_visibility::FAR) and its
754/// square.
755///
756/// What [`ForwardRenderer::probe_visibility_placeholder`] holds, and therefore
757/// what `mesh.slang` reads on a frame drawn before anything was captured or with
758/// `r_probe_visibility` off. No surface in any scene is further away than that,
759/// so `probe_weight` answers one for every probe and every fragment, and the
760/// grid is the unweighted trilinear blend it was before this rung — which is
761/// what makes the off position bit-identical rather than merely close.
762///
763/// Any *smaller* value would be a silent occluder: every probe in every scene
764/// would read as being behind a wall, and the whole grid would collapse onto
765/// `PROBE_OCCLUDED_WEIGHT`.
766fn probe_visibility_none() -> [u8; crcbl_shaders::probe_visibility::TEXEL_BYTES] {
767 let mut texel = [0u8; crcbl_shaders::probe_visibility::TEXEL_BYTES];
768 let far = crcbl_shaders::probe_visibility::FAR;
769 texel[..4].copy_from_slice(&far.to_le_bytes());
770 texel[4..].copy_from_slice(&(far * far).to_le_bytes());
771 texel
772}
773
774/// The reversed-Z far plane, in the two places that have to agree about it.
775///
776/// `ssao.slang` leaves early at exactly this depth because the unprojection there
777/// divides by a `clip.w` an infinite reversed-Z projection takes to zero. The
778/// shader cannot include the seam and `crcbl-shaders` does not depend on it, so
779/// the mirror is checked here — which is the only place both names are in scope.
780const _: () = assert!(crcbl_hal::depth::CLEAR == crcbl_shaders::ssao::DEPTH_FAR);
781
782/// How many buckets a resident mesh occupies, which is **not the same on every
783/// geometry path** — the one place in this renderer the two differ in shape
784/// rather than in the call they record.
785///
786/// A flat mesh is one bucket either way. A DAG is one bucket on
787/// [`EmitTail::Mesh`]: a bucket is a mesh's run of clusters, and the point of
788/// topic 25's per-cluster selection is that one dispatch covers
789/// several levels at once, so the run is every level's clusters end to end and
790/// the bucket's mesh id is level 0's.
791///
792/// On the two indirect tails a DAG is one bucket **per level**, because there
793/// the same plan takes a uniform cut and a level is drawn as an ordinary index
794/// range: a DAG's levels are separate mesh table entries, `draw_gen.slang`
795/// selects one per instance, and a bucket is what an indexed draw of one index
796/// range *is*. See [`ForwardRenderer::level_buckets`].
797const fn buckets_for(levels: usize, emit: EmitTail) -> usize {
798 if emit.is_mesh() { 1 } else { levels }
799}
800
801/// Every material mode this renderer routes a draw by, and the order the bucket
802/// table lays its per-mode runs of every mesh's levels down in.
803///
804/// [`GpuMaterial::mode`](mesh::GpuMaterial::mode)'s whole range, which is why
805/// the routing is total rather than checked: a row's mode is
806/// `flags & GpuMaterial::MODE_MASK`, that mask is the alpha-mask bit and the
807/// double-sided one, and the four combinations of them are these — so no
808/// material can carry a mode that is not in this list and no instance can
809/// scatter into a bucket that does not exist. Widening the mask means adding the
810/// mode here **and** giving it a depth pipeline in
811/// [`ForwardRenderer::depth_partitions`] in the same change — the two are the
812/// producer and the consumer of one list.
813///
814/// **A scene emits a twin per mode its own materials carry**, not one per
815/// entry here: two materials of two modes are two twins whichever two they are,
816/// and only a scene actually holding all four pays for four. The build below is
817/// where that filter is, and this module's
818/// `an_all_opaque_scene_keeps_one_bucket_per_mesh_level` is what holds it.
819const DEPTH_MODES: [u32; 4] = [
820 0,
821 mesh::GpuMaterial::ALPHA_MODE_MASK,
822 mesh::GpuMaterial::DOUBLE_SIDED,
823 mesh::GpuMaterial::ALPHA_MODE_MASK | mesh::GpuMaterial::DOUBLE_SIDED,
824];
825
826/// A pipeline and its [`CullMode::None`] twin: the two objects a pass binds to
827/// draw single-sided and double-sided buckets of one frame.
828///
829/// **A pipeline rather than a per-draw state, because no backend seam exposes
830/// dynamic cull mode** — and `crcbl_hal::CommandEncoder::set_stencil_reference`
831/// is the precedent for why one would not be added: a raster state a recorded
832/// stream carried per draw is a state every backend has to be able to change
833/// between two indirect calls, and the portable answer to "this draw rasterises
834/// differently" is a second pipeline. Which draws take which is
835/// [`ForwardRenderer::sided_partitions`].
836///
837/// Four passes need the pair — the colour pass, the two depth-only ones and the
838/// reflective shadow map — so it is a type rather than eight fields, and the
839/// twins are built together so a renderer can never hold one without the other.
840#[derive(Clone, Copy, Debug, PartialEq, Eq)]
841struct SidedPipelines {
842 /// [`CullMode::Back`]: every bucket whose material is single-sided, which is
843 /// every bucket of every scene that does not use `doubleSided`.
844 single: GraphicsPipelineHandle,
845 /// [`CullMode::None`]: the buckets whose material carries
846 /// [`GpuMaterial::DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED).
847 ///
848 /// Built on every scene rather than only on one that has such a material,
849 /// for [`MeshModules::depth_masked_pipeline`]'s stated reason: the modules
850 /// are released inside `build` and a pipeline built later would need them
851 /// back, which is a second shader compilation.
852 double: GraphicsPipelineHandle,
853}
854
855/// The pixel budget topic 25's descent compares a group's projected
856/// error against, unless a caller sets another with
857/// [`ForwardRenderer::set_lod_error_budget`].
858///
859/// One pixel, because that is what the metric is *for*: a level's error is how
860/// far its simplification may have moved the surface, so a budget of a pixel is
861/// the point at which a level change stops being something a viewer can see.
862/// The plan's "correct thresholds make pops sub-pixel by definition" is this
863/// number.
864const LOD_ERROR_BUDGET: f32 = 1.0;
865
866/// Bytes one bucket's draw-constant block occupies, whichever of the two blocks
867/// it holds.
868///
869/// The larger of [`mesh::DRAW_CONSTANTS_SIZE`] and
870/// [`CLUSTER_DRAW_CONSTANTS_SIZE`](crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE),
871/// because which one a bucket holds is the geometry path's decision and the
872/// buffer, its dynamic stride and the range the bind group names are all fixed
873/// before that decision reaches them.
874///
875/// **The bound range is the half that bites.** A range sized for the smaller
876/// block leaves the larger one's tail outside it, and a uniform read past the
877/// bound range is not a fault — it is a zero. Sized at sixteen bytes, the mesh
878/// path's `group_stride` read back as zero and every instance descended against
879/// instance zero's LOD state.
880const DRAW_CONSTANTS_BLOCK: u64 =
881 if mesh::DRAW_CONSTANTS_SIZE > crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE {
882 mesh::DRAW_CONSTANTS_SIZE as u64
883 } else {
884 crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE as u64
885 };
886
887/// How far below the budget an already-expanded group is held before it
888/// collapses again — topic 25's "switch-up and switch-down differ",
889/// as a fraction of [`LOD_ERROR_BUDGET`].
890///
891/// A ratio and not an offset because the band has to scale with the budget: a
892/// fixed number of pixels is most of a one-pixel budget and none of a fifty-pixel
893/// one. A fifth of the budget is a deadband a camera has to move decisively out
894/// of, and one a camera drifting along a boundary never leaves — which is the
895/// flicker the plan is about. `crcbl_shaders::cluster_select::LodBudgets` is the
896/// pair this produces, and a ratio of one is that type's `sharp`: no band, and
897/// the setting that shows the band is what stops the flicker.
898const LOD_HOLD_RATIO: f32 = 0.8;
899
900/// How much larger than the camera's the pixel budget a shadow cascade selects
901/// under is — topic 25's "**Shadow LOD bias**: shadow-pass culling
902/// selects +1/+2 coarser levels — casters are cheap where it never shows".
903///
904/// # A budget factor, because a level is not a parameter of the rule
905///
906/// The descent compares a group's projected error to a pixel budget; it never
907/// names a level. So "one or two levels coarser" is an *intent*, and the budget
908/// that produces it is the setting — and the two do not convert, because how far
909/// apart two levels' errors are is a property of the mesh. The committed dunes
910/// DAG is the demonstration: the step from one level's error to the next is
911/// several times larger in the middle of that hierarchy than at its base, and
912/// across its top levels there is no step at all — they report one error and are
913/// never separately selected by any budget. A bias expressed in levels would
914/// mean something different at each of those. `cook-clusters` prints the per
915/// level errors it built.
916///
917/// Four, then, is two doublings of the budget: enough that a caster is drawn
918/// coarser than the same object is in the colour pass, and small enough to stay
919/// inside what a shadow hides. What hides it is that a shadow edge is filtered —
920/// the atlas is read through a comparison sampler with linear filtering, so an
921/// edge arrives already spread over neighbouring texels — and that the atlas
922/// quantises every caster to [`shadow::TILE`] texels per cascade before anything
923/// samples it.
924///
925/// # Why one number, applied to the whole pass
926///
927/// **A cut is a cover only while expansion is monotone up the DAG**, and this
928/// scaling is what keeps it so. Multiplying both budgets by one positive
929/// constant leaves the rule in
930/// [`crcbl_shaders::cluster_select`]'s form with different constants in it, and
931/// that module's induction turns on the projected error being monotone up the
932/// DAG rather than on what the constants are — so the shadow pass's cut is a
933/// cover for exactly the reason the camera's is. A bias that varied by cluster,
934/// by group, by level or by cascade would not be: two groups on one branch would
935/// be judged against different budgets, and a child expanding under an
936/// unexpanded parent is a hole.
937///
938/// Being larger than one also makes the shadow pass's expanded set a **subset**
939/// of the colour pass's, since the two now select from one eye at one scale: a
940/// group over `k` times the budget is over the budget. So the shadow cut is
941/// never finer than the camera's anywhere, which is the property
942/// `crcbl-vk`'s `the_shadow_cascades_select_coarser_than_the_camera` reads back
943/// and asserts.
944pub const SHADOW_LOD_BIAS: f32 = 4.0;
945
946/// How many culls the shadow atlas needs: one per cascade and **one per shadowed
947/// light**, whatever kind of light it is.
948///
949/// Topic 18's fourth decision, as a number. A point light's six faces share the
950/// light's sphere — which is what a cull tests against — so they share one
951/// [`DrawGen`] and its visible set, and the six draws differ in a matrix and a
952/// viewport. Six generators per light would be six copies of
953/// [`TileBuffers::group_state`], which is where the cost of one is written down.
954const SHADOW_CULLS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS;
955
956/// How many shadow *views* there are: one per cascade, and one per face of every
957/// light slot.
958///
959/// A view is what has a matrix, so it is what has a frame-block copy, a bind
960/// group and a cut of its own — while a *tile* is where a view lands in the
961/// atlas and a *cull* is which visible set it draws. The three were one number
962/// until a light could own six tiles.
963///
964/// Every slot carries [`shadow::POINT_FACES`] views whether the light in it is a
965/// point or a spot, because a bind group names its buffers when it is created
966/// and the kind of light holding a slot changes per frame. A spot uses face 0's
967/// view and the other five are never recorded — they cost a uniform buffer and a
968/// descriptor each, which is nothing beside the [`DrawGen`] a second *cull*
969/// would cost.
970const SHADOW_VIEWS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS * shadow::POINT_FACES;
971
972/// Cascade 0's view, which is the one the irradiance probes'
973/// reflective shadow map is drawn through.
974///
975/// **A cascade is its own view index**, which is what `add_shadow_pass`'s view
976/// list pushes; [`shadow_view`] numbers a *light slot's* faces and starts past
977/// [`shadow::CASCADES`], so it is not the function to reach for here.
978const CASCADE_ZERO_VIEW: usize = 0;
979
980const _: () = assert!(
981 CASCADE_ZERO_VIEW < shadow::CASCADES,
982 "cascade 0's view has to be one of the cascades' own, not a light slot's"
983);
984
985/// Which view is face `face` of light slot `slot`.
986const fn shadow_view(slot: usize, face: usize) -> usize {
987 shadow::CASCADES + slot * shadow::POINT_FACES + face
988}
989
990/// Which cull light slot `slot` draws from.
991const fn shadow_cull(slot: usize) -> usize {
992 shadow::CASCADES + slot
993}
994
995/// One punctual shadow face this frame draws into the punctual reflective
996/// shadow map, and everything both halves of the updater need of it.
997///
998/// The irradiance probes' punctual producer. It carries no
999/// matrix and no visible set: a face's transform is already in the uniform block
1000/// [`ForwardRenderer::shadow_groups`] binds, and its draws are the ones its
1001/// slot's cull generated for the atlas — which is what makes this rung cost no
1002/// second cull and no second matrix.
1003#[derive(Clone, Copy, Debug)]
1004struct PunctualFace {
1005 /// Which shadow view this face is — [`shadow_view`]'s answer, and the index
1006 /// of the bind group whose block holds that face's own `view_proj`.
1007 view: usize,
1008 /// Which of the frame's shadow culls generated its draws — [`shadow_cull`]'s
1009 /// answer for the slot this face belongs to.
1010 cull: usize,
1011 /// Which face of its light this is, and so — where the light's cull tagged
1012 /// its casters by face — which draw region it draws.
1013 face: usize,
1014 /// Where it lands in the punctual map — [`rsm::punctual_tile`], which is the
1015 /// rectangle the pass sets its viewport to *and* the one the gather reads
1016 /// this face's texels out of.
1017 tile: shadow::TileRect,
1018 /// The light this is a face of, as the gather weighs its texels.
1019 producer: PunctualProducer,
1020}
1021
1022/// The draw region face `face` of a light draws: its own region where the
1023/// light's cull tagged casters by face, and region 0 — every survivor — where it
1024/// did not. See [`crcbl_shaders::draw_gen::FACE_REGION_BASE`].
1025fn face_region(by_face: bool, face: usize) -> u32 {
1026 if by_face {
1027 crcbl_shaders::draw_gen::FACE_REGION_BASE
1028 + u32::try_from(face).unwrap_or_else(|_| unreachable!("a light has six faces"))
1029 } else {
1030 0
1031 }
1032}
1033
1034/// One light's row in the gather's producer table, for the face standing at
1035/// `tile`.
1036///
1037/// **Built out of the light's own row**, which is the one place a light becomes
1038/// numbers — so the falloff, the cone and the colour the bounce is weighed by
1039/// are the very ones `mesh.slang` weighs the same light's direct term by, rather
1040/// than a second reading of the same fields that could round or widen
1041/// differently. [`Light::row`](crate::light::Light::row) is handed [`None`]
1042/// because a producer occludes through nothing: the gather gates a texel with
1043/// the probe's own visibility map, not with the light's.
1044fn producer_row(light: &Light, tile: shadow::TileRect) -> PunctualProducer {
1045 let row = light.row(None);
1046 PunctualProducer {
1047 position: [row.position[0], row.position[1], row.position[2]],
1048 radius: row.position[3],
1049 color: [row.color[0], row.color[1], row.color[2]],
1050 cos_outer: row.direction[3],
1051 axis: [row.direction[0], row.direction[1], row.direction[2]],
1052 cos_inner: row.cos_inner,
1053 origin: [tile.x, tile.y],
1054 side: tile.side,
1055 kind: row.kind,
1056 }
1057}
1058
1059const _: () = assert!(
1060 SHADOW_CULLS == shadow::GROUPS,
1061 "a cull is a cadence group: `shadow::Cadence` schedules what this file \
1062 dispatches, and two different counts would schedule a group nothing draws"
1063);
1064
1065/// Vertices in the over-sized triangle `mesh.slang`'s `depthClearVertexMain`
1066/// generates from `SV_VertexID`. No geometry is bound.
1067const TILE_CLEAR_VERTICES: u32 = 3;
1068
1069const _: () = assert!(
1070 crcbl_shaders::mesh::SHADOW_ATLAS_CLEAR_DEPTH == crcbl_hal::depth::CLEAR,
1071 "the stage that resets one tile writes a depth the attachment's own clear \
1072 does not, so a held tile and a cleared one would answer differently where \
1073 nothing was drawn"
1074);
1075
1076/// Narrows the shadow pass's viewport and scissor to one tile of the atlas.
1077///
1078/// The rectangle the allocator handed out — the same one the fragment stage
1079/// samples through, out of [`shadow::Selection`]. The graph set a viewport over
1080/// the whole atlas before the pass body ran, and this is what narrows it: the
1081/// same clip-space matrix mapped into a different part of the image, and for a
1082/// point light six different matrices into six of them off one visible set.
1083///
1084/// A function rather than the two calls inline, because the tile clear and the
1085/// draws that follow it walk the same tiles and a viewport set one way for one
1086/// of them would clear a rectangle nothing draws into.
1087fn set_shadow_tile(encoder: &mut dyn crcbl_hal::CommandEncoder, tile: shadow::TileRect) {
1088 let rect = Rect2d {
1089 x: i32::try_from(tile.x).unwrap_or(i32::MAX),
1090 y: i32::try_from(tile.y).unwrap_or(i32::MAX),
1091 width: tile.side,
1092 height: tile.side,
1093 };
1094 encoder.set_viewport(&Viewport {
1095 x: rect.x as f32,
1096 y: rect.y as f32,
1097 width: rect.width as f32,
1098 height: rect.height as f32,
1099 ..Viewport::from_size(rect.width, rect.height)
1100 });
1101 encoder.set_scissor(&rect);
1102}
1103
1104/// What the last executed graph left the renderer-owned import `image` in, as an
1105/// [`ImportedImage::initial`].
1106///
1107/// **[`ResourceState::Undefined`] is the answer to an empty ledger, not a
1108/// fallback around one.** The ledger records what a graph *executed*, so nothing
1109/// recorded means nothing has run against this image on this pool — a freshly
1110/// created image before its first frame, and an image whose pool has been
1111/// through [`TransientPool::destroy`] — and `Undefined` is what an image no
1112/// barrier has moved is in. It is also the only declaration that lets the
1113/// incoming barrier hand the image a layout at all: every other state names an
1114/// old layout the image is not in.
1115///
1116/// The reason this is a lookup and not a field the renderer advances: a graph is
1117/// built, then compiled, and [`RenderGraph::compile`] can refuse it. A field
1118/// stepped forward while the passes were declared would have moved for a frame
1119/// that never reached the GPU, and the next frame's declaration — now wrong —
1120/// has no ledger entry to contradict it, so [`InitialClaim::Tracked`] would pass
1121/// it through. One source of truth is what removes that gap rather than
1122/// narrowing it.
1123fn imported_state(pool: &TransientPool, image: ImageHandle) -> ResourceState {
1124 pool.imported_image_use(image)
1125 .unwrap_or(ResourceState::Undefined)
1126}
1127
1128/// The passes [`ForwardRenderer::add_passes`] records itself: the shadow
1129/// atlas's, the two reflective shadow maps, the depth prepass, the forward pass,
1130/// the debug draw layer, the tonemap, the ground grid and the
1131/// culling-statistics copy — plus [`Ssao::MAX_PASSES`], [`Ssr::PASSES`],
1132/// [`ProbeGather::PASSES`], [`Bloom::MAX_PASSES`], [`Exposure::PASSES`],
1133/// [`POST_TONEMAP_PASSES`] and [`Upscale::PASSES`] beside them.
1134///
1135/// [`AtlasView::PASSES`] has no term of its own and is inside
1136/// [`POST_TONEMAP_PASSES`] instead, which is where that is argued: the atlas
1137/// viewer and the resolve are never both recorded.
1138///
1139/// The reflective shadow maps and [`ProbeGather::PASSES`] are counted on the
1140/// ground grid's terms: all three are off unless a scene's
1141/// [`ProbeUpdate`] asks for them, and a bound short
1142/// of the frame that does ask would silently stop timing its last pass. The
1143/// punctual map is a pass whether or not the frame has a punctual light to draw
1144/// into it — see `ForwardRenderer::add_shadow_pass`, where the clear is what the
1145/// gather reads on a frame that lights none.
1146///
1147/// Every other pass in the frame belongs to a [`DrawGen`] or to the
1148/// [`LightGrid`], which is why this is the only count written here rather than
1149/// derived — see [`ForwardRenderer::MAX_PASSES`]. The copy is counted even
1150/// though a device that refused the readback records one fewer: this is a
1151/// ceiling, and one that came up short would silently stop timing the last pass
1152/// of every frame. It is the **all-effects-on** count for the same reason: a
1153/// frame that switched one off records fewer, and a bound that tracked the
1154/// toggles would have to be re-sized whenever they moved.
1155///
1156/// The ground grid is counted on the same terms, even though it is off by
1157/// default and is not a [`RenderEffects`] bit: a caller that switches it on
1158/// records one more pass, and a bound short of that would silently stop timing
1159/// the last pass of every frame it drew. The render-scale upscale is the second
1160/// of those — see [`ForwardRenderer::set_render_scale`], which is `1.0` and
1161/// therefore absent until a caller moves it. The debug draw layer is the third,
1162/// and [`DebugDraw::MAX_PASSES`] is its own ceiling.
1163///
1164/// **The bloom, Hi-Z and occlusion terms are ceilings where the others are
1165/// counts**: a chain's length is a function of the target's extent — see
1166/// [`crate::bloom`] and [`crate::hiz`] — and the occlusion pair's is a function
1167/// of [`crate::ssao::r_ssao_blur_passes`], while this constant is read before
1168/// either an extent or a console is known. The frame that lands on
1169/// it is a large one with bloom switched on; every smaller frame records fewer,
1170/// exactly as a frame with a free shadow slot does.
1171const RENDER_PASSES: u32 = 8
1172 // The occlusion cull's late depth prepass and its farthest pyramid, on the
1173 // ground grid's terms: off unless a caller switches the cull on.
1174 + 1
1175 + OcclusionPyramid::PASSES
1176 + DebugDraw::MAX_PASSES
1177 + ProbeGather::PASSES
1178 + Ssao::MAX_PASSES
1179 + ContactShadows::PASSES
1180 + Hiz::PASSES
1181 + Ssr::PASSES
1182 + Volumetric::PASSES
1183 + Water::PASSES
1184 + Grass::PASSES
1185 + Exposure::PASSES
1186 + Bloom::MAX_PASSES
1187 + POST_TONEMAP_PASSES
1188 + Upscale::PASSES;
1189
1190/// What the frame's one resolve slot costs at its widest: the larger of the two
1191/// antialiasing tiers.
1192///
1193/// **The larger and not the sum**, because the two are never both recorded —
1194/// [`RenderEffects::CMAA2`] carries that in writing and
1195/// [`ForwardRenderer::add_passes`] is where the choice is made. So this is the
1196/// all-effects-on count as well as the ceiling, which is the property
1197/// [`RENDER_PASSES`] needs from every term it adds up.
1198///
1199/// [`ForwardRenderer::add_passes`]: ForwardRenderer::add_passes
1200const RESOLVE_PASSES: u32 = if Fxaa::PASSES > Cmaa2::PASSES {
1201 Fxaa::PASSES
1202} else {
1203 Cmaa2::PASSES
1204};
1205
1206/// What the frame's one **post-tonemap** slot costs at its widest: the resolve
1207/// above, or [`crate::atlas_view`]'s pass, which replaces the picture instead of
1208/// filtering it.
1209///
1210/// **The larger and not the sum**, on [`RESOLVE_PASSES`]' terms and for a
1211/// reason of the same shape: [`ForwardRenderer::resolved_effects`] takes *both*
1212/// antialiasing tiers off for every debug view, and the atlas viewer records
1213/// only on the frame [`ForwardRenderer::debug_view`] resolved to
1214/// [`DebugView::ShadowAtlas`] — which is a debug view. So a frame that draws the
1215/// atlas resolves nothing, a frame that resolves is not drawing the atlas, and
1216/// neither can be short of this. `the_pass_bound_is_the_widest_frame_the_renderer_records`
1217/// is what holds the arithmetic to a frame that was actually recorded.
1218const POST_TONEMAP_PASSES: u32 = if RESOLVE_PASSES > AtlasView::PASSES {
1219 RESOLVE_PASSES
1220} else {
1221 AtlasView::PASSES
1222};
1223
1224/// Draws a full-screen pass records: the over-sized triangle, drawn once.
1225///
1226/// The smallest fraction of the target extent a frame may be drawn at.
1227///
1228/// A quarter in each dimension, which is a sixteenth of the pixels — below that
1229/// the internal frame is small enough that a Catmull-Rom reconstruction of it
1230/// stops being a picture of the scene and starts being a picture of the filter,
1231/// and the Hi-Z pyramid and the bloom chain both run out of levels. Every
1232/// engine's resolution slider bottoms out somewhere; this is where this one
1233/// does, and [`ForwardRenderer::set_render_scale`] clamps to it rather than
1234/// refusing, so a settings slider cannot hand the renderer a frame it cannot
1235/// draw.
1236pub const MIN_RENDER_SCALE: f32 = 0.25;
1237
1238/// The anisotropy the base-colour page is sampled with where the device grants
1239/// [`Features::SAMPLER_ANISOTROPY`].
1240///
1241/// Eight, which is topic 43's filtering rung's
1242/// default and the figure current engines default their own slider to: past it
1243/// the footprint's long axis is already sampled finely enough that sixteen is
1244/// invisible at a grazing angle and costs the same again in fetches. A device
1245/// whose [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) is lower gets
1246/// that limit instead — [`ForwardRenderer::anisotropy_for`] is the clamp — and a
1247/// device without the feature gets one, which is the value that turns it off.
1248pub const DEFAULT_ANISOTROPY: f32 = 8.0;
1249
1250/// Named rather than written into [`ForwardRenderer::counters`]'s arithmetic,
1251/// because these are the only draws in this file whose instance and triangle
1252/// counts the CPU knows exactly — everything else here goes through an indirect
1253/// call.
1254const FULLSCREEN_DRAWS: u64 = 1;
1255
1256/// How many full-screen passes a frame drawing `effects` at `extent` records:
1257/// the tonemap, always, and each switched-on effect's passes beside it.
1258///
1259/// **A function of the frame rather than a constant**, since
1260/// topic 48's toggles: it was the tonemap alone, then
1261/// five, and either written down is a number that stops matching the frame. The
1262/// tonemap is the one that is not conditional — a frame has to reach the
1263/// swapchain.
1264///
1265/// **`extent` is here because the bloom chain's length depends on it** — see
1266/// [`crate::bloom`] — where the two pairs above are the same two passes at every
1267/// size. A frame too small for even one chain level records none of them, which
1268/// is the same arithmetic as the toggle being off. It is the **internal** render
1269/// extent for the same reason: that is the extent every one of these passes runs
1270/// at.
1271///
1272/// `upscaling` is not a [`RenderEffects`] bit and could not be one — it is a
1273/// resolution, not an effect — so it arrives as its own argument, on the ground
1274/// grid's terms. It is false on every frame at full render scale, which is the
1275/// frame this function counted before the knob existed.
1276///
1277/// `ssao_blurs` arrives the same way and for the same reason: it is a console
1278/// variable rather than an effect bit, and it is the caller's job to read it
1279/// **once** for the frame. Reading it here as well would be a second read that
1280/// a command landing between the two could disagree with, and the disagreement
1281/// would be a counter describing a frame that was not recorded.
1282fn fullscreen_passes(
1283 effects: RenderEffects,
1284 extent: (u32, u32),
1285 upscaling: bool,
1286 ssao_blurs: u32,
1287) -> u64 {
1288 let mut passes = 1;
1289 if upscaling {
1290 passes += Upscale::PASSES as u64;
1291 }
1292 if effects.contains(RenderEffects::AMBIENT_OCCLUSION) {
1293 passes += u64::from(Ssao::passes(ssao_blurs));
1294 }
1295 if effects.contains(RenderEffects::CONTACT_SHADOWS) {
1296 passes += u64::from(ContactShadows::PASSES);
1297 }
1298 if effects.contains(RenderEffects::REFLECTIONS) {
1299 // The march's pair, and the pyramid it climbs — which is as long as the
1300 // extent allows and is zero on a frame too small to halve once, so this
1301 // term is the only one here that is not a constant per effect.
1302 passes += Ssr::PASSES as u64 + u64::from(crate::hiz::levels_for(extent));
1303 }
1304 if effects.contains(RenderEffects::BLOOM) {
1305 passes += u64::from(Bloom::passes_for(extent));
1306 }
1307 // **One resolve slot, and the higher tier takes it.** Both bits set is a
1308 // frame with CMAA2's passes and no FXAA pass at all, which is what
1309 // [`RenderEffects::CMAA2`] means by the two never both running — so this is
1310 // an `else if` rather than two independent terms.
1311 //
1312 // **[`Cmaa2::FULLSCREEN_PASSES`] and not [`Cmaa2::PASSES`]**: what this
1313 // function counts is full-screen *draws*, and two of that tier's three
1314 // passes are compute dispatches. [`crate::exposure`]'s three are left out
1315 // of this arithmetic for the same reason.
1316 if effects.contains(RenderEffects::CMAA2) {
1317 passes += Cmaa2::FULLSCREEN_PASSES;
1318 } else if effects.contains(RenderEffects::ANTIALIASING) {
1319 passes += Fxaa::PASSES as u64;
1320 }
1321 if effects.contains(RenderEffects::VOLUMETRIC_FOG) {
1322 // **[`Volumetric::COMPOSITE_PASSES`], not [`Volumetric::PASSES`].** The
1323 // scatter and the column scan are compute dispatches; what this
1324 // function counts is full-screen *draws*, and only the composite is
1325 // one. An atmosphere runs the composite without the effect, and the
1326 // caller adds that one — it is not an effect bit.
1327 passes += u64::from(Volumetric::COMPOSITE_PASSES);
1328 }
1329 // [`RenderEffects::AUTO_EXPOSURE`] adds none, and that is the whole of its
1330 // entry here: all three of its passes are compute dispatches, and the
1331 // exposure they measure reaches the picture through the tonemap's own draw.
1332 passes
1333}
1334
1335/// The budget an **orthographic** camera selects under: one no group satisfies,
1336/// so every group expands and the base level is drawn whole.
1337///
1338/// The metric divides a projected error by the distance to the group's sphere,
1339/// and an orthographic projection has no such falloff — see
1340/// [`Projection::pixels_per_unit`], which is where the trade is written down.
1341/// Drawing the finest level is the conservative answer and the honest one; a
1342/// distance term invented for a projection that has none would be neither.
1343///
1344/// [`Projection::pixels_per_unit`]: crate::camera::Projection::pixels_per_unit
1345const LOD_BUDGET_NONE: f32 = f32::NEG_INFINITY;
1346
1347/// Where a skinned object is, and what it draws: [`InstanceDesc`] with a
1348/// [`SkinnedMesh`] where the description's mesh index would be.
1349///
1350/// The mesh is a reservation rather than an index because a skinned draw is not
1351/// only a mesh — it also names a *run of the vertex pool* the skinning dispatch
1352/// fills, and which of the reservation's two runs that is changes every frame.
1353/// [`ForwardRenderer::begin_skinned_frame`] is what keeps it current, so nothing
1354/// here carries a parity.
1355#[derive(Clone, Copy, Debug)]
1356pub struct SkinnedInstanceDesc<'a> {
1357 /// The region this object is drawn out of, from
1358 /// [`ForwardRenderer::reserve_skinned`].
1359 pub mesh: &'a SkinnedMesh,
1360 /// Which [`SceneDesc::materials`] row it shades through, exactly as
1361 /// [`InstanceDesc::material`].
1362 pub material: usize,
1363 /// Where it is: a model matrix, on [`InstanceDesc::transform`]'s terms.
1364 ///
1365 /// The joints are **not** in it — a palette carries each joint's global
1366 /// transform times its inverse bind matrix, and this is what puts the
1367 /// deformed mesh in the world. See
1368 /// [`SkinRange::palette`](crate::skinning::SkinRange::palette).
1369 pub transform: Mat4,
1370}
1371
1372/// The sky-view LUT a frame is drawn from, and everything taken out of it.
1373///
1374/// **The two projections are cached beside the LUT rather than taken per
1375/// frame**, which is what makes a frame under a sun that has not moved do no
1376/// host LUT work at all: both are functions of the LUT alone, and the LUT only
1377/// changes when [`ForwardRenderer::refresh_sky_view`] swaps a finished build
1378/// in. [`crate::sky_pass`] still encodes [`SkyView::rows`] and its aerial LUT's
1379/// rows per frame, because those are writes into the frame's own ring slots
1380/// rather than projections.
1381#[derive(Clone, Debug)]
1382struct PresentedSky {
1383 /// The normalised sun and viewpoint the LUT was marched for, which is what
1384 /// [`ForwardRenderer::refresh_sky_view`] compares this frame's atmosphere
1385 /// against.
1386 parameters: crcbl_shaders::atmosphere::Atmosphere,
1387 /// The marched LUT: what [`crate::sky_pass`] uploads and the background
1388 /// samples.
1389 view: SkyView,
1390 /// [`SkyView::gradient_fit`], which `ssr.slang` reflects with and the sky
1391 /// pass's block carries.
1392 gradient: crcbl_shaders::sky::SkyGradient,
1393 /// [`SkyView::irradiance`], which is the frame block's L1 ambient term.
1394 irradiance: crcbl_shaders::probe::GpuProbe,
1395}
1396
1397impl PresentedSky {
1398 /// Takes both projections from a LUT that has just been marched.
1399 fn new(parameters: crcbl_shaders::atmosphere::Atmosphere, view: SkyView) -> Self {
1400 Self {
1401 parameters,
1402 gradient: view.gradient_fit(),
1403 irradiance: view.irradiance(),
1404 view,
1405 }
1406 }
1407}
1408
1409/// What [`ForwardRenderer::begin_frame`] fitted for the whole frame, kept so a
1410/// secondary view begun after it writes its blocks against the same sun, light
1411/// rows and shadow matrices the primary camera's were written against.
1412///
1413/// Everything here is decided by the primary camera and drawn once: the rows
1414/// carry the shadow tiles the primary camera's selection handed out, and the
1415/// cascades are fitted to its frustum. A secondary view samples the maps those
1416/// passes drew — `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
1417#[derive(Clone, Debug)]
1418struct FrameScene {
1419 light: DirectionalLight,
1420 rows: Vec<crcbl_shaders::light::GpuLight>,
1421 cascades: Cascades,
1422 shadow_view_proj: [[f32; 16]; shadow::CASCADES],
1423 light_view_proj: [[f32; 16]; shadow::LIGHT_TILES],
1424 atlas_rects: [[f32; 4]; shadow::TILES],
1425}
1426
1427/// The bucket and level tables a scene's generators are all built from, kept
1428/// so [`ForwardRenderer::create_view`] can build one more after `build` has
1429/// returned.
1430#[derive(Debug)]
1431struct DrawTables {
1432 bucket_meshes: Vec<u32>,
1433 bucket_clusters: Vec<u32>,
1434 bucket_cluster_bases: Vec<u32>,
1435 mesh_levels: Vec<level_select::MeshLevels>,
1436 level_groups: Vec<level_select::LevelGroup>,
1437 level_meshes: Vec<u32>,
1438 instance_capacity: u32,
1439 light_capacity: u32,
1440}
1441
1442/// The primary frame attachments an overlay may use before antialiasing and
1443/// render-scale reconstruction.
1444///
1445/// `display` is the display-space image the tonemap and post-tonemap overlays
1446/// have written. `depth` is the matching internal scene depth image, retained
1447/// as a read-only attachment for depth-tested overlays. Both have
1448/// `internal_extent` dimensions.
1449#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1450pub struct ForwardOverlayTargets {
1451 pub display: ImageId,
1452 pub depth: ImageId,
1453 pub internal_extent: (u32, u32),
1454}
1455
1456/// Everything the forward frame owns, created once.
1457#[derive(Debug)]
1458pub struct ForwardRenderer {
1459 // Geometry: the global pools, and the meshes resident in them. Each
1460 // range is resolved once, at build, and `MeshPool::mesh` only hands one out
1461 // for a mesh whose upload has completed — so there is no way to reach a
1462 // draw below with a mesh the GPU has not received.
1463 pool: MeshPool,
1464 /// The dynamic offset of each bucket's [`mesh::DrawConstants`] block, in
1465 /// [`SceneDesc::meshes`] order. Its length is the bucket count, which
1466 /// [`buckets_for`] says is a property of the path as well as of the scene.
1467 ///
1468 /// **The whole of what the CPU still says per draw.** Everything else a
1469 /// draw needs — how many instances, which indices, which vertices — is in
1470 /// the arguments the GPU wrote or in a table it resolves them through.
1471 bucket_constants: Vec<u32>,
1472 /// What one draw region adds to a bucket's offsets — the same for every
1473 /// generator this renderer built, because they share one bucket table.
1474 region_step: RegionStep,
1475 /// The material mode of each bucket, in the same order — the copy the
1476 /// **passes** read, where `DrawGen`'s copy is the one the GPU scatters
1477 /// against.
1478 ///
1479 /// What it is for: the depth prepass and the shadow atlas partition their
1480 /// call list on it and bind a pipeline per partition, so an opaque mesh in a
1481 /// scene with a cutout in it keeps the vertex-only stage. See
1482 /// [`ForwardRenderer::depth_partitions`].
1483 ///
1484 /// All zeroes for a scene whose materials are all opaque — every demo and
1485 /// every golden in this tree — which is exactly one bucket per mesh and one
1486 /// partition, byte for byte the stream they recorded before modes existed.
1487 bucket_modes: Vec<u32>,
1488
1489 // The instance array, and the objects' places in it. Nothing here is
1490 // rewritten per frame: the pool uploads what a caller changed and nothing
1491 // else, so a scene nobody moved costs no transfer at all.
1492 instances: InstancePool,
1493 /// The mesh table id of each description mesh's **level 0**, in
1494 /// [`SceneDesc::meshes`] order — what an [`InstanceDesc::mesh`] index
1495 /// resolves through.
1496 ///
1497 /// Level 0's and not the whole run, because that is the entry an instance
1498 /// carries: `cull.slang` reads a bounding box out of it and a DAG's coarser
1499 /// levels approximate the same surface inside the same box. The coarser
1500 /// entries are resident and no instance names one — a cluster reaches its
1501 /// own level's vertices through
1502 /// [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`], and the
1503 /// uniform cut reaches them through the bucket table.
1504 ///
1505 /// Kept rather than resolved per call because every write of an instance
1506 /// writes the whole record, and an instance that lost its mesh id would
1507 /// resolve to entry 0 — which is a mesh, and the wrong one.
1508 mesh_ids: Vec<u32>,
1509 /// Level 0's pool handle for each description mesh that can be skinned, in
1510 /// [`SceneDesc::meshes`] order, and [`None`] for the ones that cannot — see
1511 /// [`ResidentMesh::skinnable`].
1512 ///
1513 /// What [`ForwardRenderer::reserve_skinned`] resolves an
1514 /// [`InstanceDesc::mesh`] index through. Kept rather than looked up, because
1515 /// there is no way back from a table id to the handle that owns it: an id is
1516 /// a bare index and a [`MeshHandle`] is generational.
1517 skinnable_meshes: Vec<Option<MeshHandle>>,
1518 /// Every object [`ForwardRenderer::add_skinned_instance`] placed, with the
1519 /// two base vertices it alternates between.
1520 ///
1521 /// The list [`ForwardRenderer::begin_skinned_frame`] walks to point each one
1522 /// at the half of its region *this* frame's dispatch fills. Entries whose
1523 /// instance has gone stale are dropped as it walks, so
1524 /// [`ForwardRenderer::remove_instance`] needs to know nothing about
1525 /// skinning.
1526 skinned_instances: Vec<SkinnedInstance>,
1527
1528 /// §3.2's material table, and the rows in it.
1529 ///
1530 /// One buffer shared by every frame's bind group, not a ring — see
1531 /// [`crate::material_table`], which is where that decision lives.
1532 materials: MaterialTable,
1533 /// The table row of each description material, in [`SceneDesc::materials`]
1534 /// order — what an [`InstanceDesc::material`] index resolves through.
1535 ///
1536 /// Kept for the reason [`ForwardRenderer::mesh_ids`] is: a `set` writes the
1537 /// whole record, and an instance that lost its material id would name row 0
1538 /// by accident, which is a material and only *happens* to be the untinted
1539 /// one.
1540 material_ids: Vec<u32>,
1541 /// Topic 50's irradiance grid, row by row.
1542 ///
1543 /// One buffer shared by every frame's bind group, like the material table
1544 /// and for a stronger version of its reason: a probe is written when the
1545 /// scene is made resident and there is no call that rewrites one. See
1546 /// [`crate::probe`].
1547 probes: ProbeTable,
1548 /// Where those rows are, which rides in the frame block rather than in a
1549 /// buffer of its own — a fragment needs it before it knows which row to
1550 /// fetch.
1551 ///
1552 /// Kept rather than re-derived because [`SceneDesc`] is read once, at build.
1553 /// [`ProbeVolume::default`](crcbl_shaders::probe::ProbeVolume::default) is a
1554 /// grid of nothing, which is what a description with no probes leaves here
1555 /// and what makes the whole feature add zero.
1556 probe_volume: crcbl_shaders::probe::ProbeVolume,
1557 /// §3.2's texture side: one `D2Array` image whose layers the material rows
1558 /// index. One page, bound once, for every material — see the module docs on
1559 /// why this is [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) and not
1560 /// a bindless descriptor array.
1561 base_color_page: UploadedTexture,
1562 /// §2's second page: one `D2Array` image of tangent-space normals, whose
1563 /// layers [`GpuMaterial::normal_texture`](mesh::GpuMaterial::normal_texture)
1564 /// indexes.
1565 ///
1566 /// The base-colour page's own shape at [`NORMAL_PAGE_BINDING`], sampled
1567 /// through the same UV and the same sampler, and **created linear** — see
1568 /// [`NORMAL_PAGE_FORMAT`]. Its extent is its own: a description sizes each
1569 /// [`PageKind`] separately, so a 512² normal page beside a 2048²
1570 /// base-colour one is what the caller wrote and what this holds.
1571 normal_page: UploadedTexture,
1572 /// §2's third page: one `D2Array` image of glTF's packed occlusion,
1573 /// roughness and metallic, whose layers
1574 /// [`metallic_roughness_occlusion_texture`](mesh::GpuMaterial::metallic_roughness_occlusion_texture)
1575 /// indexes.
1576 ///
1577 /// The normal page's own shape at [`MRO_PAGE_BINDING`], sampled through the
1578 /// same UV and the same sampler, and **created linear** — see
1579 /// [`MRO_PAGE_FORMAT`].
1580 mro_page: UploadedTexture,
1581 /// §2's fourth page: one `D2Array` image of emitted radiance, whose layers
1582 /// [`emissive_texture`](mesh::GpuMaterial::emissive_texture) indexes.
1583 ///
1584 /// The base-colour page's own shape at [`EMISSIVE_PAGE_BINDING`], and
1585 /// **created sRGB** rather than linear, because an emissive texel is a
1586 /// colour — see [`EMISSIVE_PAGE_FORMAT`].
1587 emissive_page: UploadedTexture,
1588 /// Each [`PageKind`]'s image size in texels, as a width and a height,
1589 /// indexed by [`PageKind::index`].
1590 ///
1591 /// Square, because [`PageDesc`](crate::scene::PageDesc) carries one extent
1592 /// per kind rather than a rectangle. `(1, 1)` for a kind the description
1593 /// named no layer of, which is the placeholder's extent and not the
1594 /// description's — see [`PAGE_PLACEHOLDER_TEXEL`]. Kept rather than
1595 /// re-derived because [`add_passes`](Self::add_passes) declares both pages
1596 /// to the graph and an [`ImportedImage`] names an extent, and the
1597 /// description they came from is the caller's, read once at build.
1598 page_extents: [(u32, u32); PageKind::ALL.len()],
1599 /// The sampler the page is read through.
1600 base_color_sampler: SamplerHandle,
1601 /// The anisotropy [`ForwardRenderer::base_color_sampler`] was created
1602 /// with, after [`set_anisotropy`](ForwardRenderer::set_anisotropy)'s clamp.
1603 anisotropy: f32,
1604 /// How many layers each [`PageKind`]'s page holds, indexed by
1605 /// [`PageKind::index`] — zero for a kind the description named none of.
1606 ///
1607 /// What [`replace_page`](ForwardRenderer::replace_page) holds a
1608 /// replacement to, so every material row's layer number goes on naming the
1609 /// same texture.
1610 page_layers: [usize; PageKind::ALL.len()],
1611 /// `[frame]`: the page sampler and the four page views that slot's
1612 /// mesh-layout groups name.
1613 ///
1614 /// A slot moves onto [`ForwardRenderer::page_bindings`] at its own
1615 /// `begin_frame` and not before — see [`ForwardRenderer::adopt_pages`] —
1616 /// so this is what says which slots still name a sampler
1617 /// [`set_anisotropy`](ForwardRenderer::set_anisotropy) replaced or a page
1618 /// [`replace_page`](ForwardRenderer::replace_page) did.
1619 slot_pages: Vec<PageBindings>,
1620 /// Page samplers and pages replaced while some slot may still name them.
1621 /// Each is destroyed as the last slot naming it moves off, or at
1622 /// [`destroy`](ForwardRenderer::destroy).
1623 retired_pages: Vec<RetiredPage>,
1624
1625 /// Draw calls the last [`ForwardRenderer::add_passes`] recorded — see
1626 /// [`ForwardRenderer::counters`], which is the only thing that reads it.
1627 ///
1628 /// Kept rather than recomputed because the shadow pass's share is the number
1629 /// of **occupied** tiles, which [`ForwardRenderer::add_shadow_pass`] works
1630 /// out from topic 45's tile allocation and nothing outside
1631 /// it can restate without becoming the second copy that drifts.
1632 recorded_draws: u64,
1633 /// Which call the forward pass records — the device's [`GeometryPath`],
1634 /// resolved once.
1635 emit: EmitTail,
1636 /// The most buckets one call of the geometry passes draws, or `None` where
1637 /// they record a call per bucket — [`EmitTail::range_limit`], resolved at
1638 /// build with [`emit`](Self::emit) and for its reason.
1639 range_limit: Option<u32>,
1640 /// §3.5's clusters, and **only on [`EmitTail::Mesh`]**: the two indirect
1641 /// tails draw the same geometry out of the index pool and read none of
1642 /// this. `None` is therefore the ordinary state on most devices rather than
1643 /// a failure, and it is also what makes a fall-through impossible — see
1644 /// [`ForwardRenderer::geometry_path`].
1645 clusters: Option<ClusterPool>,
1646 /// Whether the mesh pipeline was built with §3.5's amplification stage in
1647 /// front of it — see [`ForwardRenderer::culls_clusters`], which is where
1648 /// what it means is written down.
1649 culls_clusters: bool,
1650 /// Where each description mesh's clusters are in
1651 /// [`ForwardRenderer::clusters`] — every level of it, as one run, in
1652 /// [`SceneDesc::meshes`] order. Empty off the mesh path, where there is no
1653 /// cluster pool at all. See [`ForwardRenderer::cluster_range`].
1654 mesh_clusters: Vec<ClusterRange>,
1655 /// The bucket each level of each description mesh draws through, finest
1656 /// first, in [`SceneDesc::meshes`] order — and empty on the mesh path. See
1657 /// [`ForwardRenderer::level_buckets`].
1658 ///
1659 /// **The run for the scene's first material mode**, which is `OPAQUE`
1660 /// wherever the scene has an opaque material at all: the table is every
1661 /// mesh's levels once per mode the scene holds, mode by mode, and this
1662 /// names a mesh's levels in the first of those runs. See
1663 /// [`ForwardRenderer::bucket_modes`].
1664 mesh_level_buckets: Vec<Vec<u32>>,
1665 /// The pixel budget topic 25's descent compares a group's
1666 /// projected error against. [`LOD_ERROR_BUDGET`] until
1667 /// [`ForwardRenderer::set_lod_error_budget`] says otherwise.
1668 lod_error_budget: f32,
1669 /// How far below that an expanded group is held before it collapses again.
1670 /// [`LOD_HOLD_RATIO`] until
1671 /// [`ForwardRenderer::set_lod_hold_ratio`] says otherwise.
1672 lod_hold_ratio: f32,
1673 /// The same three numbers the shadow cascades selected under, which is
1674 /// [`ForwardRenderer::lod_params`] with both budgets scaled by
1675 /// [`SHADOW_LOD_BIAS`] and the same pixels-per-unit.
1676 ///
1677 /// Kept beside the camera's for its reason: a reader comparing the two cuts
1678 /// takes both pairs from here rather than re-deriving the bias, which would
1679 /// be comparing two copies of one arithmetic instead of two selections.
1680 shadow_lod_params: [f32; 3],
1681
1682 /// The lights a caller set beside the sun, as
1683 /// [`ForwardRenderer::set_lights`] was handed them.
1684 ///
1685 /// Kept rather than converted on the way in, because a row is the *frame's*
1686 /// artefact: the sun arrives per frame at
1687 /// [`begin_frame`](ForwardRenderer::begin_frame) and is row 0, so the list a
1688 /// frame uploads cannot be assembled until then.
1689 extra_lights: Vec<Light>,
1690
1691 /// One [`mesh::DrawConstants`] block per draw, a device dynamic-offset
1692 /// alignment apart. Shared by every frame's bind group rather than ringed,
1693 /// because nothing rewrites it after `build`: a mesh's base vertex and an
1694 /// object's instance index are decided when the pools allocate them.
1695 draw_constants: BufferHandle,
1696 /// The camera's resources and history — see [`view`], which is where the
1697 /// line between a camera's state and the scene's is drawn.
1698 primary: View,
1699 /// Every secondary view [`ForwardRenderer::create_view`] built, indexed by
1700 /// [`ViewId::index`] less one — a free id is `None`.
1701 views: Vec<Option<View>>,
1702 /// The tables a view's generator is built from — see [`DrawTables`].
1703 draw_tables: DrawTables,
1704 /// Counts every [`begin_frame`](ForwardRenderer::begin_frame), so a view can
1705 /// say which frame it was last begun for — see [`View::begun`].
1706 frame_serial: u64,
1707 /// The frame the last `begin_frame` opened, for
1708 /// [`begin_view`](ForwardRenderer::begin_view). `None` before the first.
1709 frame_scene: Option<FrameScene>,
1710 /// Which frame-in-flight slot is current. Set from
1711 /// [`InstancePool::begin_frame`]'s return rather than counted here, so the
1712 /// uniform ring and the instance ring cannot drift apart.
1713 frame: usize,
1714
1715 mesh_layout: BindGroupLayoutHandle,
1716 mesh_pipeline_layout: PipelineLayoutHandle,
1717 mesh_pipeline: SidedPipelines,
1718 /// [`ForwardRenderer::mesh_pipeline`] again in
1719 /// [`PolygonMode::Line`], for
1720 /// [`set_wireframe`](ForwardRenderer::set_wireframe).
1721 ///
1722 /// [`None`] until a caller first switches the view on — the ground grid's
1723 /// arrangement exactly, and for its reason: a second pipeline compiled at
1724 /// build would be paid for by every sample, golden and headless run that
1725 /// never asks for a wireframe, which is all of them. Once built it is kept,
1726 /// because switching the view off is
1727 /// [`ForwardRenderer::wireframe_on`] and not a release.
1728 ///
1729 /// **A pair, like the pipeline it replaces**, because [`PolygonMode::Line`]
1730 /// does not disable culling: a single-sided wireframe drawn over a
1731 /// double-sided bucket would leave a surface out of the debug view that the
1732 /// shaded frame beside it draws, which is a view of the document that
1733 /// disagrees with the document.
1734 wireframe_pipeline: Option<SidedPipelines>,
1735 /// Whether [`add_passes`](ForwardRenderer::add_passes) drives the forward
1736 /// pass through [`ForwardRenderer::wireframe_pipeline`]. **`false` by
1737 /// default**: a wireframe is a tool's view of a document, and every sample
1738 /// and every golden image predates it.
1739 wireframe_on: bool,
1740 /// The occlusion and small-feature culls a caller asked for — see
1741 /// [`set_occlusion_culling`](ForwardRenderer::set_occlusion_culling).
1742 occlusion_culling: OcclusionCulling,
1743 /// Whether a point light's six faces cull separately — see
1744 /// [`set_point_face_culls`](ForwardRenderer::set_point_face_culls).
1745 point_face_culls: bool,
1746 /// What a test asked every shadow view's uploaded block to be rewritten
1747 /// with — see
1748 /// [`set_shadow_view_tamper`](ForwardRenderer::set_shadow_view_tamper).
1749 /// [`None`] outside a test.
1750 shadow_view_tamper: Option<fn(&mut mesh::FrameUniforms)>,
1751 /// Whether [`begin_frame`](ForwardRenderer::begin_frame) writes
1752 /// [`FrameUniforms::NORMALS_VIEW_ON`] into the frame block, which makes
1753 /// `mesh.slang`'s fragment stage draw world-space normals instead of shading
1754 /// — see [`set_normals_view`](ForwardRenderer::set_normals_view).
1755 ///
1756 /// **`false` by default**, on [`ForwardRenderer::wireframe_on`]'s terms
1757 /// exactly: it is a tool's view of a document, and every sample and every
1758 /// golden image predates it.
1759 ///
1760 /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
1761 normals_view: bool,
1762
1763 /// The exponential height fog the colour pass composites over its
1764 /// radiance — see [`set_fog`](ForwardRenderer::set_fog).
1765 ///
1766 /// **[`Fog::NONE`] by default**, on [`normals_view`](Self::normals_view)'s
1767 /// terms: a caller who never asks for fog draws the frame this renderer
1768 /// drew before the feature existed, and exactly that frame — the shader's
1769 /// composite is an identity at zero density rather than an interpolation
1770 /// that nearly is.
1771 fog: Fog,
1772
1773 /// The gradient sky whose irradiance the colour pass adds to the ambient
1774 /// term — see [`set_sky`](ForwardRenderer::set_sky).
1775 ///
1776 /// **[`Sky::NONE`] by default**, on [`fog`](Self::fog)'s terms: a black
1777 /// gradient projects to coefficients that are all zero, so the three dot
1778 /// products the fragment stage adds are zero and no frame drawn before a
1779 /// sky existed moves.
1780 sky: Sky,
1781 /// The atmosphere that **replaces** [`Self::sky`] when a caller sets one —
1782 /// see [`set_atmosphere`](ForwardRenderer::set_atmosphere).
1783 ///
1784 /// `None` by default, so a renderer nobody calls that on is the renderer it
1785 /// was.
1786 atmosphere: Option<Atmosphere>,
1787 /// The marched sky-view LUT this renderer is drawing, with the parameters
1788 /// it was marched for and the projections taken from it.
1789 ///
1790 /// **Cached against the parameters rather than rebuilt per frame**, because
1791 /// the march is tens of milliseconds of CPU and the sun in most frames has
1792 /// not moved. The stored parameters are the *normalised* ones the shader
1793 /// crate takes, so a caller handing over the same sun spelled two lengths
1794 /// does not force a rebuild.
1795 ///
1796 /// This is the LUT a frame is **drawn from**, which is not the one being
1797 /// marched: see [`Self::sky_view_build`].
1798 sky_view: Option<PresentedSky>,
1799 /// The march in flight, when the sun has moved away from
1800 /// [`Self::sky_view`]'s.
1801 ///
1802 /// [`ForwardRenderer::refresh_sky_view`] steps it
1803 /// [`SKY_VIEW_BUILD_ROWS`] rows per frame and swaps it into
1804 /// [`Self::sky_view`] when it finishes.
1805 ///
1806 /// **The host side is where the double buffer is**: the LUT being drawn and
1807 /// the LUT being marched are these two fields, and [`crate::sky_pass`]'s
1808 /// device ring is untouched. Putting the stripe on the device instead would
1809 /// mean writing part of a ring slot per frame, and that ring's slots are
1810 /// written whole precisely because each is a frame in flight — a partial
1811 /// write would have to track, per slot, which rows of *which* sun that slot
1812 /// already holds, which is bookkeeping the host copy does not need at all.
1813 sky_view_build: Option<SkyViewBuild>,
1814
1815 /// Whether the colour pass tints each cluster by its DAG level instead of
1816 /// shading — see [`set_lod_view`](ForwardRenderer::set_lod_view).
1817 ///
1818 /// **Wins over [`normals_view`](Self::normals_view) when both are set**,
1819 /// because one uniform lane carries both switches and the fragment stage
1820 /// tests the LOD threshold first. `crcbl_shaders`'
1821 /// `the_lod_view_threshold_lies_above_the_normals_view` is what keeps that
1822 /// order true.
1823 lod_view: bool,
1824
1825 /// Whether the colour pass shades each cluster by the projected error the
1826 /// LOD selection judged it on, instead of shading it or tinting it — see
1827 /// [`set_heatmap`](ForwardRenderer::set_heatmap).
1828 ///
1829 /// **Wins over both [`lod_view`](Self::lod_view) and
1830 /// [`normals_view`](Self::normals_view)**, on the same terms and for the same
1831 /// reason: one uniform lane carries all three switches and the shaders test
1832 /// the outermost threshold first. `crcbl_shaders`'
1833 /// `the_heatmap_view_threshold_lies_above_the_lod_view` is what keeps that
1834 /// order true, and
1835 /// `the_three_debug_views_resolve_in_one_order_however_they_are_set` is what
1836 /// holds this side to it.
1837 heatmap: bool,
1838
1839 /// Whether the colour pass draws the ambient-occlusion channel as grey
1840 /// instead of shading — see
1841 /// [`set_occlusion_view`](ForwardRenderer::set_occlusion_view).
1842 ///
1843 /// **Wins over every other view**, on [`heatmap`](Self::heatmap)'s terms and
1844 /// for its reason: one uniform lane, outermost threshold first.
1845 /// `crcbl_shaders`' `the_occlusion_view_threshold_lies_above_the_heatmap` is
1846 /// what keeps that order true, and
1847 /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1848 /// this side to it.
1849 occlusion_view: bool,
1850
1851 /// Whether the colour pass draws the motion vector instead of shading — see
1852 /// [`set_motion_view`](ForwardRenderer::set_motion_view).
1853 ///
1854 /// **Wins over every other view**, on [`occlusion_view`](Self::occlusion_view)'s
1855 /// terms and for its reason: one uniform lane, outermost threshold first.
1856 /// `crcbl_shaders`' `the_motion_view_threshold_lies_above_the_occlusion_view`
1857 /// is what keeps that order true, and
1858 /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1859 /// this side to it.
1860 motion_view: bool,
1861 /// Whether the colour pass draws the occlusion channel's bent direction
1862 /// instead of shading — see
1863 /// [`set_bent_normal_view`](ForwardRenderer::set_bent_normal_view).
1864 ///
1865 /// **Wins over every other view**, on [`motion_view`](Self::motion_view)'s
1866 /// terms: it is the outermost sentinel in the lane, and
1867 /// `crcbl_shaders`' `the_bent_normal_view_threshold_lies_above_the_motion_view`
1868 /// is what holds the shader's branch order to it.
1869 bent_normal_view: bool,
1870
1871 /// Whether the colour pass tints the shaded picture by the cascade each
1872 /// sun-lit fragment's shadow was sampled from — see
1873 /// [`set_cascade_view`](ForwardRenderer::set_cascade_view).
1874 ///
1875 /// **Loses to every other view**, which is the opposite of every field
1876 /// above and for the reason [`DebugView::Cascades`] carries: every one of them
1877 /// replaces the shaded picture and this one multiplies it, so a frame drawing
1878 /// any of them has nothing for this tint to reach. `crcbl_shaders`'
1879 /// `the_cascade_view_threshold_lies_below_every_replacing_view` is what
1880 /// holds the shader to the same order, from the other end of the lane.
1881 cascade_view: bool,
1882
1883 /// Whether the frame draws the shadow atlas over the finished picture — see
1884 /// [`set_atlas_view`](ForwardRenderer::set_atlas_view).
1885 ///
1886 /// **Not a lane of the frame block**, unlike every field above: this view is
1887 /// a pass rather than a branch in `mesh.slang`, so what reads this is
1888 /// [`ForwardRenderer::add_passes`] deciding whether to record
1889 /// [`crate::atlas_view`]'s. It resolves below every replacing view and above
1890 /// [`cascade_view`](Self::cascade_view) — see
1891 /// [`ForwardRenderer::debug_view`].
1892 atlas_view: bool,
1893
1894 /// Where [`begin_frame`](ForwardRenderer::begin_frame) projects
1895 /// topic 25's selection from, when that is not the camera's own
1896 /// eye — see
1897 /// [`set_frozen_selection_eye`](ForwardRenderer::set_frozen_selection_eye).
1898 ///
1899 /// **[`None`] is not a position, it is "follow the camera"**, and it is what
1900 /// every frame the engine has drawn so far did: the eye handed to
1901 /// [`DrawGen::begin_frame`] is `camera.eye`, byte for byte, so a caller that
1902 /// never sets this writes the parameter block it wrote before this field
1903 /// existed.
1904 ///
1905 /// **Not a [`DebugView`]**, and deliberately: the three views are one
1906 /// picture chosen between, while this is a change to what the *selection*
1907 /// answers and leaves the picture's choice alone. A reviewer freezing the
1908 /// cut and then reading it off the LOD tint is the combination the feature
1909 /// exists for, so the two cannot be alternatives.
1910 frozen_selection_eye: Option<Vec3>,
1911
1912 /// Topic 18's shadow atlas: one `D32Float` image holding
1913 /// [`shadow::TILES`] square tiles in a fixed grid — the sun's cascades
1914 /// first, then one per shadowed light.
1915 ///
1916 /// Owned here rather than created by the graph per frame, because its
1917 /// extent is a **quality setting and not a window size** — nothing about it
1918 /// changes on a resize, so a transient would be re-created for no reason
1919 /// and could not be read back by a test that does not own the graph.
1920 shadow_atlas: ImageHandle,
1921 shadow_atlas_view: ImageViewHandle,
1922 /// A 1×1 depth image that exists so the depth-only pipeline's bind group can
1923 /// fill [`SHADOW_ATLAS_BINDING`] without naming the atlas it is writing.
1924 ///
1925 /// Both halves of that sentence are forced:
1926 ///
1927 /// * **The slot has to be filled.** Slang's Metal backend materialises every
1928 /// global into every entry point — `msl/mesh.metal`'s `vertexMain` takes
1929 /// `shadow_atlas [[texture(1)]]` whether it reads it or not — so a
1930 /// depth-only pipeline sharing this layout still declares the argument. A
1931 /// layout with the slot removed would break Metal alone, on a runner this
1932 /// team cannot debug on, which is the trap binding 6's comment already
1933 /// records.
1934 /// * **It cannot be the atlas.** WebGPU refuses a texture that is a render
1935 /// attachment and a bind-group resource in the same pass, and the shadow
1936 /// pass is exactly that pass.
1937 ///
1938 /// Nothing samples it: the shadow pipeline has no fragment stage. It is
1939 /// brought into the graph beside the atlas so its layout transition is the
1940 /// graph's like every other, rather than a hand-written barrier.
1941 shadow_placeholder: ImageHandle,
1942 shadow_placeholder_view: ImageViewHandle,
1943 /// The **comparison** sampler the atlas is read through — hardware PCF.
1944 shadow_sampler: SamplerHandle,
1945 /// The depth-only pipeline every tile is rendered with — and, driven with
1946 /// the camera's own draws, the depth prepass's: `mesh.slang`'s
1947 /// `depthVertexMain` where the geometry comes from a vertex stage, the same
1948 /// geometry stage as [`ForwardRenderer::mesh_pipeline`] where it comes from
1949 /// a mesh one, and no fragment stage in either case.
1950 shadow_pipeline: SidedPipelines,
1951 /// The same two passes' pipeline for the buckets whose material mode cuts
1952 /// an alpha mask: `vertexMain` and `depthMaskedFragmentMain` — see
1953 /// [`MeshModules::depth_masked_pipeline`].
1954 ///
1955 /// Built on every scene rather than only on one that has a masked material,
1956 /// for [`ForwardRenderer::rsm_pipeline`]'s reason: the modules are released
1957 /// inside `build` and a pipeline built later would need them back, which is
1958 /// a second shader compilation. Which buckets are drawn with it is
1959 /// [`ForwardRenderer::depth_partitions`], and it is a **partition of one
1960 /// frame's draws** rather than a choice for the whole frame.
1961 depth_masked_pipeline: SidedPipelines,
1962 /// The pipeline that resets one tile of the atlas before it is redrawn, on a
1963 /// frame that is keeping some of the others — see
1964 /// [`MeshModules::depth_clear_pipeline`], which is where the whole argument
1965 /// for it lives.
1966 shadow_clear_pipeline: GraphicsPipelineHandle,
1967 /// The irradiance probes' reflective shadow map — see
1968 /// [`MeshModules::rsm_pipeline`]. Built on every scene and bound only by a
1969 /// frame whose volume asked for [`ProbeUpdate::EveryFrame`].
1970 rsm_pipeline: SidedPipelines,
1971 /// The compute pass that reads that map into the probe rows, and [`None`]
1972 /// for every scene whose volume is [`ProbeUpdate::Authored`] — which is the
1973 /// whole of what the default costs such a scene: no pipeline, no buffers, no
1974 /// pass and no frame time.
1975 probe_gather: Option<ProbeGather>,
1976 /// Whether cascade 0's view block and cull parameters were written for the
1977 /// frame being recorded, so the reflective shadow map can be drawn from
1978 /// them.
1979 ///
1980 /// Not [`ForwardRenderer::shadow_group_redrawn`], which is a claim about the
1981 /// *atlas*: a frame drawing without
1982 /// [`RenderEffects::SHADOWS`](crate::effects::RenderEffects::SHADOWS) fits
1983 /// cascade 0 for the map and writes no tile, and overloading that flag would
1984 /// report a cascade as redrawn when nothing drew it.
1985 rsm_cull_ready: bool,
1986 /// What the scene said fills the probe rows.
1987 ///
1988 /// Read by [`ForwardRenderer::begin_frame`] — which keeps cascade 0 off the
1989 /// shadow atlas's static-cache hold when the updater is on, because the map
1990 /// is that cascade's own draws — and by the pass recording below.
1991 probe_update: ProbeUpdate,
1992 /// How far cascade 0 reached on the frame being recorded, which is the
1993 /// radius of the sphere it was fitted to — `crate::rsm::texel_area` is what
1994 /// reads it.
1995 ///
1996 /// Written by [`ForwardRenderer::begin_frame`] beside the cascade matrices
1997 /// themselves, rather than recomputed at pass-record time: a frame that
1998 /// scaled its gather by one cascade's footprint while drawing the map
1999 /// through another's would be a bounce that is uniformly wrong, and nothing
2000 /// in the frame could see it.
2001 cascade_reach: f32,
2002 /// The sun's colour premultiplied by its intensity, this frame.
2003 ///
2004 /// The reflective shadow map holds albedo rather than flux — `RsmOutput` in
2005 /// `mesh.slang` argues why — so this is what the gather multiplies by, and it
2006 /// is read off the same [`DirectionalLight`] the cascades were fitted to.
2007 /// The sun's *direction* is not carried beside it: the gather needs none, on
2008 /// `probe_gather.slang`'s own derivation.
2009 sun_color: Vec3,
2010 /// One cull and draw-argument pass **per cascade and per shadowed light**,
2011 /// which is topic 18's "one cull dispatch per cascade against the same
2012 /// instance/geometry pools" with a shadowed light counting as a cascade does.
2013 ///
2014 /// A whole [`DrawGen`] rather than just its cull half: the shadow pass emits
2015 /// the same indirect call the colour pass does, so it needs the same
2016 /// arguments, and there is no "cull only" constructor to reach for. The cost
2017 /// is that each duplicates the clear and draw-argument pipelines and
2018 /// [`DrawGen`]'s own per-instance state — see
2019 /// [`TileBuffers::group_state`], which is where that price is written down,
2020 /// and [`SHADOW_CULLS`], which is why a point light has one of these rather
2021 /// than six.
2022 ///
2023 /// **Indexed by cull**: `0..shadow::CASCADES` are the sun's and
2024 /// [`shadow_cull`] is where a light slot's is.
2025 shadow_draws: Vec<DrawGen>,
2026 /// `[frame][view]`: a copy of the frame block whose `view_proj` **is** that
2027 /// view's matrix, so the depth-only pipeline runs the unmodified vertex and
2028 /// mesh stages rather than a second transform path.
2029 shadow_uniforms: Vec<Vec<BufferHandle>>,
2030 /// Empty between frame preparations, with capacity retained for assembly.
2031 shadow_prepare_views: Vec<(usize, usize, mesh::FrameUniforms)>,
2032 /// Empty between frame preparations, with capacity retained for frusta.
2033 shadow_prepare_culls: Vec<(usize, Frustum)>,
2034 /// `[frame][view]`: the mesh layout again, reading that view's uniforms and
2035 /// the survivors of the cull its slot owns.
2036 shadow_groups: Vec<Vec<BindGroupHandle>>,
2037 /// `[frame][view]`: the cut that view's amplification stage chose, one word
2038 /// per resident cluster — and empty where there is no such stage.
2039 ///
2040 /// **A buffer per view rather than the camera's**, unlike every other
2041 /// resource these passes share: the colour pass is recorded last and writes
2042 /// [`ForwardRenderer::cluster_selection`] over whatever a view left in it,
2043 /// so a view writing there leaves nothing behind to read. Without one of
2044 /// these the shadow pass's descent is unobservable — which is the state
2045 /// [`SHADOW_LOD_BIAS`] arrived in, and it is what a bias nothing can measure
2046 /// would have stayed in.
2047 shadow_selection: Vec<Vec<BufferHandle>>,
2048 /// Which of [`ForwardRenderer::extra_lights`] holds each shadow slot, where
2049 /// in the atlas's light region its tiles are, and the memory that keeps that
2050 /// answer from flickering.
2051 ///
2052 /// Re-run every [`ForwardRenderer::begin_frame`] and read by
2053 /// [`ForwardRenderer::add_shadow_pass`], which records a cull for each
2054 /// occupied slot and a viewport per face it has, and nothing at all for the
2055 /// free ones — so an unheld tile keeps the reversed-Z clear, which reads as
2056 /// "nothing stored, fully lit" wherever anything did sample it.
2057 shadow_lights: shadow::Selection,
2058 /// `[group]`: everything that group's maps would be drawn from, as
2059 /// [`ForwardRenderer::shadow_group_record`] spells it.
2060 ///
2061 /// Kept only to tell one frame's answer from the last one's: it is compared
2062 /// and then replaced, and what travels from there is the number below.
2063 ///
2064 /// **Per group rather than per atlas**, since the cadence rung: a group is a
2065 /// cascade or a light slot's whole run of tiles, and holding one map while
2066 /// redrawing another is the whole of what that rung buys.
2067 shadow_group_inputs: Vec<Vec<u8>>,
2068 /// `[group]`: a number that moves whenever that group's entry of
2069 /// [`ForwardRenderer::shadow_group_inputs`] does, and never comes back to a
2070 /// value it has had.
2071 ///
2072 /// So "the image already holds this" is one integer comparison, which is
2073 /// what lets the pass body below carry the answer out of the graph.
2074 shadow_group_id: Vec<u64>,
2075 /// `[group]`: how many instance writes that group's cull could have seen,
2076 /// over the renderer's life — the per-group stand-in for
2077 /// [`InstancePool::revision`] in
2078 /// [`ForwardRenderer::shadow_group_record`], moved by
2079 /// [`ForwardRenderer::note_caster_writes`].
2080 shadow_group_writes: Vec<u64>,
2081 /// `[element]`: where each element of the instance array could draw into a
2082 /// shadow map, as of the last [`ForwardRenderer::note_caster_writes`] —
2083 /// which is what a write's *before* is read from. Grows to the highest
2084 /// element written; an element past its end has never been written and is
2085 /// [`shadow_inputs::CasterFootprint::Nowhere`].
2086 shadow_footprints: Vec<shadow_inputs::CasterFootprint>,
2087 /// The live elements whose mesh has a DAG, and so whose level the selection
2088 /// eye chooses — the ones that put the eye into a light group's record.
2089 shadow_dag_elements: std::collections::BTreeSet<u32>,
2090 /// Scratch for [`InstancePool::take_written`], kept so a frame that moved
2091 /// an instance does not allocate its list.
2092 shadow_written: Vec<u32>,
2093 /// This frame's written elements' footprints, before and after the write,
2094 /// from [`ForwardRenderer::note_caster_writes`] for
2095 /// [`shadow_inputs::shadow_groups_reached`]. Empty on a frame nothing was
2096 /// written in.
2097 shadow_moved: Vec<(
2098 shadow_inputs::CasterFootprint,
2099 shadow_inputs::CasterFootprint,
2100 )>,
2101 /// The number given to the shadow pass this renderer recorded last.
2102 ///
2103 /// Moves once per recorded pass, so the body below can say *which* pass ran
2104 /// with one integer.
2105 shadow_pass_id: u64,
2106 /// The [`ForwardRenderer::shadow_pass_id`] of the last shadow pass that
2107 /// **ran**, written by that pass's own body.
2108 ///
2109 /// By the body rather than by the call that recorded it, and that is the
2110 /// whole of why this is shared state rather than a plain field: a frame
2111 /// whose graph was refused — or built and dropped — recorded a pass that
2112 /// never executed, so the image still holds whatever the frame before it
2113 /// left there. `a_refused_frame_leaves_the_shadow_atlas_where_it_was` is
2114 /// that case, and it is the same boundary [`TransientPool`]'s ledger of
2115 /// imported images uses for the same reason.
2116 ///
2117 /// Zero until a pass has run, and the ids start above it, so the first frame
2118 /// of all draws.
2119 shadow_pass_ran: Arc<AtomicU64>,
2120 /// What the shadow pass recorded last would leave the image holding, if its
2121 /// body ran.
2122 ///
2123 /// Taken and applied by the next [`ForwardRenderer::begin_frame`], which is
2124 /// the only place that can tell whether it did — see
2125 /// [`ForwardRenderer::shadow_pass_ran`].
2126 shadow_pending: Option<ShadowCommit>,
2127 /// `[group]`: the id, the centre that group's maps were projected from and
2128 /// how far they reach, as the record the **image** holds describes them.
2129 ///
2130 /// The id is what says a map is out of date. The centre and reach are what
2131 /// say it is about somewhere else: a map whose own centre has moved further
2132 /// than its own reach covers ground it was never drawn for, and holding
2133 /// that is worse than a shadow that lags — see
2134 /// [`ForwardRenderer::shadow_cadence_reset`].
2135 shadow_group_held: Vec<(u64, Vec3, f32)>,
2136 /// `[group]`: whether this frame redraws that group's maps.
2137 ///
2138 /// Frozen by [`ForwardRenderer::begin_frame`] for
2139 /// [`ForwardRenderer::frame_effects`]' reason: this call decides it and
2140 /// `add_passes` acts on it, and a value that moved between them would skip
2141 /// a cull whose draws were recorded, or the other way about.
2142 shadow_group_redrawn: Vec<bool>,
2143 /// Where every atlas slot's map was laid out on the frame the **image** was
2144 /// drawn from, so a frame can tell whether the texels it is keeping still
2145 /// describe the layout it is about to sample through.
2146 ///
2147 /// A layout that has moved is what makes a frame clear the whole attachment
2148 /// and redraw every group: a tile left over from a different layout is
2149 /// texels nothing this frame can account for. Promoted beside
2150 /// [`ForwardRenderer::shadow_group_held`].
2151 ///
2152 /// [`None`] until a pass has drawn, which is **not** the layout a frame
2153 /// with shadows off produces: an image no pass has touched holds undefined
2154 /// memory rather than a clear, so the first frame of all has to write one
2155 /// whatever it is asked for.
2156 shadow_atlas_layout: Option<Vec<shadow::TileRect>>,
2157 /// Whether any map this frame samples is one an earlier frame drew, rather
2158 /// than one this frame did.
2159 ///
2160 /// The cadence's own readback — see
2161 /// [`ForwardRenderer::shadow_atlas_cached`], which is this for the whole
2162 /// atlas.
2163 shadow_atlas_cached: bool,
2164 /// Whether this frame ignored the cadence because some map's region moved
2165 /// out from under it — see [`ForwardRenderer::shadow_cadence_reset`].
2166 shadow_cadence_reset: bool,
2167 /// How many tiles this frame redraws — see
2168 /// [`ForwardRenderer::shadow_faces_redrawn`].
2169 shadow_faces_redrawn: u32,
2170 /// A shadow cadence the caller pinned, or [`None`] to take the console's.
2171 ///
2172 /// [`ForwardRenderer::set_effect_request`]'s shape at this knob and for its
2173 /// reason: `shadow::r_shadow_cadence` and `shadow::r_shadow_faces` are
2174 /// process-global, and an application that wants a tier's own pair — or a
2175 /// test that wants a frame nothing else in the process can move — needs one
2176 /// that is not.
2177 shadow_cadence_request: Option<shadow::Cadence>,
2178 /// Whether this frame's shadow pass clears the whole attachment, rather
2179 /// than loading it and resetting only the tiles it redraws.
2180 ///
2181 /// Frozen beside [`ForwardRenderer::shadow_group_redrawn`] and for its
2182 /// reason: the decision is `begin_frame`'s and the recording is
2183 /// `add_shadow_pass`'s, and a value that moved between them would load an
2184 /// attachment whose tiles nothing had reset.
2185 shadow_atlas_clears: bool,
2186 /// How many frames have been opened, which is what the cadence is keyed to.
2187 ///
2188 /// **Monotonic, unlike [`ForwardRenderer::frame`]**, which is the index of
2189 /// the frame in flight and wraps every [`FRAMES_IN_FLIGHT`]. A schedule
2190 /// keyed to that would repeat every few frames and bound nothing.
2191 shadow_frame: u64,
2192 /// Whether this frame dispatches skinning, and so rewrites part of the
2193 /// vertex pool the shadow pass draws from.
2194 ///
2195 /// The atlas's one **always redraw**: a skinned caster's vertices are
2196 /// produced by a compute pass into the pool, so there is nothing on the
2197 /// host to compare a frame's geometry against — the palette a caller hands
2198 /// over is not the vertices, and the vertices are never read back. Set by
2199 /// [`ForwardRenderer::begin_skinned_frame`], which is the only call that
2200 /// can make it true, and cleared by [`ForwardRenderer::begin_frame`], which
2201 /// dispatches none.
2202 frame_skins: bool,
2203
2204 /// Topic 03 §3.6's one permitted readback: the camera cull's statistics, on
2205 /// a delayed ring — see [`crate::cull_stats`], which is where the shape and
2206 /// the latency are argued.
2207 ///
2208 /// **The camera's cull only.** [`ForwardRenderer::shadow_draws`] each have a
2209 /// statistics buffer of their own and none of them is read: a cascade's
2210 /// survivor count is a different question about a different frustum, and
2211 /// added into this one it would produce a number larger than the pool holds.
2212 ///
2213 /// [`None`] on a device that would not give out the buffers, which is what
2214 /// makes the counters row degrade to `indirect` rather than fail.
2215 cull_stats: Option<CullStatsRing>,
2216
2217 tonemap_layout: BindGroupLayoutHandle,
2218 tonemap_pipeline_layout: PipelineLayoutHandle,
2219 tonemap_pipeline: GraphicsPipelineHandle,
2220 sampler: SamplerHandle,
2221 /// The multiplier the tonemap pass applies before its clamp — see
2222 /// [`set_exposure`](ForwardRenderer::set_exposure).
2223 ///
2224 /// Always within [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`], because the setter is
2225 /// the only thing that writes it and it clamps.
2226 exposure: f32,
2227 /// How far auto-exposure may move in one frame — see
2228 /// [`set_exposure_adaptation`](ForwardRenderer::set_exposure_adaptation).
2229 ///
2230 /// [`None`] until a caller says otherwise, and that is the whole distance in
2231 /// one frame: the picture the pass drew before adaptation existed.
2232 exposure_adaptation: Option<ExposureAdaptation>,
2233 /// Which operator the tonemap pass runs — see
2234 /// [`set_tonemap_curve`](ForwardRenderer::set_tonemap_curve).
2235 ///
2236 /// [`TonemapCurve::Aces`](crcbl_shaders::tonemap::TonemapCurve::Aces) until
2237 /// a caller says otherwise: this renderer shades in linear HDR, so the
2238 /// filmic roll-off is what a view that has said nothing wants. A
2239 /// display-referred view — a 2D sample, or a fixture whose assertions
2240 /// predict a code value — asks for
2241 /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp),
2242 /// which is the identity on `0..=1`.
2243 tonemap_curve: tonemap::TonemapCurve,
2244
2245 /// The format the tonemap pipeline was built for. A swapchain format change
2246 /// needs a new pipeline, which is why it is remembered rather than assumed.
2247 target_format: Format,
2248
2249 /// A 1×1 `R8Unorm` image holding [`AMBIENT_OCCLUSION_NONE`], so a group of
2250 /// the mesh layout can fill [`AMBIENT_OCCLUSION_BINDING`] without naming an
2251 /// occlusion image that does not exist yet.
2252 ///
2253 /// [`ForwardRenderer::shadow_placeholder`]'s argument, one binding along.
2254 /// The shadow pass and the depth prepass name it and never sample it — a
2255 /// depth-only pipeline has no fragment stage — and **the forward pass names
2256 /// it too on a frame drawing without [`RenderEffects::AMBIENT_OCCLUSION`]**,
2257 /// where it is the whole of that effect's off-switch. An AO-on frame binds
2258 /// the occlusion pair's blurred output instead.
2259 ///
2260 /// **It is white because that is the value that occludes nothing**, which is
2261 /// what makes it an honest stand-in for "no occlusion was computed" rather
2262 /// than decoration. That it *reads* as white is `mesh.slang`'s doing: the
2263 /// binding is fetched with a `Load`, and a `Load` past a 1×1 image's one
2264 /// texel is zero on every backend, so the shader clamps the coordinate to the
2265 /// image's extent. See [`add_passes`](ForwardRenderer::add_passes).
2266 ///
2267 /// It is uploaded rather than cleared, so it is in
2268 /// [`ResourceState::ShaderRead`] from the moment it exists and no pass has to
2269 /// declare it to give it a layout.
2270 ambient_occlusion_placeholder: UploadedTexture,
2271 /// A 1×1 `R8Unorm` image holding [`CONTACT_SHADOW_NONE`], so a group of the
2272 /// mesh layout can fill [`CONTACT_SHADOW_BINDING`] without naming a
2273 /// contact-shadow image that does not exist yet.
2274 ///
2275 /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, one
2276 /// binding along and with one difference worth stating: an unclamped `Load`
2277 /// past this one's single texel would cost the frame its **sun**, not its
2278 /// ambient. `mesh.slang`'s `contact_at` is what clamps it.
2279 contact_shadow_placeholder: UploadedTexture,
2280 /// A 1×1×1 `Rg32Float` image holding [`probe_visibility_none`], so a group
2281 /// of the mesh layout can fill [`PROBE_VISIBILITY_BINDING`] before anything
2282 /// has been captured — and so the console switch has something to name when
2283 /// the maps are turned off.
2284 ///
2285 /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, with the
2286 /// same clamp on the shader's side: `mesh.slang`'s `probe_moments` clamps
2287 /// against `GetDimensions`, so all four of its taps land on this image's one
2288 /// texel and every probe reads as unobstructed.
2289 probe_visibility_placeholder: UploadedTexture,
2290 /// The captured maps, one `Rg32Float` layer per probe — `None` until
2291 /// [`ForwardRenderer::capture_probe_visibility`] has run, which is every
2292 /// frame drawn by a caller that never calls it.
2293 probe_visibility: Option<UploadedTexture>,
2294 /// The scene's static triangles, kept for that capture and for nothing else.
2295 ///
2296 /// Empty for a description that reserved no probes, which is what makes the
2297 /// retention cost of this rung zero for every caller that does not use it —
2298 /// see [`crate::probe_visibility`].
2299 probe_occluders: crate::probe_visibility::Occluders,
2300 /// The split-sum `DFG` table as an `Rgba8Unorm` image — binding
2301 /// [`SPECULAR_DFG_BINDING`], read by multi-scatter energy compensation and
2302 /// by every area light's specular term.
2303 ///
2304 /// Uploaded once from `crcbl_shaders::dfg::pair_texels` and never written
2305 /// again: it is a property of the GGX lobe rather than of a scene, a view or
2306 /// a frame. Unlike [`ForwardRenderer::ambient_occlusion_placeholder`] beside
2307 /// it this is not a stand-in for anything — there is no path on which the
2308 /// table is absent, because there is no path on which the lobe is.
2309 specular_dfg: UploadedTexture,
2310 /// The linearly transformed cosine fit as an `Rgba16Float` image — binding
2311 /// [`LTC_TABLE_BINDING`], and the whole of an area light's specular shape.
2312 ///
2313 /// Uploaded once from `crcbl_shaders::ltc::texels`, on the table above it's
2314 /// terms exactly and for the same reason: it is a property of the lobe, and
2315 /// it is bound on every path because Slang's Metal backend materialises
2316 /// every global into every entry point.
2317 ltc_table: UploadedTexture,
2318 /// `[frame][view]`: the entries [`ForwardRenderer::shadow_groups`] was built
2319 /// from.
2320 ///
2321 /// Kept for one rebuild only: the pages' and their sampler's, which
2322 /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
2323 /// layout a slot holds — [`View::prepass_group_entries`]' reason.
2324 shadow_group_entries: Vec<Vec<Vec<BindGroupEntry>>>,
2325
2326 /// The ground grid's pipeline and uniform ring — see [`crate::grid`].
2327 ///
2328 /// [`None`] until a caller first switches it on with
2329 /// [`set_ground_grid`](ForwardRenderer::set_ground_grid), which is what
2330 /// keeps a sample that never asks for a grid from building a pipeline and a
2331 /// ring of blocks for a pass it does not record. Once built it is kept —
2332 /// switching the grid off is [`ForwardRenderer::ground_grid_on`] and not a
2333 /// release, because releasing a uniform ring the frames in flight may still
2334 /// be reading is exactly what the ring exists to prevent.
2335 ground_grid: Option<GroundGrid>,
2336 /// Whether [`add_passes`](ForwardRenderer::add_passes) records the ground
2337 /// grid's pass. **`false` by default**: the grid is a tool's chrome, and
2338 /// every sample and every golden image predates it.
2339 ground_grid_on: bool,
2340
2341 /// The debug draw layer's immediate-mode buffer and its pass — see
2342 /// [`crate::debug_draw`].
2343 ///
2344 /// Always present and empty by default, because appending to it is what a
2345 /// system does and the buffer is a `Vec`; the pipeline and the rings inside
2346 /// it are what stay unbuilt until a frame has both a segment and
2347 /// [`crate::debug_draw::r_debug_draw`] switched on.
2348 debug_draw: DebugDraw,
2349
2350 /// The shadow atlas viewer — see [`crate::atlas_view`]. It draws on no frame
2351 /// but the one [`debug_view`](Self::debug_view) resolved to
2352 /// [`DebugView::ShadowAtlas`], which is none until a caller calls
2353 /// [`set_atlas_view`](Self::set_atlas_view).
2354 atlas_viewer: AtlasView,
2355 /// How large the internal render target is as a fraction of the extent a
2356 /// caller hands `begin_frame` — see [`set_render_scale`](Self::set_render_scale).
2357 render_scale: f32,
2358
2359 /// The three layers a caller supplies — see [`crate::effects`].
2360 effect_request: EffectRequest,
2361 /// The fourth layer: what this device can draw, which clamps last and
2362 /// absolutely.
2363 ///
2364 /// **Every effect, and that is a fact about the effects rather than an
2365 /// unfinished clamp.** Topic 18 says so of the occlusion pair in as many
2366 /// words — "there is no device fact to gate on … inventing a capability that
2367 /// is really a performance opinion is what topic 39 exists to prevent" — and
2368 /// the reflection pair's module says it of itself. The shadow atlas is a
2369 /// `D32Float` image and a depth-only pass, which is not something a device
2370 /// that got this far can be missing either: one too small for the atlas
2371 /// fails to *build* this renderer rather than degrading past it.
2372 ///
2373 /// So the clamp is real and its rule set is empty. The first rule arrives
2374 /// with the ray-traced variants of these same three effects, which
2375 /// [`LightingPath`](crcbl_hal::LightingPath) selects and which nothing
2376 /// builds yet.
2377 device_effects: RenderEffects,
2378 /// What the frame [`begin_frame`](ForwardRenderer::begin_frame) opened
2379 /// draws, resolved once there.
2380 ///
2381 /// **Frozen for the frame on purpose.** `begin_frame` skips a shadow cull's
2382 /// parameter write when shadows are off and
2383 /// [`add_passes`](ForwardRenderer::add_passes) skips its dispatch; a request
2384 /// changed between the two would dispatch a cull whose counters nothing
2385 /// zeroed, which is a plausible frame drawn off last frame's numbers.
2386 frame_effects: RenderEffects,
2387 /// How many blur passes the frame [`begin_frame`](ForwardRenderer::begin_frame)
2388 /// opened runs over the raw occlusion channel — [`crate::ssao::blur_passes`],
2389 /// read once there.
2390 ///
2391 /// **Frozen for the frame on [`ForwardRenderer::frame_effects`]'s terms.**
2392 /// [`add_passes`](ForwardRenderer::add_passes) both counts the frame's
2393 /// full-screen triangles and records its passes, and a console command
2394 /// landing between the two reads would leave `counters` describing a frame
2395 /// that was never submitted.
2396 frame_ssao_blurs: u32,
2397 /// Full-screen passes the last [`add_passes`](ForwardRenderer::add_passes)
2398 /// recorded, which is what [`counters`](ForwardRenderer::counters) reports
2399 /// as submitted beside the pool's instances.
2400 ///
2401 /// Stored rather than re-derived from [`ForwardRenderer::frame_effects`]:
2402 /// `counters` describes the frame that *was* recorded, and a request set
2403 /// after it would otherwise change the count of a frame already submitted.
2404 recorded_fullscreen: u64,
2405
2406 /// Whether the last [`add_passes`](ForwardRenderer::add_passes) recorded the
2407 /// debug draw layer's pass, as the one direct draw it costs.
2408 ///
2409 /// Separate from [`ForwardRenderer::recorded_fullscreen`] because it is not
2410 /// a full-screen triangle: it is one line-list draw of every segment this
2411 /// frame appended. Both are direct draws of one instance, which is what
2412 /// [`ForwardRenderer::direct_draws`] adds up.
2413 recorded_debug_draw: u64,
2414 /// How many tiles of the shadow atlas the last
2415 /// [`add_passes`](ForwardRenderer::add_passes) reset with a draw rather
2416 /// than with the attachment's own clear.
2417 ///
2418 /// Zero on every frame that clears the whole attachment, which is every
2419 /// frame until the cadence is switched on — see
2420 /// [`MeshModules::depth_clear_pipeline`]. One over-sized triangle of one
2421 /// instance each, so it joins the full-screen draws rather than the
2422 /// indirect ones.
2423 recorded_tile_clears: u64,
2424 /// `docs/plan/55-water.md`'s bodies of water, meshed, and the ring of
2425 /// buffers every view draws them from — see [`crate::water`]. Empty until
2426 /// [`set_water`](ForwardRenderer::set_water), and an empty set records no
2427 /// pass.
2428 water: WaterBodies,
2429 /// The surface draws the last [`add_passes`](ForwardRenderer::add_passes)
2430 /// recorded for the primary camera: one indexed draw per body, each of one
2431 /// instance, so they join the direct draws on the debug draw layer's terms.
2432 recorded_water_draws: u64,
2433 /// `docs/plan/57-grass.md`'s field, its device resources and the ring of
2434 /// retirements a replaced one leaves — see [`crate::grass`]. Empty until
2435 /// [`set_grass`](ForwardRenderer::set_grass), and an empty field records no
2436 /// pass.
2437 grass: GrassScene,
2438 /// The wind block every view writes into its own ring — see
2439 /// [`set_wind`](ForwardRenderer::set_wind). Calm until a caller sets one.
2440 wind: crcbl_shaders::wind::WindParams,
2441 /// The grass draws the last [`add_passes`](ForwardRenderer::add_passes)
2442 /// recorded for the primary camera: one per tile slot per look the field
2443 /// draws.
2444 ///
2445 /// **Not among the direct draws**, unlike the water surface's: every one of
2446 /// them is an indirect call whose instance count lives in a buffer a
2447 /// dispatch wrote, so the CPU knows how many *calls* it submitted and
2448 /// nothing about how many blades came out of them.
2449 recorded_grass_draws: u64,
2450}
2451
2452/// What a partly-built [`ForwardRenderer`] has to give back.
2453///
2454/// `new` creates a dozen objects with `?` between them, and the seam's
2455/// `destroy_*` is explicit — so a failure half way through used to leak
2456/// everything created before it. The recorder's leak assertions cover the happy
2457/// path; this covers the other one.
2458#[derive(Debug, Default)]
2459struct Rollback {
2460 buffers: Vec<BufferHandle>,
2461 bind_groups: Vec<BindGroupHandle>,
2462 bind_group_layouts: Vec<BindGroupLayoutHandle>,
2463 pipeline_layouts: Vec<PipelineLayoutHandle>,
2464 pipelines: Vec<GraphicsPipelineHandle>,
2465 samplers: Vec<SamplerHandle>,
2466 /// The shadow atlas and its placeholder, which are created here rather than
2467 /// uploaded — so unlike [`Rollback::textures`] they are a plain handle each,
2468 /// with their views beside them.
2469 images: Vec<ImageHandle>,
2470 image_views: Vec<ImageViewHandle>,
2471 /// Uploaded images, which own a view each and so cannot be rolled back as
2472 /// one list of handles.
2473 textures: Vec<UploadedTexture>,
2474 /// The geometry pool, which owns two buffers, a semaphore and anything
2475 /// still staged — so it cannot be rolled back as a list of handles.
2476 pool: Option<MeshPool>,
2477 /// The instance pool, which owns one buffer per frame in flight.
2478 instances: Option<InstancePool>,
2479 /// The material table, which owns one buffer.
2480 materials: Option<MaterialTable>,
2481 /// The irradiance probe table, which owns one buffer.
2482 probes: Option<ProbeTable>,
2483 /// The irradiance probes' updater, which owns one pipeline,
2484 /// one layout and a ring of blocks — and only exists for a scene whose
2485 /// volume asked to be updated.
2486 probe_gather: Option<ProbeGather>,
2487 /// The cull and draw-argument passes, which own two pipelines and a ring of
2488 /// buffers each — and which clean themselves up on their own failure path,
2489 /// so this only carries one that was built.
2490 draws: Option<DrawGen>,
2491 /// One more of the same per shadow-atlas tile — a `Vec` rather than an
2492 /// `Option`, because a failure part way through the tiles has to release the
2493 /// ones already built.
2494 shadow_draws: Vec<DrawGen>,
2495 /// The cluster buffers, which own three buffers and are built on the
2496 /// mesh-shader path alone.
2497 clusters: Option<ClusterPool>,
2498 /// Topic 18's light list and froxel grid, which own a pipeline and a ring of
2499 /// three buffers — and which clean themselves up on their own failure path,
2500 /// so this only carries one that was built.
2501 lights: Option<LightGrid>,
2502 /// Topic 46's occlusion pair, which owns two
2503 /// pipelines, two layouts and a ring of blocks.
2504 ssao: Option<Ssao>,
2505 /// Topic 45's contact-shadow march, which owns one
2506 /// pipeline, one layout and a ring of blocks.
2507 contact_shadows: Option<ContactShadows>,
2508 /// Topic 47's depth pyramid, which owns one
2509 /// pipeline, one layout and a ring of blocks per level.
2510 hiz: Option<Hiz>,
2511 /// Topic 03 §3.3's farthest-depth pyramid,
2512 /// which owns one pipeline, one layout and — once a frame culled — a chain
2513 /// of level images.
2514 occlusion_pyramid: Option<OcclusionPyramid>,
2515 /// Topic 47's reflection march, which owns one
2516 /// pipeline, one layout and a ring of blocks.
2517 ssr: Option<Ssr>,
2518 /// The froxel volume, which owns three
2519 /// pipelines, two layouts and two rings of buffers.
2520 volumetric: Option<Volumetric>,
2521 /// Topic 43 §6's auto-exposure, which owns three
2522 /// pipelines, one layout and three rings of buffers.
2523 exposure: Option<Exposure>,
2524 /// Topic 48's bloom chain, which owns three
2525 /// pipelines, two layouts, a sampler and a ring of blocks.
2526 bloom: Option<Bloom>,
2527 /// The cheap antialiasing tier, which owns one
2528 /// pipeline, one layout, a sampler and a ring of blocks.
2529 fxaa: Option<Fxaa>,
2530 /// The higher antialiasing tier, which owns
2531 /// four compute pipelines, one graphics pipeline, two layouts and a ring of
2532 /// blocks.
2533 cmaa2: Option<Cmaa2>,
2534 upscale: Option<Upscale>,
2535 /// The background pass, which owns one pipeline, one layout and a ring of
2536 /// blocks and groups.
2537 sky_pass: Option<SkyPass>,
2538 /// The water surface's two pipelines, their layouts and a ring of blocks.
2539 water: Option<Water>,
2540 /// The grass passes' pipelines, their layouts and their rings of
2541 /// blocks.
2542 grass: Option<Grass>,
2543 /// The shadow atlas viewer, which owns one pipeline, one layout and a ring
2544 /// of blocks and groups.
2545 atlas_viewer: Option<AtlasView>,
2546 /// The camera, once [`View::build`] has made it whole — released as one,
2547 /// by [`View::destroy`].
2548 primary: Option<View>,
2549}
2550
2551impl Rollback {
2552 /// Releases everything, in the same dependency order as
2553 /// [`ForwardRenderer::destroy`].
2554 fn run(self, device: &dyn Device) {
2555 if let Some(view) = self.primary {
2556 view.destroy(device);
2557 }
2558 for texture in self.textures {
2559 texture.destroy(device);
2560 }
2561 for handle in self.samplers {
2562 device.destroy_sampler(handle);
2563 }
2564 for handle in self.image_views {
2565 device.destroy_image_view(handle);
2566 }
2567 for handle in self.images {
2568 device.destroy_image(handle);
2569 }
2570 for handle in self.pipelines {
2571 device.destroy_graphics_pipeline(handle);
2572 }
2573 for handle in self.pipeline_layouts {
2574 device.destroy_pipeline_layout(handle);
2575 }
2576 for handle in self.bind_groups {
2577 device.destroy_bind_group(handle);
2578 }
2579 for handle in self.bind_group_layouts {
2580 device.destroy_bind_group_layout(handle);
2581 }
2582 for handle in self.buffers {
2583 device.destroy_buffer(handle);
2584 }
2585 if let Some(clusters) = self.clusters {
2586 clusters.destroy(device);
2587 }
2588 for draws in self.shadow_draws {
2589 draws.destroy(device);
2590 }
2591 if let Some(lights) = self.lights {
2592 lights.destroy(device);
2593 }
2594 if let Some(atlas_viewer) = self.atlas_viewer {
2595 atlas_viewer.destroy(device);
2596 }
2597 if let Some(grass) = self.grass {
2598 grass.destroy(device);
2599 }
2600 if let Some(water) = self.water {
2601 water.destroy(device);
2602 }
2603 if let Some(sky_pass) = self.sky_pass {
2604 sky_pass.destroy(device);
2605 }
2606 if let Some(upscale) = self.upscale {
2607 upscale.destroy(device);
2608 }
2609 if let Some(cmaa2) = self.cmaa2 {
2610 cmaa2.destroy(device);
2611 }
2612 if let Some(fxaa) = self.fxaa {
2613 fxaa.destroy(device);
2614 }
2615 if let Some(bloom) = self.bloom {
2616 bloom.destroy(device);
2617 }
2618 if let Some(exposure) = self.exposure {
2619 exposure.destroy(device);
2620 }
2621 if let Some(volumetric) = self.volumetric {
2622 volumetric.destroy(device);
2623 }
2624 if let Some(ssr) = self.ssr {
2625 ssr.destroy(device);
2626 }
2627 if let Some(occlusion_pyramid) = self.occlusion_pyramid {
2628 occlusion_pyramid.destroy(device);
2629 }
2630 if let Some(hiz) = self.hiz {
2631 hiz.destroy(device);
2632 }
2633 if let Some(contact_shadows) = self.contact_shadows {
2634 contact_shadows.destroy(device);
2635 }
2636 if let Some(ssao) = self.ssao {
2637 ssao.destroy(device);
2638 }
2639 if let Some(draws) = self.draws {
2640 draws.destroy(device);
2641 }
2642 // Before the table, because its bind groups name that table's rows.
2643 if let Some(gather) = self.probe_gather {
2644 gather.destroy(device);
2645 }
2646 if let Some(table) = self.probes {
2647 table.destroy(device);
2648 }
2649 if let Some(table) = self.materials {
2650 table.destroy(device);
2651 }
2652 if let Some(pool) = self.instances {
2653 pool.destroy(device);
2654 }
2655 if let Some(pool) = self.pool {
2656 pool.destroy(device);
2657 }
2658 }
2659}
2660
2661/// What every bind group of the mesh layout names identically.
2662///
2663/// Split from [`MeshGroup`] rather than folded into it because the split *is*
2664/// the claim: a resource here cannot differ between the colour pass's group and
2665/// a cascade's, and one there must be looked at.
2666struct SharedBindings<'a> {
2667 vertices: BufferHandle,
2668 draw_constants: BufferHandle,
2669 mesh_table: BufferHandle,
2670 materials: BufferHandle,
2671 /// Bindings [`BASE_COLOR_PAGE_BINDING`], [`NORMAL_PAGE_BINDING`],
2672 /// [`MRO_PAGE_BINDING`] and [`EMISSIVE_PAGE_BINDING`] — the four material
2673 /// pages, every one read through the sampler at [`PAGE_SAMPLER_BINDING`]
2674 /// beside them — as this frame slot names them, which is what
2675 /// [`ForwardRenderer::adopt_pages`] moves one slot at a time.
2676 pages: PageBindings,
2677 /// `Some` on [`GeometryPath::MeshShader`] and on no other path, which is
2678 /// what decides whether the mesh-only bindings exist at all.
2679 clusters: Option<&'a ClusterPool>,
2680 shadow_sampler: SamplerHandle,
2681 /// Bindings [`LIGHT_LIST_BINDING`] and [`LIGHT_GRID_BINDING`], this frame's
2682 /// slots of the light ring.
2683 ///
2684 /// Shared rather than per-group, unlike the instance array beside them, and
2685 /// that is the claim: **a cascade shades nothing**, so it reads the same
2686 /// list and the same grid the colour pass does — the depth-only pipeline
2687 /// simply never looks. Two buffers per pass would be two clustering
2688 /// dispatches for one camera.
2689 lights: BufferHandle,
2690 light_grid: BufferHandle,
2691 /// Binding [`PROBE_TABLE_BINDING`], **this frame's slot** of the irradiance
2692 /// grid's ring.
2693 ///
2694 /// Shared across the *groups of one frame* rather than across frames, which
2695 /// is the light list's arrangement exactly: a cascade shades nothing, so it
2696 /// reads the same rows the colour pass does and the depth-only pipeline
2697 /// simply never looks. What it is not is shared across the ring — see
2698 /// [`crate::probe`] for why the table is per-frame at all.
2699 probes: BufferHandle,
2700 /// Binding [`LEVEL_GROUP_TABLE_BINDING`], `DrawGen`'s packed table buffer.
2701 ///
2702 /// Shared rather than per-group for the probe grid's reason exactly: the
2703 /// regions are written when a mesh becomes resident and never per frame, so
2704 /// a cascade and the colour pass read the same words. What varies between
2705 /// them is the *budget* the mesh stage projects against, and that rides in
2706 /// each pass's own frame block.
2707 tables: BufferHandle,
2708 /// Binding [`SPECULAR_DFG_BINDING`], the split-sum `DFG` pair — see
2709 /// [`ForwardRenderer::specular_dfg`].
2710 ///
2711 /// Shared rather than per-group for the probe grid's reason and more
2712 /// strongly: it is cooked into the binary, uploaded once at build and
2713 /// identical for every view this engine will ever draw. A cascade names it
2714 /// and never looks.
2715 specular_dfg: ImageViewHandle,
2716 /// Binding [`LTC_TABLE_BINDING`], the area lights' fit — see
2717 /// [`ForwardRenderer::ltc_table`]. Shared for the table above it's reason.
2718 ltc_table: ImageViewHandle,
2719}
2720
2721/// The half of a mesh-layout bind group that differs between the colour pass and
2722/// each shadow cascade.
2723///
2724/// One description for both, so the two cannot drift: a cascade's group is the
2725/// colour pass's with six resources swapped, and swapping the wrong five of them
2726/// is a shadow map rendered from the camera — which looks like a shadow map.
2727struct MeshGroup {
2728 /// Binding 0. The colour pass's frame block, or a cascade's copy whose
2729 /// `view_proj` is that cascade's matrix.
2730 uniforms: BufferHandle,
2731 /// Binding 2. This frame's slot of the instance ring.
2732 instances: BufferHandle,
2733 /// Binding 5. Whose survivors this group draws.
2734 runs: BufferHandle,
2735 /// Binding 12, on the mesh path: the same survivors' indirect arguments,
2736 /// read as data.
2737 args: BufferHandle,
2738 /// Binding 13, where there is an amplification stage: the frustum it culls
2739 /// clusters against.
2740 cull_params: BufferHandle,
2741 /// Binding 14, likewise: what it counts survivors into.
2742 cull_stats: BufferHandle,
2743 /// Binding 18, likewise: the cut the descent chose, one word per resident
2744 /// cluster. `None` exactly where there is no amplification stage, which is
2745 /// where the layout has no CLUSTER_SELECTION_BINDING either.
2746 ///
2747 /// **A buffer per pass**, not one shared: the colour pass is recorded last,
2748 /// so a cascade writing the camera's would leave nothing of its own to read.
2749 /// See [`ForwardRenderer::shadow_selection`].
2750 cluster_selection: Option<BufferHandle>,
2751 /// Binding 19, likewise: topic 25's hysteresis state, which the
2752 /// draw-argument pass wrote this frame and this one only reads.
2753 ///
2754 /// **A buffer per pass** as well, because the colour pass and a cascade
2755 /// judge the same groups under different budgets — see
2756 /// [`TileBuffers::group_state`].
2757 group_state: Option<BufferHandle>,
2758 /// Binding [`SHADOW_ATLAS_BINDING`]. The atlas for the pass that reads it,
2759 /// and the placeholder for the pass that writes it — see
2760 /// [`ForwardRenderer::shadow_placeholder`], which is where that is argued.
2761 shadow_map: ImageViewHandle,
2762 /// Binding [`AMBIENT_OCCLUSION_BINDING`]. The blurred occlusion channel for
2763 /// a forward pass that computed one, and the white placeholder everywhere
2764 /// else — see [`ForwardRenderer::ambient_occlusion_placeholder`].
2765 ///
2766 /// **Every group built at `build` names the placeholder**, including the
2767 /// camera's: the occlusion image may be a graph transient whose view exists
2768 /// only at execute time, so the camera's group is rebuilt against whatever
2769 /// the frame bound inside the forward pass and cached — the shape
2770 /// [`View::tonemap_groups`] already has.
2771 ambient_occlusion: ImageViewHandle,
2772 /// Binding [`CONTACT_SHADOW_BINDING`]. The contact-shadow channel for a
2773 /// forward pass that marched one, and the white placeholder everywhere else
2774 /// — see [`ForwardRenderer::contact_shadow_placeholder`].
2775 ///
2776 /// [`MeshGroup::ambient_occlusion`]'s terms exactly, including that every
2777 /// group built at `build` names the placeholder.
2778 contact_shadow: ImageViewHandle,
2779 /// Binding [`PROBE_VISIBILITY_BINDING`]. The captured per-probe visibility
2780 /// maps for the camera's pass, and the one-texel placeholder everywhere
2781 /// else — see [`ForwardRenderer::probe_visibility_placeholder`].
2782 ///
2783 /// [`MeshGroup::ambient_occlusion`]'s terms, with one difference: the image
2784 /// is not a graph transient but an ordinary uploaded texture, so what makes
2785 /// this a per-frame swap is the console switch and whether a capture has
2786 /// happened yet — neither of which is known at `build`.
2787 probe_visibility: ImageViewHandle,
2788}
2789
2790impl MeshGroup {
2791 fn entries(&self, shared: &SharedBindings<'_>) -> Vec<BindGroupEntry> {
2792 let mut entries = vec![
2793 BindGroupEntry {
2794 binding: 0,
2795 array_index: 0,
2796 resource: BindingResource::whole_buffer(self.uniforms),
2797 },
2798 BindGroupEntry {
2799 binding: 1,
2800 array_index: 0,
2801 resource: BindingResource::whole_buffer(shared.vertices),
2802 },
2803 BindGroupEntry {
2804 binding: 2,
2805 array_index: 0,
2806 // **This frame's slot of the instance ring, not a shared
2807 // buffer.** Binding one buffer here for every group would undo
2808 // the ring and reintroduce the cross-submission
2809 // read-after-write hazard it exists to prevent.
2810 resource: BindingResource::whole_buffer(self.instances),
2811 },
2812 BindGroupEntry {
2813 binding: 3,
2814 array_index: 0,
2815 // **One block, not the whole buffer.** The binding is dynamic,
2816 // so the bind's offset is added on top of this one and both
2817 // Vulkan and WebGPU require `offset + dynamic + size` to stay
2818 // inside the buffer — bound whole, the very first non-zero
2819 // dynamic offset would be out of range.
2820 resource: BindingResource::Buffer {
2821 buffer: shared.draw_constants,
2822 offset: 0,
2823 size: DRAW_CONSTANTS_BLOCK,
2824 },
2825 },
2826 BindGroupEntry {
2827 binding: 4,
2828 array_index: 0,
2829 // The same table in every group, unlike the instance array
2830 // above it: the pool writes an entry when a mesh is uploaded or
2831 // freed, neither of which happens between frames here.
2832 resource: BindingResource::whole_buffer(shared.mesh_table),
2833 },
2834 BindGroupEntry {
2835 binding: 5,
2836 array_index: 0,
2837 // Whose cull this group draws from. This is the binding a
2838 // cascade's group differs in most consequentially: it is what
2839 // makes the shadow pass draw what the *light* can see rather
2840 // than what the camera can.
2841 resource: BindingResource::whole_buffer(self.runs),
2842 },
2843 BindGroupEntry {
2844 binding: 6,
2845 array_index: 0,
2846 resource: BindingResource::whole_buffer(shared.materials),
2847 },
2848 BindGroupEntry {
2849 binding: BASE_COLOR_PAGE_BINDING,
2850 array_index: 0,
2851 // **One entry, `array_index: 0`**, because the page is one
2852 // image and the layer is chosen in the shader. A bindless array
2853 // would be one entry per texture at ascending array indices,
2854 // which is the write path `BindGroupEntry`'s own docs describe
2855 // and the one this pass does not take.
2856 resource: BindingResource::ImageView(
2857 shared.pages.views[PageKind::BaseColor.index()],
2858 ),
2859 },
2860 BindGroupEntry {
2861 binding: PAGE_SAMPLER_BINDING,
2862 array_index: 0,
2863 resource: BindingResource::Sampler(shared.pages.sampler),
2864 },
2865 ];
2866 if let Some(clusters) = shared.clusters {
2867 entries.extend([
2868 BindGroupEntry {
2869 binding: CLUSTERS_BINDING,
2870 array_index: 0,
2871 // The same three buffers in every group, on the mesh table's
2872 // terms: clusters are written when the pool is built and
2873 // never again.
2874 resource: BindingResource::whole_buffer(clusters.clusters()),
2875 },
2876 BindGroupEntry {
2877 binding: CLUSTER_VERTICES_BINDING,
2878 array_index: 0,
2879 resource: BindingResource::whole_buffer(clusters.vertices()),
2880 },
2881 BindGroupEntry {
2882 binding: CLUSTER_CORNERS_BINDING,
2883 array_index: 0,
2884 resource: BindingResource::whole_buffer(clusters.corners()),
2885 },
2886 BindGroupEntry {
2887 binding: CLUSTER_DRAW_ARGS_BINDING,
2888 array_index: 0,
2889 // **Arguments read as data.** The mesh path records no
2890 // indirect draw at all; what it wants out of this buffer is
2891 // the one word only the GPU knows — how many instances
2892 // survived into each bucket.
2893 resource: BindingResource::whole_buffer(self.args),
2894 },
2895 ]);
2896 }
2897 // Both mesh entry points retain these native buffer arguments even
2898 // when no amplification stage reads them.
2899 if shared.clusters.is_some() {
2900 entries.extend([
2901 BindGroupEntry {
2902 binding: CLUSTER_CULL_BINDING,
2903 array_index: 0,
2904 resource: BindingResource::whole_buffer(self.cull_params),
2905 },
2906 BindGroupEntry {
2907 binding: CLUSTER_CULL_STATS_BINDING,
2908 array_index: 0,
2909 resource: BindingResource::whole_buffer(self.cull_stats),
2910 },
2911 ]);
2912 }
2913 entries.push(BindGroupEntry {
2914 binding: SHADOW_ATLAS_BINDING,
2915 array_index: 0,
2916 resource: BindingResource::ImageView(self.shadow_map),
2917 });
2918 entries.push(BindGroupEntry {
2919 binding: SHADOW_SAMPLER_BINDING,
2920 array_index: 0,
2921 resource: BindingResource::Sampler(shared.shadow_sampler),
2922 });
2923 // Mesh-only buffers are sorted after the common fragment prefix below.
2924 if let Some(clusters) = shared.clusters {
2925 entries.push(BindGroupEntry {
2926 binding: CLUSTER_SELECT_BINDING,
2927 array_index: 0,
2928 // Bound with the geometry rather than with the cull, because
2929 // `vertex_base` *is* geometry: it is which level of a DAG a
2930 // cluster's vertices live in, and both mesh entry points resolve
2931 // a vertex through it.
2932 resource: BindingResource::whole_buffer(clusters.selection()),
2933 });
2934 }
2935 if let Some(selection) = self.cluster_selection {
2936 entries.push(BindGroupEntry {
2937 binding: CLUSTER_SELECTION_BINDING,
2938 array_index: 0,
2939 resource: BindingResource::whole_buffer(selection),
2940 });
2941 }
2942 if let Some(state) = self.group_state {
2943 entries.push(BindGroupEntry {
2944 binding: CLUSTER_GROUP_STATE_BINDING,
2945 array_index: 0,
2946 resource: BindingResource::whole_buffer(state),
2947 });
2948 }
2949 // Topic 18's pair, on every path and in every group — see the layout,
2950 // which has no configuration that omits them either.
2951 entries.push(BindGroupEntry {
2952 binding: LIGHT_LIST_BINDING,
2953 array_index: 0,
2954 resource: BindingResource::whole_buffer(shared.lights),
2955 });
2956 entries.push(BindGroupEntry {
2957 binding: LIGHT_GRID_BINDING,
2958 array_index: 0,
2959 resource: BindingResource::whole_buffer(shared.light_grid),
2960 });
2961 // Shared fragment textures and probes retain their raster bindings.
2962 entries.push(BindGroupEntry {
2963 binding: AMBIENT_OCCLUSION_BINDING,
2964 array_index: 0,
2965 resource: BindingResource::ImageView(self.ambient_occlusion),
2966 });
2967 // And the irradiance grid past it — see [`PROBE_TABLE_BINDING`].
2968 entries.push(BindGroupEntry {
2969 binding: PROBE_TABLE_BINDING,
2970 array_index: 0,
2971 resource: BindingResource::whole_buffer(shared.probes),
2972 });
2973 // Group records are present on both mesh paths, matching the layout.
2974 if shared.clusters.is_some() {
2975 entries.push(BindGroupEntry {
2976 binding: LEVEL_GROUP_TABLE_BINDING,
2977 array_index: 0,
2978 resource: BindingResource::whole_buffer(shared.tables),
2979 });
2980 }
2981 // The DFG texture is read by the fragment stage of every path.
2982 entries.push(BindGroupEntry {
2983 binding: SPECULAR_DFG_BINDING,
2984 array_index: 0,
2985 resource: BindingResource::ImageView(shared.specular_dfg),
2986 });
2987 // And §2's normal page above that, on the same ascending terms — see
2988 // [`NORMAL_PAGE_BINDING`]. Unconditional and `array_index: 0` for
2989 // binding 7's reason: one image, and the layer is chosen in the shader.
2990 entries.push(BindGroupEntry {
2991 binding: NORMAL_PAGE_BINDING,
2992 array_index: 0,
2993 resource: BindingResource::ImageView(shared.pages.views[PageKind::Normal.index()]),
2994 });
2995 // And the area lights' table above that, on the same ascending terms —
2996 // see [`LTC_TABLE_BINDING`].
2997 entries.push(BindGroupEntry {
2998 binding: LTC_TABLE_BINDING,
2999 array_index: 0,
3000 resource: BindingResource::ImageView(shared.ltc_table),
3001 });
3002 // And the contact-shadow channel above that, last of the set and on the
3003 // same ascending terms — see [`CONTACT_SHADOW_BINDING`].
3004 entries.push(BindGroupEntry {
3005 binding: CONTACT_SHADOW_BINDING,
3006 array_index: 0,
3007 resource: BindingResource::ImageView(self.contact_shadow),
3008 });
3009 // And the probe visibility maps above that, on the same ascending terms
3010 // — see [`PROBE_VISIBILITY_BINDING`].
3011 entries.push(BindGroupEntry {
3012 binding: PROBE_VISIBILITY_BINDING,
3013 array_index: 0,
3014 resource: BindingResource::ImageView(self.probe_visibility),
3015 });
3016 // And §2's other two pages above that, last of the set and on the same
3017 // ascending terms — see [`MRO_PAGE_BINDING`] and
3018 // [`EMISSIVE_PAGE_BINDING`]. Unconditional and `array_index: 0` for the
3019 // normal page's reason: one image apiece, and the layer is chosen in
3020 // the shader.
3021 entries.push(BindGroupEntry {
3022 binding: MRO_PAGE_BINDING,
3023 array_index: 0,
3024 resource: BindingResource::ImageView(
3025 shared.pages.views[PageKind::MetallicRoughnessOcclusion.index()],
3026 ),
3027 });
3028 entries.push(BindGroupEntry {
3029 binding: EMISSIVE_PAGE_BINDING,
3030 array_index: 0,
3031 resource: BindingResource::ImageView(shared.pages.views[PageKind::Emissive.index()]),
3032 });
3033 entries.sort_by_key(|entry| entry.binding);
3034 entries
3035 }
3036}
3037
3038/// The two `ArrayPages` images every group of the mesh layout names, as the
3039/// graph knows them.
3040///
3041/// One value rather than two arguments because the two travel together
3042/// everywhere: every pass that declares one declares the other, and a pass
3043/// handed them the wrong way round would order a caller's copy into the wrong
3044/// image — which is a barrier bug, and therefore one that reproduces on one
3045/// backend and not the others.
3046#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3047struct MaterialPages {
3048 /// §3.2's base-colour page — [`ForwardRenderer::base_color_page_import`].
3049 base_color: ImageId,
3050 /// §2's normal page — [`ForwardRenderer::normal_page_import`].
3051 normal: ImageId,
3052 /// §2's metallic-roughness-occlusion page —
3053 /// [`ForwardRenderer::mro_page_import`].
3054 mro: ImageId,
3055 /// §2's emissive page — [`ForwardRenderer::emissive_page_import`].
3056 emissive: ImageId,
3057}
3058
3059/// Everything [`ForwardRenderer::add_shadow_pass`] declares and does not write,
3060/// as the graph knows it.
3061///
3062/// One value rather than an argument apiece for [`MaterialPages`]' reason, and
3063/// the list grew past what an argument list should be the moment the probe rows
3064/// joined it: each of these is in every cascade's bind group and read by no
3065/// cascade, so what the pass does with them is one thing — declare them, so the
3066/// graph can order whoever writes them against these draws.
3067#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3068struct ShadowReads {
3069 /// The occlusion placeholder every cascade's group stands the real channel
3070 /// in for — [`ForwardRenderer::ambient_occlusion_placeholder`].
3071 occlusion_placeholder: ImageId,
3072 /// §3.2's and §2's pages, which the cascades name and never sample.
3073 pages: MaterialPages,
3074 /// The skinned vertex region, where a frame has one — the cascades pull the
3075 /// same geometry the colour pass does.
3076 skinned: Option<BufferId>,
3077 /// This frame's slot of the probe ring — see [`crate::probe`].
3078 probes: BufferId,
3079}
3080
3081/// What the mesh pass's bind-group layout is called.
3082///
3083/// Named rather than written twice because a test asserts on it: the layout's
3084/// *binding numbers* are what `crcbl-mtl` turns into Metal argument-table
3085/// indices by counting, so `the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage`
3086/// has to find this one layout among the recorder's.
3087const MESH_LAYOUT_LABEL: &str = "mesh frame";
3088
3089/// Imports a buffer a pass both reads and writes, carried from one frame on
3090/// its slot to the next: it arrives in the state the previous frame that used
3091/// the slot left it in, and that is the state it is declared to leave in.
3092///
3093/// A record of the cut or a statistics sink, which a pass writes and the next
3094/// frame on the same slot writes again — a barrier naming `Undefined` as its
3095/// source would carry no source scope and order this frame's write against
3096/// nothing.
3097fn import_read_write(graph: &mut RenderGraph<'_>, label: &str, buffer: BufferHandle) -> BufferId {
3098 graph.import_buffer(
3099 label,
3100 ImportedBuffer {
3101 buffer,
3102 initial: ResourceState::ShaderReadWrite,
3103 final_state: ResourceState::ShaderReadWrite,
3104 },
3105 )
3106}
3107
3108/// Declares the buffers a geometry pass reads to find its draws.
3109///
3110/// The other half of [`BucketDraws`]: what the *graph* has to be told, where that
3111/// struct is what the encoder is told. Three passes declare exactly this set, and
3112/// the seam calls the barrier it produces the single most important one in a
3113/// GPU-driven frame — its absence produces "sometimes nothing draws".
3114///
3115/// A caller with a cluster-selection buffer of its own appends it; that is the
3116/// one declaration that differs between the colour pass, a cascade and the depth
3117/// prepass.
3118fn read_draw_sources<'g, 'a>(
3119 pass: PassBuilder<'g, 'a>,
3120 draws: &GeneratedDraws,
3121 emit: EmitTail,
3122) -> PassBuilder<'g, 'a> {
3123 // The buffers the draws come out of. Declaring them is what makes the graph
3124 // transition them out of the compute pass's `ShaderReadWrite`.
3125 let pass = pass.read_buffer(draws.runs_id);
3126 if emit.is_mesh() {
3127 // **The same arguments, read as data rather than executed**, which is
3128 // what the stages use to bound the run of surviving instances they index.
3129 // The per-bucket draw *counts* are not read at all, because nothing here
3130 // is a draw whose count could come from memory.
3131 //
3132 // The dispatch *extents* are a real indirect read — one structure per
3133 // bucket, written by the same pass. They are in a **different buffer**
3134 // from the arguments above and that separation is load-bearing: a
3135 // resource is in exactly one state per pass and these two are in
3136 // different ones. They share a buffer with the counts instead, which
3137 // this path does not read at all — see [`GeneratedDraws::counts`].
3138 let pass = pass
3139 .read_buffer(draws.args_id)
3140 .use_buffer(draws.counts_id, ResourceState::IndirectArgument);
3141 // The amplification stage counts its survivors into the culling
3142 // statistics, which the draw-argument pass read a moment ago — so this
3143 // is a write-after-read the graph has to order, and declaring it is
3144 // the whole of how it learns to.
3145 //
3146 // Topic 25's hysteresis state is read here and written by
3147 // the draw-argument pass a moment ago. Declaring it is what orders the
3148 // two — and what puts it back into `ShaderReadWrite` at the end of the
3149 // graph, which is where the next frame's draw-argument pass expects to
3150 // find it.
3151 //
3152 // **Declared on the whole mesh path, not only where there is an
3153 // amplification stage**, because that is where the bind group now
3154 // names both — see the layout, which is where the Metal argument-table
3155 // arithmetic that forced it is argued. A buffer bound writable and
3156 // never transitioned is a descriptor in the wrong resource state, which
3157 // is what the graph exists to prevent.
3158 pass.use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite)
3159 .read_buffer(draws.group_state_id)
3160 } else {
3161 pass.use_buffer(draws.args_id, ResourceState::IndirectArgument)
3162 .use_buffer(draws.counts_id, ResourceState::IndirectArgument)
3163 }
3164}
3165
3166/// What one [`MeshDesc`](crate::scene::MeshDesc) became once it was resident.
3167///
3168/// One of these per description mesh, in description order — so a mesh's index
3169/// here is its index there, which is what lets the bucket table, the level
3170/// tables and the cluster pool all be filled in by walking one list.
3171struct ResidentMesh {
3172 /// This mesh's table ids, finest first: one entry for a flat mesh, one per
3173 /// level for a DAG. Never empty.
3174 ///
3175 /// Every level is its own vertex range and so its own table entry. Level 0's
3176 /// id is the one the *instance* carries and the one the cull pass reads a
3177 /// bounding box out of; the coarser ones are named by the bucket table on a
3178 /// path that takes a uniform cut, and by nothing at all on the mesh path,
3179 /// where a cluster reaches its own level through
3180 /// [`vertex_bases`](Self::vertex_bases) instead.
3181 levels: Vec<u32>,
3182 /// Per level, how far that level's vertices start past level 0's — so a flat
3183 /// mesh's single entry is zero.
3184 ///
3185 /// What [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`] holds,
3186 /// and the whole of what makes a DAG drawable from one instance: the mesh
3187 /// stage adds this to the instance's own `base_vertex`, so a cut spanning
3188 /// three levels reads three different vertex ranges out of one pool.
3189 vertex_bases: Vec<u32>,
3190 /// Level 0's pool handle, for a mesh that can be **skinned** — and [`None`]
3191 /// for a [`Geometry::Dag`].
3192 ///
3193 /// A DAG is refused because its coarser levels are separate vertex runs no
3194 /// skinning dispatch writes: an instance drawn out of a skinned region
3195 /// resolves every level through [`vertex_bases`](Self::vertex_bases) added
3196 /// to the region's base, which for anything but level 0 is memory the
3197 /// dispatch never touched.
3198 skinnable: Option<MeshHandle>,
3199}
3200
3201impl ResidentMesh {
3202 /// The table id an instance of this mesh carries: **level 0's**, whatever
3203 /// the geometry path, because it is the entry `cull.slang` reads a bounding
3204 /// box out of and the coarser levels approximate the same surface inside the
3205 /// same box.
3206 fn id(&self) -> u32 {
3207 self.levels[0]
3208 }
3209}
3210
3211/// One skinned object the renderer re-points every frame: the instance, and the
3212/// base vertex it draws out of under each parity.
3213///
3214/// The bases are copied out of the [`SkinnedMesh`] rather than borrowed from it,
3215/// so placing an object does not tie the renderer's lifetime to the caller's
3216/// reservation — the renderer never needs the region again, only the two
3217/// numbers.
3218#[derive(Clone, Copy, Debug)]
3219struct SkinnedInstance {
3220 handle: InstanceHandle,
3221 /// Indexed by parity, in [`crate::skinning::SkinnedRegion::base`]'s
3222 /// indexing — so the half a frame of parity `p` draws out of is
3223 /// `bases[p & 1]` and the half the frame before it filled is
3224 /// `bases[(p ^ 1) & 1]`, which is
3225 /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base)'s
3226 /// answer for the same `p`.
3227 bases: [u32; 2],
3228 /// Whether a frame has already pointed this entry at a half of the region
3229 /// it now names.
3230 ///
3231 /// **What makes the previous base meaningful.** The half a frame did not
3232 /// write holds whatever its reservation came with until a dispatch fills
3233 /// it, so an object's first frame out of a region has no previous
3234 /// deformation to point at — naming that half would give it a motion vector
3235 /// against undefined vertices. Such an entry is put at rest instead, which
3236 /// is the rule [`InstancePool::insert`](crate::instance_pool::InstancePool::insert)
3237 /// applies to `previous_transform` for the same reason: a spawn did not
3238 /// travel from anywhere.
3239 pointed: bool,
3240}
3241
3242/// The two base vertices an object drawn out of `mesh` alternates between, in
3243/// [`SkinnedInstance::bases`]' indexing.
3244fn skinned_bases(mesh: &SkinnedMesh) -> [u32; 2] {
3245 [mesh.region().base(0), mesh.region().base(1)]
3246}
3247
3248/// One shadow cull's per-frame buffers, read out of its [`DrawGen`] before that
3249/// generator is handed to the rollback.
3250struct TileBuffers {
3251 runs: Vec<BufferHandle>,
3252 args: Vec<BufferHandle>,
3253 cull_params: Vec<BufferHandle>,
3254 cull_stats: Vec<BufferHandle>,
3255 /// This cull's own hysteresis state, and not the camera's.
3256 ///
3257 /// A shadow view selects from the camera's eye at the camera's scale, like
3258 /// the colour pass, but under budgets [`SHADOW_LOD_BIAS`] times as large — so
3259 /// it reaches a different answer for the same group, and an answer carried
3260 /// between frames needs somewhere of its own to be carried. Sharing the
3261 /// camera's buffer would be two rules writing one history and each undoing
3262 /// the other's band every frame.
3263 ///
3264 /// One per cull rather than one for the shadow pass, even though every one of
3265 /// them selects identically: each cull is its own [`DrawGen`], and one buffer
3266 /// between them would be several dispatches writing one element with nothing
3267 /// ordering them.
3268 ///
3269 /// **This is what a cull costs that is not a dispatch.** It is
3270 /// [`Capacities::instances`](crate::scene::Capacities::instances) × the
3271 /// resident group count words of device-local
3272 /// memory, held for the renderer's whole life whether anything is drawn
3273 /// through it or not, and it is the reason [`shadow::LIGHT_SLOTS`] is a
3274 /// budget rather than "however many lights the scene has" — and the reason a
3275 /// point light's six faces share one of these rather than owning six.
3276 group_state: BufferHandle,
3277}
3278
3279impl ForwardRenderer {
3280 /// Builds both pipelines and makes [`scene::demo`] resident.
3281 ///
3282 /// [`ForwardRenderer::with_scene`] with the engine's own description, and
3283 /// nothing else — so the frame this draws is the one the golden suite has
3284 /// always compared, and every existing caller is untouched.
3285 ///
3286 /// `target_format` must be the format the tonemap pass will render into —
3287 /// dynamic rendering checks pipeline and attachment formats against each
3288 /// other at pass-begin time, not at creation.
3289 ///
3290 /// # Errors
3291 ///
3292 /// [`HalError`], on [`ForwardRenderer::with_scene`]'s terms.
3293 pub fn new(
3294 device: &dyn Device,
3295 queue: QueueHandle,
3296 target_format: Format,
3297 ) -> Result<Self, HalError> {
3298 Self::with_scene(device, queue, target_format, &scene::demo())
3299 }
3300
3301 /// Builds both pipelines and makes `scene` resident.
3302 ///
3303 /// Everything in the description is created here and never grows: the
3304 /// geometry pools, the cluster pool, the material table, the page, the
3305 /// instance array and the bucket table are all sized and filled once. See
3306 /// [`crate::scene`] for why that split is where the seam is, and for the
3307 /// four places a description's *order* decides what the frame looks like.
3308 ///
3309 /// `target_format` must be the format the tonemap pass will render into —
3310 /// dynamic rendering checks pipeline and attachment formats against each
3311 /// other at pass-begin time, not at creation.
3312 ///
3313 /// # No description is too small
3314 ///
3315 /// One mesh and one material row is a scene, and so is
3316 /// [`scene::demo`]'s four and three. Nothing on this type names a
3317 /// description entry by position any more — the five `set_*` demo wrappers
3318 /// that did are gone, and [`ForwardRenderer::add_instance`] takes the mesh
3319 /// and the row a caller wrote its **own** description in.
3320 ///
3321 /// # Errors
3322 ///
3323 /// [`HalError::InvalidDescriptor`] if the description cannot be made
3324 /// resident as written: a page layer that is not its kind's extent's worth of
3325 /// RGBA8, a page kind holding layers at no extent, a material row naming a
3326 /// layer that kind's page has not got, a DAG carrying a vertex array for anything but each of its
3327 /// levels, a cluster array with a read outside itself in it (see
3328 /// [`MeshClusters::check`]), or more vertices, indices, mesh table entries or
3329 /// material rows than [`SceneDesc::capacities`] reserves — that last naming the pool, the
3330 /// capacity and what the description needs, because the answer to it is to
3331 /// raise the number. Every one of those is settled **before the first device
3332 /// object exists**, so a refusal leaks nothing.
3333 ///
3334 /// [`HalError`] otherwise, from any seam call — including the geometry a
3335 /// pool refuses for itself, such as vertex bytes that are not a whole number
3336 /// of vertices. A backend that cannot build a pipeline says so here rather
3337 /// than drawing nothing later, and a failure part-way through releases
3338 /// everything already created, so a caller that retries or exits leaves
3339 /// nothing behind.
3340 pub fn with_scene(
3341 device: &dyn Device,
3342 queue: QueueHandle,
3343 target_format: Format,
3344 scene: &SceneDesc<'_>,
3345 ) -> Result<Self, HalError> {
3346 Self::with_scene_serviced(device, queue, target_format, scene, &mut || {})
3347 }
3348
3349 /// [`ForwardRenderer::with_scene`], calling `service` between the steps of
3350 /// the build so the thread running it can keep its window alive.
3351 ///
3352 /// # What it is for: a build on the thread that owns the window
3353 ///
3354 /// The build needs the device, so it runs on whichever thread holds it —
3355 /// for a game that is the loop thread, which also owns the window, and a
3356 /// desktop marks a window hung when its thread takes no message for a few
3357 /// seconds (see `crcbl_shell::Shell::keep_alive`). A game passes
3358 /// `&mut || shell.keep_alive()` here and the window keeps answering for the
3359 /// whole build.
3360 ///
3361 /// # Where it is called
3362 ///
3363 /// Where the time is, which was measured rather than guessed. With a cold
3364 /// driver shader cache — a player's first launch, or the first after a
3365 /// driver update — **pipeline creation is most of the build**. Measured in
3366 /// 2026-09 on an RX 7900 XTX, release, building one glTF scene: 2.2 to 2.4 s
3367 /// on Vulkan and 1.9 to 2.2 s on D3D12 cold against 0.25 s warm, while the
3368 /// mesh and page uploads took about 0.1 s either way. So `service` runs
3369 /// after every mesh upload (each level of a DAG), after every page layer's
3370 /// mip chain and each page's upload, after each of the camera's
3371 /// post-processing subsystems, before every mesh-pass and grass pipeline,
3372 /// and between the build's other phases.
3373 ///
3374 /// **The longest gap left is one pipeline**, and a pipeline cannot be
3375 /// split: on that scene, cold, it was the forward pass's colour pipeline
3376 /// at 0.31 s on Vulkan and 0.36 s on D3D12, where the build without calls
3377 /// had been one gap of 2 s. Warm, the longest was about 0.04 s. A machine
3378 /// eight times slower under contention still calls back inside the five
3379 /// seconds Windows allows.
3380 ///
3381 /// `service` sees nothing of the build and cannot touch the renderer or the
3382 /// scene. Whatever reaches the window meanwhile — input, a resize, a close
3383 /// request — is the caller's to keep for later, as
3384 /// `crcbl_shell::Shell::keep_alive` does.
3385 ///
3386 /// # Errors
3387 ///
3388 /// [`ForwardRenderer::with_scene`]'s, on its terms: a failure part-way
3389 /// through releases everything already created.
3390 pub fn with_scene_serviced(
3391 device: &dyn Device,
3392 queue: QueueHandle,
3393 target_format: Format,
3394 scene: &SceneDesc<'_>,
3395 service: &mut dyn FnMut(),
3396 ) -> Result<Self, HalError> {
3397 Self::build_on_path(
3398 device,
3399 queue,
3400 target_format,
3401 scene,
3402 device.preferred_geometry_path(),
3403 service,
3404 )
3405 }
3406
3407 /// Builds exactly the requested geometry tail, independently of the device's
3408 /// performance preference. Capabilities remain available to other callers.
3409 ///
3410 /// # Errors
3411 ///
3412 /// Returns [`HalError::UnsupportedFeatures`] before creating device objects
3413 /// when the requested tail lacks its required feature. Other failures follow
3414 /// [`Self::with_scene`]'s rollback contract.
3415 pub fn with_scene_on_path(
3416 device: &dyn Device,
3417 queue: QueueHandle,
3418 target_format: Format,
3419 scene: &SceneDesc<'_>,
3420 geometry_path: GeometryPath,
3421 ) -> Result<Self, HalError> {
3422 Self::build_on_path(
3423 device,
3424 queue,
3425 target_format,
3426 scene,
3427 geometry_path,
3428 &mut || {},
3429 )
3430 }
3431
3432 /// The body of [`Self::with_scene_on_path`] and
3433 /// [`Self::with_scene_serviced`], calling `service` where the latter
3434 /// documents.
3435 fn build_on_path(
3436 device: &dyn Device,
3437 queue: QueueHandle,
3438 target_format: Format,
3439 scene: &SceneDesc<'_>,
3440 geometry_path: GeometryPath,
3441 service: &mut dyn FnMut(),
3442 ) -> Result<Self, HalError> {
3443 let required = match geometry_path {
3444 GeometryPath::MeshShader => crcbl_hal::Features::MESH_SHADER,
3445 GeometryPath::IndirectCount => crcbl_hal::Features::DRAW_INDIRECT_COUNT,
3446 GeometryPath::IndirectPerBatch => crcbl_hal::Features::empty(),
3447 };
3448 let missing = required.difference(device.caps().features);
3449 if !missing.is_empty() {
3450 return Err(HalError::UnsupportedFeatures { missing });
3451 }
3452 let mut rollback = Rollback::default();
3453 match Self::build(
3454 device,
3455 queue,
3456 target_format,
3457 scene,
3458 geometry_path,
3459 &mut rollback,
3460 service,
3461 ) {
3462 Ok(renderer) => Ok(renderer),
3463 Err(error) => {
3464 rollback.run(device);
3465 Err(error)
3466 }
3467 }
3468 }
3469
3470 /// Everything `build` needs to be true of a description, checked **before
3471 /// the first device object exists**.
3472 ///
3473 /// That placement is the whole design of this function. `build` hands the
3474 /// geometry pool and the material table to the rollback and creates a dozen
3475 /// objects with `?` between them; a check that ran part way down that list
3476 /// would be a new early exit on the wrong side of a handover, and a rejected
3477 /// description would leak two device-local buffers. Run from the top of
3478 /// `build`, a refusal costs nothing to unwind because nothing was made.
3479 ///
3480 /// # Errors
3481 ///
3482 /// [`HalError::InvalidDescriptor`] naming the entry that is wrong and what
3483 /// is wrong with it.
3484 fn check_scene(scene: &SceneDesc<'_>) -> Result<(), HalError> {
3485 let refuse = |what: String| Err(HalError::InvalidDescriptor(what));
3486 // A renderer draws meshes, and every table below is sized from them:
3487 // with none, the mesh table's sizing has no level to take a maximum
3488 // of. A scene that draws only the sky is one with meshes and no
3489 // instances.
3490 if scene.meshes.is_empty() {
3491 return refuse(
3492 "a scene description needs at least one mesh; one with meshes and no \
3493 instances draws only the sky"
3494 .to_owned(),
3495 );
3496 }
3497 // Every layer's length against its own kind's extent, and layers at no
3498 // extent at all. Checked by the type that owns the page rather than
3499 // here, because that is where a page can be built wrong and where the
3500 // check can be made to fail; see `PageDesc::check`.
3501 scene.page.check()?;
3502 // The probe grid's counts against the rows it carries, which is what
3503 // bounds the shader's fetch. Checked by the type that owns the grid, on
3504 // `PageDesc::check`'s terms exactly — see `ProbeGrid::check`.
3505 scene.probes.check()?;
3506 // A row naming a layer the page does not have is an out-of-range sample,
3507 // which nothing below the seam reports.
3508 //
3509 // **A column carrying `NO_PAGE` is exempt**, and it is the only exempt
3510 // value: it is a sentinel rather than an index — `0xFFFF`, one past
3511 // `mesh::MAX_PAGE_LAYER`, so no page can grow to hold it — and the
3512 // fragment stage never reads a page for it. Exempting it here is what
3513 // lets a material name no texture without the page having to carry a
3514 // layer for it to point at — or, since row (d), having to exist at all.
3515 //
3516 // **Per kind**, because the kinds are separate images with separate
3517 // layer lists and separate extents: a row pointed at a base-colour layer
3518 // number would pass a check that only counted one of them and then
3519 // sample past the end of the other image.
3520 for (row, material) in scene.materials.iter().enumerate() {
3521 for kind in PageKind::ALL {
3522 let names = match kind {
3523 PageKind::BaseColor => material.base_color_texture,
3524 PageKind::Normal => material.normal_texture,
3525 PageKind::MetallicRoughnessOcclusion => {
3526 material.metallic_roughness_occlusion_texture
3527 }
3528 PageKind::Emissive => material.emissive_texture,
3529 };
3530 if names == mesh::GpuMaterial::NO_PAGE {
3531 continue;
3532 }
3533 let have = scene.page.layers(kind).len();
3534 if names as usize >= have {
3535 return refuse(format!(
3536 "material row {row} samples {} page layer {names}, and that page \
3537 has {have}",
3538 kind.label()
3539 ));
3540 }
3541 }
3542 }
3543
3544 for (index, desc) in scene.meshes.iter().enumerate() {
3545 let Geometry::Dag { levels, dag, .. } = &desc.geometry else {
3546 continue;
3547 };
3548 // Zipped together at upload and again at
3549 // `ClusterDag::selection_records`, so a short list would silently
3550 // leave a level's clusters reading the level below's vertices.
3551 if levels.len() != dag.levels.len() {
3552 return refuse(format!(
3553 "mesh {index} ({}) carries {} vertex array(s) for a DAG of {} level(s)",
3554 desc.label,
3555 levels.len(),
3556 dag.levels.len()
3557 ));
3558 }
3559 for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
3560 let want = level.positions.len() * mesh::VERTEX_STRIDE;
3561 if bytes.len() != want {
3562 return refuse(format!(
3563 "mesh {index} ({}) level {depth} carries {} vertex byte(s) for {} \
3564 position(s), which is {want}",
3565 desc.label,
3566 bytes.len(),
3567 level.positions.len()
3568 ));
3569 }
3570 }
3571 }
3572
3573 // **Every read the mesh stage makes from a cluster array lands inside
3574 // it.** Checked by the type that owns the arrays, on `PageDesc::check`'s
3575 // terms exactly — see `MeshClusters::check`, which is where the reason
3576 // it cannot be checked below the seam is argued. Both variants carry
3577 // the same type beside a vertex count, so both are checked the same way.
3578 for (index, desc) in scene.meshes.iter().enumerate() {
3579 let levels: Vec<(usize, &MeshClusters)> = match &desc.geometry {
3580 Geometry::Flat {
3581 vertices, clusters, ..
3582 } => vec![(vertices.len() / mesh::VERTEX_STRIDE, clusters)],
3583 Geometry::Dag { dag, .. } => dag
3584 .levels
3585 .iter()
3586 .map(|level| (level.positions.len(), &level.clusters))
3587 .collect(),
3588 };
3589 for (depth, (vertices, clusters)) in levels.into_iter().enumerate() {
3590 if let Err(fault) = clusters.check(vertices) {
3591 return refuse(format!(
3592 "mesh {index} ({}) level {depth} {fault}",
3593 desc.label
3594 ));
3595 }
3596 }
3597 }
3598
3599 // **Capacity, summed over the whole description**, which is the one
3600 // refusal no pool can make for itself. `MeshPool` and `MaterialTable`
3601 // do refuse their own overflow, but they refuse it part way through
3602 // filling something that already exists, and the pair of numbers
3603 // [`MeshPoolError::PoolExhausted`](crate::mesh_pool::MeshPoolError::PoolExhausted)
3604 // carries to tell fragmentation from a full pool says nothing *here*:
3605 // the pool was created empty a few lines below, nothing has been freed
3606 // in it, so its free list is one block and the largest block and the
3607 // total are the same number. At build the answer is always "raise this
3608 // capacity", so it is said by name and before anything is created.
3609 let mut vertices: u64 = 0;
3610 let mut indices: u64 = 0;
3611 for desc in &scene.meshes {
3612 match &desc.geometry {
3613 Geometry::Flat {
3614 vertices: bytes,
3615 indices: list,
3616 ..
3617 } => {
3618 // Bytes that are not a whole number of vertices are the
3619 // pool's to refuse, and it refuses before it allocates.
3620 vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3621 indices += list.len() as u64;
3622 }
3623 Geometry::Dag { levels, dag, .. } => {
3624 for bytes in levels {
3625 vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3626 }
3627 for level in &dag.levels {
3628 // The call the upload itself makes, so the two cannot
3629 // disagree about what a level costs.
3630 indices += level.indices().len() as u64;
3631 }
3632 }
3633 }
3634 }
3635 let entries: u64 = scene
3636 .meshes
3637 .iter()
3638 .map(|desc| desc.geometry.levels() as u64)
3639 .sum();
3640 for (pool, needed, capacity) in [
3641 ("vertex pool", vertices, scene.capacities.vertices),
3642 ("index pool", indices, scene.capacities.indices),
3643 ("mesh table", entries, scene.capacities.meshes),
3644 (
3645 "material table",
3646 scene.materials.len() as u64,
3647 scene.capacities.materials,
3648 ),
3649 (
3650 "probe table",
3651 scene.probes.probes.len() as u64,
3652 scene.capacities.probes,
3653 ),
3654 ] {
3655 if needed > u64::from(capacity) {
3656 return refuse(format!(
3657 "the {pool} holds {capacity} and the description needs {needed}"
3658 ));
3659 }
3660 }
3661 Ok(())
3662 }
3663
3664 /// The body of [`ForwardRenderer::with_scene`], recording what it has
3665 /// created into `rollback` as it goes and calling `service` where
3666 /// [`ForwardRenderer::with_scene_serviced`] documents.
3667 fn build(
3668 device: &dyn Device,
3669 queue: QueueHandle,
3670 target_format: Format,
3671 scene: &SceneDesc<'_>,
3672 geometry_path: GeometryPath,
3673 rollback: &mut Rollback,
3674 service: &mut dyn FnMut(),
3675 ) -> Result<Self, HalError> {
3676 // Before anything exists, so a refused description leaks nothing — see
3677 // `check_scene`, which is where that placement is argued.
3678 Self::check_scene(scene)?;
3679
3680 // Resolved before anything is created, because it decides the *shape*
3681 // of what is created — the bind group layout, which pipeline kind the
3682 // pass builds, and what a bucket's constant block says. A device on the
3683 // mesh path never builds the raster pipeline and a device on either
3684 // indirect tail never builds the mesh one, which is what makes "the
3685 // frame came out of the mesh stage" a fact about the object graph
3686 // rather than a claim about a branch.
3687 let emit = EmitTail::from_path(geometry_path);
3688 // And whether that tail draws a range of buckets per call, which only
3689 // changes what the passes record — the constant blocks carry the words
3690 // both shapes read — so it decides nothing about what is created.
3691 let range_limit = emit.range_limit(&device.caps());
3692 // **A second capability, asked separately.** `Features::TASK_SHADER` is
3693 // not implied by `MESH_SHADER`, so §3.5's per-cluster cull is an
3694 // amplification stage this renderer builds where the device has one and
3695 // leaves out where it does not — and a device without it keeps drawing
3696 // through `mesh_cluster.slang`'s un-amplified `meshMain`, which culls
3697 // nothing and emits every cluster. Same picture, more work.
3698 let culls_clusters = emit.is_mesh()
3699 && device
3700 .caps()
3701 .features
3702 .contains(crcbl_hal::Features::TASK_SHADER);
3703
3704 let (pool, residents) = Self::build_geometry(device, queue, scene, service)?;
3705 // What an `InstanceDesc::mesh` index resolves through: one id per
3706 // description mesh, in description order, and each of them that mesh's
3707 // **level 0** whatever the path — because it is the entry the cull pass
3708 // reads a bounding box out of, and a DAG's coarser levels approximate
3709 // the same surface inside the same box.
3710 let mesh_ids: Vec<u32> = residents.iter().map(ResidentMesh::id).collect();
3711 // The scene's own triangles, kept for the probe-visibility capture and
3712 // for nothing else — and kept at all only when the description reserves
3713 // a probe, so a scene without one pays no memory for this rung. Taken
3714 // here because `scene` is the caller's and is read once.
3715 let probe_occluders = crate::probe_visibility::Occluders::from_scene(scene, &mesh_ids);
3716 // The same list one level down: what a caller reserving a skinned region
3717 // names its mesh with. Read here beside the ids rather than from
3718 // `residents` later, because the descriptions this came from are the
3719 // caller's and are read once.
3720 let skinnable_meshes: Vec<Option<MeshHandle>> =
3721 residents.iter().map(|mesh| mesh.skinnable).collect();
3722 // The handles are `Copy`, so they can be read out before the pool
3723 // becomes the rollback's — which it must be before the first `?` below,
3724 // or a failed pipeline would leak two device-local buffers. The index
3725 // pool is not named here at all: it is bound at draw time rather than
3726 // descriptor-written, so only the vertex pool and the mesh table reach a
3727 // bind group.
3728 let vertices = pool.vertex_buffer();
3729 let mesh_table = pool.table_buffer();
3730 rollback.pool = Some(pool);
3731
3732 // §3.2's texture side, before the table that indexes it: a material row
3733 // is written with a layer number, so the layer has to exist to be named.
3734 //
3735 // **One loop over [`PageKind::ALL`]**, because the kinds differ only in
3736 // three answers the kind itself owns — its format, its mip filter and
3737 // its device label — and everything else about creating a page is the
3738 // same code. Two hand-written copies were what let the normal page be
3739 // created through the colour page's filter for as long as nobody
3740 // compared the two, and rung 3 adds two more kinds to get wrong.
3741 //
3742 // **`Rgba8UnormSrgb` on the base-colour page, `Rgba8Unorm` on the
3743 // normal page, and that is the colour-space decision.** A base-colour
3744 // description's texels are sRGB-encoded, which is what glTF defines a
3745 // base-colour texture to be, so the format is what makes the sampler
3746 // decode them — and `mesh.slang` then multiplies a linear texel by a
3747 // linear `base_color` and lights in linear, exactly as it did before
3748 // there was a texture. A normal texel is a *number* and nothing decodes
3749 // it. See `PageKind::format`, and topic 44's rung 2.
3750 //
3751 // Every layer's length against its kind's extent was settled by
3752 // `check_scene` above, before this device object existed.
3753 //
3754 // **Every layer goes up with its mip chain**, built here on the host by
3755 // [`crate::mip`] — topic 43's filtering rung.
3756 // The chain is what a trilinear sampler needs to stop shimmering on a
3757 // minified surface, and it is built at upload rather than by a compute
3758 // pass because the page's format is what decodes it and a host chain is
3759 // the same bytes on every backend.
3760 //
3761 // **A kind with no layers takes one texel.** `upload_texture_mip_layers`
3762 // refuses a zero-layer image and every bind group has to fill both page
3763 // bindings, so a page nothing names is created 1×1 in its own format
3764 // holding [`PAGE_PLACEHOLDER_TEXEL`] — which the shader never reads,
3765 // and which is magenta so that a frame says so if it ever does.
3766 //
3767 // The upload itself is [`upload_page`], shared with
3768 // [`ForwardRenderer::replace_page`] so a page reloaded under a running
3769 // renderer is built exactly as this one was. A layer's chain is host
3770 // work proportional to its texels, so a page of many large layers is
3771 // serviced one layer at a time.
3772 let mut pages: [Option<UploadedTexture>; PageKind::ALL.len()] = [None; PageKind::ALL.len()];
3773 let mut page_extents = [(1, 1); PageKind::ALL.len()];
3774 let mut page_layers = [0; PageKind::ALL.len()];
3775 for kind in PageKind::ALL {
3776 let layers = scene.page.layers(kind);
3777 let (page, extent) = upload_page(
3778 device,
3779 queue,
3780 kind,
3781 scene.page.extent(kind),
3782 layers,
3783 service,
3784 )?;
3785 rollback.textures.push(page);
3786 page_extents[kind.index()] = (extent, extent);
3787 page_layers[kind.index()] = layers.len();
3788 pages[kind.index()] = Some(page);
3789 service();
3790 }
3791 let [
3792 Some(base_color_page),
3793 Some(normal_page),
3794 Some(mro_page),
3795 Some(emissive_page),
3796 ] = pages
3797 else {
3798 unreachable!("the loop above fills a slot for every PageKind::ALL entry");
3799 };
3800
3801 // The page's sampler at the device's default — see `create_page_sampler`
3802 // for what it filters, and `set_anisotropy` for how a caller moves it.
3803 let anisotropy = Self::anisotropy_for(&device.caps());
3804 let base_color_sampler = Self::create_page_sampler(device, anisotropy)?;
3805 rollback.samplers.push(base_color_sampler);
3806 // What every slot's groups are built naming, and what each moves off
3807 // only at its own frame — see `ForwardRenderer::adopt_pages`.
3808 let page_bindings = PageBindings {
3809 sampler: base_color_sampler,
3810 views: [
3811 base_color_page.view,
3812 normal_page.view,
3813 mro_page.view,
3814 emissive_page.view,
3815 ],
3816 };
3817
3818 // The material table, before the instances: an instance is written with
3819 // the material id it carries, so the row has to exist to be named.
3820 let (materials, material_ids) = Self::build_materials(device, scene)?;
3821 let material_buffer = materials.buffer();
3822 rollback.materials = Some(materials);
3823
3824 // Topic 50's irradiance grid: the table is created here once, and
3825 // `crate::probe_gather`'s compute pass rewrites its rows every frame —
3826 // see [`crate::probe`]. **Created even for a description with no probes**, because
3827 // every group of this layout has to fill [`PROBE_TABLE_BINDING`] and the
3828 // honest filler for "no probes were authored" is the zeroed row the
3829 // shader's clamp lands on.
3830 let probe_table = ProbeTable::new(
3831 device,
3832 queue,
3833 &ProbeTableDesc {
3834 label: Some("forward"),
3835 capacity: scene.capacities.probes,
3836 frames: FRAMES_IN_FLIGHT,
3837 },
3838 )?;
3839 // Into the rollback before it is filled, so a copy that fails releases
3840 // the buffers rather than leaking them.
3841 rollback.probes = Some(probe_table);
3842 let probe_table = rollback.probes.as_ref().expect("just stored");
3843 probe_table.fill(device, queue, &scene.probes.probes)?;
3844 // Read out here, like the instance ring's below and for the same
3845 // reason: the handles are `Copy`, and the loop that builds the bind
3846 // groups mutates the rollback the table now lives in.
3847 let probe_buffers: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
3848 .map(|frame| probe_table.buffer(frame))
3849 .collect();
3850 // The irradiance probes' updater, built **only** for a
3851 // description that asked for it. A volume left at
3852 // [`ProbeUpdate::Authored`] gets no pipeline, no buffers and no pass, so
3853 // the default really is the frame every scene drew before this landed.
3854 let probe_gather = match scene.probes.update {
3855 ProbeUpdate::Authored => None,
3856 ProbeUpdate::EveryFrame => Some(ProbeGather::new(
3857 device,
3858 &ProbeGatherDesc {
3859 label: Some("forward probes"),
3860 volume: scene.probes.volume,
3861 probes: &probe_buffers,
3862 },
3863 )?),
3864 };
3865 rollback.probe_gather = probe_gather;
3866 let probe_gather = rollback.probe_gather.take();
3867 service();
3868
3869 // **Empty.** Every object in the scene arrives through
3870 // [`ForwardRenderer::add_instance`], including the demo scene's cube: a
3871 // renderer that inserted one of its description's meshes here would put
3872 // an object in a caller's frame that the caller never asked for.
3873 let instances = InstancePool::new(
3874 device,
3875 &InstancePoolDesc {
3876 label: Some("forward instances"),
3877 capacity: scene.capacities.instances,
3878 frames_in_flight: FRAMES_IN_FLIGHT,
3879 },
3880 )?;
3881 // Same handle-then-hand-over dance as the geometry pool above: the
3882 // buffers are `Copy` and are read out before the pool becomes the
3883 // rollback's, which it must be before the first `?` below — after which
3884 // nothing needs the pool again until `begin_frame`.
3885 let instance_buffers: Vec<BufferHandle> = instances.buffers().to_vec();
3886 rollback.instances = Some(instances);
3887
3888 // The two compute passes, and the buffers the draws come out of. Built
3889 // here rather than beside the pipelines below because the mesh bind
3890 // group names one of its buffers, so it has to exist first.
3891 //
3892 // The bucket table, and the one place its order is decided.
3893 //
3894 // **Built by walking the description**, which is what makes a duplicate
3895 // structurally impossible rather than refused: every bucket's mesh id is
3896 // the id of the description mesh it came from, and two description
3897 // meshes are two uploads with two table entries however alike their
3898 // geometry is. That matters because `draw_gen.slang`'s scatter takes the
3899 // *first* bucket whose mesh id matches, so a second bucket naming one
3900 // mesh would never draw anything at all.
3901 //
3902 // One bucket per mesh, except for two things. A DAG is one bucket where
3903 // an amplification stage picks its cut per cluster and one per level
3904 // where the cull pass picks a uniform one — see [`buckets_for`]. And the
3905 // whole run is repeated once per **material mode** the scene holds, so
3906 // an instance's mode picks a bucket exactly as its mesh does; see
3907 // [`ForwardRenderer::bucket_modes`].
3908 //
3909 // **Mode-major: every mesh's run for one mode, then the next mode's.**
3910 // A mode picks the pipeline a pass binds, so this makes each pipeline's
3911 // partition — [`ForwardRenderer::depth_partitions`] and
3912 // [`ForwardRenderer::sided_partitions`] — one contiguous run of
3913 // buckets, which a device with a draw index records as one ranged call
3914 // rather than a call per bucket — and which the mesh tail behind a
3915 // task stage must have, because it draws each partition as one flat
3916 // call of its run. `DEPTH_MODES` order makes a sided partition one run
3917 // too: opaque sits beside masked, and double-sided beside both.
3918 //
3919 // **Once per mode the scene holds, not once per mode that exists.** A
3920 // scene whose materials are all opaque gets exactly the table it always
3921 // had — same length, same order, same bytes — so the twin costs nothing
3922 // where nothing is masked, which is every demo and every golden here. A
3923 // bucket is not free: every pass records one indirect call per bucket
3924 // per view, and every generator holds its run start.
3925 let scene_modes: Vec<u32> = {
3926 let held: Vec<u32> = DEPTH_MODES
3927 .into_iter()
3928 .filter(|mode| {
3929 scene
3930 .materials
3931 .iter()
3932 .any(|material| material.mode() == *mode)
3933 })
3934 .collect();
3935 // A description with no materials at all still needs a bucket per
3936 // mesh, or nothing it holds can be drawn.
3937 if held.is_empty() {
3938 vec![DEPTH_MODES[0]]
3939 } else {
3940 held
3941 }
3942 };
3943 // One mode's run: every description mesh's levels, in description
3944 // order. `bucket_bases` is where each mesh starts within it, so the
3945 // tables below can be filled in mesh by mesh rather than by re-deriving
3946 // the arithmetic; mode slot `s` of the mesh is `s` runs further on.
3947 let mut mode_run: Vec<u32> = Vec::new();
3948 let mut bucket_bases: Vec<usize> = Vec::with_capacity(residents.len());
3949 for resident in &residents {
3950 bucket_bases.push(mode_run.len());
3951 mode_run
3952 .extend_from_slice(&resident.levels[..buckets_for(resident.levels.len(), emit)]);
3953 }
3954 let mut bucket_meshes: Vec<u32> = Vec::with_capacity(mode_run.len() * scene_modes.len());
3955 // The mode each of those buckets draws, in step with it.
3956 let mut bucket_modes: Vec<u32> = Vec::with_capacity(bucket_meshes.capacity());
3957 for mode in &scene_modes {
3958 bucket_meshes.extend_from_slice(&mode_run);
3959 bucket_modes.extend(std::iter::repeat_n(*mode, mode_run.len()));
3960 }
3961 let bucket_count = u32::try_from(bucket_meshes.len())
3962 .unwrap_or_else(|_| unreachable!("a table of a few buckets"));
3963
3964 // Topic 25's selection tables, and the one thing that
3965 // decides whether `draw_gen.slang` takes a uniform cut at all.
3966 //
3967 // Every mesh id gets an entry, because the shader indexes this with
3968 // `GpuInstance::mesh` and an instance can name any of them; the default
3969 // is `MeshLevels::FLAT` pointing at a level run that is the mesh itself,
3970 // so a mesh with no hierarchy resolves back to itself with no branch.
3971 // **A DAG keeps that default on the mesh path**, which is how a device
3972 // already descending it per cluster avoids a second, coarser cut on top
3973 // of it — the suppression is data rather than a branch in the shader.
3974 //
3975 // **Sized by the mesh table's capacity, not by the meshes resident in
3976 // it**, because that is the invariant `draw_gen.slang`'s
3977 // `mesh_levels_of` states and indexes on: "every entry an instance can
3978 // name is filled". The read is unbounded and an instance's mesh id is a
3979 // bare table index, so a table sized to the description alone is an
3980 // out-of-range read of whatever the packer laid down next for any id the
3981 // description did not fill. What it finds there decides the frame: zeros
3982 // resolve to mesh 0 and draw another mesh's geometry, and a live
3983 // `group_count` sends `select_level`'s loop over a count no allocation
3984 // backs, which on radv is a hard GPU recovery rather than a wrong
3985 // picture. That is not a hypothetical: it is what a skinned instance
3986 // naming an alias entry did until 2026-08, before it learned to name its
3987 // source mesh instead.
3988 let table_len = usize::try_from(scene.capacities.meshes)
3989 .unwrap_or(usize::MAX)
3990 .max(
3991 usize::try_from(
3992 residents
3993 .iter()
3994 .flat_map(|resident| resident.levels.iter().copied())
3995 .max()
3996 .unwrap_or_else(|| {
3997 unreachable!("check_scene refused an empty description")
3998 })
3999 + 1,
4000 )
4001 .unwrap_or_else(|_| unreachable!("a table of a few meshes")),
4002 );
4003 let mut level_meshes: Vec<u32> = (0..table_len)
4004 .map(|id| u32::try_from(id).unwrap_or_else(|_| unreachable!("bounded by table_len")))
4005 .collect();
4006 let mut mesh_levels: Vec<level_select::MeshLevels> = level_meshes
4007 .iter()
4008 .map(|&id| level_select::MeshLevels {
4009 first_level: id,
4010 ..level_select::MeshLevels::FLAT
4011 })
4012 .collect();
4013 // Every DAG's groups end to end, in description order, and where each
4014 // one's run starts. `ClusterSelect` records name a group by its index in
4015 // *this* array — see `ClusterDag::selection_records`' `first_group` — so
4016 // several DAGs concatenate without `crcbl-shaders` knowing they did.
4017 let mut level_groups: Vec<level_select::LevelGroup> = Vec::new();
4018 let mut first_groups: Vec<u32> = Vec::with_capacity(residents.len());
4019 for (index, desc) in scene.meshes.iter().enumerate() {
4020 first_groups.push(
4021 u32::try_from(level_groups.len())
4022 .unwrap_or_else(|_| unreachable!("a few dozen groups per DAG")),
4023 );
4024 let Geometry::Dag { dag, .. } = &desc.geometry else {
4025 continue;
4026 };
4027 let groups = dag.level_groups();
4028 let id = residents[index].id();
4029 mesh_levels[id as usize] = level_select::MeshLevels {
4030 first_group: first_groups[index],
4031 group_count: u32::try_from(groups.len())
4032 .unwrap_or_else(|_| unreachable!("a DAG of a few dozen groups")),
4033 // **The mesh path suppresses the uniform cut with a top level of
4034 // zero, not with a group count of zero**, and the difference is
4035 // the hysteresis state: `draw_gen.slang` judges every group it is
4036 // given whatever level it answers, and the amplification stage
4037 // reads those answers. A record naming no groups would leave the
4038 // state untouched and every cluster of the patch collapsed. A
4039 // top level of zero makes the level loop's minimum unreachable,
4040 // so the instance routes to the mesh it already names — which is
4041 // level 0.
4042 first_level: if emit.is_mesh() {
4043 id
4044 } else {
4045 u32::try_from(level_meshes.len())
4046 .unwrap_or_else(|_| unreachable!("a table of a few meshes"))
4047 },
4048 top_level: if emit.is_mesh() {
4049 0
4050 } else {
4051 u32::try_from(residents[index].levels.len() - 1)
4052 .unwrap_or_else(|_| unreachable!("a DAG of a few levels"))
4053 },
4054 };
4055 level_groups.extend(groups);
4056 if !emit.is_mesh() {
4057 level_meshes.extend_from_slice(&residents[index].levels);
4058 }
4059 }
4060
4061 // §3.5's clusters, on the path that reads them and on no other. The
4062 // records are `crcbl-shaders`' — cooked, because the builder is
4063 // `crcbl-scene`'s and the renderer must not depend on that crate — and
4064 // they arrive in bucket-mesh order so a bucket's range is its own
4065 // index. See `crate::cluster_pool`.
4066 //
4067 // Before the draw generation below rather than after it, because the
4068 // per-bucket cluster counts are the x extent of each bucket's mesh
4069 // dispatch and that pass writes the argument structure carrying them.
4070 let mut bucket_clusters = vec![0u32; bucket_meshes.len()];
4071 let mut bucket_cluster_bases = vec![0u32; bucket_meshes.len()];
4072 let mut mesh_clusters: Vec<ClusterRange> = Vec::new();
4073 if emit.is_mesh() {
4074 // A flat mesh is one pool entry and its clusters carry
4075 // `ClusterSelect::ALWAYS`, so the descent draws them from every
4076 // camera; a DAG is **one entry per level**, laid end to end.
4077 let mut cooked: Vec<PooledMesh> = Vec::with_capacity(residents.len());
4078 // Where each description mesh's entries start, on `bucket_bases`'
4079 // terms — the two differ exactly where a DAG's levels are one bucket
4080 // and several entries.
4081 let mut entry_bases: Vec<usize> = Vec::with_capacity(residents.len());
4082 for (index, desc) in scene.meshes.iter().enumerate() {
4083 entry_bases.push(cooked.len());
4084 match &desc.geometry {
4085 Geometry::Flat { clusters, .. } => {
4086 cooked.push(PooledMesh::without_lod(clusters.clone()));
4087 }
4088 Geometry::Dag { dag, .. } => {
4089 let selection = dag
4090 .selection_records(&residents[index].vertex_bases, first_groups[index]);
4091 for (level, records) in dag.levels.iter().zip(selection) {
4092 cooked.push(PooledMesh {
4093 clusters: level.clusters.clone(),
4094 selection: records,
4095 });
4096 }
4097 }
4098 }
4099 }
4100
4101 let clusters = ClusterPool::new(device, "forward", &cooked)?;
4102 let range = |entry: usize| {
4103 clusters
4104 .range(entry)
4105 .unwrap_or_else(|| unreachable!("one range per entry, in order"))
4106 };
4107 // **A DAG's levels are one run, not one per bucket.** `concatenate`
4108 // lays the entries down in the order it was given them, so the
4109 // levels are contiguous: the bucket starts where level 0 does and
4110 // reaches to the end of the last level. That is what lets one
4111 // dispatch cover a cut spanning several of them — and it is why a
4112 // flat mesh, whose one entry is the whole sum, needs no second case.
4113 mesh_clusters.reserve(residents.len());
4114 for (index, resident) in residents.iter().enumerate() {
4115 let entry = entry_bases[index];
4116 let base = range(entry).base;
4117 let count: u32 = (entry..entry + resident.levels.len())
4118 .map(|entry| range(entry).count)
4119 .sum();
4120 // **Every one of this mesh's buckets, not only the first.** A
4121 // mode twin draws the same geometry, so it dispatches over the
4122 // same clusters; a twin left at zero launches no workgroup and
4123 // its instances vanish from the frame. One bucket per mode here,
4124 // because the mesh path takes `buckets_for` of one, each a whole
4125 // mode's run past the one before.
4126 for slot in 0..scene_modes.len() {
4127 let bucket = slot * mode_run.len() + bucket_bases[index];
4128 bucket_cluster_bases[bucket] = base;
4129 bucket_clusters[bucket] = count;
4130 }
4131 mesh_clusters.push(ClusterRange { base, count });
4132 }
4133
4134 rollback.clusters = Some(clusters);
4135 service();
4136 }
4137
4138 // One ring per shadow view, indexed `[view][frame]`: topic 25's
4139 // observable, one word per resident cluster holding the cut the descent
4140 // chose — see `ForwardRenderer::shadow_selection` for why a view cannot
4141 // share the camera's, which [`View::build`] allocates beside its cull.
4142 //
4143 // Allocated on the whole mesh path rather than only where there is an
4144 // amplification stage to write them, because the layout declares
4145 // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued.
4146 let mut tile_selection: Vec<Vec<BufferHandle>> = Vec::new();
4147 if emit.is_mesh() {
4148 let count = rollback
4149 .clusters
4150 .as_ref()
4151 .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
4152 .count();
4153 let mut ring = |label: &str| -> Result<Vec<BufferHandle>, HalError> {
4154 let mut buffers = Vec::with_capacity(instance_buffers.len());
4155 for frame in 0..instance_buffers.len() {
4156 let buffer = device.create_buffer(&BufferDesc {
4157 label: Some(&format!("{label} {frame}")),
4158 size: u64::from(count) * 4,
4159 usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
4160 memory: MemoryLocation::DeviceLocal,
4161 })?;
4162 rollback.buffers.push(buffer);
4163 buffers.push(buffer);
4164 }
4165 Ok(buffers)
4166 };
4167 for view in 0..SHADOW_VIEWS {
4168 tile_selection.push(ring(&format!("shadow selection {view}"))?);
4169 }
4170 }
4171
4172 // --- the mesh pass ---
4173 //
4174 // No `BindingFlags` anywhere: this layout is legal on **both** tiers,
4175 // because a lit mesh is not a Tier A feature. The bindless shape — a
4176 // trailing `VARIABLE_COUNT | PARTIALLY_BOUND | UPDATE_AFTER_BIND`
4177 // texture array — is topic 03's, at P3.
4178 // **Which stage pulls the geometry**, and the only thing the two shapes
4179 // of this layout disagree about for bindings 0 to 8. `ShaderStages::MESH`
4180 // is outside `GRAPHICS` and `ALL`, so it is named rather than implied,
4181 // and every backend refuses a layout carrying it on a device without
4182 // `Features::MESH_SHADER` — which is exactly the device that never
4183 // reaches this arm.
4184 //
4185 // **`TASK` joins it when there is an amplification stage**, and the
4186 // union is deliberately over every binding rather than the eight
4187 // `taskMain` actually reads. Slang's Metal backend materialises every
4188 // global in every entry point of a module — the argument bindings 6 to
4189 // 8 already carry — so a layout that named only the task stage's own
4190 // reads would be a layout `msl/mesh_cluster.metal` disagrees with, on a
4191 // runner this team cannot debug on.
4192 let geometry = match (emit.is_mesh(), culls_clusters) {
4193 (true, true) => ShaderStages::MESH.union(ShaderStages::TASK),
4194 (true, false) => ShaderStages::MESH,
4195 (false, _) => ShaderStages::VERTEX,
4196 };
4197 let mut mesh_entries = vec![
4198 BindGroupLayoutEntry {
4199 binding: 0,
4200 visibility: geometry.union(ShaderStages::FRAGMENT),
4201 kind: BindingKind::UniformBuffer { dynamic: false },
4202 count: 1,
4203 flags: BindingFlags::empty(),
4204 },
4205 BindGroupLayoutEntry {
4206 binding: 1,
4207 // **Both stages, and here it is the FRAGMENT half that needs
4208 // saying** — binding 6 and 7 are the mirror image, where the
4209 // fragment stage plainly reads the row and the vertex half is
4210 // the one Slang forces. Slang's Metal backend materialises
4211 // every module global into every entry point, so
4212 // `msl/mesh.metal`'s `fragmentMain` takes this buffer whether
4213 // its body dereferences it or not — and Metal's debug layer
4214 // answers a declared-but-unbound fragment argument with
4215 // `missing Buffer binding at index N`, once per draw. Vulkan,
4216 // D3D12 and WebGPU all accept a visibility wider than the
4217 // shader's reads, so naming FRAGMENT costs them nothing but the
4218 // entry itself.
4219 //
4220 // **It does not cost a redundant bind on Metal either**, and
4221 // that is what makes it safe rather than a trade: `crcbl-mtl`
4222 // consults `MTLPipelineOption::BindingInfo` reflection and
4223 // issues the fragment-stage bind only where `MTLBinding::isUsed`
4224 // says the compiled function kept the argument. This entry is
4225 // the permission; the reflection is the decision.
4226 visibility: geometry.union(ShaderStages::FRAGMENT),
4227 kind: BindingKind::StorageBuffer {
4228 // The shader says `StructuredBuffer`, not
4229 // `RWStructuredBuffer`, so this is the truth rather than a
4230 // hint — and it is what lets the graph merge read-after-read.
4231 read_only: true,
4232 dynamic: false,
4233 stride: size_of::<u32>() as u32,
4234 },
4235 count: 1,
4236 flags: BindingFlags::empty(),
4237 },
4238 BindGroupLayoutEntry {
4239 binding: 2,
4240 // Both stages, for binding 1's reason exactly.
4241 visibility: geometry.union(ShaderStages::FRAGMENT),
4242 kind: BindingKind::StorageBuffer {
4243 // `StructuredBuffer` again: the vertex stage reads its
4244 // instance and writes nothing. The *host* writes this one
4245 // every frame, which is a mapped write rather than a shader
4246 // one and does not make it read-write here.
4247 read_only: true,
4248 dynamic: false,
4249 stride: crcbl_shaders::mesh::INSTANCE_STRIDE as u32,
4250 },
4251 count: 1,
4252 flags: BindingFlags::empty(),
4253 },
4254 BindGroupLayoutEntry {
4255 binding: 3,
4256 // Both stages, for binding 1's reason exactly.
4257 visibility: geometry.union(ShaderStages::FRAGMENT),
4258 // `dynamic: true`, and it is the whole mechanism: it is what
4259 // lets a draw say where its run of instances starts without
4260 // `draw_indexed`'s own base instance, which the module docs and
4261 // `mesh.slang`'s header explain the targets disagree about.
4262 // Same shape, for the same reason, as `crate::sprite_pass`'s.
4263 kind: BindingKind::UniformBuffer { dynamic: true },
4264 count: 1,
4265 flags: BindingFlags::empty(),
4266 },
4267 BindGroupLayoutEntry {
4268 binding: 4,
4269 // Both stages, for binding 1's reason exactly.
4270 visibility: geometry.union(ShaderStages::FRAGMENT),
4271 kind: BindingKind::StorageBuffer {
4272 // The mesh table. `StructuredBuffer` again — the vertex
4273 // stage looks its mesh up and writes nothing — and one
4274 // buffer shared by every frame's group, because unlike the
4275 // instance array nothing rewrites it between frames.
4276 read_only: true,
4277 dynamic: false,
4278 stride: crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32,
4279 },
4280 count: 1,
4281 flags: BindingFlags::empty(),
4282 },
4283 BindGroupLayoutEntry {
4284 binding: 5,
4285 // Both stages, for binding 1's reason exactly.
4286 visibility: geometry.union(ShaderStages::FRAGMENT),
4287 kind: BindingKind::StorageBuffer {
4288 // The per-bucket runs of surviving instances. Read-only
4289 // here and written by the draw-argument pass, which is a
4290 // different bind group and a different pass — the graph is
4291 // what orders the two.
4292 read_only: true,
4293 dynamic: false,
4294 stride: size_of::<u32>() as u32,
4295 },
4296 count: 1,
4297 flags: BindingFlags::empty(),
4298 },
4299 BindGroupLayoutEntry {
4300 binding: 6,
4301 // **Both stages, and the union is not belt-and-braces.** The
4302 // fragment stage is where `mesh.slang` now reads the table, so
4303 // it plainly needs it — a pipeline layout that leaves it out is
4304 // refused outright by wgpu and reported as
4305 // `VUID-VkGraphicsPipelineCreateInfo-layout-07988` by Vulkan.
4306 // The vertex half has to stay because Slang's Metal backend
4307 // materialises every global in every entry point: `vertexMain`
4308 // in `msl/mesh.metal` still takes `materials [[buffer(6)]]`
4309 // whether it reads it or not, so dropping VERTEX would break
4310 // Metal alone, on a runner this team cannot debug on.
4311 visibility: geometry.union(ShaderStages::FRAGMENT),
4312 kind: BindingKind::StorageBuffer {
4313 // The material table. One buffer in every frame's group,
4314 // like the mesh table above and unlike the instance ring:
4315 // a material is written when it is created, not per frame.
4316 read_only: true,
4317 dynamic: false,
4318 stride: crcbl_shaders::mesh::MATERIAL_STRIDE as u32,
4319 },
4320 count: 1,
4321 flags: BindingFlags::empty(),
4322 },
4323 BindGroupLayoutEntry {
4324 binding: BASE_COLOR_PAGE_BINDING,
4325 // Both stages, for binding 6's reason exactly: the fragment
4326 // stage samples it, and Slang's Metal backend materialises
4327 // every global in every entry point — `vertexMain` in
4328 // `msl/mesh.metal` takes the texture whether it reads it or
4329 // not, so a layout without VERTEX would break Metal alone.
4330 visibility: geometry.union(ShaderStages::FRAGMENT),
4331 // **`D2Array`, and the layout is where wgpu wants to hear it.**
4332 // The other three backends read the dimension off the bound
4333 // view and never consult this; WebGPU compares the two at
4334 // pipeline creation and refuses the pair, which is what a
4335 // layout claiming `D2` over an array view got — "expects
4336 // dimension = D2, but given a view with dimension = D2Array".
4337 kind: BindingKind::SampledImage {
4338 view_type: ImageViewType::D2Array,
4339 sample_type: SampleType::Float,
4340 },
4341 // **`count: 1`, and this is the binding-model decision.** One
4342 // `D2Array` image whose *layers* the material rows index is
4343 // `BindingModel::ArrayPages`; an array of `count` descriptors
4344 // indexed per fragment would be `Bindless` and would need
4345 // `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws.
4346 // So this layout is legal on every device, exactly as the six
4347 // buffers above are, and no `BindingFlags` appear anywhere in
4348 // this file yet.
4349 count: 1,
4350 flags: BindingFlags::empty(),
4351 },
4352 BindGroupLayoutEntry {
4353 binding: PAGE_SAMPLER_BINDING,
4354 visibility: geometry.union(ShaderStages::FRAGMENT),
4355 kind: BindingKind::Sampler { comparison: false },
4356 count: 1,
4357 flags: BindingFlags::empty(),
4358 },
4359 ];
4360 if emit.is_mesh() {
4361 // §3.5's four extra reads, and only on the path that has them.
4362 // Adding them unconditionally would make every device declare four
4363 // buffers `mesh.slang` does not name — and WebGPU, which checks a
4364 // bind group against its layout entry for entry, would then need
4365 // four buffers created for a path that never reads them.
4366 //
4367 // `read_only: true` on all four, which is the truth rather than a
4368 // hint: the mesh stage indexes them and writes nothing, and it is
4369 // what lets the graph merge read-after-read.
4370 //
4371 // Four different element types, so four strides, in binding order:
4372 // the clusters (`Meshlet`), the cluster vertex and corner pools
4373 // (`uint` each), and the per-cluster draw arguments
4374 // (`DrawIndexedArgs`, the indirect layout every API agrees on).
4375 let cluster_strides = [
4376 crcbl_shaders::meshlet::MESHLET_STRIDE as u32,
4377 size_of::<u32>() as u32,
4378 size_of::<u32>() as u32,
4379 crcbl_hal::indirect::DRAW_INDEXED_ARGS_BYTES as u32,
4380 ];
4381 mesh_entries.extend(
4382 (CLUSTERS_BINDING..=CLUSTER_DRAW_ARGS_BINDING)
4383 .zip(cluster_strides)
4384 .map(|(binding, stride)| {
4385 BindGroupLayoutEntry {
4386 binding,
4387 // **Not the fragment stage.** These four are the geometry
4388 // stage's alone, and `mesh_cluster.slang` has no fragment entry
4389 // point of its own to materialise them into — its fragment
4390 // stage is `mesh.slang`'s, which does not declare mesh-only
4391 // buffers.
4392 visibility: geometry,
4393 kind: BindingKind::StorageBuffer {
4394 read_only: true,
4395 dynamic: false,
4396 stride,
4397 },
4398 count: 1,
4399 flags: BindingFlags::empty(),
4400 }
4401 }),
4402 );
4403 }
4404 // Both mesh entry points retain these declarations. Omitting unused
4405 // task buffers would shift later native buffer indices on the plain
4406 // mesh path, so the layout includes them on both paths.
4407 if emit.is_mesh() {
4408 mesh_entries.push(BindGroupLayoutEntry {
4409 binding: CLUSTER_CULL_BINDING,
4410 visibility: geometry,
4411 // **The same block the instance cull reads**, not a copy: one
4412 // camera, one frustum, and no way for the two rejections to
4413 // disagree about which. `dynamic: false` because there is one
4414 // block per frame rather than one per bucket.
4415 kind: BindingKind::UniformBuffer { dynamic: false },
4416 count: 1,
4417 flags: BindingFlags::empty(),
4418 });
4419 mesh_entries.push(BindGroupLayoutEntry {
4420 binding: CLUSTER_CULL_STATS_BINDING,
4421 visibility: geometry,
4422 kind: BindingKind::StorageBuffer {
4423 // **The one writable binding this pass has.** The stage adds
4424 // to a counter, so `read_only: false` is the truth rather
4425 // than a hint, and it is what makes the graph order this
4426 // write after the draw-argument pass's read of the same
4427 // buffer.
4428 read_only: false,
4429 dynamic: false,
4430 stride: size_of::<u32>() as u32,
4431 },
4432 count: 1,
4433 flags: BindingFlags::empty(),
4434 });
4435 }
4436 // Topic 18's cascades, read by the fragment stage and declared last —
4437 // above `mesh_cluster.slang`'s range rather than inside it, for the
4438 // reason `SHADOW_ATLAS_BINDING` gives.
4439 //
4440 // Both carry `geometry` in their visibility beside `FRAGMENT`, for
4441 // binding 7's reason exactly: Slang's Metal backend materialises every
4442 // global into every entry point, and `msl/mesh.metal`'s `vertexMain`
4443 // takes `shadow_atlas [[texture(1)]]` and `shadow_sampler
4444 // [[sampler(1)]]` whether it reads them or not.
4445 mesh_entries.push(BindGroupLayoutEntry {
4446 binding: SHADOW_ATLAS_BINDING,
4447 visibility: geometry.union(ShaderStages::FRAGMENT),
4448 kind: BindingKind::SampledImage {
4449 view_type: ImageViewType::D2,
4450 // **`Depth`, and this is the field the seam grew for this
4451 // pass.** WebGPU will only bind a `D32Float` view through a
4452 // depth sample type, and its shader side agrees — the WGSL
4453 // artifact declares `texture_depth_2d`. The other three
4454 // backends take the interpretation off the view's format and
4455 // never read this.
4456 sample_type: SampleType::Depth,
4457 },
4458 count: 1,
4459 flags: BindingFlags::empty(),
4460 });
4461 mesh_entries.push(BindGroupLayoutEntry {
4462 binding: SHADOW_SAMPLER_BINDING,
4463 visibility: geometry.union(ShaderStages::FRAGMENT),
4464 // The sampler-side twin of the line above: `sampler_comparison` in
4465 // the WGSL, `SamplerComparisonState` in the HLSL, and a
4466 // `compareEnable` on the Vulkan sampler object. The layout has to
4467 // say so on WebGPU and cannot on the other three.
4468 kind: BindingKind::Sampler { comparison: true },
4469 count: 1,
4470 flags: BindingFlags::empty(),
4471 });
4472 // DAG geometry and selection state, in the mesh-only binding range.
4473 if emit.is_mesh() {
4474 mesh_entries.push(BindGroupLayoutEntry {
4475 binding: CLUSTER_SELECT_BINDING,
4476 visibility: geometry,
4477 // Read-only and read by **both** mesh entry points, unlike the
4478 // pair below: a cluster's `vertex_base` is which level of a DAG
4479 // its geometry lives in, which an un-amplified stage needs just
4480 // as much as an amplified one.
4481 kind: BindingKind::StorageBuffer {
4482 read_only: true,
4483 dynamic: false,
4484 stride: crcbl_shaders::cluster_select::CLUSTER_SELECT_STRIDE as u32,
4485 },
4486 count: 1,
4487 flags: BindingFlags::empty(),
4488 });
4489 }
4490 // Both on the whole mesh path, for the two above's reason exactly: the
4491 // amplification stage is the only writer and the only reader, and the
4492 // Metal argument table counts entries rather than reading binding
4493 // numbers.
4494 if emit.is_mesh() {
4495 mesh_entries.push(BindGroupLayoutEntry {
4496 binding: CLUSTER_SELECTION_BINDING,
4497 visibility: geometry,
4498 kind: BindingKind::StorageBuffer {
4499 // The second writable binding: the amplification stage
4500 // records the cut it chose, one word per resident cluster.
4501 read_only: false,
4502 dynamic: false,
4503 stride: size_of::<u32>() as u32,
4504 },
4505 count: 1,
4506 flags: BindingFlags::empty(),
4507 });
4508 mesh_entries.push(BindGroupLayoutEntry {
4509 binding: CLUSTER_GROUP_STATE_BINDING,
4510 visibility: geometry,
4511 kind: BindingKind::StorageBuffer {
4512 // Topic 25's hysteresis state, and read-only
4513 // here: the draw-argument pass is its only writer, which is
4514 // what lets a stage with one workgroup per cluster use a
4515 // decision that has to survive a frame.
4516 read_only: true,
4517 dynamic: false,
4518 stride: size_of::<u32>() as u32,
4519 },
4520 count: 1,
4521 flags: BindingFlags::empty(),
4522 });
4523 }
4524
4525 // The shared fragment light list and froxel grid are bound on every
4526 // path and in every group, unlike the four
4527 // conditional ranges above: `mesh.slang`'s fragment stage reads them
4528 // whatever geometry produced the primitive, so there is no configuration
4529 // in which the layout can omit them.
4530 //
4531 // `geometry` joins `FRAGMENT` in the visibility for binding 7's reason
4532 // exactly: Slang's Metal backend materialises every global into every
4533 // entry point, so the vertex and mesh stages take these buffers whether
4534 // they read them or not.
4535 mesh_entries.push(BindGroupLayoutEntry {
4536 binding: LIGHT_LIST_BINDING,
4537 visibility: geometry.union(ShaderStages::FRAGMENT),
4538 kind: BindingKind::StorageBuffer {
4539 read_only: true,
4540 dynamic: false,
4541 stride: crcbl_shaders::light::LIGHT_STRIDE as u32,
4542 },
4543 count: 1,
4544 flags: BindingFlags::empty(),
4545 });
4546 mesh_entries.push(BindGroupLayoutEntry {
4547 binding: LIGHT_GRID_BINDING,
4548 visibility: geometry.union(ShaderStages::FRAGMENT),
4549 kind: BindingKind::StorageBuffer {
4550 // **Read-only here**, and written by the clustering pass through
4551 // a layout of its own. The graph is what orders the two.
4552 read_only: true,
4553 dynamic: false,
4554 stride: size_of::<u32>() as u32,
4555 },
4556 count: 1,
4557 flags: BindingFlags::empty(),
4558 });
4559 // Topic 46's occlusion channel, last of the set
4560 // — see [`AMBIENT_OCCLUSION_BINDING`] on why last is structural rather
4561 // than tidy.
4562 //
4563 // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4564 // `msl/mesh.metal` is the proof rather than the theory: its `vertexMain`
4565 // takes `ambient_occlusion [[texture(2)]]` whether it reads it or not.
4566 mesh_entries.push(BindGroupLayoutEntry {
4567 binding: AMBIENT_OCCLUSION_BINDING,
4568 visibility: geometry.union(ShaderStages::FRAGMENT),
4569 kind: BindingKind::SampledImage {
4570 view_type: ImageViewType::D2,
4571 // **`Float`, unlike the shadow atlas above.** This one is an
4572 // ordinary `R8Unorm` colour image and the WGSL artifact declares
4573 // `texture_2d<f32>` for it; `Depth` here would be a layout
4574 // claiming a depth format the view does not have.
4575 sample_type: SampleType::Float,
4576 },
4577 count: 1,
4578 flags: BindingFlags::empty(),
4579 });
4580 // The irradiance grid, past the occlusion channel — see
4581 // [`PROBE_TABLE_BINDING`] on why the list only ever grows at its top.
4582 //
4583 // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4584 // `msl/mesh.metal` is again the proof rather than the theory: its
4585 // `vertexMain` takes `probes [[buffer(9)]]` whether it reads it or not.
4586 mesh_entries.push(BindGroupLayoutEntry {
4587 binding: PROBE_TABLE_BINDING,
4588 visibility: geometry.union(ShaderStages::FRAGMENT),
4589 kind: BindingKind::StorageBuffer {
4590 // **Read-only, and it stays read-only when the updater lands.**
4591 // The rows are device-local now — see [`crate::probe`], which is
4592 // where that is argued — so the seam no longer forces this;
4593 // what forces it is that the shading path does not write a
4594 // probe and this layout has no headroom to pretend otherwise.
4595 // The raster path is at the WebGPU per-stage storage-buffer
4596 // ceiling already, which the check at the end of the layout
4597 // holds it to, so `read_only: false` here would buy a write
4598 // nothing performs at the price of a binding budget there is
4599 // none of. The irradiance probes' gather is a
4600 // compute pass with a layout of its own, and that is where the
4601 // writable binding of these rows belongs.
4602 read_only: true,
4603 dynamic: false,
4604 stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
4605 },
4606 count: 1,
4607 flags: BindingFlags::empty(),
4608 });
4609 if emit.is_mesh() {
4610 // DAG group records follow the common buffer prefix; the
4611 // remaining mesh-only buffers are sorted after them below.
4612 //
4613 // **Conditional like the mesh-only bindings**, and not for tidiness:
4614 // the raster path's layout is at the WebGPU storage-buffer ceiling
4615 // already, so a row bound unconditionally would be a renderer that
4616 // cannot be built in a browser. The mesh path's own reads sit outside
4617 // that count because `ShaderStages::MESH` is not one of the three
4618 // stages it sums.
4619 mesh_entries.push(BindGroupLayoutEntry {
4620 binding: LEVEL_GROUP_TABLE_BINDING,
4621 // Only the geometry stage reads this table: the
4622 // heatmap's colour is chosen where the cluster is known, and
4623 // `mesh.slang`'s fragment stage — which is this pipeline's —
4624 // does not declare this buffer.
4625 visibility: geometry,
4626 kind: BindingKind::StorageBuffer {
4627 // Read-only and read by **both** mesh entry points, like
4628 // CLUSTER_SELECT_BINDING: an un-amplified stage draws through the same
4629 // `emit_cluster`, so a row present for one and absent for the
4630 // other is a descriptor read out of an empty slot.
4631 read_only: true,
4632 dynamic: false,
4633 stride: size_of::<u32>() as u32,
4634 },
4635 count: 1,
4636 flags: BindingFlags::empty(),
4637 });
4638 }
4639
4640 // The `DFG` table, above everything — see [`SPECULAR_DFG_BINDING`].
4641 //
4642 // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4643 // Metal backend materialises every global into every entry point, so
4644 // `msl/mesh.metal`'s `vertexMain` takes `specular_dfg [[texture(3)]]`
4645 // whether it reads it or not.
4646 mesh_entries.push(BindGroupLayoutEntry {
4647 binding: SPECULAR_DFG_BINDING,
4648 visibility: geometry.union(ShaderStages::FRAGMENT),
4649 kind: BindingKind::SampledImage {
4650 view_type: ImageViewType::D2,
4651 // `Float`, as the occlusion channel above: an `Rgba8Unorm`
4652 // colour image, declared `texture_2d<f32>` by the WGSL artifact.
4653 sample_type: SampleType::Float,
4654 },
4655 count: 1,
4656 flags: BindingFlags::empty(),
4657 });
4658
4659 // §2's normal page, above everything — see [`NORMAL_PAGE_BINDING`].
4660 //
4661 // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4662 // Metal backend materialises every global into every entry point, so
4663 // `msl/mesh.metal`'s `vertexMain` takes the page whether it samples it
4664 // or not. **A sampled image and not a storage buffer**, which costs this
4665 // layout nothing at the WebGPU ceiling checked below — that limit counts
4666 // storage buffers, and this row is a texture.
4667 mesh_entries.push(BindGroupLayoutEntry {
4668 binding: NORMAL_PAGE_BINDING,
4669 visibility: geometry.union(ShaderStages::FRAGMENT),
4670 kind: BindingKind::SampledImage {
4671 view_type: ImageViewType::D2Array,
4672 // `Float`: an `Rgba8Unorm` image, declared
4673 // `texture_2d_array<f32>` by the WGSL artifact — the same
4674 // sample type the sRGB base-colour page reports, since both
4675 // decode to floats.
4676 sample_type: SampleType::Float,
4677 },
4678 count: 1,
4679 flags: BindingFlags::empty(),
4680 });
4681 // The area lights' table, above the page — see [`LTC_TABLE_BINDING`].
4682 //
4683 // `geometry` beside `FRAGMENT` for the two rows above it's reason.
4684 // `Float` because `Rgba16Float` is a filterable sampled format on every
4685 // target this engine opens, and the WGSL artifact declares it
4686 // `texture_2d<f32>` — the shader only ever `Load`s it, but the layout
4687 // has to say what the module declared.
4688 mesh_entries.push(BindGroupLayoutEntry {
4689 binding: LTC_TABLE_BINDING,
4690 visibility: geometry.union(ShaderStages::FRAGMENT),
4691 kind: BindingKind::SampledImage {
4692 view_type: ImageViewType::D2,
4693 sample_type: SampleType::Float,
4694 },
4695 count: 1,
4696 flags: BindingFlags::empty(),
4697 });
4698 // Topic 45's contact-shadow channel, last of the set —
4699 // see [`CONTACT_SHADOW_BINDING`] on why last is structural rather than
4700 // tidy.
4701 //
4702 // `geometry` beside `FRAGMENT` and `Float` for the occlusion channel's
4703 // reasons exactly: it is the same `R8Unorm` shape, and Slang's Metal
4704 // backend materialises every global into every entry point whether that
4705 // stage reads it or not.
4706 mesh_entries.push(BindGroupLayoutEntry {
4707 binding: CONTACT_SHADOW_BINDING,
4708 visibility: geometry.union(ShaderStages::FRAGMENT),
4709 kind: BindingKind::SampledImage {
4710 view_type: ImageViewType::D2,
4711 sample_type: SampleType::Float,
4712 },
4713 count: 1,
4714 flags: BindingFlags::empty(),
4715 });
4716 // The irradiance probes' per-probe visibility maps, last
4717 // of the set — see [`PROBE_VISIBILITY_BINDING`] on why last is
4718 // structural.
4719 //
4720 // `D2Array` has to be *declared*, not merely bound: WebGPU compares the
4721 // dimension a layout entry claims against the view handed to it at
4722 // pipeline creation, which is the normal page's own note.
4723 // `UnfilterableFloat` for the same reason and measured the same way: the
4724 // image is `Rg32Float`, which is unfilterable without WebGPU's
4725 // `float32-filterable`, and this slot declared `Float` made Chromium
4726 // refuse the whole mesh bind group — "None of the supported sample types
4727 // (UnfilterableFloat) ... match the expected sample types (Float)" —
4728 // which took every 3D demo's frame to black. Reading it only with `Load`
4729 // does not lift that: the check is on the layout against the view's
4730 // format, not on how the shader gets at it.
4731 mesh_entries.push(BindGroupLayoutEntry {
4732 binding: PROBE_VISIBILITY_BINDING,
4733 visibility: geometry.union(ShaderStages::FRAGMENT),
4734 kind: BindingKind::SampledImage {
4735 view_type: ImageViewType::D2Array,
4736 sample_type: SampleType::UnfilterableFloat,
4737 },
4738 count: 1,
4739 flags: BindingFlags::empty(),
4740 });
4741 // §2's other two pages, last of the set — see [`MRO_PAGE_BINDING`] and
4742 // [`EMISSIVE_PAGE_BINDING`] on why last is structural rather than tidy.
4743 //
4744 // `geometry` beside `FRAGMENT`, `D2Array` and `Float` are the normal
4745 // page's three answers exactly, and for its reasons: Slang's Metal
4746 // backend materialises every global into every entry point, WebGPU
4747 // compares the declared dimension against the bound view, and both
4748 // images are `Rgba8Unorm`-family formats that decode to filterable
4749 // floats.
4750 for binding in [MRO_PAGE_BINDING, EMISSIVE_PAGE_BINDING] {
4751 mesh_entries.push(BindGroupLayoutEntry {
4752 binding,
4753 visibility: geometry.union(ShaderStages::FRAGMENT),
4754 kind: BindingKind::SampledImage {
4755 view_type: ImageViewType::D2Array,
4756 sample_type: SampleType::Float,
4757 },
4758 count: 1,
4759 flags: BindingFlags::empty(),
4760 });
4761 }
4762 mesh_entries.sort_by_key(|entry| entry.binding);
4763 let mesh_desc = BindGroupLayoutDesc {
4764 label: Some(MESH_LAYOUT_LABEL),
4765 entries: &mesh_entries,
4766 };
4767 // **This layout is at the guaranteed limit with no headroom on the
4768 // raster path, in both raster stages**: the vertex stage takes every
4769 // storage buffer a WebGPU device promises, and since bindings 1 to 5
4770 // gained FRAGMENT visibility for Metal's debug layer the fragment stage
4771 // takes the same number. A ninth in either is a renderer that cannot be
4772 // built in a browser or on SwiftShader, so it fails here rather than at
4773 // somebody else's `createPipelineLayout` — see
4774 // [`crcbl_hal::check_portable_storage_buffers`], which also says why the
4775 // mesh path's extra reads are outside the count.
4776 // `Some("mesh")`, which is the *pipeline* layout's label, not
4777 // `mesh_desc.label` — the error text reads "pipeline layout {label}
4778 // binds …", so naming the bind group layout there sends the reader to
4779 // the wrong object.
4780 check_portable_storage_buffers(Some("mesh"), &[&mesh_desc])?;
4781 let mesh_layout = device.create_bind_group_layout(&mesh_desc)?;
4782 rollback.bind_group_layouts.push(mesh_layout);
4783
4784 // A dynamic offset must be a multiple of the device's alignment, and one
4785 // block has to fit inside one stride. Read from the device rather than
4786 // assumed, exactly as `crate::sprite_pass` does: 256 on WebGPU, 64 on a
4787 // typical desktop Vulkan driver.
4788 //
4789 // One stride for both blocks, sized for the larger — see
4790 // [`DRAW_CONSTANTS_BLOCK`]. Which of the two a bucket's block holds is
4791 // decided below.
4792 let alignment = device.caps().limits.min_uniform_buffer_offset_alignment;
4793 let draw_stride =
4794 u32::try_from(DRAW_CONSTANTS_BLOCK.next_multiple_of(alignment)).map_err(|_| {
4795 HalError::InvalidDescriptor(format!(
4796 "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic \
4797 offset can express"
4798 ))
4799 })?;
4800 let draw_constants = device.create_buffer(&BufferDesc {
4801 label: Some("mesh draw constants"),
4802 // A block per bucket per draw region: a region's draws name their
4803 // own run starts, and the mesh path's block names the region's
4804 // argument structure. See `crcbl_shaders::draw_gen::DRAW_REGIONS`.
4805 size: u64::from(draw_stride)
4806 * u64::from(bucket_count)
4807 * u64::from(crcbl_shaders::draw_gen::DRAW_REGIONS),
4808 usage: BufferUsage::UNIFORM,
4809 memory: MemoryLocation::HostUpload,
4810 })?;
4811 rollback.buffers.push(draw_constants);
4812 // --- the shadow map's own resources ---
4813 //
4814 // Before the bind groups, because every one of them names the atlas or
4815 // the placeholder standing in for it.
4816 let (atlas_width, atlas_height) = shadow::atlas_extent();
4817 let shadow_atlas = device.create_image(&ImageDesc {
4818 label: Some("shadow atlas"),
4819 image_type: ImageType::D2,
4820 format: Format::D32Float,
4821 extent: crcbl_hal::Extent3d::d2(atlas_width, atlas_height),
4822 mip_levels: 1,
4823 samples: 1,
4824 // `TRANSFER_SRC` so a test can copy the cascades back and check
4825 // that something was written into them. A shadow map that stayed at
4826 // its clear value produces a frame that looks entirely plausible —
4827 // everything is lit — so the readback is the only thing that can
4828 // tell a working pass from one that drew nothing.
4829 usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
4830 .union(ImageUsage::SAMPLED)
4831 .union(ImageUsage::TRANSFER_SRC),
4832 })?;
4833 rollback.images.push(shadow_atlas);
4834 let shadow_atlas_view = device.create_image_view(&ImageViewDesc {
4835 label: Some("shadow atlas"),
4836 image: shadow_atlas,
4837 view_type: ImageViewType::D2,
4838 format: Format::D32Float,
4839 range: ImageSubresourceRange::all(Format::D32Float),
4840 })?;
4841 rollback.image_views.push(shadow_atlas_view);
4842
4843 let shadow_placeholder = device.create_image(&ImageDesc {
4844 label: Some("shadow placeholder"),
4845 image_type: ImageType::D2,
4846 format: Format::D32Float,
4847 extent: crcbl_hal::Extent3d::d2(1, 1),
4848 mip_levels: 1,
4849 samples: 1,
4850 usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT.union(ImageUsage::SAMPLED),
4851 })?;
4852 rollback.images.push(shadow_placeholder);
4853 let shadow_placeholder_view = device.create_image_view(&ImageViewDesc {
4854 label: Some("shadow placeholder"),
4855 image: shadow_placeholder,
4856 view_type: ImageViewType::D2,
4857 format: Format::D32Float,
4858 range: ImageSubresourceRange::all(Format::D32Float),
4859 })?;
4860 rollback.image_views.push(shadow_placeholder_view);
4861
4862 // The occlusion placeholder, beside the shadow one and for the same
4863 // reason: every group of this layout has to fill
4864 // [`AMBIENT_OCCLUSION_BINDING`], and most of them are built before the
4865 // graph has an occlusion image to name.
4866 //
4867 // **Uploaded rather than cleared**, unlike the depth placeholder above,
4868 // and the four bytes are the whole point — see
4869 // [`AMBIENT_OCCLUSION_NONE`], which is where each of them is argued.
4870 // Left undefined this would be a random ambient scale *and* a random
4871 // direction to steer it along, on any frame that fell back to it.
4872 let ambient_occlusion_placeholder = upload_texture(
4873 device,
4874 queue,
4875 "ssao placeholder",
4876 Format::Rgba8Unorm,
4877 1,
4878 1,
4879 &AMBIENT_OCCLUSION_NONE,
4880 )?;
4881 rollback.textures.push(ambient_occlusion_placeholder);
4882
4883 // The contact-shadow placeholder, beside the occlusion one and on its
4884 // terms exactly: every group of this layout has to fill
4885 // [`CONTACT_SHADOW_BINDING`], and most of them are built before the graph
4886 // has a contact-shadow image to name. `0xFF` is `1.0` through `R8Unorm`,
4887 // so a fragment that reads this one is a fragment the sun reaches
4888 // unobstructed.
4889 let contact_shadow_placeholder = upload_texture(
4890 device,
4891 queue,
4892 "contact shadow placeholder",
4893 Format::R8Unorm,
4894 1,
4895 1,
4896 &[CONTACT_SHADOW_NONE],
4897 )?;
4898 rollback.textures.push(contact_shadow_placeholder);
4899
4900 // The probe-visibility placeholder, on the two above it's terms: every
4901 // group of this layout has to fill [`PROBE_VISIBILITY_BINDING`], and
4902 // nothing has been captured when they are built. One texel of
4903 // [`probe_visibility_none`], which no surface is further away than, so a
4904 // probe read through it keeps all of its weight.
4905 let probe_visibility_placeholder = upload_texture_layers(
4906 device,
4907 queue,
4908 "probe visibility placeholder",
4909 Format::Rg32Float,
4910 1,
4911 1,
4912 &[&probe_visibility_none()],
4913 )?;
4914 rollback.textures.push(probe_visibility_placeholder);
4915
4916 // The split-sum `DFG` table, uploaded once and read by every frame this
4917 // renderer will draw — `crcbl_shaders::dfg` is where it is integrated,
4918 // committed and encoded, and `SPECULAR_ALBEDO_BINDING` is where it lands.
4919 //
4920 // **Cooked bytes rather than a computed image**: the integrator
4921 // importance-samples a lobe, which is `sin`, `cos` and a `powf`, and this
4922 // engine's goldens are compared across four backends with no tolerance.
4923 // Baking here would be four slightly different tables.
4924 let specular_dfg = upload_texture(
4925 device,
4926 queue,
4927 "dfg table",
4928 // Two bytes of fixed point per channel, high byte first — see
4929 // `crcbl_shaders::dfg::PAIR_TEXEL_BYTES`, which argues why this is
4930 // not the `Rg16Float` the format's own doc anticipated.
4931 Format::Rgba8Unorm,
4932 DFG_SIZE_U32,
4933 DFG_SIZE_U32,
4934 &dfg::pair_texels(),
4935 )?;
4936 rollback.textures.push(specular_dfg);
4937
4938 // The area lights' fit, beside it and on its terms — cooked bytes for
4939 // the same reason, and `Rgba16Float` rather than fixed point because
4940 // these are matrix entries rather than shares of arriving light.
4941 // `crcbl_shaders::ltc::LTC_TEXEL_BYTES` argues the format.
4942 let ltc_table = upload_texture(
4943 device,
4944 queue,
4945 "ltc table",
4946 Format::Rgba16Float,
4947 LTC_SIZE_U32,
4948 LTC_SIZE_U32,
4949 <c::texels(),
4950 )?;
4951 rollback.textures.push(ltc_table);
4952 service();
4953
4954 // **A comparison sampler, and that is the PCF.** Each
4955 // `SampleCmpLevelZero` returns the filtered fraction of four texels that
4956 // passed the test, so the shader's 3×3 kernel is nine hardware-bilinear
4957 // comparisons rather than nine raw fetches it averages itself.
4958 //
4959 // `Greater` for the engine's reversed-Z, exactly as the depth *test*
4960 // is: the receiver survives when it is nearer the light than whatever
4961 // the map stored. `SamplerDesc::compare` carries the same warning.
4962 //
4963 // Clamped on every axis so a receiver just outside a cascade's box
4964 // reads the edge rather than wrapping into the opposite corner — the
4965 // shader's own bounds check is what actually handles that case, and this
4966 // is the second line of defence one texel wide.
4967 let shadow_sampler = device.create_sampler(&SamplerDesc {
4968 label: Some("shadow comparison"),
4969 mag_filter: FilterMode::Linear,
4970 min_filter: FilterMode::Linear,
4971 mip_filter: FilterMode::Nearest,
4972 address_mode: [SamplerAddressMode::ClampToEdge; 3],
4973 compare: Some(crcbl_hal::CompareOp::Greater),
4974 ..SamplerDesc::default()
4975 })?;
4976 rollback.samplers.push(shadow_sampler);
4977
4978 // --- the camera ---
4979 //
4980 // Everything the camera's picture needs of its own, built against the
4981 // scene resources above — see [`view`], which is where the line between
4982 // the two is drawn. Into the rollback whole as soon as it exists, so a
4983 // failure further down releases it with everything else.
4984 let slot_pages = vec![page_bindings; instance_buffers.len()];
4985 rollback.primary = Some(View::build(
4986 device,
4987 queue,
4988 &ViewInputs {
4989 id: ViewId::PRIMARY,
4990 effects: RenderEffects::all(),
4991 background: ViewBackground::Scene,
4992 lighting: ViewLighting::Scene,
4993 target_format,
4994 emit,
4995 instances: &instance_buffers,
4996 mesh_table,
4997 bucket_meshes: &bucket_meshes,
4998 bucket_modes: &bucket_modes,
4999 bucket_clusters: &bucket_clusters,
5000 bucket_cluster_bases: &bucket_cluster_bases,
5001 mesh_levels: &mesh_levels,
5002 level_groups: &level_groups,
5003 level_meshes: &level_meshes,
5004 instance_capacity: scene.capacities.instances,
5005 light_capacity: scene.capacities.lights,
5006 clusters: rollback.clusters.as_ref(),
5007 task_lanes: view::task_lanes(culls_clusters),
5008 mesh_layout,
5009 vertices,
5010 draw_constants,
5011 materials: material_buffer,
5012 pages: &slot_pages,
5013 probes: &probe_buffers,
5014 specular_dfg: specular_dfg.view,
5015 ltc_table: ltc_table.view,
5016 shadow_map: shadow_atlas_view,
5017 shadow_sampler,
5018 ambient_occlusion: ambient_occlusion_placeholder.view,
5019 contact_shadow: contact_shadow_placeholder.view,
5020 probe_visibility: probe_visibility_placeholder.view,
5021 },
5022 service,
5023 )?);
5024 let primary = rollback.primary.as_ref().expect("just stored");
5025
5026 // Written here and never again: **which word holds** a bucket's run
5027 // start is fixed by the bucket table and the capacity, and both are
5028 // fixed at build. What varies per frame is where the run starts and how
5029 // much of it is filled, and the GPU writes both — the start into that
5030 // word, the count into the bucket's indirect arguments. See
5031 // `mesh.slang`'s header for why the block names a word rather than
5032 // carrying the start.
5033 //
5034 // Taken from the camera's generator and bound for every generator's
5035 // draws: the shadow culls and every secondary view are built from the
5036 // same table and the same capacity, so `bucket_start_word` answers the
5037 // same for all of them.
5038 let draws = &primary.draws;
5039 let mut bucket_constants = vec![0u32; bucket_meshes.len()];
5040 // **Every draw region's copy**, region 0's at the offsets
5041 // `bucket_constants` records and each further region a bucket count of
5042 // strides behind the one before: a region's draw reads its own run
5043 // start and — on the mesh path — its own argument structure, and the
5044 // two are the only words a region changes. See
5045 // `crcbl_shaders::draw_gen::DRAW_REGIONS`.
5046 for (region, (bucket, index)) in
5047 (0..crcbl_shaders::draw_gen::DRAW_REGIONS).flat_map(|region| {
5048 (0..bucket_count).map(move |bucket| (region, (bucket, bucket as usize)))
5049 })
5050 {
5051 let offset = (region * bucket_count + bucket) * draw_stride;
5052 if region == 0 {
5053 bucket_constants[index] = offset;
5054 }
5055 let start_at = draws.region_start_word(region, bucket);
5056 // The mesh path's block says three more things — where this
5057 // bucket's mesh's clusters are, how many it has, and which element
5058 // of the indirect arguments holds its instance count — because a
5059 // dispatch carries none of them and a `draw_indexed_indirect` does
5060 // not need them. All three are fixed when the bucket table is,
5061 // exactly like `start_at`.
5062 let block = if emit.is_mesh() {
5063 crcbl_shaders::meshlet::ClusterDrawConstants {
5064 start_at,
5065 cluster_base: bucket_cluster_bases[index],
5066 cluster_count: bucket_clusters[index],
5067 // The region's argument structure, which is where this
5068 // region's instance count is.
5069 bucket: region * bucket_count + bucket,
5070 // The same number the draw-argument pass indexes the state
5071 // with, taken from the object that owns the buffer rather
5072 // than recomputed from the group table — the two indexing it
5073 // differently is a cluster reading another instance's
5074 // decision.
5075 group_stride: draws.group_stride(),
5076 // Where the group records are in the table buffer, from the
5077 // object that packed it — the screen-error heatmap's one
5078 // input that is not already in the frame block. Taken from
5079 // `DrawGen` rather than recomputed here for `group_stride`'s
5080 // reason: two spellings of one offset is an overlay reading
5081 // another region's words as a group.
5082 level_groups_at: draws.table_offsets().level_groups_at,
5083 // The same two numbers again as words of that buffer,
5084 // which is where a draw that is not the first of a ranged
5085 // call reads them — `mesh_cluster.slang`'s "One call for
5086 // a range of buckets". This bucket's, not the region's
5087 // argument structure's: the tables hold one word a bucket.
5088 cluster_base_at: draws.table_offsets().bucket_cluster_bases_at + bucket,
5089 cluster_count_at: draws.table_offsets().bucket_clusters_at + bucket,
5090 // Where this bucket's task chunks start in this region,
5091 // and where the region's end: what a flat call binding
5092 // this block searches between — `mesh_cluster.slang`'s
5093 // `taskMain`.
5094 chunk_starts_at: draws.chunk_start_word(region, bucket),
5095 chunk_starts_end: draws.chunk_start_word(region, bucket_count),
5096 }
5097 .to_bytes()
5098 .to_vec()
5099 } else {
5100 // **The bucket's mesh, which is not always the drawn instance's.**
5101 // A uniform cut selects one of a DAG's levels and each level is
5102 // a mesh table entry of its own, so this is what says which
5103 // geometry the draw's index range belongs to; the instance goes
5104 // on naming level 0. See `mesh::DrawConstants::mesh`.
5105 mesh::DrawConstants {
5106 start_at,
5107 mesh: bucket_meshes[index],
5108 mesh_at: draws.bucket_mesh_word(bucket),
5109 }
5110 .to_bytes()
5111 .to_vec()
5112 };
5113 device.write_buffer(draw_constants, u64::from(offset), &block)?;
5114 }
5115
5116 let region_step = RegionStep {
5117 constants: bucket_count * draw_stride,
5118 args: draws.args_region_offset(1),
5119 counts: draws.counts_region_offset(1),
5120 };
5121
5122 // §3.3's cull, once per cascade and once per shadowed light. Each gets
5123 // its own `DrawGen` and therefore its own frustum, survivor list and
5124 // indirect arguments — which is what "one cull dispatch per cascade
5125 // against the same instance/geometry pools" means, and why the instance
5126 // ring and the mesh table below are the same handles the camera's cull
5127 // was given.
5128 //
5129 // **One per light rather than one per tile**, which is topic 18's fourth
5130 // decision and what `SHADOW_CULLS` is: a point light's six faces cull
5131 // against the light's sphere once and draw that one visible set through
5132 // six matrices.
5133 //
5134 // **Built for every slot, including the ones no light may ever hold.** A
5135 // generator's buffers are sized by the instance capacity rather than by
5136 // the scene, so building one on demand would mean allocating device
5137 // memory inside `begin_frame` — and a frame that cannot allocate is a
5138 // frame that cannot draw. The unused ones cost memory and no dispatch:
5139 // `add_shadow_pass` records passes for the occupied slots alone.
5140 for cull in 0..SHADOW_CULLS {
5141 // Into the rollback as each is built, on the same terms as the
5142 // camera's: a failure two culls in has to release the first one,
5143 // and the rollback is the only thing that knows about it.
5144 let label = if cull < shadow::CASCADES {
5145 format!("shadow cascade {cull}")
5146 } else {
5147 format!("shadow light {}", cull - shadow::CASCADES)
5148 };
5149 let draws = DrawGen::new(
5150 device,
5151 queue,
5152 &DrawGenDesc {
5153 label: Some(&label),
5154 instances: &instance_buffers,
5155 mesh_table,
5156 bucket_meshes: &bucket_meshes,
5157 bucket_modes: &bucket_modes,
5158 bucket_clusters: &bucket_clusters,
5159 bucket_cluster_bases: &bucket_cluster_bases,
5160 mesh_levels: &mesh_levels,
5161 level_groups: &level_groups,
5162 level_meshes: &level_meshes,
5163 instance_capacity: scene.capacities.instances,
5164 // No view's: a shadow map is drawn from everything resident
5165 // that casts, so an instance a camera hides still casts its
5166 // shadow and one `set_instance_casts_shadow` turned off does
5167 // not — on every geometry path, since this is the cull they
5168 // all draw from. The reflective shadow maps draw these same
5169 // survivors, so such an instance bounces no light either.
5170 hidden_view: mesh::GpuInstance::CASTS_NO_SHADOW,
5171 // A light slot may hold a point light, whose six faces cull
5172 // separately into six regions of the one generator; a
5173 // cascade never does.
5174 mode: if cull < shadow::CASCADES {
5175 crcbl_shaders::draw_gen::DrawMode::Plain
5176 } else {
5177 crcbl_shaders::draw_gen::DrawMode::Faces
5178 },
5179 task_lanes: view::task_lanes(culls_clusters),
5180 },
5181 )?;
5182 rollback.shadow_draws.push(draws);
5183 service();
5184 }
5185 // The handles are `Copy` and are read out here for the same reason the
5186 // camera's are above: the pool they came from is the rollback's now.
5187 let tile_buffers: Vec<TileBuffers> = rollback
5188 .shadow_draws
5189 .iter()
5190 .map(|draws| TileBuffers {
5191 runs: (0..instance_buffers.len())
5192 .map(|frame| draws.runs(frame))
5193 .collect(),
5194 args: (0..instance_buffers.len())
5195 .map(|frame| draws.args(frame))
5196 .collect(),
5197 cull_params: (0..instance_buffers.len())
5198 .map(|frame| draws.cull_params(frame))
5199 .collect(),
5200 cull_stats: (0..instance_buffers.len())
5201 .map(|frame| draws.visible_count(frame))
5202 .collect(),
5203 group_state: draws.group_state(),
5204 })
5205 .collect();
5206
5207 let mut shadow_uniforms = Vec::with_capacity(FRAMES_IN_FLIGHT);
5208 let mut shadow_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
5209 let mut shadow_selection = Vec::with_capacity(FRAMES_IN_FLIGHT);
5210 let mut shadow_group_entries = Vec::with_capacity(FRAMES_IN_FLIGHT);
5211 for (frame, &slot_instances) in instance_buffers.iter().enumerate() {
5212 // Everything a group of this layout names that is the same in all of
5213 // this frame's — the camera's list and table buffers included, which
5214 // a shadow view binds because the layout declares them and reads
5215 // nothing of. The per-group half is what `MeshGroup` below varies,
5216 // and the two exist so the colour pass's group and the shadow pass's
5217 // are one description rather than two that agree today.
5218 let shared = SharedBindings {
5219 vertices,
5220 draw_constants,
5221 mesh_table,
5222 materials: material_buffer,
5223 pages: page_bindings,
5224 clusters: rollback.clusters.as_ref(),
5225 shadow_sampler,
5226 lights: primary.lights.lights(frame),
5227 light_grid: primary.lights.grid(frame),
5228 probes: probe_buffers[frame],
5229 tables: primary.draws.tables(),
5230 specular_dfg: specular_dfg.view,
5231 ltc_table: ltc_table.view,
5232 };
5233
5234 // The same layout again, once per shadow view, differing in exactly
5235 // the things a view is: which matrix, and which cull's survivors.
5236 //
5237 // **The view's own uniforms and the cull's shared buffers**, which
5238 // is the whole of what a point light's six faces are: one visible
5239 // set, six matrices. `shadow_cull` is the map from a view to the
5240 // generator behind it, and it is a compile-time one because a bind
5241 // group names its buffers when it is created — where a face's *tile*
5242 // is decided per frame and reaches the device as a viewport.
5243 let mut frame_shadow_uniforms = Vec::with_capacity(SHADOW_VIEWS);
5244 let mut frame_shadow_groups = Vec::with_capacity(SHADOW_VIEWS);
5245 let mut frame_shadow_selection = Vec::with_capacity(SHADOW_VIEWS);
5246 let mut frame_shadow_entries = Vec::with_capacity(SHADOW_VIEWS);
5247 for view in 0..SHADOW_VIEWS {
5248 let buffers = &tile_buffers[if view < shadow::CASCADES {
5249 view
5250 } else {
5251 shadow_cull((view - shadow::CASCADES) / shadow::POINT_FACES)
5252 }];
5253 let tile_uniforms = device.create_buffer(&BufferDesc {
5254 label: Some("shadow view uniforms"),
5255 size: mesh::FRAME_UNIFORMS_SIZE as u64,
5256 usage: BufferUsage::UNIFORM,
5257 memory: MemoryLocation::HostUpload,
5258 })?;
5259 rollback.buffers.push(tile_uniforms);
5260 let entries = MeshGroup {
5261 uniforms: tile_uniforms,
5262 instances: slot_instances,
5263 runs: buffers.runs[frame],
5264 args: buffers.args[frame],
5265 // The amplification stage culls clusters against whatever
5266 // frustum is in this block, and against
5267 // `frame.camera_position` — which in a view's copy is the
5268 // *light*. So the per-cluster cull rejects what faces away
5269 // from the light, which is the right question for a shadow
5270 // map and the wrong one to have asked with the camera's
5271 // frustum.
5272 cull_params: buffers.cull_params[frame],
5273 cull_stats: buffers.cull_stats[frame],
5274 // **This view's own**, and not the colour pass's: that pass
5275 // is recorded last and would write over it. See
5276 // `ForwardRenderer::shadow_selection`.
5277 cluster_selection: tile_selection.get(view).map(|ring| ring[frame]),
5278 // Its cull's — see `TileBuffers::group_state`, which is
5279 // where that budget is argued.
5280 group_state: emit.is_mesh().then_some(buffers.group_state),
5281 shadow_map: shadow_placeholder_view,
5282 // A cascade shades nothing — the pipeline has no fragment
5283 // stage — so this slot exists only because Metal
5284 // materialises every global into every entry point.
5285 ambient_occlusion: ambient_occlusion_placeholder.view,
5286 contact_shadow: contact_shadow_placeholder.view,
5287 probe_visibility: probe_visibility_placeholder.view,
5288 }
5289 .entries(&shared);
5290 let group = device.create_bind_group(&BindGroupDesc {
5291 label: Some("shadow view"),
5292 layout: mesh_layout,
5293 entries: &entries,
5294 variable_count: None,
5295 })?;
5296 rollback.bind_groups.push(group);
5297 frame_shadow_uniforms.push(tile_uniforms);
5298 frame_shadow_groups.push(group);
5299 frame_shadow_entries.push(entries);
5300 frame_shadow_selection.extend(tile_selection.get(view).map(|ring| ring[frame]));
5301 }
5302 shadow_uniforms.push(frame_shadow_uniforms);
5303 shadow_groups.push(frame_shadow_groups);
5304 shadow_group_entries.push(frame_shadow_entries);
5305 shadow_selection.push(frame_shadow_selection);
5306 service();
5307 }
5308
5309 let mesh_set_layouts = [mesh_layout];
5310 let mesh_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5311 label: Some("mesh"),
5312 bind_group_layouts: &mesh_set_layouts,
5313 // The camera goes in the uniform buffer above rather than here:
5314 // `Features::PUSH_CONSTANTS` is absent on Tier B and the seam is
5315 // explicit that the substitute is a data-layout decision. So this
5316 // file needs no tier branch at all — it has been on Tier B's shape
5317 // since P1, and `crate::ui_pass` is where the split actually bites.
5318 push_constants: None,
5319 })?;
5320 rollback.pipeline_layouts.push(mesh_pipeline_layout);
5321
5322 // The colour pass's pipeline and its depth-only twin, out of one set of
5323 // modules — see [`MeshModules`], which is where the two shapes and the
5324 // reasons for them live. Both are created before either is unwrapped and
5325 // the modules are released between, so a failing creation leaks nothing.
5326 //
5327 // **Each shape is built twice, once per material side** — see
5328 // [`SidedPipelines`], which is where the cull modes and the reason for a
5329 // pipeline rather than a per-draw state live. The shadow tile clear is
5330 // the one exception: its triangle comes out of `SV_VertexID` and it
5331 // already culls nothing.
5332 //
5333 // **`service` before every one of them**: on a cold driver cache each is
5334 // a shader compilation, and this batch is the build's longest run of
5335 // them — see [`ForwardRenderer::with_scene_serviced`].
5336 let modules = MeshModules::new(device, emit, culls_clusters)?;
5337 let mesh_results = MeshModules::sided(|cull| {
5338 service();
5339 modules.color_pipeline(
5340 device,
5341 mesh_pipeline_layout,
5342 PolygonMode::Fill,
5343 cull,
5344 "forward",
5345 )
5346 });
5347 let shadow_results = MeshModules::sided(|cull| {
5348 service();
5349 modules.depth_pipeline(device, mesh_pipeline_layout, cull)
5350 });
5351 // And its cutout twin, which a frame whose material table masks alpha is
5352 // recorded with instead — see [`MeshModules::depth_masked_pipeline`].
5353 let depth_masked_results = MeshModules::sided(|cull| {
5354 service();
5355 modules.depth_masked_pipeline(device, mesh_pipeline_layout, cull)
5356 });
5357 // And the one that resets a tile, which the cadence rung needs and the
5358 // attachment's load operation cannot express — see
5359 // [`MeshModules::depth_clear_pipeline`].
5360 service();
5361 let shadow_clear_result = modules.depth_clear_pipeline(device, mesh_pipeline_layout);
5362 // And the irradiance probes' reflective shadow map, built
5363 // from the same modules and the same layout — see
5364 // [`MeshModules::rsm_pipeline`]. Built on every scene rather than only
5365 // on one whose probes ask to be updated: the modules are released a line
5366 // below and a pipeline built later would need them back, which is a
5367 // second shader compilation for a field a `ProbeGrid` decides.
5368 let rsm_results = MeshModules::sided(|cull| {
5369 service();
5370 modules.rsm_pipeline(device, mesh_pipeline_layout, cull)
5371 });
5372 modules.destroy(device);
5373 // Register every successful creation before propagating any error.
5374 // Results later in this batch may own pipelines even when the first
5375 // result failed; dropping an unvisited Result does not release a HAL
5376 // handle. The outer rollback owns all of them until build succeeds.
5377 for pipeline in mesh_results
5378 .iter()
5379 .chain(&shadow_results)
5380 .chain(&depth_masked_results)
5381 .chain(std::iter::once(&shadow_clear_result))
5382 .chain(&rsm_results)
5383 .flatten()
5384 {
5385 rollback.pipelines.push(*pipeline);
5386 }
5387 let into_sided = |results: [Result<GraphicsPipelineHandle, HalError>; 2]|
5388 -> Result<SidedPipelines, HalError> {
5389 let [single, double] = results;
5390 Ok(SidedPipelines { single: single?, double: double? })
5391 };
5392 let mesh_pipeline = into_sided(mesh_results)?;
5393 let shadow_pipeline = into_sided(shadow_results)?;
5394 let depth_masked_pipeline = into_sided(depth_masked_results)?;
5395 let shadow_clear_pipeline = shadow_clear_result?;
5396 let rsm_pipeline = into_sided(rsm_results)?;
5397
5398 // --- the tonemap pass ---
5399 let tonemap_entries = [
5400 BindGroupLayoutEntry {
5401 binding: 0,
5402 visibility: ShaderStages::FRAGMENT,
5403 kind: BindingKind::SampledImage {
5404 view_type: ImageViewType::D2,
5405 sample_type: SampleType::Float,
5406 },
5407 count: 1,
5408 flags: BindingFlags::empty(),
5409 },
5410 BindGroupLayoutEntry {
5411 binding: 1,
5412 visibility: ShaderStages::FRAGMENT,
5413 kind: BindingKind::Sampler { comparison: false },
5414 count: 1,
5415 flags: BindingFlags::empty(),
5416 },
5417 // The exposure — see [`set_exposure`](Self::set_exposure). A uniform
5418 // buffer rather than a push constant, which is [`crate::ui_pass`]'s
5419 // decision restated: WebGPU has no push constants at all, so a range
5420 // here would split this pass into a tier A and a tier B form —
5421 // two layouts, two buffers and, because one Slang entry point reads
5422 // either a `[[vk::push_constant]]` block or a `[[vk::binding]]`ed
5423 // one and never both, a second copy of `tonemap.slang`. Four bytes
5424 // once a frame do not buy that.
5425 //
5426 // `FRAGMENT` alone, and the artifact agrees: `spirv/tonemap.spv`
5427 // lists `%params` in the fragment `OpEntryPoint`'s interface and not
5428 // in the vertex one, because the vertex stage generates three
5429 // corners out of `SV_VertexID` and reads nothing.
5430 BindGroupLayoutEntry {
5431 binding: 2,
5432 visibility: ShaderStages::FRAGMENT,
5433 kind: BindingKind::UniformBuffer { dynamic: false },
5434 count: 1,
5435 flags: BindingFlags::empty(),
5436 },
5437 // The measured exposure — see [`crate::exposure`]. **Bound on every
5438 // frame, whether or not anything measured**, because a binding that
5439 // comes and goes is a second pipeline layout and a second group
5440 // cache keyed on which one is live, to save four bytes. The block
5441 // above carries the switch that decides whether the shader reads it.
5442 BindGroupLayoutEntry {
5443 binding: 3,
5444 visibility: ShaderStages::FRAGMENT,
5445 kind: BindingKind::StorageBuffer {
5446 // Written by `exposure.slang`'s reduce and read here —
5447 // `StructuredBuffer` in this shader, which is the truth
5448 // rather than a hint.
5449 read_only: true,
5450 dynamic: false,
5451 stride: size_of::<u32>() as u32,
5452 },
5453 count: 1,
5454 flags: BindingFlags::empty(),
5455 },
5456 ];
5457 let tonemap_desc = BindGroupLayoutDesc {
5458 label: Some("tonemap scene"),
5459 entries: &tonemap_entries,
5460 };
5461 check_portable_storage_buffers(Some("tonemap"), &[&tonemap_desc])?;
5462 let tonemap_layout = device.create_bind_group_layout(&tonemap_desc)?;
5463 rollback.bind_group_layouts.push(tonemap_layout);
5464 let tonemap_set_layouts = [tonemap_layout];
5465 let tonemap_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5466 label: Some("tonemap"),
5467 bind_group_layouts: &tonemap_set_layouts,
5468 push_constants: None,
5469 })?;
5470 rollback.pipeline_layouts.push(tonemap_pipeline_layout);
5471 let tonemap_vertex = entry(&TONEMAP, Stage::Vertex)?;
5472 let tonemap_fragment = entry(&TONEMAP, Stage::Fragment)?;
5473 let tonemap_module = device.create_shader_module(&ShaderModuleDesc {
5474 label: Some("tonemap.slang"),
5475 spirv: TONEMAP.spirv(),
5476 wgsl: TONEMAP.wgsl(),
5477 msl: TONEMAP.msl(),
5478 // A container per entry point, for the reason the mesh module above
5479 // gives.
5480 dxil: &TONEMAP.dxil_containers(),
5481 })?;
5482 let tonemap_targets = [ColorTargetState::opaque(target_format)];
5483 let tonemap_pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5484 label: Some("tonemap"),
5485 layout: tonemap_pipeline_layout,
5486 vertex: ShaderEntry {
5487 module: tonemap_module,
5488 entry_point: tonemap_vertex,
5489 },
5490 fragment: Some(ShaderEntry {
5491 module: tonemap_module,
5492 entry_point: tonemap_fragment,
5493 }),
5494 // The full-screen triangle is deliberately oversized, so two of its
5495 // vertices are outside the viewport and its winding is not worth
5496 // reasoning about. `CullMode::None` is the honest setting.
5497 primitive: PrimitiveState::default(),
5498 depth_stencil: None,
5499 multisample: MultisampleState::default(),
5500 color_targets: &tonemap_targets,
5501 });
5502 device.destroy_shader_module(tonemap_module);
5503 let tonemap_pipeline = tonemap_pipeline?;
5504 rollback.pipelines.push(tonemap_pipeline);
5505 service();
5506
5507 // Nearest, not linear: see `tonemap.slang` on why a 1:1 blit must not
5508 // leave a golden image depending on two rasterisers agreeing about
5509 // texel-centre arithmetic.
5510 let sampler = device.create_sampler(&SamplerDesc {
5511 label: Some("tonemap scene"),
5512 mag_filter: FilterMode::Nearest,
5513 min_filter: FilterMode::Nearest,
5514 mip_filter: FilterMode::Nearest,
5515 address_mode: [SamplerAddressMode::ClampToEdge; 3],
5516 ..SamplerDesc::default()
5517 })?;
5518 rollback.samplers.push(sampler);
5519
5520 // --- the shadow atlas viewer ---
5521 //
5522 // Built last, so `Rollback::run` releases it first. It writes the
5523 // caller's target rather than a transient — it replaces the picture the
5524 // tonemap put there, which is [`crate::atlas_view`]'s argument — and it
5525 // records on no frame but the one that resolved
5526 // [`DebugView::ShadowAtlas`].
5527 rollback.atlas_viewer = Some(AtlasView::new(
5528 device,
5529 instance_buffers.len(),
5530 target_format,
5531 Self::build_fullscreen,
5532 )?);
5533 service();
5534
5535 Ok(Self {
5536 pool: rollback
5537 .pool
5538 .take()
5539 .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5540 bucket_constants,
5541 region_step,
5542 bucket_modes,
5543 instances: rollback
5544 .instances
5545 .take()
5546 .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5547 mesh_ids,
5548 skinnable_meshes,
5549 skinned_instances: Vec::new(),
5550 materials: rollback
5551 .materials
5552 .take()
5553 .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5554 material_ids,
5555 probes: rollback
5556 .probes
5557 .take()
5558 .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5559 probe_volume: scene.probes.volume,
5560 base_color_page,
5561 normal_page,
5562 mro_page,
5563 emissive_page,
5564 page_extents,
5565 page_layers,
5566 base_color_sampler,
5567 anisotropy,
5568 // Every slot's groups were just built naming these.
5569 slot_pages: vec![page_bindings; FRAMES_IN_FLIGHT],
5570 retired_pages: Vec::new(),
5571 // No frame has been recorded yet, and the counters say so rather
5572 // than reporting the count a frame *would* have.
5573 recorded_draws: 0,
5574 emit,
5575 range_limit,
5576 clusters: rollback.clusters.take(),
5577 culls_clusters,
5578 draw_constants,
5579 mesh_clusters,
5580 // One entry per description mesh, each holding one bucket per level,
5581 // where the cull pass takes a uniform cut — and nothing at all where
5582 // the amplification stage takes a per-cluster one. Read off the
5583 // bucket table that was actually built rather than re-derived from
5584 // the path.
5585 mesh_level_buckets: if emit.is_mesh() {
5586 Vec::new()
5587 } else {
5588 residents
5589 .iter()
5590 .enumerate()
5591 .map(|(index, resident)| {
5592 let base = bucket_bases[index];
5593 (base..base + resident.levels.len())
5594 .map(|bucket| {
5595 u32::try_from(bucket)
5596 .unwrap_or_else(|_| unreachable!("a table of a few buckets"))
5597 })
5598 .collect()
5599 })
5600 .collect()
5601 },
5602 lod_error_budget: LOD_ERROR_BUDGET,
5603 lod_hold_ratio: LOD_HOLD_RATIO,
5604 // Overwritten by the first `begin_frame`, which is the only thing
5605 // that can know the viewport.
5606 shadow_lod_params: [0.0, 0.0, 0.0],
5607 extra_lights: Vec::new(),
5608 primary: rollback
5609 .primary
5610 .take()
5611 .unwrap_or_else(|| unreachable!("the camera was placed in the rollback above")),
5612 views: Vec::new(),
5613 draw_tables: DrawTables {
5614 bucket_meshes,
5615 bucket_clusters,
5616 bucket_cluster_bases,
5617 mesh_levels,
5618 level_groups,
5619 level_meshes,
5620 instance_capacity: scene.capacities.instances,
5621 light_capacity: scene.capacities.lights,
5622 },
5623 frame_serial: 0,
5624 frame_scene: None,
5625 frame: 0,
5626 mesh_layout,
5627 mesh_pipeline_layout,
5628 mesh_pipeline,
5629 // Off, and unbuilt, on the ground grid's terms below: the wireframe
5630 // view is opt-in, so a caller that never asks for one draws the
5631 // frame it drew before `set_wireframe` existed.
5632 wireframe_pipeline: None,
5633 wireframe_on: false,
5634 occlusion_culling: OcclusionCulling::OFF,
5635 point_face_culls: true,
5636 shadow_view_tamper: None,
5637 // Off, on the line above's terms: the normals view is opt-in, so a
5638 // caller that never asks for one draws the frame it drew before
5639 // `set_normals_view` existed. It builds nothing, so there is no
5640 // second field here.
5641 normals_view: false,
5642 // Off on the same terms, and "off" here is a density of zero: the
5643 // shader's composite is exactly the identity there, so a caller who
5644 // never calls `set_fog` gets the frame byte for byte.
5645 fog: Fog::NONE,
5646 sky: Sky::NONE,
5647 atmosphere: None,
5648 sky_view: None,
5649 sky_view_build: None,
5650 lod_view: false,
5651 heatmap: false,
5652 occlusion_view: false,
5653 motion_view: false,
5654 bent_normal_view: false,
5655 cascade_view: false,
5656 atlas_view: false,
5657 // Following the camera, on the line above's terms: the selection eye
5658 // is the camera's until a caller pins it, so a renderer nobody calls
5659 // `set_frozen_selection_eye` on hands `begin_frame` exactly what it
5660 // handed before this field existed.
5661 frozen_selection_eye: None,
5662 shadow_atlas,
5663 shadow_atlas_view,
5664 shadow_placeholder,
5665 shadow_placeholder_view,
5666 shadow_sampler,
5667 shadow_pipeline,
5668 depth_masked_pipeline,
5669 shadow_clear_pipeline,
5670 rsm_pipeline,
5671 probe_gather,
5672 probe_update: scene.probes.update,
5673 // Overwritten by the first `begin_frame`, which is the only reader's
5674 // only source. Zero is the honest placeholder: no cascade has been
5675 // fitted yet, and a gather recorded against it would scale by zero
5676 // rather than by a number nobody chose.
5677 cascade_reach: 0.0,
5678 // Nothing has been fitted before the first `begin_frame`.
5679 rsm_cull_ready: false,
5680 sun_color: Vec3::ZERO,
5681 shadow_draws: std::mem::take(&mut rollback.shadow_draws),
5682 shadow_uniforms,
5683 shadow_prepare_views: Vec::new(),
5684 shadow_prepare_culls: Vec::new(),
5685 shadow_groups,
5686 shadow_selection,
5687 shadow_lights: shadow::Selection::default(),
5688 // Nothing has drawn the atlas, so the first frame draws every group
5689 // whatever it is asked for — which is also what gives the image a
5690 // defined content before anything samples it. A record is never
5691 // empty, so the first frame's is a change and takes every id past
5692 // the zero below it.
5693 shadow_group_inputs: vec![Vec::new(); SHADOW_CULLS],
5694 shadow_group_id: vec![0; SHADOW_CULLS],
5695 shadow_group_writes: vec![0; SHADOW_CULLS],
5696 shadow_footprints: Vec::new(),
5697 shadow_dag_elements: std::collections::BTreeSet::new(),
5698 shadow_written: Vec::new(),
5699 shadow_moved: Vec::new(),
5700 shadow_pass_id: 0,
5701 shadow_pass_ran: Arc::new(AtomicU64::new(0)),
5702 shadow_pending: None,
5703 // A reach of zero, so every centre on the first frame is further
5704 // from what the image holds than the nothing it holds reaches —
5705 // which is the reset that frame should be.
5706 shadow_group_held: vec![(0, Vec3::ZERO, 0.0); SHADOW_CULLS],
5707 shadow_group_redrawn: vec![false; SHADOW_CULLS],
5708 shadow_atlas_layout: None,
5709 shadow_atlas_cached: false,
5710 shadow_cadence_reset: false,
5711 shadow_faces_redrawn: 0,
5712 shadow_cadence_request: None,
5713 shadow_atlas_clears: true,
5714 shadow_frame: 0,
5715 frame_skins: false,
5716 // [`FRAMES_IN_FLIGHT`], the number every other ring here is sized
5717 // by, so a slot has been through the whole loop before it is read.
5718 // `culls_clusters` rather than the device's feature bits: what
5719 // decides whether the cluster word is a count is whether *this
5720 // renderer* built an amplification stage.
5721 cull_stats: CullStatsRing::new(device, FRAMES_IN_FLIGHT, culls_clusters),
5722 tonemap_layout,
5723 tonemap_pipeline_layout,
5724 tonemap_pipeline,
5725 sampler,
5726 // The value `tonemap.slang`'s `EXPOSURE` constant held, so a
5727 // renderer nobody has called `set_exposure` on writes the frame it
5728 // wrote before the block existed.
5729 exposure: tonemap::DEFAULT_EXPOSURE,
5730 exposure_adaptation: None,
5731 // And the filmic roll-off over it: this renderer shades in linear
5732 // HDR, so a view that has asked for nothing gets the operator that
5733 // range was shaded for.
5734 tonemap_curve: tonemap::TonemapCurve::Aces,
5735 target_format,
5736 ambient_occlusion_placeholder,
5737 contact_shadow_placeholder,
5738 probe_visibility_placeholder,
5739 // Nothing has been captured, so every frame drawn before
5740 // `capture_probe_visibility` reads the placeholder and weighs every
5741 // probe at one — which is the frame this renderer drew before the
5742 // maps existed.
5743 probe_visibility: None,
5744 probe_occluders,
5745 specular_dfg,
5746 ltc_table,
5747 shadow_group_entries,
5748 // Off, and unbuilt: the grid is opt-in, so a caller that never asks
5749 // for one draws the frame it drew before this module existed.
5750 ground_grid: None,
5751 ground_grid_on: false,
5752 // Empty, and unbuilt: nothing has appended a segment, so this
5753 // renderer records the frame it recorded before the layer existed.
5754 debug_draw: DebugDraw::default(),
5755 atlas_viewer: rollback
5756 .atlas_viewer
5757 .take()
5758 .unwrap_or_else(|| unreachable!("the viewer was placed in the rollback above")),
5759 // Full resolution, which is the frame every caller of this type drew
5760 // before there was a knob — see [`Self::set_render_scale`].
5761 render_scale: 1.0,
5762 // The default stack the view wants, no quality clamp and no
5763 // override, which resolves to every effect this device permits but
5764 // the lens one — the frame every caller of this type drew before
5765 // there were toggles. See [`RenderEffects::DEFAULT_STACK`].
5766 effect_request: EffectRequest::default(),
5767 device_effects: RenderEffects::all(),
5768 frame_effects: RenderEffects::DEFAULT_STACK,
5769 // What the switch says today, so a renderer built and never opened
5770 // still describes the frame it would draw. `begin_frame` reads it
5771 // again for the frame it opens.
5772 frame_ssao_blurs: crate::ssao::blur_passes(),
5773 // No frame has been recorded yet, on `recorded_draws`' terms.
5774 recorded_fullscreen: 0,
5775 // No frame has been recorded yet, on `recorded_fullscreen`'s terms.
5776 recorded_debug_draw: 0,
5777 recorded_tile_clears: 0,
5778 // No bodies, so no pass: the frame every caller of this type drew
5779 // before water existed. Nothing is allocated until a body is set.
5780 water: WaterBodies::new(FRAMES_IN_FLIGHT),
5781 recorded_water_draws: 0,
5782 // No field, so no pass: the frame every caller of this type drew
5783 // before grass existed. The two calm wind layers are one texel
5784 // each and are what makes a field with no weather set still.
5785 grass: GrassScene::new(device, queue, FRAMES_IN_FLIGHT)?,
5786 wind: crcbl_shaders::wind::WindParams::default(),
5787 recorded_grass_draws: 0,
5788 })
5789 }
5790
5791 /// Builds a full-screen-triangle pipeline out of `shader`'s vertex and
5792 /// fragment entry points.
5793 ///
5794 /// One helper because every post pass in this crate wants the same
5795 /// pipeline — the tonemap's, `ssao`'s, `ssao-blur`'s, `ssr`'s and the rest —
5796 /// differing in the module, the layout and the target format alone. The
5797 /// tonemap's stays written out where it is: it is the one that carries the
5798 /// *why* of the shape, and this is the shape repeated.
5799 ///
5800 /// The module is destroyed before the pipeline result is unwrapped, so a
5801 /// failing creation leaks nothing.
5802 ///
5803 /// # Errors
5804 ///
5805 /// [`HalError`] from the manifest lookup, the module or the pipeline.
5806 fn build_fullscreen(
5807 device: &dyn Device,
5808 label: &str,
5809 shader: &crcbl_shaders::Shader,
5810 layout: PipelineLayoutHandle,
5811 color_targets: &[ColorTargetState],
5812 ) -> Result<GraphicsPipelineHandle, HalError> {
5813 Self::build_fullscreen_with(device, label, shader, layout, color_targets, None)
5814 }
5815
5816 /// [`Self::build_fullscreen`] for a pass that **depth-tests** what it draws
5817 /// against an attachment it does not write.
5818 ///
5819 /// The state is [`DepthStencilState::equal_depth_read_only`], whose
5820 /// [`CompareOp::GreaterOrEqual`] is the reversed-Z pair for "the fragment's
5821 /// depth must equal what is already there". One caller, [`crate::sky_pass`],
5822 /// which emits its triangle at the far plane so that the test selects
5823 /// exactly the pixels no geometry covered — see that module.
5824 ///
5825 /// # Errors
5826 ///
5827 /// [`HalError`] from the manifest lookup, the module or the pipeline.
5828 fn build_tested_fullscreen(
5829 device: &dyn Device,
5830 label: &str,
5831 shader: &crcbl_shaders::Shader,
5832 layout: PipelineLayoutHandle,
5833 color_targets: &[ColorTargetState],
5834 depth_format: Format,
5835 ) -> Result<GraphicsPipelineHandle, HalError> {
5836 Self::build_fullscreen_with(
5837 device,
5838 label,
5839 shader,
5840 layout,
5841 color_targets,
5842 Some(DepthStencilState::equal_depth_read_only(depth_format)),
5843 )
5844 }
5845
5846 /// The body of the two above, which differ in their depth state and in
5847 /// nothing else.
5848 ///
5849 /// # Errors
5850 ///
5851 /// [`HalError`] from the manifest lookup, the module or the pipeline.
5852 fn build_fullscreen_with(
5853 device: &dyn Device,
5854 label: &str,
5855 shader: &crcbl_shaders::Shader,
5856 layout: PipelineLayoutHandle,
5857 color_targets: &[ColorTargetState],
5858 depth_stencil: Option<DepthStencilState>,
5859 ) -> Result<GraphicsPipelineHandle, HalError> {
5860 let vertex = entry(shader, Stage::Vertex)?;
5861 let fragment = entry(shader, Stage::Fragment)?;
5862 let module = device.create_shader_module(&ShaderModuleDesc {
5863 label: Some(shader.source()),
5864 spirv: shader.spirv(),
5865 wgsl: shader.wgsl(),
5866 msl: shader.msl(),
5867 // A container per entry point, for the reason the mesh module gives.
5868 dxil: &shader.dxil_containers(),
5869 })?;
5870 let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5871 label: Some(label),
5872 layout,
5873 vertex: ShaderEntry {
5874 module,
5875 entry_point: vertex,
5876 },
5877 fragment: Some(ShaderEntry {
5878 module,
5879 entry_point: fragment,
5880 }),
5881 // The triangle is deliberately oversized, so two of its vertices are
5882 // outside the viewport and its winding is not worth reasoning about.
5883 primitive: PrimitiveState::default(),
5884 depth_stencil,
5885 multisample: MultisampleState::default(),
5886 color_targets,
5887 });
5888 device.destroy_shader_module(module);
5889 pipeline
5890 }
5891
5892 /// Builds a full-screen-triangle pipeline that writes a **depth**
5893 /// attachment and no colour one.
5894 ///
5895 /// [`Self::build_fullscreen`]'s shape with the two halves of that swapped:
5896 /// no colour target at all, and a depth state whose comparison always
5897 /// passes so every texel of the destination takes the value the fragment
5898 /// computed. The reversed-Z [`CompareOp::Greater`] every geometry pipeline
5899 /// in this file uses would be wrong here — this pass is not depth-testing
5900 /// anything, it is writing a reduction, and a test against the target's
5901 /// undefined contents would drop texels at random.
5902 ///
5903 /// Two callers, [`crate::hiz`] and [`crate::occlusion_cull`], and it stays
5904 /// a method rather than moving there because the module and the
5905 /// destroy-before-unwrap above are this file's, and both take it in exactly
5906 /// as `crate::ssao` takes the sibling.
5907 ///
5908 /// **The entry points are named**, unlike the sibling's: `hiz.slang` has a
5909 /// fragment stage per pyramid, and a stage looked up by kind would be
5910 /// ambiguous.
5911 ///
5912 /// # Errors
5913 ///
5914 /// [`HalError`] from the module or the pipeline.
5915 fn build_depth_fullscreen(
5916 device: &dyn Device,
5917 label: &str,
5918 shader: &crcbl_shaders::Shader,
5919 vertex: &str,
5920 fragment: &str,
5921 layout: PipelineLayoutHandle,
5922 format: Format,
5923 ) -> Result<GraphicsPipelineHandle, HalError> {
5924 let module = device.create_shader_module(&ShaderModuleDesc {
5925 label: Some(shader.source()),
5926 spirv: shader.spirv(),
5927 wgsl: shader.wgsl(),
5928 msl: shader.msl(),
5929 dxil: &shader.dxil_containers(),
5930 })?;
5931 let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5932 label: Some(label),
5933 layout,
5934 vertex: ShaderEntry {
5935 module,
5936 entry_point: vertex,
5937 },
5938 fragment: Some(ShaderEntry {
5939 module,
5940 entry_point: fragment,
5941 }),
5942 primitive: PrimitiveState::default(),
5943 depth_stencil: Some(DepthStencilState {
5944 format,
5945 depth_write: true,
5946 depth_compare: CompareOp::Always,
5947 stencil: None,
5948 bias: DepthBias::default(),
5949 }),
5950 multisample: MultisampleState::default(),
5951 color_targets: &[],
5952 });
5953 device.destroy_shader_module(module);
5954 pipeline
5955 }
5956
5957 /// Creates the geometry pool and makes every mesh of `scene` resident in it.
5958 ///
5959 /// Separate from [`ForwardRenderer::build`] because it is **self-cleaning**:
5960 /// the pool is not the rollback's until this has returned, so a failure
5961 /// between creating it and flushing the last upload releases it here.
5962 fn build_geometry(
5963 device: &dyn Device,
5964 queue: QueueHandle,
5965 scene: &SceneDesc<'_>,
5966 service: &mut dyn FnMut(),
5967 ) -> Result<(MeshPool, Vec<ResidentMesh>), HalError> {
5968 let mut pool = MeshPool::new(
5969 device,
5970 &MeshPoolDesc {
5971 label: Some("forward geometry"),
5972 vertex_capacity: scene.capacities.vertices,
5973 index_capacity: scene.capacities.indices,
5974 mesh_capacity: scene.capacities.meshes,
5975 },
5976 )?;
5977 match Self::residents(device, queue, &mut pool, scene, service) {
5978 Ok(residents) => Ok((pool, residents)),
5979 Err(error) => {
5980 pool.destroy(device);
5981 Err(error)
5982 }
5983 }
5984 }
5985
5986 /// Creates the material table and fills it with `scene`'s rows, returning it
5987 /// and the id of each.
5988 ///
5989 /// Self-cleaning for the same reason [`ForwardRenderer::build_geometry`] is:
5990 /// the table is not the rollback's until this has returned.
5991 fn build_materials(
5992 device: &dyn Device,
5993 scene: &SceneDesc<'_>,
5994 ) -> Result<(MaterialTable, Vec<u32>), HalError> {
5995 let mut materials = MaterialTable::new(
5996 device,
5997 &MaterialTableDesc {
5998 label: Some("forward"),
5999 capacity: scene.capacities.materials,
6000 },
6001 )?;
6002 match Self::material_rows(device, &mut materials, &scene.materials) {
6003 Ok(ids) => Ok((materials, ids)),
6004 Err(error) => {
6005 materials.destroy(device);
6006 Err(error)
6007 }
6008 }
6009 }
6010
6011 /// Inserts `rows` **in order** and returns the id of each.
6012 ///
6013 /// Split out of [`ForwardRenderer::build_materials`] only so the table can
6014 /// be released on a failure without the borrow that filling it takes, which
6015 /// is the same shape [`ForwardRenderer::residents`] has.
6016 ///
6017 /// **In order, because row 0 is not this function's to choose**: it is what
6018 /// [`mesh::GpuInstance::default`] names, so it is what an instance written
6019 /// without a material id shades with. Inserting a description's rows in any
6020 /// other order would move that row under every caller — see
6021 /// [`SceneDesc::materials`], which is where it is a caller's decision.
6022 fn material_rows(
6023 device: &dyn Device,
6024 materials: &mut MaterialTable,
6025 rows: &[mesh::GpuMaterial],
6026 ) -> Result<Vec<u32>, HalError> {
6027 let mut ids = Vec::with_capacity(rows.len());
6028 for row in rows {
6029 let handle = materials.insert(device, row)?;
6030 // The id is asked for rather than assumed, because the number an
6031 // instance carries is this one and nothing else knows it.
6032 ids.push(materials.index(handle).ok_or_else(|| {
6033 HalError::Backend(
6034 "a material inserted into an empty table did not resolve".to_string(),
6035 )
6036 })?);
6037 }
6038 Ok(ids)
6039 }
6040
6041 /// Uploads every mesh of `scene` and returns their mesh ids — **only** once
6042 /// the transfers have completed.
6043 ///
6044 /// The calls are §3.1's upload path in order: the copies are recorded and
6045 /// submitted against timeline values, [`MeshPool::flush`] is what makes those
6046 /// values pass, and [`MeshPool::mesh`] is what refuses to hand out a range
6047 /// before they have.
6048 ///
6049 /// **In description order**, which is what makes a mesh's table id a
6050 /// property of the description rather than of this loop — the second mesh
6051 /// uploaded is the pool's first resident at a non-zero base vertex, which is
6052 /// what the module docs call the one thing that can tell a working base
6053 /// vertex from a cancelled one.
6054 ///
6055 /// A DAG is **one upload per level**. Every level was decimated separately,
6056 /// so a coarser level's vertices are wherever the collapses put them and
6057 /// belong to no vertex of the level below — a DAG is several vertex ranges,
6058 /// and the pool suballocates in vertices, so several ranges means several
6059 /// uploads. Level 0 goes first, so every other level starts past it and the
6060 /// offsets a cluster carries are non-negative; that is checked rather than
6061 /// assumed, because the pool's free list makes no promise about where a mesh
6062 /// lands.
6063 fn residents(
6064 device: &dyn Device,
6065 queue: QueueHandle,
6066 pool: &mut MeshPool,
6067 scene: &SceneDesc<'_>,
6068 service: &mut dyn FnMut(),
6069 ) -> Result<Vec<ResidentMesh>, HalError> {
6070 let mut uploaded: Vec<Vec<crate::mesh_pool::MeshHandle>> =
6071 Vec::with_capacity(scene.meshes.len());
6072 for desc in &scene.meshes {
6073 match &desc.geometry {
6074 Geometry::Flat {
6075 vertices,
6076 indices,
6077 uv_range,
6078 flags,
6079 ..
6080 } => {
6081 uploaded.push(vec![pool.upload(
6082 device,
6083 queue,
6084 &MeshUpload {
6085 label: &desc.label,
6086 vertices,
6087 indices,
6088 uv_range: *uv_range,
6089 flags: *flags,
6090 },
6091 )?]);
6092 service();
6093 }
6094 Geometry::Dag {
6095 levels,
6096 dag,
6097 uv_range,
6098 flags,
6099 } => {
6100 let mut handles = Vec::with_capacity(levels.len());
6101 for (depth, (vertices, level)) in levels.iter().zip(&dag.levels).enumerate() {
6102 handles.push(pool.upload(
6103 device,
6104 queue,
6105 &MeshUpload {
6106 label: &format!("{} level {depth}", desc.label),
6107 vertices,
6108 indices: &level.indices(),
6109 // Level 0's range for every level, which is the
6110 // one the mesh path reads whichever level it
6111 // draws — see `Geometry::Dag::uv_range`.
6112 uv_range: *uv_range,
6113 // And the description's flags for every level,
6114 // for the same reason: the levels are one
6115 // surface, so a tangent frame either describes
6116 // all of them or none.
6117 flags: *flags,
6118 },
6119 )?);
6120 service();
6121 }
6122 uploaded.push(handles);
6123 }
6124 }
6125 }
6126
6127 pool.flush(device)?;
6128 service();
6129 // The table index is the only number that leaves here — where the
6130 // geometry actually is reaches the GPU through the mesh table, and the
6131 // draw arguments are built from that table by a shader. `MeshPool::mesh`
6132 // is still asked, because it is the call that refuses a mesh whose
6133 // upload has not completed, and an id for a mesh that is not there yet
6134 // would be a draw of nothing.
6135 let resolve = |handle| match (pool.mesh(handle), pool.table_index(handle)) {
6136 (Some(_), Some(id)) => Ok(id),
6137 _ => Err(MeshPoolError::NotResident { handle }),
6138 };
6139 let base_vertex = |handle| match pool.mesh(handle) {
6140 Some(range) => Ok(range.base_vertex),
6141 None => Err(MeshPoolError::NotResident { handle }),
6142 };
6143
6144 let mut residents = Vec::with_capacity(uploaded.len());
6145 for (desc, handles) in scene.meshes.iter().zip(&uploaded) {
6146 // **Relative to level 0's base**, because that is the base the
6147 // instance resolves through its mesh id and the one the stage adds
6148 // this on top of. A level that landed *below* level 0 would make the
6149 // sum wrap, so it is refused here rather than drawn as another
6150 // mesh's vertices. A flat mesh is one level and reads zero.
6151 let level_zero = base_vertex(handles[0])?;
6152 let mut vertex_bases = Vec::with_capacity(handles.len());
6153 for (depth, &handle) in handles.iter().enumerate() {
6154 let base = base_vertex(handle)?;
6155 vertex_bases.push(base.checked_sub(level_zero).ok_or_else(|| {
6156 HalError::InvalidDescriptor(format!(
6157 "{} level {depth} landed at vertex {base}, below level 0's \
6158 {level_zero}, so its clusters cannot name their own geometry",
6159 desc.label
6160 ))
6161 })?);
6162 }
6163 residents.push(ResidentMesh {
6164 levels: handles
6165 .iter()
6166 .map(|&handle| resolve(handle))
6167 .collect::<Result<_, _>>()?,
6168 vertex_bases,
6169 // Matched on the description rather than counted off `handles`,
6170 // so a DAG decimated to a single level is still refused: what
6171 // makes a mesh skinnable is that every draw of it reads one
6172 // vertex run, and that is a property of the geometry rather than
6173 // of how many levels it happened to arrive with.
6174 skinnable: matches!(desc.geometry, Geometry::Flat { .. }).then(|| handles[0]),
6175 });
6176 }
6177 Ok(residents)
6178 }
6179
6180 /// Rotates to the next frame's uniform buffer and instance buffer, writes
6181 /// this frame's camera and light into the first, and uploads whatever
6182 /// changed into the second.
6183 ///
6184 /// Must be called once per frame, before [`ForwardRenderer::add_passes`].
6185 /// Separate from `add_passes` because the write happens on the CPU and the
6186 /// passes are recorded on the GPU timeline: fusing them would hide the ring
6187 /// rotation inside a function whose name says nothing about it.
6188 ///
6189 /// **It moves nothing.** Every object's transform is the caller's, written
6190 /// through [`ForwardRenderer::set_instance`] whenever it changes, so the
6191 /// transfer this records is [`InstancePool::begin_frame`]'s delta and a
6192 /// frame in which nothing moved uploads no instance bytes at all. The
6193 /// sandbox's spinning cube is one 80-byte write a frame because the sandbox
6194 /// spins it; a still scene is free.
6195 ///
6196 /// It also writes this frame's **cull parameters** — the camera's frustum,
6197 /// extracted from the very same view-projection the uniform block carries,
6198 /// so the pass that decides what is on screen and the pass that draws it
6199 /// cannot be looking at two different cameras — and zeroes the counters the
6200 /// two compute passes only ever add to. See [`crate::draw_gen`] on why those
6201 /// zeroes come from the host.
6202 ///
6203 /// # Errors
6204 ///
6205 /// [`HalError`] if the uniform buffer, the instance buffer or any of the
6206 /// draw-generation buffers could not be written.
6207 pub fn begin_frame(
6208 &mut self,
6209 device: &dyn Device,
6210 camera: &Camera,
6211 light: &DirectionalLight,
6212 extent: (u32, u32),
6213 ) -> Result<(), HalError> {
6214 // The instance pool owns the ring, so its slot is the frame index the
6215 // uniform buffer and the bind group below are picked with.
6216 self.frame = self.instances.rotate();
6217 self.frame_skins = false;
6218 self.instances.flush(device)?;
6219 self.begin_frame_body(device, camera, light, extent)
6220 }
6221
6222 /// [`begin_frame`](Self::begin_frame) for a frame that **skins**: the same
6223 /// call with the skinning plan folded into it.
6224 ///
6225 /// It does four things in the one order that is correct, which is why it is
6226 /// a call and not a note in someone's docs:
6227 ///
6228 /// 1. rotates the instance ring, so the frame slot exists;
6229 /// 2. hands that slot and `ranges` to `skinning`, which validates them,
6230 /// uploads the palettes and **moves the ping-pong** — the only place the
6231 /// parity ever moves;
6232 /// 3. points every object placed by
6233 /// [`add_skinned_instance`](Self::add_skinned_instance) at the half of its
6234 /// region the parity now names;
6235 /// 4. uploads the instance delta, so those bases are the ones this frame
6236 /// draws.
6237 ///
6238 /// Do those three and four in the other order and the objects carry the
6239 /// previous frame's half — a character posed one frame late, every frame,
6240 /// with nothing to report it. A caller never sees a parity or a table id, and
6241 /// so cannot get that wrong.
6242 ///
6243 /// Build `ranges` with [`SkinnedMesh::skin_range`], one per reserved region
6244 /// this frame animates. A frame with **no** skinned object still calls this
6245 /// with an empty slice — see [`Skinning::begin_frame`], whose slot would
6246 /// otherwise re-dispatch whichever frame last used it.
6247 ///
6248 /// [`add_skinned_passes`](Self::add_skinned_passes) is the other half, and
6249 /// the one that orders the dispatch before the draws.
6250 ///
6251 /// # Errors
6252 ///
6253 /// Whatever [`Skinning::begin_frame`] refuses — a joint index past its
6254 /// palette, a binding count that is not the region's vertex count, more than
6255 /// the pass was built for — and [`SkinningError::Hal`] for anything the seam
6256 /// refused, this renderer's own uniform and instance writes included.
6257 ///
6258 /// # Panics
6259 ///
6260 /// If `skinning` was not built with at least [`FRAMES_IN_FLIGHT`] frames:
6261 /// its rings are indexed by this renderer's frame slot, and
6262 /// [`Skinning::begin_frame`] refuses a slot it has no buffers for.
6263 pub fn begin_skinned_frame(
6264 &mut self,
6265 device: &dyn Device,
6266 skinning: &mut Skinning,
6267 ranges: &[SkinRange<'_>],
6268 camera: &Camera,
6269 light: &DirectionalLight,
6270 extent: (u32, u32),
6271 ) -> Result<(), SkinningError> {
6272 self.frame = self.instances.rotate();
6273 // An empty plan dispatches nothing — see [`Skinning::begin_frame`] — so
6274 // it leaves the vertex pool where it was, and the shadow atlas with it.
6275 self.frame_skins = !ranges.is_empty();
6276 skinning.begin_frame(device, self.frame, ranges)?;
6277 self.point_skinned_instances(skinning.parity());
6278 self.instances.flush(device)?;
6279 self.begin_frame_body(device, camera, light, extent)?;
6280 Ok(())
6281 }
6282
6283 /// Whether this frame records the irradiance probes' two
6284 /// updater passes.
6285 ///
6286 /// The scene's own answer and the console's together: the volume decides
6287 /// whether the feature applies at all — see [`ProbeUpdate`], which is where
6288 /// the reason it is not an effect bit lives — and `r_probe_bounce` is the
6289 /// on/off pair a pricing run reads the two passes' cost off with everything
6290 /// else held still.
6291 ///
6292 /// **It is not the whole condition.** The map is cascade 0's own draws, so
6293 /// the pass is recorded only where that cascade is being drawn too — see
6294 /// `add_shadow_pass`, which is where the rest of it is.
6295 fn probe_update_runs(&self) -> bool {
6296 self.probe_update == ProbeUpdate::EveryFrame && rsm::enabled()
6297 }
6298
6299 /// The six side-plane sets a point light's face culls test, or `None` for
6300 /// a light that is not a point — or with the face culls switched off, which
6301 /// is one cull against the light's box drawn into all six faces.
6302 ///
6303 /// `faces` are the light's face matrices in face order, the ones its tiles
6304 /// render through.
6305 fn point_face_planes(&self, light: &Light, faces: &[Mat4]) -> Option<crate::cull::FacePlanes> {
6306 if !self.point_face_culls || !matches!(light, Light::Point(_)) {
6307 return None;
6308 }
6309 let matrices: [Mat4; shadow::POINT_FACES] = faces.try_into().ok()?;
6310 Some(crate::cull::face_planes(&matrices))
6311 }
6312
6313 /// Every punctual shadow face this frame draws into the punctual reflective
6314 /// shadow map, in the order the pass draws them and the producer table lists
6315 /// them.
6316 ///
6317 /// **One list for both halves of the updater**, and that is the point:
6318 /// `add_shadow_pass` sets a viewport from a face's
6319 /// [`tile`](PunctualFace::tile) and the gather reads that same rectangle out
6320 /// of the matching producer row, so a face the pass drew and a row the
6321 /// gather walked have to be the same face. Building the two from separate
6322 /// filters is two things that can drift, and the drift would be a light
6323 /// bouncing another light's map.
6324 ///
6325 /// **The occupied slots this frame redraws**, which is the same set
6326 /// `add_shadow_pass` gives the atlas: a face's transform is a shadow view's
6327 /// block and its draws are a shadow cull's, and
6328 /// [`Self::begin_frame_body`](Self::begin_frame) writes neither for a slot
6329 /// it is holding.
6330 ///
6331 /// # Every occupied tile, and no budget of its own
6332 ///
6333 /// The producers are exactly the atlas's occupied faces — up to
6334 /// [`shadow::LIGHT_SLOTS`] lights and [`shadow::LIGHT_TILES`] tiles between
6335 /// them — rather than the highest-ranked light or some smaller count.
6336 ///
6337 /// **Because the budget already exists and is spent.**
6338 /// [`shadow::Selection`] has ranked these lights by projected screen
6339 /// influence and handed out every tile there is; a second budget on top
6340 /// would rank the same lights again, differently, and produce a light that
6341 /// casts a shadow and lends no bounce. That is a difference no picture shows
6342 /// — the same argument [`Self::shadow_lights`] makes about a map's size —
6343 /// and it is the kind of quiet inconsistency the two halves of one light are
6344 /// worst placed to have.
6345 ///
6346 /// It is affordable at the extent that was chosen for it:
6347 /// `apps/lantern` lights seven faces, and
6348 /// [`PUNCTUAL_RSM_SIDE`](crcbl_shaders::probe_gather::PUNCTUAL_RSM_SIDE)
6349 /// carries the sweep that priced them.
6350 ///
6351 /// **Empty where shadows are off**, for that same reason — a punctual face
6352 /// *is* a shadow view. The sun's half is not, which is what
6353 /// `updater_drives_cascade_zero` exists for: switching shadows off keeps the
6354 /// sun's bounce and loses every punctual one, rather than switching the
6355 /// whole updater off with them.
6356 fn punctual_faces(&self) -> Vec<PunctualFace> {
6357 if !self.probe_update_runs() {
6358 return Vec::new();
6359 }
6360 // A frame with the shadows switched off draws no atlas, so no group of
6361 // it is *redrawn* — and `begin_frame_body`'s `updater_drives_cascade_zero`
6362 // branch has still written every one of these views and dispatched every
6363 // one of these culls, for this pass to draw through.
6364 let updater_drives = !self.frame_effects.contains(RenderEffects::SHADOWS);
6365 let mut faces = Vec::new();
6366 for (slot, held) in self.shadow_lights.slots().iter().enumerate() {
6367 let Some(held) = *held else {
6368 continue;
6369 };
6370 if !updater_drives && !self.shadow_group_redrawn[shadow_cull(slot)] {
6371 continue;
6372 }
6373 let Some(light) = self.extra_lights.get(held.light) else {
6374 continue;
6375 };
6376 // A spot draws face 0 alone and a point light all six, each through
6377 // its own matrix into its own tile — `shadow::tile_span` is the same
6378 // function `Selection` allocated the run with, so a face here and a
6379 // tile there cannot disagree about how many there are.
6380 for face in 0..shadow::tile_span(light) {
6381 let tile = rsm::punctual_tile(held.base + face);
6382 faces.push(PunctualFace {
6383 view: shadow_view(slot, face),
6384 cull: shadow_cull(slot),
6385 face,
6386 tile,
6387 producer: producer_row(light, tile),
6388 });
6389 }
6390 }
6391 faces
6392 }
6393
6394 /// Puts an object in the scene and returns the handle that names it.
6395 ///
6396 /// An instance in the pool **is** an object in the scene: the frame records
6397 /// a fixed number of draws and the cull pass decides which instances they
6398 /// walk, so adding one costs a slot in an array and not a command. It is
6399 /// drawn from the next [`ForwardRenderer::begin_frame`], which is what
6400 /// uploads it.
6401 ///
6402 /// # The index it lands at is not decoration
6403 ///
6404 /// `draw_gen.slang` keys topic 25's hysteresis state by the
6405 /// instance's **array index**, at `instance_index * group_stride`, and
6406 /// `mesh_cluster.slang`'s amplification stage reads the same address. So the
6407 /// record of which of a DAG's groups an object had expanded belongs to the
6408 /// *slot*, not to the object — and a slot that [`remove_instance`] freed is
6409 /// handed to the next `add_instance`, which inherits it. What that costs is
6410 /// one frame selected against a history that is not this object's, and the
6411 /// next frame's own judgement replaces it; it is never a wrong picture,
6412 /// because every group is judged afresh whatever the state said.
6413 ///
6414 /// That inheritance is inert while the scene holds **one** instance of a DAG
6415 /// mesh, which is every frame the engine has drawn so far — one instance's
6416 /// run has no previous occupant, and a flat mesh's
6417 /// [`MeshLevels`](level_select::MeshLevels) record names no groups at all, so
6418 /// nothing indexes the state for it. It stops being inert the moment an
6419 /// application places a second.
6420 ///
6421 /// [`remove_instance`]: ForwardRenderer::remove_instance
6422 ///
6423 /// # A DAG mesh needs a device that can choose a level
6424 ///
6425 /// One device shape cannot draw a [`Geometry::Dag`] mesh: a mesh stage with
6426 /// **no** amplification stage in front of it emits every cluster of the
6427 /// bucket, which for a DAG is every level at once — several overlapping
6428 /// copies of one surface. This does not refuse it, because it has no
6429 /// vocabulary for that refusal; a caller placing a DAG asks
6430 /// [`ForwardRenderer::selects_levels`] first, and places it only where that
6431 /// says yes. A flat mesh is unaffected on every path.
6432 ///
6433 /// # Errors
6434 ///
6435 /// [`InstancePoolError::PoolFull`] when the instance pool is full. It never
6436 /// grows — [`Capacities::instances`](crate::scene::Capacities::instances) is
6437 /// what a caller sizes it with.
6438 ///
6439 /// # Panics
6440 ///
6441 /// If [`InstanceDesc::mesh`] or [`InstanceDesc::material`] is past the end of
6442 /// the description this renderer was built from. Both are indices a caller
6443 /// wrote against a description it holds, so an out-of-range one is a mistake
6444 /// in the calling code rather than a condition the frame can be in — and the
6445 /// alternative is an object silently drawn as some other mesh, in some other
6446 /// colour.
6447 pub fn add_instance(
6448 &mut self,
6449 desc: &InstanceDesc,
6450 ) -> Result<InstanceHandle, InstancePoolError> {
6451 let instance = self.gpu_instance(desc);
6452 self.instances.insert(&instance)
6453 }
6454
6455 /// Rewrites the object `handle` names — its mesh, its material and its
6456 /// transform, all three.
6457 ///
6458 /// A stale handle — one [`ForwardRenderer::remove_instance`] retired — writes
6459 /// nothing, rather than overwriting whatever took its slot.
6460 ///
6461 /// Takes effect at the next [`ForwardRenderer::begin_frame`], which uploads
6462 /// the element and nothing else: an object that did not move costs no
6463 /// transfer at all.
6464 ///
6465 /// # Panics
6466 ///
6467 /// On [`ForwardRenderer::add_instance`]'s terms, for the same reason.
6468 pub fn set_instance(&mut self, handle: InstanceHandle, desc: &InstanceDesc) {
6469 let mut instance = self.gpu_instance(desc);
6470 instance.flags |= self.kept_flags(handle);
6471 self.instances.set(handle, &instance);
6472 }
6473
6474 /// The bits of `handle`'s record a rewrite of it keeps: its hidden views
6475 /// and whether it casts — see [`ForwardRenderer::set_instance_views`] and
6476 /// [`ForwardRenderer::set_instance_casts_shadow`]. Zero for a stale
6477 /// handle, whose rewrite writes nothing anyway.
6478 fn kept_flags(&self, handle: InstanceHandle) -> u32 {
6479 self.instances.get(handle).map_or(0, |record| {
6480 record.flags
6481 & (mesh::GpuInstance::HIDDEN_VIEWS_MASK | mesh::GpuInstance::CASTS_NO_SHADOW)
6482 })
6483 }
6484
6485 /// Sets whether `handle` casts a shadow. Every instance starts casting.
6486 ///
6487 /// **Every shadow map and nothing else**: an instance that casts none is
6488 /// rejected by the cull of the sun's cascades and of every shadowed light,
6489 /// on every geometry path, so it lands in no tile of the atlas — and in no
6490 /// reflective shadow map, which draws those same culls' survivors, so it
6491 /// bounces no light into the probes either. Every camera still draws it,
6492 /// and it still receives the shadows the rest of the scene casts.
6493 ///
6494 /// What a model drawn for an icon wants, placed where the scene's sun can
6495 /// see it: see [`ViewBackground::Transparent`] and
6496 /// [`set_instance_views`](Self::set_instance_views).
6497 ///
6498 /// A change redraws every shadow map whose cull the instance could be kept
6499 /// by, because it is a write [`InstancePool::take_written`] names. Not a
6500 /// move, on
6501 /// [`set_instance_views`](Self::set_instance_views)' terms, and a stale
6502 /// handle is ignored.
6503 pub fn set_instance_casts_shadow(&mut self, handle: InstanceHandle, casts: bool) {
6504 if let Some(record) = self.instances.get(handle) {
6505 let flags = if casts {
6506 record.flags & !mesh::GpuInstance::CASTS_NO_SHADOW
6507 } else {
6508 record.flags | mesh::GpuInstance::CASTS_NO_SHADOW
6509 };
6510 self.instances.set_flags(handle, flags);
6511 }
6512 }
6513
6514 /// Whether `handle` casts a shadow, or `None` for a stale handle.
6515 #[must_use]
6516 pub fn instance_casts_shadow(&self, handle: InstanceHandle) -> Option<bool> {
6517 self.instances
6518 .get(handle)
6519 .map(|record| record.flags & mesh::GpuInstance::CASTS_NO_SHADOW == 0)
6520 }
6521
6522 /// Takes the object `handle` names back out of the scene, freeing its slot.
6523 ///
6524 /// **A removal is a cleared live bit, not a skipped draw**, because the frame
6525 /// no longer records a draw per object: `cull.slang` asks whether an instance
6526 /// is live before it reads anything else, so removing an object and culling
6527 /// it off screen take the same path out of the frame. An instance left in the
6528 /// pool would be drawn wherever its transform put it.
6529 ///
6530 /// A stale handle removes nothing. Takes effect at the next
6531 /// [`ForwardRenderer::begin_frame`], on
6532 /// [`ForwardRenderer::set_instance`]'s terms.
6533 pub fn remove_instance(&mut self, handle: InstanceHandle) {
6534 self.instances.remove(handle);
6535 }
6536
6537 /// Captures a visibility map for every probe, from the static geometry
6538 /// standing in the scene right now.
6539 ///
6540 /// The probe visibility rung: each probe records how far
6541 /// away the nearest surface is in every direction, and `mesh.slang`'s
6542 /// `probe_irradiance` then weighs each of a fragment's eight probes by
6543 /// whether it can *see* that fragment — so a probe on the far side of a wall
6544 /// contributes nothing and a room stops lighting the room next door.
6545 /// This crate's own `probe_capture` module is the pass, `probe_visibility`
6546 /// is the geometry it draws, and [`crcbl_shaders::probe_visibility`] is the
6547 /// format.
6548 ///
6549 /// # Call it once, after the scene's walls are placed
6550 ///
6551 /// **A description carries no instances** — [`SceneDesc`] is meshes,
6552 /// materials, a page and the probe rows, and the objects arrive afterwards
6553 /// through [`ForwardRenderer::add_instance`] — so there is nothing for a
6554 /// capture inside [`ForwardRenderer::with_scene`] to be about. This is the
6555 /// call that has the room in it, and an application makes it once its static
6556 /// geometry is placed.
6557 ///
6558 /// A caller that never makes it draws exactly the frame this renderer drew
6559 /// before the maps existed: every group names the one-texel placeholder,
6560 /// which no surface is further away than, and every probe keeps all of its
6561 /// weight.
6562 ///
6563 /// **It is a capture of geometry and not a bake of light.** Nothing about
6564 /// the lights is recorded, every one of them still moves, and the rows the
6565 /// probes carry are untouched.
6566 ///
6567 /// # What it sees, and what it does not
6568 ///
6569 /// Every instance live in the pool when it is called, at the transform it
6570 /// then has, rasterised from its mesh's level-0 triangles into six 90°
6571 /// faces per probe. Objects that move
6572 /// afterwards keep the occlusion they had here, which is the accepted limit
6573 /// this technique has everywhere it is used — a probe volume is about the
6574 /// walls. Recapturing after a wall moves is this call again.
6575 ///
6576 /// **The device must be idle.** The previous capture's image is released
6577 /// here, and a frame in flight may still be reading it.
6578 ///
6579 /// # Errors
6580 ///
6581 /// [`HalError`] from the capture. The previous maps are kept on the failing
6582 /// path, so a renderer that has captured once and then failed goes on
6583 /// drawing with what it had.
6584 pub fn capture_probe_visibility(
6585 &mut self,
6586 device: &dyn Device,
6587 queue: QueueHandle,
6588 ) -> Result<(), HalError> {
6589 let placed: Vec<crate::probe_visibility::Occluder> = self
6590 .instances
6591 .live()
6592 .into_iter()
6593 .map(|record| crate::probe_visibility::Occluder {
6594 mesh: record.mesh,
6595 transform: Mat4::from_cols_array(&record.transform),
6596 })
6597 .collect();
6598 let Some(uploaded) = crate::probe_capture::capture(
6599 device,
6600 queue,
6601 &self.probe_volume,
6602 &self.probe_occluders,
6603 &placed,
6604 )?
6605 else {
6606 // No probes, or nothing placed for a map to be about. Leaving the
6607 // placeholder bound is the honest answer, and it is what a scene
6608 // with no probes has always read.
6609 return Ok(());
6610 };
6611 // The cached groups name the view this replaces, so they go before it
6612 // does — a bind group outliving the image it names is a validation
6613 // error on every backend that checks, and a use-after-free on the ones
6614 // that do not.
6615 for slot in &mut self.primary.screen_channel_groups {
6616 if let Some((_, stale)) = slot.take() {
6617 device.destroy_bind_group(stale);
6618 }
6619 }
6620 if let Some(previous) = self.probe_visibility.replace(uploaded) {
6621 previous.destroy(device);
6622 }
6623 Ok(())
6624 }
6625
6626 /// Re-centres the irradiance clipmap on `point` by whole probe steps, and
6627 /// captures the probes the step exposed.
6628 ///
6629 /// The irradiance probes' scrolling: each level moves a whole
6630 /// number of its own probe spacings towards `point`, so the probes that stay
6631 /// inside it stand exactly where they stood and go on being addressed at the
6632 /// rows they already had — and only the slabs the step brought in are
6633 /// captured. Answers how many rows that was, which is **zero for the
6634 /// ordinary frame**: the point has to travel half a probe spacing before the
6635 /// nearest whole step changes at all.
6636 ///
6637 /// [`ProbeVolume::follow`](crcbl_shaders::probe::ProbeVolume::follow) is the
6638 /// rule and `exposed` beside it is the invalidation; this is the two of them
6639 /// plus the device work they imply — the visibility maps of the exposed
6640 /// rows, and the position table the reflective-shadow-map gather reads.
6641 ///
6642 /// # A volume authored to cover its whole world does not move
6643 ///
6644 /// The steps are the ones that centre a level on `point`, and a caller whose
6645 /// volume is already the world it is in wants none of them — so a caller
6646 /// passes the point it wants the *centre* at rather than the camera outright
6647 /// when the two differ. `apps/lantern` and `apps/shard` are that case and
6648 /// their own modules say so.
6649 ///
6650 /// # A step stalls, and a frame that does not step costs a comparison
6651 ///
6652 /// The recapture is [`ForwardRenderer::capture_probe_visibility`]'s pass
6653 /// over fewer rows, and it waits on [`Device::wait_idle`] exactly as that
6654 /// one does — so a step drains the device before it rewrites anything and
6655 /// leaves it drained. That is a stall, and it is why the probe records price a step
6656 /// separately from a frame. A call that steps nothing returns before the
6657 /// wait, so the ordinary frame pays a rounding per level and per axis and
6658 /// nothing else.
6659 ///
6660 /// It may therefore be called from a frame loop, but **not after**
6661 /// [`ForwardRenderer::begin_frame`] has been called for the frame being
6662 /// recorded: the header it moves is the one that frame's uniform block has
6663 /// already been written from.
6664 ///
6665 /// A renderer that has never captured re-centres the header and captures
6666 /// nothing: there is no image to write slabs into, every group still names
6667 /// the placeholder, and the first
6668 /// [`ForwardRenderer::capture_probe_visibility`] covers the scrolled volume
6669 /// whole.
6670 ///
6671 /// # It moves the geometry and not the light
6672 ///
6673 /// What a step re-captures is the *visibility* of the probes it exposed,
6674 /// which is what the maps are about. The **rows** are not touched, so under
6675 /// [`ProbeUpdate::Authored`] a probe
6676 /// that a step brought in keeps the irradiance the probe that left had —
6677 /// authored for somewhere else. A volume that scrolls therefore wants
6678 /// [`ProbeUpdate::EveryFrame`], whose
6679 /// gather refills every row from the scene each frame and has no such gap;
6680 /// `docs/backlog.md` carries what an authored one would need instead.
6681 ///
6682 /// # Errors
6683 ///
6684 /// [`HalError`] from the recapture or from the position rewrite. The volume
6685 /// keeps the steps it had on either failing path, so a renderer that could
6686 /// not capture a slab does not go on drawing with rows about somewhere else.
6687 pub fn follow_probe_volume(
6688 &mut self,
6689 device: &dyn Device,
6690 queue: QueueHandle,
6691 point: [f32; 3],
6692 ) -> Result<u32, HalError> {
6693 let mut moved = self.probe_volume;
6694 let rows = moved.follow(point);
6695 if rows.is_empty() && moved.steps == self.probe_volume.steps {
6696 return Ok(0);
6697 }
6698 // **Before anything is written**, so a caller may make this call from
6699 // its frame loop: the layers the recapture rewrites and the position
6700 // table beside them are read by whatever frames are still in flight, and
6701 // neither is a ring. A frame that does not step never reaches this line,
6702 // which is what keeps the ordinary frame free of it.
6703 device.wait_idle()?;
6704 if let Some(captured) = &self.probe_visibility {
6705 let placed: Vec<crate::probe_visibility::Occluder> = self
6706 .instances
6707 .live()
6708 .into_iter()
6709 .map(|record| crate::probe_visibility::Occluder {
6710 mesh: record.mesh,
6711 transform: Mat4::from_cols_array(&record.transform),
6712 })
6713 .collect();
6714 crate::probe_capture::recapture(
6715 device,
6716 queue,
6717 &moved,
6718 &self.probe_occluders,
6719 &placed,
6720 &rows,
6721 captured.image,
6722 )?;
6723 }
6724 // After the capture, so a volume whose slabs could not be drawn keeps
6725 // the header its maps are about.
6726 if let Some(gather) = &self.probe_gather {
6727 gather.rewrite_positions(device, &moved)?;
6728 }
6729 self.probe_volume = moved;
6730 Ok(u32::try_from(rows.len()).unwrap_or(u32::MAX))
6731 }
6732
6733 /// Where the irradiance clipmap stands right now — the header the frame
6734 /// block carries, [`ForwardRenderer::follow_probe_volume`]'s scroll
6735 /// included.
6736 #[must_use]
6737 pub const fn probe_volume(&self) -> crcbl_shaders::probe::ProbeVolume {
6738 self.probe_volume
6739 }
6740
6741 /// `draws` split by the **whole** material mode, each partition under the
6742 /// depth-only pipeline that honours it — what the depth prepass and every
6743 /// shadow view record instead of one call list under one pipeline.
6744 ///
6745 /// Four pipelines for [`DEPTH_MODES`]' four values, which is what makes the
6746 /// split total: the opaque buckets are drawn with
6747 /// [`shadow_pipeline`](Self::shadow_pipeline) — `depthVertexMain` and no
6748 /// fragment stage — the masked ones with
6749 /// [`depth_masked_pipeline`](Self::depth_masked_pipeline), which can
6750 /// `discard`, and each of those has a [`CullMode::None`] twin for the
6751 /// buckets whose material is double-sided. A scene with one cutout in it
6752 /// pays a fragment stage for that mesh's draws and for no others; before
6753 /// this it paid for the whole frame, which on lavapipe roughly doubled the
6754 /// prepass and added two thirds to the shadow pass.
6755 ///
6756 /// **Both depth passes and not just the atlas.** A double-sided plate whose
6757 /// back face the prepass culled writes no depth there, so the colour pass's
6758 /// `GreaterOrEqual` test against it rejects the fragment and the surface is
6759 /// missing from the frame; and a cascade that culled it casts no shadow.
6760 fn depth_partitions(&self, draws: &BucketDraws) -> Vec<BucketDraws> {
6761 self.partitions(
6762 draws,
6763 mesh::GpuMaterial::MODE_MASK,
6764 &[
6765 (DEPTH_MODES[0], self.shadow_pipeline.single),
6766 (DEPTH_MODES[1], self.depth_masked_pipeline.single),
6767 (DEPTH_MODES[2], self.shadow_pipeline.double),
6768 (DEPTH_MODES[3], self.depth_masked_pipeline.double),
6769 ],
6770 )
6771 }
6772
6773 /// `draws` split by the material's **side** alone, each partition under the
6774 /// matching half of `pipelines` — what the colour pass and the two
6775 /// reflective shadow maps record.
6776 ///
6777 /// Two partitions where [`depth_partitions`](Self::depth_partitions) has
6778 /// four, and the difference is the whole of what these passes do not care
6779 /// about: their pipelines carry a fragment stage either way and cut the
6780 /// alpha mask inside it, so a masked bucket and an opaque one are the same
6781 /// draw here. What they cannot express inside the stage is the cull mode.
6782 fn sided_partitions(&self, draws: &BucketDraws, pipelines: SidedPipelines) -> Vec<BucketDraws> {
6783 self.partitions(
6784 draws,
6785 mesh::GpuMaterial::DOUBLE_SIDED,
6786 &[
6787 (0, pipelines.single),
6788 (mesh::GpuMaterial::DOUBLE_SIDED, pipelines.double),
6789 ],
6790 )
6791 }
6792
6793 /// Resolves a description's mesh and material indices into the table ids the
6794 /// GPU reads.
6795 ///
6796 /// The whole record every time, because [`InstancePool::set`] writes the
6797 /// whole record: an instance that lost either id would name entry 0 of that
6798 /// table, which is a mesh and a material rather than an absence.
6799 fn gpu_instance(&self, desc: &InstanceDesc) -> mesh::GpuInstance {
6800 mesh::GpuInstance {
6801 transform: desc.transform.to_cols_array(),
6802 mesh: self.mesh_ids[desc.mesh],
6803 material: self.material_ids[desc.material],
6804 flags: self.material_mode_bits(desc.material),
6805 ..mesh::GpuInstance::default()
6806 }
6807 }
6808
6809 /// The material mode of description material `material`, in the bits an
6810 /// instance record carries it in.
6811 ///
6812 /// **Read out of the table rather than out of the description**, because the
6813 /// table is what a `set` would move and the row is what the shader shades
6814 /// through. It is the other half of the record's routing key: `draw_gen`
6815 /// buckets an instance by [`mesh`](mesh::GpuInstance::mesh) and by this,
6816 /// which is how a masked material costs a fragment stage in the depth passes
6817 /// for its own mesh alone.
6818 ///
6819 /// The mode is captured **here**, when the record is written — see
6820 /// [`GpuInstance::MATERIAL_MODE_SHIFT`](mesh::GpuInstance::MATERIAL_MODE_SHIFT)
6821 /// for what that means for a material rewritten afterwards.
6822 fn material_mode_bits(&self, material: usize) -> u32 {
6823 self.materials.mode(self.material_ids[material]) << mesh::GpuInstance::MATERIAL_MODE_SHIFT
6824 }
6825
6826 // --- skinning: reserving the region, placing the object, ordering the
6827 // dispatch ---
6828
6829 /// The vertex pool every mesh here is resident in — what
6830 /// [`SkinningDesc::vertices`](crate::skinning::SkinningDesc::vertices)
6831 /// takes.
6832 ///
6833 /// The skinning pass reads a bind pose out of this buffer and writes the
6834 /// deformed vertices back into another run of it, which is what makes a
6835 /// skinned draw an ordinary draw. It must be *this* pool's buffer: a
6836 /// [`Skinning`] built against any other writes vertices no draw here can
6837 /// reach.
6838 #[must_use]
6839 pub const fn vertex_buffer(&self) -> BufferHandle {
6840 self.pool.vertex_buffer()
6841 }
6842
6843 /// Where that pool's **attribute** region begins, in words — what
6844 /// [`SkinningDesc::attribute_base`](crate::skinning::SkinningDesc::attribute_base)
6845 /// takes.
6846 ///
6847 /// The buffer holds two streams, so a pass that writes it needs the
6848 /// boundary as well as the handle; a [`Skinning`] built with the wrong one
6849 /// writes a mesh's attributes over another mesh's positions. See
6850 /// [`MeshPool::attribute_base`](crate::MeshPool::attribute_base).
6851 #[must_use]
6852 pub const fn attribute_base(&self) -> u32 {
6853 self.pool.attribute_base()
6854 }
6855
6856 /// Reserves a skinned region for description mesh `mesh`.
6857 ///
6858 /// The whole of what a caller needs to skin something, in one value: hand
6859 /// [`SkinnedMesh::skin_range`] a palette and a set of bindings to get the
6860 /// frame's [`SkinRange`], hand the result to
6861 /// [`begin_skinned_frame`](Self::begin_skinned_frame), and place it with
6862 /// [`add_skinned_instance`](Self::add_skinned_instance). The bases and the
6863 /// parity never have to be spelled by the caller at all — see
6864 /// [`crate::skinning::SkinnedMesh`], where the ping-pong lives.
6865 ///
6866 /// **The mesh keeps its own entry and the region takes none**, so the same
6867 /// description mesh can be drawn skinned through this and in its bind pose
6868 /// through [`add_instance`](Self::add_instance) in the same frame, both
6869 /// resolving through the one table entry it already had.
6870 ///
6871 /// Give it back with [`release_skinned`](Self::release_skinned).
6872 ///
6873 /// # Errors
6874 ///
6875 /// Whatever [`SkinnedMesh::reserve`] refuses: a vertex pool with no room for
6876 /// both halves. **Two vertex runs per skinned primitive** is what a scene's
6877 /// [`Capacities`](crate::scene::Capacities) has to have been sized for.
6878 ///
6879 /// # Panics
6880 ///
6881 /// If `mesh` is past the end of the description this renderer was built
6882 /// from, on [`add_instance`](Self::add_instance)'s terms — and if it names a
6883 /// [`Geometry::Dag`], which cannot be drawn out of a skinned region at all.
6884 /// A DAG is refused rather than skinned wrongly: its coarser levels are
6885 /// separate vertex runs no dispatch writes, so a cut that descended past
6886 /// level 0 would draw whatever the pool happened to be holding there.
6887 pub fn reserve_skinned(&mut self, mesh: usize) -> Result<SkinnedMesh, MeshPoolError> {
6888 let source = self.skinnable_meshes[mesh].unwrap_or_else(|| {
6889 panic!(
6890 "description mesh {mesh} is a Geometry::Dag, whose coarser levels are vertex \
6891 runs no skinning dispatch writes; only a flat mesh can be skinned"
6892 )
6893 });
6894 SkinnedMesh::reserve(&mut self.pool, source)
6895 }
6896
6897 /// Gives `skinned`'s region back to the vertex pool.
6898 ///
6899 /// The device must not still be drawing it: this records no barrier, on
6900 /// [`SkinnedMesh::release`]'s terms. Objects placed through it are **not**
6901 /// removed — [`remove_instance`](Self::remove_instance) is what does that,
6902 /// and an instance left behind goes on drawing its source mesh's geometry
6903 /// out of vertices the pool has handed back. Remove the objects first.
6904 pub fn release_skinned(&mut self, skinned: SkinnedMesh) {
6905 skinned.release(&mut self.pool);
6906 }
6907
6908 /// Places a skinned object in the scene.
6909 ///
6910 /// [`add_instance`](Self::add_instance) with a reserved region in place of a
6911 /// description mesh. The renderer keeps the object in a list of its own and
6912 /// **re-points it every [`begin_skinned_frame`](Self::begin_skinned_frame)**
6913 /// at the half of the region that frame's dispatch fills, so the parity is
6914 /// never something a caller writes.
6915 ///
6916 /// A skinned object driven by plain [`begin_frame`](Self::begin_frame) is
6917 /// therefore left pointing wherever it last was, which after the first frame
6918 /// is the pose of the frame before — the reason the two entry points are
6919 /// separate calls rather than a flag.
6920 ///
6921 /// # Errors
6922 ///
6923 /// [`InstancePoolError::PoolFull`], on
6924 /// [`add_instance`](Self::add_instance)'s terms.
6925 ///
6926 /// # Panics
6927 ///
6928 /// If [`SkinnedInstanceDesc::material`] is past the end of the description
6929 /// this renderer was built from, on
6930 /// [`add_instance`](Self::add_instance)'s terms.
6931 pub fn add_skinned_instance(
6932 &mut self,
6933 desc: &SkinnedInstanceDesc<'_>,
6934 ) -> Result<InstanceHandle, InstancePoolError> {
6935 // Parity zero, and it never reaches the GPU as such: the instance pool
6936 // uploads by delta at `begin_skinned_frame`, which re-points every entry
6937 // of the list below before it flushes. What this writes is the rest of
6938 // the record.
6939 let instance = self.skinned_gpu_instance(desc, 0);
6940 let handle = self.instances.insert(&instance)?;
6941 self.skinned_instances.push(SkinnedInstance {
6942 handle,
6943 bases: skinned_bases(desc.mesh),
6944 pointed: false,
6945 });
6946 Ok(handle)
6947 }
6948
6949 /// Rewrites the skinned object `handle` names — its region, its material and
6950 /// its transform.
6951 ///
6952 /// [`set_instance`](Self::set_instance) for an object placed by
6953 /// [`add_skinned_instance`](Self::add_skinned_instance), and the call a
6954 /// character's transform changes through. A stale handle writes nothing.
6955 ///
6956 /// Passing a handle this renderer has never seen skinned adopts it: the
6957 /// object joins the re-pointed list from here on. That is what lets a caller
6958 /// swap a bind-pose instance over to a region without removing and replacing
6959 /// it.
6960 ///
6961 /// # Panics
6962 ///
6963 /// On [`add_skinned_instance`](Self::add_skinned_instance)'s terms.
6964 pub fn set_skinned_instance(&mut self, handle: InstanceHandle, desc: &SkinnedInstanceDesc<'_>) {
6965 let mut instance = self.skinned_gpu_instance(desc, 0);
6966 instance.flags |= self.kept_flags(handle);
6967 if !self.instances.set(handle, &instance) {
6968 return;
6969 }
6970 let bases = skinned_bases(desc.mesh);
6971 match self
6972 .skinned_instances
6973 .iter_mut()
6974 .find(|entry| entry.handle == handle)
6975 {
6976 // **A different region is a fresh entry.** The half this object has
6977 // never been drawn out of holds whatever its reservation came with,
6978 // so the next pointing owes it rest rather than a previous
6979 // deformation — see [`SkinnedInstance::pointed`]. The pair of bases
6980 // is what "different" means here: two calls naming one region give
6981 // the same two runs, so rewriting an object's material or transform
6982 // is not a change of region.
6983 Some(entry) => {
6984 entry.pointed &= entry.bases == bases;
6985 entry.bases = bases;
6986 }
6987 None => self.skinned_instances.push(SkinnedInstance {
6988 handle,
6989 bases,
6990 pointed: false,
6991 }),
6992 }
6993 }
6994
6995 /// A skinned object's record, at one parity — [`gpu_instance`](Self::gpu_instance)
6996 /// with the region's base vertex carried in the record and the bit that says
6997 /// to read it.
6998 ///
6999 /// The mesh id is the **source** mesh's, not a second entry's, so the bucket
7000 /// this instance is scattered into, the levels it selects through and the
7001 /// box it is culled against are the ones the undeformed mesh already had.
7002 fn skinned_gpu_instance(
7003 &self,
7004 desc: &SkinnedInstanceDesc<'_>,
7005 parity: u32,
7006 ) -> mesh::GpuInstance {
7007 let base_vertex = desc.mesh.region().base(parity);
7008 mesh::GpuInstance {
7009 transform: desc.transform.to_cols_array(),
7010 mesh: desc.mesh.mesh_id(),
7011 material: self.material_ids[desc.material],
7012 // The override bit **and** the material mode: a skinned instance is
7013 // routed by the same key as a rigid one, so a skinned cutout lands
7014 // in its mesh's masked bucket rather than in the opaque twin.
7015 flags: mesh::GpuInstance::BASE_VERTEX_OVERRIDE | self.material_mode_bits(desc.material),
7016 base_vertex,
7017 // At rest, which is what a record this call writes has to be: the
7018 // object has not been drawn out of this region yet, so the other
7019 // half holds whatever its reservation came with. A frame that runs
7020 // [`point_skinned_instances`](Self::point_skinned_instances) is
7021 // what starts pointing this at the half before.
7022 previous_base_vertex: base_vertex,
7023 ..mesh::GpuInstance::default()
7024 }
7025 }
7026
7027 /// Points every skinned object at the half of its region a frame of this
7028 /// parity fills **and at the half the frame before it filled**, and forgets
7029 /// the ones whose instance has gone.
7030 ///
7031 /// Called between the instance ring's rotation and its upload, which is the
7032 /// whole reason those two are separate calls — see
7033 /// [`InstancePool::rotate`](crate::instance_pool::InstancePool::rotate).
7034 ///
7035 /// The second base is what a skinned fragment's motion vector is subtracted
7036 /// against — see
7037 /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
7038 /// **A region this frame's `ranges` left out was not skinned this frame**,
7039 /// so the half this points at as the current one already holds an earlier
7040 /// frame's pose. That is pre-existing — it is what a caller driving a
7041 /// skinned object through plain [`begin_frame`](Self::begin_frame) gets, and
7042 /// it predates this second base — and the previous half is then no worse off
7043 /// than the current one.
7044 fn point_skinned_instances(&mut self, parity: u32) {
7045 let Self {
7046 instances,
7047 skinned_instances,
7048 ..
7049 } = self;
7050 skinned_instances.retain_mut(|entry| {
7051 // `SkinnedRegion::base`'s indexing and `SkinnedRegion::previous_base`'s,
7052 // applied to the entry's own copy of the pair — see
7053 // [`SkinnedInstance::bases`].
7054 let base_vertex = entry.bases[(parity & 1) as usize];
7055 let previous_base_vertex = if entry.pointed {
7056 entry.bases[((parity ^ 1) & 1) as usize]
7057 } else {
7058 // Nothing has been written into the other half for this object,
7059 // so it is put at rest — see [`SkinnedInstance::pointed`].
7060 base_vertex
7061 };
7062 entry.pointed = true;
7063 // The two bases and nothing else: the transform, the material and
7064 // the mesh the caller last set survive, and so does the transform
7065 // the record moved *from* — which
7066 // [`InstancePool::set`](crate::instance_pool::InstancePool::set)
7067 // would overwrite with this frame's, leaving a skinned object's own
7068 // travel out of the motion target. See
7069 // [`InstancePool::set_bases`](crate::instance_pool::InstancePool::set_bases).
7070 // Its answer is also what says the instance is still there, so an
7071 // object a caller removed drops out of the list here.
7072 instances.set_bases(entry.handle, base_vertex, previous_base_vertex)
7073 });
7074 }
7075
7076 /// The lights in the frame **beside the sun**, which
7077 /// [`begin_frame`](Self::begin_frame) still takes on its own.
7078 ///
7079 /// Topic 44's light list, minus its first row: the
7080 /// sun is row 0 of every frame's list and the ones set here follow it, in
7081 /// the order given. That order is the one a froxel keeps a prefix of when it
7082 /// runs out of budget — see [`ForwardRenderer::light_capacity`] and the
7083 /// overflow counter beside it — so it is a caller's lever and not an
7084 /// accident.
7085 ///
7086 /// The sun keeps a parameter of its own because it is the light that owns
7087 /// the ambient term and the shadow cascades, neither of which a [`Light`]
7088 /// has. What it stopped being is a special case in the *shader*, which is
7089 /// what the list bought.
7090 ///
7091 /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7092 /// what uploads the rows.
7093 ///
7094 /// # Panics
7095 ///
7096 /// If there are more lights than [`ForwardRenderer::light_capacity`] leaves
7097 /// room for once the sun has its row. Refused rather than truncated: a light
7098 /// missing from the list is missing from every froxel, and **no counter in
7099 /// the frame would report it** — the overflow counter counts what a froxel's
7100 /// budget refused, which is a different number.
7101 pub fn set_lights(&mut self, lights: &[Light]) {
7102 assert!(
7103 lights.len() < self.primary.lights.capacity() as usize,
7104 "{} lights beside the sun, in a list of {}",
7105 lights.len(),
7106 self.primary.lights.capacity()
7107 );
7108 self.extra_lights.clear();
7109 self.extra_lights.extend_from_slice(lights);
7110 }
7111
7112 /// Rows the light list holds, the sun's included.
7113 #[must_use]
7114 pub const fn light_capacity(&self) -> u32 {
7115 self.primary.lights.capacity()
7116 }
7117
7118 /// This frame's froxel grid, as [`begin_frame`](Self::begin_frame) sized it
7119 /// from the viewport and the camera.
7120 ///
7121 /// Exposed for the reason [`lod_params`](Self::lod_params) is: a test that
7122 /// wants to know which froxel a point was shaded out of has to use the grid
7123 /// the frame really used, and re-deriving it would be a second copy of the
7124 /// arithmetic rather than a reading of the first.
7125 #[must_use]
7126 pub const fn grid(&self) -> Grid {
7127 self.primary.grid
7128 }
7129
7130 /// `frame`'s froxel grid buffer, for a test copying out what the clustering
7131 /// pass decided.
7132 ///
7133 /// # Panics
7134 ///
7135 /// If `frame` is not a slot this was built with.
7136 #[must_use]
7137 pub fn light_grid_buffer(&self, frame: usize) -> BufferHandle {
7138 self.primary.lights.grid(frame)
7139 }
7140
7141 /// The pixel budget the descent compares a group's projected error against.
7142 ///
7143 /// One pixel until this is called — see the constant this crate keeps it
7144 /// in. Larger is coarser: a group
7145 /// projecting *over* the budget is expanded and its children are drawn, so
7146 /// raising it stops the descent higher up the DAG.
7147 ///
7148 /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7149 /// what writes it into the frame block.
7150 pub const fn set_lod_error_budget(&mut self, budget: f32) {
7151 self.lod_error_budget = budget;
7152 }
7153
7154 /// The budget this renderer selects under unless
7155 /// [`set_lod_error_budget`](Self::set_lod_error_budget) says otherwise, and
7156 /// the ratio the hold budget sits at below whichever one is in force.
7157 ///
7158 /// Public because a test that drives a camera across a level boundary has to
7159 /// know where the boundary is, and where it is depends on both numbers —
7160 /// re-deriving either in the test would be a second copy to drift.
7161 pub const LOD_ERROR_BUDGET: f32 = LOD_ERROR_BUDGET;
7162 /// See [`LOD_ERROR_BUDGET`](Self::LOD_ERROR_BUDGET).
7163 pub const LOD_HOLD_RATIO: f32 = LOD_HOLD_RATIO;
7164
7165 /// How far below the budget an already-expanded group is held before it
7166 /// collapses again — topic 25's hysteresis, as a fraction of
7167 /// the budget.
7168 ///
7169 /// [`LOD_HOLD_RATIO`](Self::LOD_HOLD_RATIO) until this is called. **A ratio
7170 /// of one removes the band**, which makes the two budgets equal and the
7171 /// previous frame's answer stop mattering — the setting a test uses to show
7172 /// that the band is what stops a drifting camera flickering, on the same
7173 /// code path and one number apart.
7174 ///
7175 /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7176 /// what writes it into the two params blocks.
7177 pub const fn set_lod_hold_ratio(&mut self, ratio: f32) {
7178 self.lod_hold_ratio = ratio;
7179 }
7180
7181 /// What the last [`begin_frame`](Self::begin_frame) handed the descent:
7182 /// pixels per unit at one unit from the eye, and the pixel budget.
7183 ///
7184 /// Pixels per unit at one unit from the eye, the budget an unexpanded group
7185 /// starts expanding over, and the budget an expanded one is held down to.
7186 ///
7187 /// What `ClusterDag::expand` takes, so a caller reading
7188 /// [`cluster_selection`](Self::cluster_selection) back can run the same
7189 /// frames host-side rather than re-deriving the numbers from the camera and
7190 /// hoping they agree. `[0.0, 0.0, 0.0]` before the first frame.
7191 #[must_use]
7192 pub const fn lod_params(&self) -> [f32; 3] {
7193 self.primary.lod_params
7194 }
7195
7196 /// The same three numbers the **shadow cascades** selected under, which is
7197 /// [`lod_params`](Self::lod_params) with both budgets multiplied by
7198 /// [`SHADOW_LOD_BIAS`] — topic 25's shadow LOD bias, as the
7199 /// parameters it actually reaches the GPU as.
7200 ///
7201 /// The pixels-per-unit is the camera's, unchanged, because the cascades
7202 /// select from the camera's eye at the camera's scale; see
7203 /// [`begin_frame`](Self::begin_frame). `[0.0, 0.0, 0.0]` before the first
7204 /// frame.
7205 #[must_use]
7206 pub const fn shadow_lod_params(&self) -> [f32; 3] {
7207 self.shadow_lod_params
7208 }
7209
7210 /// Where description mesh `mesh`'s clusters are in the cluster pool — every
7211 /// level of it, as one run — or `None` off the mesh path, where there is no
7212 /// cluster pool at all.
7213 ///
7214 /// The base a reader adds a `(level, cluster)` to in order to index
7215 /// [`cluster_selection`](Self::cluster_selection): the levels are laid down
7216 /// finest first and contiguously, so level `d` cluster `c` is at
7217 /// `base + (clusters of levels below d) + c`. A flat mesh is one level, so
7218 /// its run is its clusters and `c` indexes it directly.
7219 ///
7220 /// # Panics
7221 ///
7222 /// If `mesh` is past the end of the description this renderer was built
7223 /// from, on [`add_instance`](Self::add_instance)'s terms.
7224 #[must_use]
7225 pub fn cluster_range(&self, mesh: usize) -> Option<ClusterRange> {
7226 (!self.mesh_clusters.is_empty()).then(|| self.mesh_clusters[mesh])
7227 }
7228
7229 /// The buffer `frame`'s amplification stage recorded its chosen cut into:
7230 /// one `u32` per resident cluster, `1` where the cluster was drawn.
7231 ///
7232 /// `None` where there is no amplification stage, which is every device that
7233 /// reports no [`Features::TASK_SHADER`] and every non-mesh geometry path.
7234 ///
7235 /// **This is topic 25's observable and nothing in the frame
7236 /// reads it.** A frame whose every cluster came from one level is a
7237 /// plausible picture and matches any golden blessed from it, so a golden
7238 /// cannot show per-cluster selection happening at all; this can. It is
7239 /// `TRANSFER_SRC`, and copying it out is the caller's to record.
7240 ///
7241 /// [`Features::TASK_SHADER`]: crcbl_hal::Features::TASK_SHADER
7242 #[must_use]
7243 pub fn cluster_selection(&self, frame: usize) -> Option<BufferHandle> {
7244 self.primary.cluster_selection.get(frame).copied()
7245 }
7246
7247 /// The same, for `cascade`'s shadow pass: the cut that cascade's
7248 /// amplification stage chose this frame.
7249 ///
7250 /// **The shadow LOD bias' observable.** A budget the cascades merely *were
7251 /// passed* is a parameter; the cut they reached under it is the behaviour,
7252 /// and this is the only thing that carries it out of a frame — the colour
7253 /// pass overwrites [`cluster_selection`](Self::cluster_selection) after the
7254 /// cascades have run. Indexed and read exactly as that buffer is, through
7255 /// [`cluster_range`](Self::cluster_range).
7256 ///
7257 /// `None` where there is no amplification stage, and where `cascade` is not
7258 /// one of [`shadow::CASCADES`].
7259 #[must_use]
7260 pub fn shadow_selection(&self, frame: usize, cascade: usize) -> Option<BufferHandle> {
7261 self.shadow_selection
7262 .get(frame)
7263 .and_then(|cascades| cascades.get(cascade))
7264 .copied()
7265 }
7266
7267 /// The buckets description mesh `mesh`'s levels draw through, finest first —
7268 /// element `d` is level `d`'s bucket, and it is empty on the mesh path.
7269 ///
7270 /// **This is the uniform cut's observable**, and it is the indirect
7271 /// arguments rather than a buffer of its own: `draw_gen.slang` scatters an
7272 /// instance into the bucket for the level it selected, so exactly one of
7273 /// these buckets comes out of a frame with a non-zero instance count and
7274 /// which one it is *is* the chosen level. A reader takes
7275 /// [`DrawGen::args_offset`](crate::draw_gen::DrawGen::args_offset) of each
7276 /// and looks at
7277 /// [`DrawIndexedArgs::instance_count`](crcbl_shaders::draw_gen::DrawIndexedArgs::instance_count).
7278 ///
7279 /// Empty on [`GeometryPath::MeshShader`], where a mesh is one bucket and the
7280 /// level is chosen per cluster instead — see
7281 /// [`cluster_selection`](Self::cluster_selection), which is that path's
7282 /// observable.
7283 ///
7284 /// **These are the buckets of the scene's first material mode** — `OPAQUE`
7285 /// in any scene that has an opaque material, since the table is every
7286 /// mesh's levels once per mode the scene holds, mode by mode in
7287 /// `DEPTH_MODES` order. An instance of another mode selects the same level
7288 /// and lands in that level's bucket in its own mode's run, which this does
7289 /// not name; every scene in this tree that reads this accessor is all
7290 /// opaque, so "exactly one of these has a non-zero instance count" holds for
7291 /// them as it always did.
7292 ///
7293 /// # Panics
7294 ///
7295 /// If `mesh` is past the end of the description this renderer was built
7296 /// from, on [`add_instance`](Self::add_instance)'s terms.
7297 #[must_use]
7298 pub fn level_buckets(&self, mesh: usize) -> &[u32] {
7299 if self.mesh_level_buckets.is_empty() {
7300 return &[];
7301 }
7302 &self.mesh_level_buckets[mesh]
7303 }
7304
7305 /// `frame`'s indirect draw arguments, [`crcbl_shaders::draw_gen::DRAW_ARGS_SIZE`]
7306 /// bytes per bucket — what a reader of
7307 /// [`level_buckets`](Self::level_buckets) copies out.
7308 ///
7309 /// # Panics
7310 ///
7311 /// If `frame` is not a slot this renderer was built with.
7312 #[must_use]
7313 pub fn draw_args(&self, frame: usize) -> BufferHandle {
7314 self.primary.draws.args(frame)
7315 }
7316
7317 /// `frame`'s survivor list for the primary camera and the culling
7318 /// statistics beside it — `cull.slang`'s entries, tags and all, in the first
7319 /// [`DrawGen::visible_capacity`](crate::DrawGen::visible_capacity) words of
7320 /// the first buffer, and their count in word
7321 /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
7322 /// of the second — for a test holding the GPU's occlusion verdicts against
7323 /// [`crate::cull`]'s oracle. The first buffer holds the routes and runs
7324 /// behind the list; see [`crate::draw_gen`].
7325 ///
7326 /// # Panics
7327 ///
7328 /// If `frame` is not a slot this renderer was built with.
7329 #[must_use]
7330 pub fn camera_cull_buffers(&self, frame: usize) -> (BufferHandle, BufferHandle) {
7331 (
7332 self.primary.draws.visible(frame),
7333 self.primary.draws.visible_count(frame),
7334 )
7335 }
7336
7337 /// What the primary camera's cull reads, as the oracle in [`crate::cull`]
7338 /// takes it: every instance slot the pool has handed out, and the whole mesh
7339 /// table — both decoded from the host's own copies of what was uploaded.
7340 #[must_use]
7341 pub fn cull_records(&self) -> (Vec<mesh::GpuInstance>, Vec<mesh::GpuMesh>) {
7342 (self.instances.records(), self.pool.table_entries())
7343 }
7344
7345 /// The generator behind shadow cull `cull` — a cascade's below
7346 /// [`shadow::CASCADES`], a light slot's after —
7347 /// for a test reading back what a point light's face culls kept.
7348 ///
7349 /// # Panics
7350 ///
7351 /// If `cull` is not one of the renderer's shadow culls.
7352 #[must_use]
7353 pub fn shadow_generator(&self, cull: usize) -> &DrawGen {
7354 &self.shadow_draws[cull]
7355 }
7356
7357 /// The primary camera's farthest-depth pyramid — every level's image, view
7358 /// and extent, level 1 first — or empty before a frame culled by occlusion.
7359 ///
7360 /// For a test reading a level back: the images carry `TRANSFER_SRC` for
7361 /// exactly that, and they hold the last frame's early depth once that frame
7362 /// has finished.
7363 #[must_use]
7364 pub fn occlusion_pyramid(&self) -> Vec<(crcbl_hal::ImageHandle, ImageViewHandle, (u32, u32))> {
7365 self.primary.occlusion_pyramid.level_images()
7366 }
7367
7368 /// The most passes [`add_passes`](Self::add_passes) adds to one frame.
7369 ///
7370 /// [`DrawGen::MAX_PASSES`] per cull — the camera's, and one per shadow cull
7371 /// beside it — plus [`LightGrid::MAX_PASSES`] for the froxel grid and the
7372 /// passes that draw. **A ceiling, not a count**: a frame whose shadow slots
7373 /// are not all filled runs fewer culls, which is what makes a free tile
7374 /// free.
7375 ///
7376 /// Derived rather than written down, because a number written down is one
7377 /// that stops matching the frame the day a pass is added — which is exactly
7378 /// how the samples' hand-picked `8` came to time the first eight passes of a
7379 /// fourteen-pass frame. A caller sizing
7380 /// [`PassTimers`](crate::timing::PassTimers) wants
7381 /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES), which adds this to
7382 /// what the overlay renderers record.
7383 pub const MAX_PASSES: u32 = DrawGen::MAX_PASSES * (1 + SHADOW_CULLS as u32)
7384 + DrawGen::LATE_PASSES
7385 + LightGrid::MAX_PASSES
7386 + RENDER_PASSES;
7387
7388 /// Adds the forward and tonemap passes to `graph`, rendering into `target`,
7389 /// and returns the HDR scene target they went through.
7390 ///
7391 /// `target` is normally the imported swapchain image. Everything else — the
7392 /// HDR scene colour, the depth buffer, and every barrier between them — is
7393 /// the graph's.
7394 ///
7395 /// The returned [`ImageId`] is the `Rgba16Float` frame the tonemap read:
7396 /// the scene colour **with the screen-space reflections already added**, not
7397 /// the target the forward pass wrote. A caller that wants to add a pass of
7398 /// its own after the tonemap — a debug overlay, or a readback proving the
7399 /// HDR range is real — declares a read of it and the graph works out the
7400 /// transition, exactly as it does for the tonemap.
7401 ///
7402 /// The two are the same description and different images, which is the
7403 /// design's off-switch as data rather than as a branch: a frame with
7404 /// [`RenderEffects::REFLECTIONS`] off adds neither pass, returns the forward
7405 /// pass's own id, and is bit-identical.
7406 ///
7407 /// # Which passes this adds is [`effects`](Self::effects)
7408 ///
7409 /// Resolved by the [`begin_frame`](Self::begin_frame) that opened this frame
7410 /// and read here — see [`crate::effects`] for the four layers and for what
7411 /// each toggle removes. Every effect is on by default, which is the frame
7412 /// every caller drew before the toggles existed.
7413 ///
7414 /// A switched-off effect is **fewer passes and one different bound
7415 /// descriptor**, never a shader permutation: the shadow atlas keeps its
7416 /// reversed-Z clear and reads as fully lit, the occlusion binding falls back
7417 /// to the renderer's white 1×1, and the reflection pair simply is not there.
7418 ///
7419 /// # The ground grid comes last, and after the tonemap
7420 ///
7421 /// [`set_ground_grid`](Self::set_ground_grid) is what puts it in the frame,
7422 /// and it is off by default. When it is on, its pass is added **after** the
7423 /// tonemap and writes `target` rather than the HDR scene colour, depth-tested
7424 /// against the scene depth: the grid is reference chrome, and a grid drawn
7425 /// before the tonemap would be exposed and tonemapped like geometry, so its
7426 /// colour would move with how bright the scene is. See [`crate::grid`].
7427 ///
7428 /// # `pool` is where the shadow atlas's incoming state comes from
7429 ///
7430 /// It must be the same pool the caller is about to
7431 /// [`compile`](RenderGraph::compile) and
7432 /// [`execute`](crate::CompiledGraph::execute) against, because the atlas and
7433 /// its placeholder are imports this renderer owns across frames and the
7434 /// pool's ledger is the record of what the last executed graph left them in
7435 /// — [`TransientPool::imported_image_use`], with [`None`] read as
7436 /// [`ResourceState::Undefined`]. Reading it here rather than carrying a
7437 /// field of our own is what keeps the declaration and the audit
7438 /// ([`InitialClaim::Tracked`]) one answer instead of two that drift: a frame
7439 /// whose `compile` fails is a frame that never ran, and a field advanced at
7440 /// build time would already have moved on without it.
7441 pub fn add_passes<'a>(
7442 &'a mut self,
7443 graph: &mut RenderGraph<'a>,
7444 pool: &TransientPool,
7445 target: ImageId,
7446 extent: (u32, u32),
7447 ) -> ImageId {
7448 self.add_frame_passes(
7449 graph,
7450 pool,
7451 FrameTargets::primary(target, extent, None),
7452 |_, _| {},
7453 )
7454 }
7455
7456 /// [`add_passes`](Self::add_passes) for a frame that **skins**: the same
7457 /// frame with `skinning`'s dispatch in front of every pass that draws.
7458 ///
7459 /// # This takes the pass rather than its [`BufferId`], and that is the point
7460 ///
7461 /// [`Skinning::add_pass`] hands back the id of the vertex pool so that a
7462 /// mesh pass can declare a read of it and be ordered after the dispatch. The
7463 /// obvious seam is therefore an id parameter here — and it is the wrong one,
7464 /// because every way of getting it wrong is silent. A caller can pass the id
7465 /// of a *different* import, add the skinning pass after this one, or not add
7466 /// it at all, and in each case the graph orders nothing, the draws read the
7467 /// region before the compute write has been made visible, and what comes out
7468 /// is a mesh that flickers between two poses on hardware and looks perfect
7469 /// under a validation layer.
7470 ///
7471 /// So this takes the [`Skinning`] and **adds the pass itself**, first, with
7472 /// this renderer's own frame slot, and declares the read on the three passes
7473 /// that pull vertices out of the pool — the shadow atlas, the depth prepass
7474 /// and the forward pass. There is no order for a caller to get right,
7475 /// because there is only one call.
7476 ///
7477 /// A frame whose [`begin_skinned_frame`](Self::begin_skinned_frame) was
7478 /// handed no ranges adds no dispatch and no declarations, and is the frame
7479 /// [`add_passes`](Self::add_passes) would have built.
7480 ///
7481 /// # It records one pass more than [`MAX_PASSES`](Self::MAX_PASSES)
7482 ///
7483 /// That constant is the bound on [`add_passes`](Self::add_passes) and stays
7484 /// so; the skinning dispatch is [`Skinning::MAX_PASSES`], and
7485 /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES) — what a caller
7486 /// sizes [`PassTimers`](crate::PassTimers) with — already sums the two.
7487 pub fn add_skinned_passes<'a>(
7488 &'a mut self,
7489 graph: &mut RenderGraph<'a>,
7490 pool: &TransientPool,
7491 target: ImageId,
7492 extent: (u32, u32),
7493 skinning: &Skinning,
7494 ) -> ImageId {
7495 self.add_frame_passes(
7496 graph,
7497 pool,
7498 FrameTargets::primary(target, extent, Some(skinning)),
7499 |_, _| {},
7500 )
7501 }
7502
7503 /// [`add_skinned_passes`](Self::add_skinned_passes) with one game-owned
7504 /// overlay inserted after the display-space frame is complete and before
7505 /// antialiasing or render-scale reconstruction.
7506 ///
7507 /// The callback receives the display target and its matching scene depth
7508 /// attachment at the internal render extent. It may add graph passes that
7509 /// sample `display` and attach `depth` read-only; it must leave both images
7510 /// in states its declarations name. The forward renderer continues with its
7511 /// existing resolve and upscale passes after the callback returns.
7512 pub fn add_skinned_passes_with_overlay<'a, F>(
7513 &'a mut self,
7514 graph: &mut RenderGraph<'a>,
7515 pool: &TransientPool,
7516 target: ImageId,
7517 extent: (u32, u32),
7518 skinning: &Skinning,
7519 overlay: F,
7520 ) -> ImageId
7521 where
7522 F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7523 {
7524 self.add_frame_passes(
7525 graph,
7526 pool,
7527 FrameTargets::primary(target, extent, Some(skinning)),
7528 overlay,
7529 )
7530 }
7531
7532 /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
7533 /// for a frame that also draws secondary views — see
7534 /// [`create_view`](Self::create_view).
7535 ///
7536 /// **The scene's passes are recorded once**: one skinning dispatch (where
7537 /// `skinning` is `Some`), one shadow atlas, one probe gather. Then each view
7538 /// in `views` records its own cull, clustering and frame into its own
7539 /// target, and the primary camera's frame into `target` comes last — so
7540 /// `overlay` may read a view's target, which is already drawn by then.
7541 ///
7542 /// Every view named must have been begun this frame by
7543 /// [`begin_view`](Self::begin_view).
7544 ///
7545 /// # Panics
7546 ///
7547 /// If a [`ViewTarget`] in [`FrameTargets::views`] names [`ViewId::PRIMARY`],
7548 /// a view this renderer did not build, a view not begun this frame, or a
7549 /// view twice.
7550 pub fn add_passes_with_views<'a, F>(
7551 &'a mut self,
7552 graph: &mut RenderGraph<'a>,
7553 pool: &TransientPool,
7554 frame: FrameTargets<'_>,
7555 overlay: F,
7556 ) -> ImageId
7557 where
7558 F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7559 {
7560 self.add_frame_passes(graph, pool, frame, overlay)
7561 }
7562
7563 /// The body of every `add_*passes` entry point, which differ in their
7564 /// arguments and in nothing else.
7565 fn add_frame_passes<'a, F>(
7566 &'a mut self,
7567 graph: &mut RenderGraph<'a>,
7568 pool: &TransientPool,
7569 frame: FrameTargets<'_>,
7570 overlay: F,
7571 ) -> ImageId
7572 where
7573 F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7574 {
7575 let FrameTargets {
7576 target,
7577 extent,
7578 skinning,
7579 views,
7580 } = frame;
7581 // **From here down `extent` is the extent the frame is *drawn* at**,
7582 // which is the caller's at a render scale of `1.0` and smaller below it.
7583 // Every use of it in this function sizes a transient, and every one of
7584 // those transients belongs to the internal frame; `target` is the only
7585 // thing here at the caller's extent, and it is an id whose image already
7586 // knows how big it is. `begin_frame_body` shadows it the same way and
7587 // for the same reason, so the two halves of a frame cannot disagree.
7588 //
7589 // `upscaling` is derived from the two extents rather than from the scale
7590 // itself, which is what makes it exact: a target small enough that the
7591 // scaled extent rounds back onto it adds no pass, because there would be
7592 // nothing for the pass to do.
7593 let target_extent = extent;
7594 let extent = self.internal_extent(target_extent);
7595 let upscaling = extent != target_extent;
7596 let frame = self.frame;
7597 let instance_count = self.instances.slot_count();
7598 let emit = self.emit;
7599
7600 // Every secondary view the caller asked for, checked before anything of
7601 // theirs is recorded: a view that does not exist, or one nothing began
7602 // this frame, would draw out of blocks written for some other frame.
7603 let secondary: Vec<(ViewTarget, (u32, u32))> = views
7604 .iter()
7605 .map(|view| {
7606 assert!(
7607 view.view != ViewId::PRIMARY,
7608 "the primary camera draws into the target `add_passes_with_views` takes, \
7609 not into a `ViewTarget`"
7610 );
7611 let built = self
7612 .views
7613 .get(view.view.index() - 1)
7614 .and_then(Option::as_ref)
7615 .unwrap_or_else(|| panic!("{:?} is not a view this renderer built", view.view));
7616 assert_eq!(
7617 built.begun, self.frame_serial,
7618 "{:?} was not begun this frame; call `begin_view` after `begin_frame`",
7619 view.view
7620 );
7621 assert!(
7622 views.iter().filter(|other| other.view == view.view).count() == 1,
7623 "{:?} was named twice in one frame",
7624 view.view
7625 );
7626 (*view, self.view_extent(built.background, view.extent))
7627 })
7628 .collect();
7629
7630 // **The skinning dispatch, before anything else is added.** It imports
7631 // the vertex pool and hands back that node's id; every pass below that
7632 // pulls vertices declares a read of it, and the graph is what turns the
7633 // two declarations into the barrier between the compute write and the
7634 // draws. `None` is a frame with nothing to skin, which adds no pass and
7635 // declares nothing — see `Skinning::add_pass`.
7636 let skinned = skinning.and_then(|skinning| skinning.add_pass(graph, frame));
7637
7638 // The camera's cull dispatch and the draw-argument dispatch, and the
7639 // light clustering after them — before anything draws, and before the
7640 // shadow atlas, which is where they always ran. See [`View::add_cull`].
7641 let cull = self.primary.add_cull(graph, pool, frame, instance_count);
7642
7643 // Topic 25's record of each cascade's cut. Each is written by
7644 // exactly one mesh pass, so what the graph orders here is this frame's
7645 // write against the next frame's use of the same slot. Each arrives in
7646 // the state the previous frame left it in, which is the one declared as
7647 // final.
7648 let tile_selection: Vec<BufferId> = self
7649 .shadow_selection
7650 .get(self.frame)
7651 .into_iter()
7652 .flatten()
7653 .enumerate()
7654 .map(|(tile, &buffer)| {
7655 import_read_write(graph, &format!("shadow-selection-{tile}"), buffer)
7656 })
7657 .collect();
7658
7659 // **This frame's slot of the probe ring**, which is the buffer every
7660 // one of this frame's bind groups names — see [`crate::probe`] for why
7661 // there is more than one. Imported in `ShaderRead` and handed back in
7662 // it: the build's staging copy left it there and no pass in the frame
7663 // writes it yet.
7664 let probe_buffer = self.probes.buffer(frame);
7665 let probe_table = graph.import_buffer(
7666 "probes",
7667 ImportedBuffer {
7668 buffer: probe_buffer,
7669 initial: ResourceState::ShaderRead,
7670 final_state: ResourceState::ShaderRead,
7671 },
7672 );
7673
7674 // The occlusion placeholder, imported once and read by every pass whose
7675 // bind group names it: the shadow pass's views, the depth prepass's copy
7676 // of the camera's group, and — on a frame drawing without
7677 // `RenderEffects::AMBIENT_OCCLUSION` — the forward pass itself. It was
7678 // uploaded at build, so it is already in `ShaderRead` and the graph has
7679 // nothing to transition; declaring it is what keeps that true if a later
7680 // pass wants it in some other state.
7681 let occlusion_placeholder = graph.import_image(
7682 "ssao-placeholder",
7683 ImportedImage {
7684 image: self.ambient_occlusion_placeholder.image,
7685 view: self.ambient_occlusion_placeholder.view,
7686 format: Format::R8Unorm,
7687 extent: (1, 1),
7688 initial: ResourceState::ShaderRead,
7689 claim: InitialClaim::Tracked,
7690 final_state: ResourceState::ShaderRead,
7691 },
7692 );
7693
7694 // The contact-shadow placeholder, imported beside the occlusion one and
7695 // on its terms exactly: every group of the mesh layout names this
7696 // binding, and on a frame drawing without `RenderEffects::CONTACT_SHADOWS`
7697 // it is what the forward pass binds.
7698 let contact_placeholder = graph.import_image(
7699 "contact-shadows-placeholder",
7700 ImportedImage {
7701 image: self.contact_shadow_placeholder.image,
7702 view: self.contact_shadow_placeholder.view,
7703 format: Format::R8Unorm,
7704 extent: (1, 1),
7705 initial: ResourceState::ShaderRead,
7706 claim: InitialClaim::Tracked,
7707 final_state: ResourceState::ShaderRead,
7708 },
7709 );
7710
7711 // §3.2's base-colour page, in every bind group of `mesh_layout` and so
7712 // read by all three of the passes that draw geometry. Like the
7713 // placeholder above it is already in `ShaderRead` and the graph has
7714 // nothing to transition on a frame nothing writes it — **the
7715 // declaration is for the frames something does**. A caller that copies a
7716 // render-to-texture view into one of its layers imports the same handle,
7717 // gets this same id back (`RenderGraph::import_image`), and the graph
7718 // then has an edge to order its write against these reads. Without the
7719 // declaration there is no such edge: the page is bound out of a
7720 // descriptor the graph never hears about, and a copy scheduled anywhere
7721 // but the tail of the frame leaves it in `TransferDst` for the passes
7722 // that sample it.
7723 let base_color_page =
7724 graph.import_image(Self::BASE_COLOR_PAGE_LABEL, self.base_color_page_import());
7725 // §2's normal page beside it, declared for exactly the reason above: it
7726 // is in every group of `mesh_layout` too, so a caller copying into one
7727 // of its layers needs the same edge against these draws.
7728 let normal_page = graph.import_image(Self::NORMAL_PAGE_LABEL, self.normal_page_import());
7729 // §2's other two pages beside them, declared for exactly the same
7730 // reason: both are in every group of `mesh_layout`, so a caller copying
7731 // into one of their layers needs the same edge against these draws.
7732 let mro_page = graph.import_image(Self::MRO_PAGE_LABEL, self.mro_page_import());
7733 let emissive_page =
7734 graph.import_image(Self::EMISSIVE_PAGE_LABEL, self.emissive_page_import());
7735
7736 // What this frame draws, resolved by the `begin_frame` that opened it —
7737 // see [`crate::effects`]. Read once here so every conditional below is
7738 // about one value rather than about four reads of a field.
7739 let effects = self.frame_effects;
7740 // Read here for `effects`' reason and for one more: the passes below
7741 // borrow `self` field by field, and a `&self` method called between
7742 // them would borrow the whole of it.
7743 let draws_sky = self.draws_sky();
7744 // What the frame's water draws, or `None` for a frame with none — read
7745 // here for `draws_sky`'s reason, and the same value every view records
7746 // from.
7747 let water = self.water.frame(self.frame);
7748 // The same, for the grass field: read here for `draws_sky`'s reason,
7749 // and the same value every view records from.
7750 let grass = self.grass.frame();
7751 // Whether this frame ends by drawing the shadow atlas over itself — the
7752 // resolved view rather than the switch, so a caller who left the atlas
7753 // up and then asked for normals gets normals. Read here for
7754 // `draws_sky`'s reason exactly: `debug_view` takes `&self`.
7755 let draws_atlas_view = self.debug_view() == DebugView::ShadowAtlas;
7756
7757 let pages = MaterialPages {
7758 base_color: base_color_page,
7759 normal: normal_page,
7760 mro: mro_page,
7761 emissive: emissive_page,
7762 };
7763 let (shadow_atlas, shadow_draws, shadow_tile_clears, rsm_images) = self.add_shadow_pass(
7764 graph,
7765 pool,
7766 &tile_selection,
7767 ShadowReads {
7768 occlusion_placeholder,
7769 pages,
7770 skinned,
7771 probes: probe_table,
7772 },
7773 );
7774
7775 // The wireframe twin where a caller switched the view on, and `None`
7776 // everywhere else — see `set_wireframe`. Written on `ground_grid`'s
7777 // terms, and the `filter` is what keeps "switched on" from outrunning
7778 // "built": the field is only `Some` after a build that succeeded.
7779 //
7780 // The depth prepass below takes the depth-only pipeline and is untouched
7781 // by this, which is the half that makes a wireframe frame legible: the
7782 // occlusion pair still reads solid depth. **It is also what makes this
7783 // one variable rather than two**: the colour pass's depth attachment
7784 // branches on it as well, because a wireframe is not the geometry the
7785 // prepass drew — see `MeshModules::color_depth_stencil`.
7786 let wireframe = self.wireframe_pipeline.filter(|_| self.wireframe_on);
7787 let bucket_draws = BucketDraws {
7788 // Replaced per partition below, in both passes that draw this list —
7789 // see [`ForwardRenderer::sided_partitions`] and
7790 // [`ForwardRenderer::depth_partitions`]. The field is what the
7791 // partitions inherit everything else from.
7792 pipeline: self.mesh_pipeline.single,
7793 layout: self.mesh_pipeline_layout,
7794 indices: self.pool.index_buffer(),
7795 emit,
7796 calls: self
7797 .bucket_constants
7798 .iter()
7799 .enumerate()
7800 .map(|(bucket, constant_offset)| {
7801 let bucket = u32::try_from(bucket)
7802 .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
7803 (
7804 *constant_offset,
7805 self.primary.draws.args_offset(bucket),
7806 self.primary.draws.count_offset(bucket),
7807 self.primary.draws.mesh_args_offset(bucket),
7808 )
7809 })
7810 .collect(),
7811 region_step: self.region_step,
7812 // Packed per partition, where the partition's buckets are known.
7813 ranges: None,
7814 flat: None,
7815 };
7816
7817 // Every draw this frame records: the shadow pass's, one per bucket — or
7818 // per range of buckets, or per partition behind a task stage — in
7819 // **each** of the depth prepass and the forward pass, and one full-screen
7820 // triangle per full-screen pass. Assigned before the passes below borrow
7821 // the fields they need, so it is the count for the frame being built
7822 // rather than the one before it — and off this frame's resolved effects
7823 // rather than off a constant, so a switched-off effect's triangle is not
7824 // counted as submitted.
7825 //
7826 // The ground grid is added on top rather than folded into
7827 // `fullscreen_passes`: it is not a [`RenderEffects`] bit and is not
7828 // resolved by the toggle order — it is a caller's opt-in, off by
7829 // default — so what decides it is the field and not this frame's
7830 // effects.
7831 self.recorded_fullscreen = fullscreen_passes(effects, extent, upscaling, self.frame_ssao_blurs)
7832 + u64::from(self.ground_grid().is_some() && !draws_atlas_view)
7833 + if draws_sky { SkyPass::PASSES } else { 0 }
7834 // The composite on an atmosphere frame whose fog effect is off,
7835 // on the sky's terms: it is there for the air in front of the
7836 // scene, which the atmosphere decides and no effect bit does.
7837 // With the effect on, `fullscreen_passes` already counted it.
7838 + if self.primary.frame_aerial
7839 && !effects.contains(RenderEffects::VOLUMETRIC_FOG)
7840 {
7841 u64::from(Volumetric::COMPOSITE_PASSES)
7842 } else {
7843 0
7844 }
7845 // The water copy's triangle, on the sky's terms: content rather
7846 // than an effect bit, so the bodies decide it.
7847 + if water.is_some() { Water::FULLSCREEN_PASSES } else { 0 }
7848 // The atlas viewer, on the ground grid's terms: not an effect
7849 // bit and not resolved by the toggle order, so what decides it
7850 // is the debug view and not this frame's effects. It *replaces*
7851 // the tonemap `fullscreen_passes` counted and the grid above —
7852 // see `View::add_passes` — so its passes stand in for the one.
7853 + if draws_atlas_view {
7854 u64::from(AtlasView::PASSES) - 1
7855 } else {
7856 0
7857 };
7858 // The debug draw layer's own call, on the ground grid's terms: not an
7859 // effect bit, and decided by whether this frame's slot has a segment in
7860 // it. One direct draw of one instance covering every segment appended,
7861 // which is why it joins the full-screen triangles rather than the
7862 // indirect draws — `counters` counts both as submitted *and* drawn,
7863 // because the CPU knows what they cover.
7864 self.recorded_debug_draw = u64::from(self.debug_draw.records_pass(self.frame));
7865 // The shadow pass's tile resets, on the same terms: one over-sized
7866 // triangle of one instance per tile it redrew, and none at all on a
7867 // frame that cleared the whole attachment — see
7868 // [`MeshModules::depth_clear_pipeline`].
7869 self.recorded_tile_clears = shadow_tile_clears;
7870 // One indexed draw per body the frame's water holds.
7871 self.recorded_water_draws = water
7872 .as_ref()
7873 .map_or(0, |water: &WaterFrame| water.draws.len() as u64);
7874 // One indirect draw per tile slot the frame's field holds, per look it
7875 // draws.
7876 self.recorded_grass_draws = grass.as_ref().map_or(0, |grass: &GrassFrame| {
7877 u64::from(grass.slots) * u64::from(grass.draws_per_slot())
7878 });
7879 // The late depth prepass is a third list of calls, on a frame whose
7880 // camera culls in two phases.
7881 let camera_passes: u64 = if self.primary.draws.frame_mode(frame)
7882 == crcbl_shaders::draw_gen::DrawMode::Occlusion
7883 {
7884 3
7885 } else {
7886 2
7887 };
7888 let prepass_partitions = self.depth_partitions(&bucket_draws);
7889 // And the colour pass's own split, which is by **side** alone: its
7890 // pipeline has a fragment stage either way, so an alpha mask is nothing
7891 // it has to route around and a cull mode is. The wireframe twin pair
7892 // substitutes for the shaded one here exactly as the single pipeline
7893 // used to.
7894 let color_partitions =
7895 self.sided_partitions(&bucket_draws, wireframe.unwrap_or(self.mesh_pipeline));
7896 // Off the partitions the passes below record, because where a call
7897 // draws a range of buckets the two splits pack into different numbers
7898 // of ranges — see [`BucketDraws::call_count`].
7899 let calls = |partitions: &[BucketDraws]| -> u64 {
7900 partitions.iter().map(BucketDraws::call_count).sum()
7901 };
7902 self.recorded_draws = shadow_draws
7903 + (camera_passes - 1) * calls(&prepass_partitions)
7904 + calls(&color_partitions)
7905 + self.recorded_grass_draws
7906 + self.direct_draws();
7907
7908 // --- the probe gather ---
7909 //
7910 // The irradiance probes' updater, second half: the map
7911 // the pass above drew, read into every row of the table. **Here rather
7912 // than beside that pass** because the write is `&mut` — the group naming
7913 // the map's transient views is cached across frames, and a group naming a
7914 // transient cannot be built where the others are; see
7915 // [`crate::ssao::cached_group`].
7916 //
7917 // It is before the depth prepass and the forward pass, which is the
7918 // ordering that matters: both declare a read of these rows, so the graph
7919 // barriers this write against them.
7920 //
7921 // Which map layer a row is weighed against is the row's own index, so
7922 // the view is resolved exactly as the drawing passes resolve it — the
7923 // placeholder until `capture_probe_visibility` has run, and off entirely
7924 // where `r_probe_visibility` is off. A gather against the placeholder
7925 // occludes nothing, which is the honest answer for a scene that never
7926 // captured.
7927 let probe_visibility_view = match &self.probe_visibility {
7928 Some(captured) if crate::probe_visibility::enabled() => captured.view,
7929 _ => self.probe_visibility_placeholder.view,
7930 };
7931 let frame = self.frame;
7932 if let Some((gather, images)) = self.probe_gather.as_mut().zip(rsm_images) {
7933 gather.add_pass(graph, frame, images, probe_visibility_view, probe_table);
7934 }
7935
7936 let passes = FramePasses {
7937 slot: frame,
7938 emit,
7939 target_format: self.target_format,
7940 ssao_blurs: self.frame_ssao_blurs,
7941 draws_sky,
7942 water,
7943 grass,
7944 skinned,
7945 probe_buffer,
7946 probe_table,
7947 occlusion_placeholder,
7948 contact_placeholder,
7949 pages,
7950 shadow_atlas,
7951 probe_visibility: probe_visibility_view,
7952 mesh_layout: self.mesh_layout,
7953 wireframe,
7954 prepass_partitions,
7955 color_partitions,
7956 tonemap: TonemapPipeline {
7957 sampler: self.sampler,
7958 layout: self.tonemap_layout,
7959 pipeline_layout: self.tonemap_pipeline_layout,
7960 pipeline: self.tonemap_pipeline,
7961 },
7962 };
7963 // From here the frame is borrowed field by field, because every view's
7964 // passes hold its own caches for the life of the graph.
7965 let Self {
7966 primary,
7967 views: built,
7968 debug_draw,
7969 ground_grid,
7970 ground_grid_on,
7971 atlas_viewer,
7972 cull_stats,
7973 ..
7974 } = self;
7975
7976 // **Every secondary view before the primary camera's frame**, so a pass
7977 // the primary records — an overlay compositing a scope's picture onto
7978 // the lens it is seen through — reads a view that is already drawn. Each
7979 // records its whole frame straight through: its own cull, its own
7980 // clustering, and every pass the primary records after them, against the
7981 // atlas and the probe rows the scene passes above left behind.
7982 for (index, slot) in built.iter_mut().enumerate() {
7983 let Some((view_target, view_extent)) = secondary
7984 .iter()
7985 .find(|(view, _)| view.view.index() == index + 1)
7986 else {
7987 continue;
7988 };
7989 let view = slot
7990 .as_mut()
7991 .unwrap_or_else(|| unreachable!("checked against the built views above"));
7992 let view_cull = view.add_cull(graph, pool, frame, instance_count);
7993 view.add_passes(
7994 graph,
7995 &passes,
7996 view_cull,
7997 ViewOutput {
7998 target: view_target.target,
7999 target_extent: view_target.extent,
8000 extent: *view_extent,
8001 },
8002 Overlays::default(),
8003 |_, _| {},
8004 );
8005 }
8006
8007 // The statistics buffer's id, read before the cull moves into the pass
8008 // recording below: the copy that reads it is the frame's last pass.
8009 let stats_id = cull.generated.visible_count_id;
8010 let tonemapped = primary.add_passes(
8011 graph,
8012 &passes,
8013 cull,
8014 ViewOutput {
8015 target,
8016 target_extent,
8017 extent,
8018 },
8019 Overlays {
8020 debug_draw: Some(debug_draw),
8021 ground_grid: ground_grid.as_ref().filter(|_| *ground_grid_on),
8022 atlas_viewer: draws_atlas_view.then_some(atlas_viewer),
8023 },
8024 overlay,
8025 );
8026
8027 // **Last, and that is the point.** Three passes add to the statistics
8028 // buffer — the cull dispatch, the light grid's overflow counter and the
8029 // amplification stage inside the forward pass — so a copy scheduled any
8030 // earlier would take a total the frame had not finished writing. The
8031 // graph puts it in `TransferSrc` for this and back into the state the
8032 // next frame on this slot imports it in; there is not a barrier written
8033 // here.
8034 if let Some(stats) = cull_stats.as_mut() {
8035 stats.add_copy_pass(graph, stats_id);
8036 }
8037
8038 tonemapped
8039 }
8040
8041 /// Adds the cull dispatches and the depth-only pass that fill the shadow
8042 /// atlas, and returns the atlas as the graph knows it.
8043 ///
8044 /// Every tile is one viewport of one render pass. A pass per tile would be
8045 /// one clear of the same image and one more barrier per tile, and the graph
8046 /// would have to be told each of them only touches part of it — where one
8047 /// pass with a viewport per tile is what a shadow *atlas* is for in the first
8048 /// place.
8049 ///
8050 /// **Only the occupied tiles get a cull and a viewport.** The cascades
8051 /// always are; a light tile is occupied when
8052 /// [`shadow::Selection`] gave it to a light. A free one keeps the
8053 /// reversed-Z clear the pass wrote, which is `0.0` — "nothing stored, as far
8054 /// away as depth goes" — so anything that did sample it would come back
8055 /// fully lit rather than fully shadowed.
8056 ///
8057 /// # With [`RenderEffects::SHADOWS`] off, every tile is a free one
8058 ///
8059 /// That is the whole switch, and it is the same mechanism a free tile
8060 /// already had rather than a second one: no cull is dispatched and no
8061 /// viewport is drawn, the pass records its clear and nothing else, and every
8062 /// comparison against the atlas comes back fully lit. The pass itself stays
8063 /// on the frame that switches it off — it is what *writes* that clear, and a
8064 /// frame that skipped it would leave the atlas holding the last frame that
8065 /// did draw into it, or undefined memory on the first frame of all.
8066 ///
8067 /// # A cached atlas records nothing at all
8068 ///
8069 /// Topic 45's static-caching rung. When
8070 /// [`ForwardRenderer::shadow_atlas_cached`] says the image already holds
8071 /// what this frame would draw, this adds **no cull and no pass**: the atlas
8072 /// is imported so the passes that sample it have an edge to the resource,
8073 /// and it keeps the contents an earlier frame left in it. That is why the
8074 /// image is a persistent one with a tracked ledger entry rather than a
8075 /// transient — nothing else in the frame can alias it, so what it holds is
8076 /// what the last pass to write it wrote.
8077 ///
8078 /// # Per group, and what pays for the tiles it keeps
8079 ///
8080 /// Topic 45's cadence rung. A **group** — a cascade, or a
8081 /// light slot's whole run of tiles — is redrawn or held on its own, and
8082 /// [`ForwardRenderer::shadow_group_redrawn`] is what says which. A frame
8083 /// that holds nothing clears the whole attachment, which is the recording
8084 /// that shipped before the rung; a frame that holds something **loads** the
8085 /// attachment instead and resets each tile it redraws with
8086 /// [`MeshModules::depth_clear_pipeline`], which is the portable statement of
8087 /// a clear bounded to one tile.
8088 ///
8089 /// The attachment's own [`LoadOp::Clear`] cannot serve there: it covers
8090 /// every tile including the ones being kept, and the region-bounded
8091 /// alternatives are not portable — Metal's load action and WebGPU's
8092 /// `loadOp` have no render area to bound them, so a clear that covered part
8093 /// of the image on Vulkan and all of it on Metal would be a held tile that
8094 /// survives on one backend and is erased on another.
8095 fn add_shadow_pass(
8096 &self,
8097 graph: &mut RenderGraph<'_>,
8098 pool: &TransientPool,
8099 selection: &[BufferId],
8100 reads: ShadowReads,
8101 ) -> (ImageId, u64, u64, Option<RsmImages>) {
8102 let shadows = self.frame_effects.contains(RenderEffects::SHADOWS);
8103 let (atlas_width, atlas_height) = shadow::atlas_extent();
8104 let atlas = graph.import_image(
8105 "shadow-atlas",
8106 ImportedImage {
8107 image: self.shadow_atlas,
8108 view: self.shadow_atlas_view,
8109 format: Format::D32Float,
8110 extent: (atlas_width, atlas_height),
8111 // What the previous executed frame left it in — `Undefined` on
8112 // the first, which is what makes the graph give it a layout at
8113 // all.
8114 initial: imported_state(pool, self.shadow_atlas),
8115 // The renderer keeps this image across frames, so the pool's
8116 // ledger is the record of what happened to it and the line above
8117 // is that record read back rather than a second copy of it.
8118 claim: InitialClaim::Tracked,
8119 final_state: ResourceState::ShaderRead,
8120 },
8121 );
8122 // The cached frame's whole answer: the image above and nothing that
8123 // touches it. It is already in `ShaderRead` — the frame that drew it
8124 // handed it back that way — so the graph has no transition to make, and
8125 // the passes that sample it read the maps an earlier frame left there.
8126 if self.shadow_atlas_cached {
8127 // **And no reflective shadow map either**, which cannot happen while
8128 // the updater is on: `begin_frame` keeps cascade 0 off the hold in
8129 // exactly that case, so a frame reaching here has nothing to draw
8130 // the map from. See `probe_update_runs`.
8131 return (atlas, 0, 0, None);
8132 }
8133 let placeholder = graph.import_image(
8134 "shadow-placeholder",
8135 ImportedImage {
8136 image: self.shadow_placeholder,
8137 view: self.shadow_placeholder_view,
8138 format: Format::D32Float,
8139 extent: (1, 1),
8140 // **Its own ledger entry, not the atlas's.** The two move
8141 // together today — both are imported by this function on every
8142 // frame and both are handed back in `ShaderRead` — so one lookup
8143 // would answer both, and that is exactly the coincidence a
8144 // second declared state here stops depending on.
8145 initial: imported_state(pool, self.shadow_placeholder),
8146 claim: InitialClaim::Tracked,
8147 final_state: ResourceState::ShaderRead,
8148 },
8149 );
8150
8151 // Which light slots have a light this frame, resolved once: a slot's
8152 // cull is dispatched and its faces are drawn together or not at all, and
8153 // `begin_frame` filled that generator's parameters under exactly this
8154 // condition.
8155 //
8156 // **And only the ones this frame redraws**, since the cadence rung: a
8157 // held slot keeps the texels it has, so recording its cull and its
8158 // draws would be the same picture at the full price.
8159 let occupied: Vec<(usize, shadow::Assignment, &Light)> = self
8160 .shadow_lights
8161 .slots()
8162 .iter()
8163 .enumerate()
8164 .filter(|_| shadows)
8165 .filter(|(slot, _)| self.shadow_group_redrawn[shadow_cull(*slot)])
8166 .filter_map(|(slot, held)| {
8167 let held = (*held)?;
8168 Some((slot, held, self.extra_lights.get(held.light)?))
8169 })
8170 .collect();
8171
8172 // One cull dispatch per cascade and per occupied slot, before the pass
8173 // that draws from them — **not one per tile**, which is topic 18's
8174 // fourth decision: a point light's six faces draw one visible set.
8175 let cascades: Vec<usize> = if shadows {
8176 (0..shadow::CASCADES)
8177 .filter(|cascade| self.shadow_group_redrawn[*cascade])
8178 .collect()
8179 } else {
8180 Vec::new()
8181 };
8182 // **Cascade 0's cull, on a frame that is not drawing it into the
8183 // atlas.** `begin_frame` fits it whenever the updater is on, shadows or
8184 // no shadows — see `rsm_cull_ready` — so this is the case where the map
8185 // is drawn and the atlas keeps its clear. Chained **last**, because the
8186 // occupied slots' entries are indexed by `cascades.len() + index` a few
8187 // lines below and an insertion before them would hand a light's draws to
8188 // the wrong viewport.
8189 let rsm_only_cull = self.rsm_cull_ready && !cascades.contains(&0);
8190 // The punctual producer's faces, which are also the light slots'
8191 // atlas views — see `punctual_faces`, the one list both halves of the
8192 // updater walk.
8193 let punctual = self.punctual_faces();
8194 // And their culls on a frame that is not drawing the atlas, which
8195 // `occupied` is empty on for the same reason `cascades` is. Deduplicated
8196 // because a point light's six faces draw one visible set, and chained
8197 // **after** the entries `views` indexes positionally below.
8198 let punctual_only_culls: Vec<usize> = if shadows {
8199 Vec::new()
8200 } else {
8201 punctual
8202 .iter()
8203 .map(|face| face.cull)
8204 .collect::<std::collections::BTreeSet<_>>()
8205 .into_iter()
8206 .collect()
8207 };
8208 let generated: Vec<(usize, GeneratedDraws)> = cascades
8209 .iter()
8210 .copied()
8211 .chain(occupied.iter().map(|(slot, _, _)| shadow_cull(*slot)))
8212 .chain(rsm_only_cull.then_some(0))
8213 .chain(punctual_only_culls)
8214 .map(|cull| {
8215 (
8216 cull,
8217 self.shadow_draws[cull].add_passes(
8218 graph,
8219 self.frame,
8220 self.instances.slot_count(),
8221 ),
8222 )
8223 })
8224 .collect();
8225
8226 // What the pass body records, in order: which view's bind group, which
8227 // rectangle of the atlas its viewport covers, and which of the culls
8228 // above it draws from. Paired rather than positional, because the free
8229 // slots are missing from every one of these lists and a bare index into
8230 // one would hand a light's draws to the wrong viewport the moment one
8231 // slot is free and a later one is not.
8232 //
8233 // **The rectangle rather than the slot**, resolved here: the body runs
8234 // in a closure that outlives this borrow, and asking the selection for
8235 // it there would be a second reading of an allocation that has to be the
8236 // one the frame block was written from.
8237 //
8238 // **And which draw region of that cull**: region 0, every survivor, for
8239 // a cascade and a spot; and for a point light whose cull tagged its
8240 // casters by face, the region of the face being drawn — see
8241 // `set_point_face_culls`.
8242 let mut views: Vec<(usize, shadow::TileRect, usize, u32)> = cascades
8243 .iter()
8244 .enumerate()
8245 .map(|(position, cascade)| {
8246 (
8247 *cascade,
8248 self.shadow_lights.atlas_rect(*cascade),
8249 position,
8250 0,
8251 )
8252 })
8253 .collect();
8254 for (index, (slot, held, light)) in occupied.iter().enumerate() {
8255 // A spot draws face 0 alone; a point light draws all six, each
8256 // through its own matrix into its own tile. `shadow::tile_span` is
8257 // the same function `Selection` allocated the run with, so a face
8258 // here and a tile there cannot disagree about how many there are.
8259 let by_face = self.shadow_draws[shadow_cull(*slot)].frame_mode(self.frame)
8260 == crcbl_shaders::draw_gen::DrawMode::Faces;
8261 for face in 0..shadow::tile_span(light) {
8262 views.push((
8263 shadow_view(*slot, face),
8264 self.shadow_lights
8265 .atlas_rect(shadow::light_tile(held.base + face)),
8266 cascades.len() + index,
8267 face_region(by_face, face),
8268 ));
8269 }
8270 }
8271
8272 let mut pass = graph
8273 .add_render_pass("shadow")
8274 // **Stored, unlike the scene's depth.** This is the one depth buffer
8275 // in the engine that something downstream reads, which is what
8276 // `PassBuilder::clear_depth`'s docs said would need a `StoreOp` the
8277 // day a prepass existed.
8278 .depth(
8279 atlas,
8280 // **Loaded on a frame that is keeping a tile**, which is the
8281 // cadence rung's whole seam: a clear here covers the image, so
8282 // the tiles this frame *does* redraw are reset one at a time by
8283 // the pipeline below instead. A frame keeping nothing clears,
8284 // which is what shipped.
8285 if self.shadow_atlas_clears {
8286 LoadOp::Clear
8287 } else {
8288 LoadOp::Load
8289 },
8290 StoreOp::Store,
8291 crcbl_hal::ClearValue {
8292 depth: crcbl_hal::depth::CLEAR,
8293 ..crcbl_hal::ClearValue::default()
8294 },
8295 )
8296 // Declared so the graph gives it a shader-read layout: it is in
8297 // every cascade's bind group, standing in for the atlas this pass is
8298 // writing. See `ForwardRenderer::shadow_placeholder`.
8299 .read_image(placeholder)
8300 // Likewise, and it is in every one of those groups too — see
8301 // `ForwardRenderer::ambient_occlusion_placeholder`. Nothing samples
8302 // it here either: the depth-only pipeline has no fragment stage.
8303 .read_image(reads.occlusion_placeholder)
8304 // And §3.2's page, which `mesh_layout` names in every group — a
8305 // cascade's included. See `ForwardRenderer::base_color_page_import`
8306 // for what the declaration buys a caller that writes the page.
8307 .read_image(reads.pages.base_color)
8308 // And §2's other three pages beside it, in those same groups and
8309 // sampled by no cascade — see
8310 // `ForwardRenderer::normal_page_import`.
8311 .read_image(reads.pages.normal)
8312 .read_image(reads.pages.mro)
8313 .read_image(reads.pages.emissive)
8314 // And the probe rows, which are in those groups too and which no
8315 // cascade reads — declared on the placeholder's and the pages'
8316 // terms, plus one of their own: the rows are device-local and a copy
8317 // destination so the irradiance probes' gather can
8318 // write them, and a pass that binds a buffer it has not declared is
8319 // one the graph cannot order that write against.
8320 .read_buffer(reads.probes);
8321 // Each tile's mesh pass records the cut it descended to, into a buffer
8322 // of its own — see `ForwardRenderer::shadow_selection`. Empty where
8323 // there is no amplification stage to descend anything.
8324 //
8325 // Declared for every tile rather than for the occupied ones: the state
8326 // is what the buffer is *in*, which does not depend on whether this
8327 // frame happened to write it, and a free tile's buffer still has to
8328 // arrive in the state the next frame's import claims.
8329 for &buffer in selection {
8330 pass = pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8331 }
8332 // The skinned vertices this pass may pull, and the reason it is declared
8333 // here as well as on the colour passes: a cascade draws the same
8334 // geometry out of the same pool, so a shadow that fell before the
8335 // dispatch was visible would be cast by the previous pose — a shadow
8336 // that does not match its caster, on a frame whose picture is otherwise
8337 // right.
8338 if let Some(vertices) = reads.skinned {
8339 pass = pass.read_buffer(vertices);
8340 }
8341 for (_, draws) in &generated {
8342 pass = read_draw_sources(pass, draws, self.emit);
8343 }
8344
8345 let groups = self.shadow_groups[self.frame].clone();
8346 // **What the reflective shadow map is drawn from**, read out here rather
8347 // than reconstructed by the caller: cascade 0's bind group — whose
8348 // uniform block already holds that cascade's `view_proj`, which is what
8349 // "reusing cascade 0's matrix" means — and the `GeneratedDraws` its cull
8350 // produced a moment ago. Both are `Copy`, so recording a second pass
8351 // from them costs no second cull and no second matrix.
8352 //
8353 // [`None`] on a frame that is not drawing cascade 0 at all: shadows off,
8354 // or a `r_shadow_cadence` past one that held the group anyway. The rows
8355 // then keep what the last gather wrote — see [`ProbeUpdate::EveryFrame`],
8356 // which says so.
8357 let cascade_zero: Option<(BindGroupHandle, GeneratedDraws)> = self
8358 .rsm_cull_ready
8359 .then(|| {
8360 generated
8361 .iter()
8362 .find(|(cull, _)| *cull == 0)
8363 .map(|(_, draws)| (groups[CASCADE_ZERO_VIEW], *draws))
8364 })
8365 .flatten();
8366 // **What the punctual reflective shadow map is drawn from**, resolved
8367 // here for `cascade_zero`'s reason and on its terms: each face's own
8368 // bind group — whose uniform block already holds that face's
8369 // `view_proj` — and the `GeneratedDraws` its slot's cull produced a
8370 // moment ago. Both are `Copy`, so the second pass costs no second cull
8371 // and no second matrix.
8372 //
8373 // Found by cull id rather than by position, so this list and the atlas's
8374 // cannot be knocked out of step by a slot the other one skipped.
8375 //
8376 // And the face's draw region, on the atlas's terms: a point light whose
8377 // cull tagged its casters draws each face from that face's region.
8378 let punctual_views: Vec<(BindGroupHandle, shadow::TileRect, GeneratedDraws, u32)> =
8379 punctual
8380 .iter()
8381 .filter_map(|face| {
8382 let (_, draws) = generated.iter().find(|(cull, _)| *cull == face.cull)?;
8383 let by_face = self.shadow_draws[face.cull].frame_mode(self.frame)
8384 == crcbl_shaders::draw_gen::DrawMode::Faces;
8385 Some((
8386 groups[face.view],
8387 face.tile,
8388 *draws,
8389 face_region(by_face, face.face),
8390 ))
8391 })
8392 .collect();
8393 // The culls those faces draw from, **once each**: a point light's six
8394 // faces draw one visible set, so declaring a face's sources would
8395 // declare the same buffers six times in one pass.
8396 let punctual_sources: Vec<GeneratedDraws> = punctual
8397 .iter()
8398 .map(|face| face.cull)
8399 .collect::<std::collections::BTreeSet<_>>()
8400 .into_iter()
8401 .filter_map(|cull| {
8402 let (_, draws) = generated.iter().find(|(candidate, _)| *candidate == cull)?;
8403 Some(*draws)
8404 })
8405 .collect();
8406 let bucket_draws = BucketDraws {
8407 // Replaced per partition below; the field is what the tile clears
8408 // and the reflective shadow map inherit, and neither binds it.
8409 pipeline: self.shadow_pipeline.single,
8410 layout: self.mesh_pipeline_layout,
8411 indices: self.pool.index_buffer(),
8412 emit: self.emit,
8413 calls: self
8414 .bucket_constants
8415 .iter()
8416 .enumerate()
8417 .map(|(bucket, constant_offset)| {
8418 let bucket = u32::try_from(bucket)
8419 .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8420 (
8421 *constant_offset,
8422 self.primary.draws.args_offset(bucket),
8423 self.primary.draws.count_offset(bucket),
8424 self.primary.draws.mesh_args_offset(bucket),
8425 )
8426 })
8427 .collect(),
8428 region_step: self.region_step,
8429 // Packed per partition, where the partition's buckets are known.
8430 ranges: None,
8431 flat: None,
8432 };
8433 // Kept back for the reflective shadow map below, which is the same
8434 // per-bucket call list under a different pipeline — the depth prepass
8435 // plays exactly this trick with the camera's. Cloned before the pass
8436 // body takes the original.
8437 let bucket_calls = bucket_draws.clone();
8438 // The atlas's own split by material mode: an opaque bucket's tile is
8439 // drawn with no fragment stage in a scene that has a cutout in it. Every
8440 // view draws every partition — one call per bucket, per range of
8441 // buckets, or behind a task stage one flat call, per view, under a
8442 // pipeline per mode.
8443 let tile_partitions = self.depth_partitions(&bucket_draws);
8444
8445 // Counted off the two loops the body below runs, before it takes them:
8446 // every partition's calls per occupied view. `ForwardRenderer::counters`
8447 // is what reports it, and reading it back off the same `Vec`s is what
8448 // makes it move when the tile allocation does.
8449 let recorded = views.len() as u64
8450 * tile_partitions
8451 .iter()
8452 .map(BucketDraws::call_count)
8453 .sum::<u64>();
8454 // And the tile resets beside them, which are direct draws of one
8455 // instance rather than indirect ones: a frame that cleared the whole
8456 // attachment records none, and a frame that loaded it records one per
8457 // tile it redraws.
8458 let clears = if self.shadow_atlas_clears {
8459 0
8460 } else {
8461 views.len() as u64
8462 };
8463
8464 // What the image will hold once this body has run, carried into it so
8465 // that *recording* the pass is not what claims the atlas was drawn — see
8466 // [`ForwardRenderer::shadow_atlas_drawn`].
8467 let ran = Arc::clone(&self.shadow_pass_ran);
8468 let pass_id = self.shadow_pass_id;
8469 // The tiles this pass redraws have to be reset before anything is drawn
8470 // into them, and on a frame that loaded the attachment there is nothing
8471 // else that will — see [`MeshModules::depth_clear_pipeline`]. A frame
8472 // that cleared has already had every tile reset by the attachment, so
8473 // this is `None` and the recording is the one that shipped.
8474 let clear = (!self.shadow_atlas_clears).then_some(self.shadow_clear_pipeline);
8475 // **The reset draw has to bind a group, and only a browser says so.**
8476 // `MeshModules::depth_clear_pipeline` builds this pipeline from
8477 // `mesh_pipeline_layout`, so its layout declares group 0 whether or not
8478 // the one triangle's vertex shader reads a byte of it — and WebGPU
8479 // refuses a draw with any group the *layout* declares left unset, where
8480 // Vulkan and the others only care about what the shader dereferences. An
8481 // unbound reset therefore fails no native run and rejects the whole
8482 // browser frame: `No bind group set at group index 0` arrives when the
8483 // encoder is finished, so every pass recorded after it is thrown away
8484 // with it and the canvas stays at the clear colour.
8485 //
8486 // Any bucket's offset does: the block is what the mesh draws index and
8487 // this draw reads none of it, so what matters is that the offset is one
8488 // the layout accepts rather than which bucket it names.
8489 let clear_layout = bucket_draws.layout;
8490 let clear_offset = bucket_draws
8491 .calls
8492 .first()
8493 .map_or(0, |(constant_offset, ..)| *constant_offset);
8494 pass.execute(move |ctx| {
8495 ran.store(pass_id, Ordering::Relaxed);
8496 let encoder = ctx.encoder();
8497 if let Some(clear) = clear {
8498 encoder.bind_graphics_pipeline(clear);
8499 for (view, tile, _, _) in &views {
8500 set_shadow_tile(encoder, *tile);
8501 encoder.bind_group(0, groups[*view], &[clear_offset], clear_layout);
8502 encoder.draw(0..TILE_CLEAR_VERTICES, 0..1);
8503 }
8504 }
8505 for partition in &tile_partitions {
8506 partition.open(encoder);
8507 for (view, tile, cull, region) in &views {
8508 set_shadow_tile(encoder, *tile);
8509 partition.record_region(encoder, groups[*view], &generated[*cull].1, *region);
8510 }
8511 }
8512 });
8513
8514 // --- the reflective shadow map ---
8515 //
8516 // The irradiance probes' updater, first half, recorded
8517 // here because this is where cascade 0's bind group and its
8518 // already-generated draws are. **A pass of its own at its own extent**,
8519 // and [`crate::rsm`]'s header argues why it cannot ride the atlas above:
8520 // one colour attachment there spans the whole 3072² image for data only
8521 // one 768² tile is read from, and it would give all fourteen light tiles
8522 // a fragment stage.
8523 //
8524 // No viewport is set: the graph opens a pass with a full-target viewport
8525 // and scissor already, and every attachment here is the map's own square.
8526 let Some((cascade_group, cascade_draws)) = cascade_zero else {
8527 return (atlas, recorded, clears, None);
8528 };
8529 let extent = rsm::extent();
8530 let sun = RsmTargets {
8531 albedo: graph.create_image("rsm-albedo", rsm::albedo_target(extent)),
8532 normal: graph.create_image("rsm-normal", rsm::normal_target(extent)),
8533 world: graph.create_image("rsm-world", rsm::world_target(extent)),
8534 };
8535 // Its own depth, cleared and discarded: it resolves which surface a
8536 // texel of the map holds and nothing reads it afterwards.
8537 let rsm_depth = graph.create_image("rsm-depth", rsm::depth_target(extent));
8538 let mut rsm = graph
8539 .add_render_pass("rsm")
8540 // **Cleared, and the world target's clear is load-bearing**: `w` is
8541 // the coverage flag `RsmOutput::world` writes, so a texel the pass
8542 // draws nothing into reads back zero there and the gather skips it.
8543 // Without the clear the world origin would stand in for every part
8544 // of the cascade the geometry does not cover.
8545 .clear_color(sun.albedo, [0.0; 4])
8546 .clear_color(sun.normal, [0.0; 4])
8547 .clear_color(sun.world, [0.0; 4])
8548 .clear_depth(rsm_depth)
8549 // The same declarations the cascade above makes, for the same
8550 // reason: every group of the mesh layout names these, and this pass
8551 // binds one of those groups. Unlike the cascade, this one has a
8552 // fragment stage — so the pages really are sampled here.
8553 .read_image(placeholder)
8554 .read_image(reads.occlusion_placeholder)
8555 .read_image(reads.pages.base_color)
8556 .read_image(reads.pages.normal)
8557 .read_image(reads.pages.mro)
8558 .read_image(reads.pages.emissive)
8559 .read_buffer(reads.probes);
8560 if let Some(vertices) = reads.skinned {
8561 rsm = rsm.read_buffer(vertices);
8562 }
8563 // Cascade 0's cluster-selection buffer, which the mesh path's stages
8564 // write — declared on the atlas pass's terms, and only for the one view
8565 // this pass draws.
8566 if let Some(&buffer) = selection.get(CASCADE_ZERO_VIEW) {
8567 rsm = rsm.use_buffer(buffer, ResourceState::ShaderReadWrite);
8568 }
8569 rsm = read_draw_sources(rsm, &cascade_draws, self.emit);
8570 // Split by side, on the colour pass's terms: this stage cuts the alpha
8571 // mask itself, so the only thing it cannot say inside the fragment stage
8572 // is which faces the rasteriser keeps.
8573 let rsm_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
8574 let rsm_recorded: u64 = rsm_partitions.iter().map(BucketDraws::call_count).sum();
8575 rsm.execute(move |ctx| {
8576 let encoder = ctx.encoder();
8577 for partition in &rsm_partitions {
8578 partition.open(encoder);
8579 partition.record(encoder, cascade_group, &cascade_draws);
8580 }
8581 });
8582
8583 // --- the punctual reflective shadow map ---
8584 //
8585 // The irradiance probes' punctual producer: the same
8586 // pipeline and the same per-bucket call list as the pass above, under
8587 // one viewport per shadowed light face instead of one whole map. A spot
8588 // is a tile and a point light is six, which is `shadow::tile_span` — so
8589 // this is the atlas pass's own view loop drawn into a second, much
8590 // smaller set of targets.
8591 //
8592 // **Recorded whether or not the frame lights a punctual face**, unlike
8593 // the map above. The clear is a legitimate answer — a frame with no
8594 // shadowed punctual light has no punctual bounce, and the coverage flag
8595 // in `w` says so at every texel — and a pass that came and went with the
8596 // lights would be a pass list that changes shape with the scene, which
8597 // is what `RENDER_PASSES` and every timing reader are written against.
8598 let punctual_extent = rsm::punctual_extent();
8599 let punctual_targets = RsmTargets {
8600 albedo: graph.create_image("rsm-punctual-albedo", rsm::albedo_target(punctual_extent)),
8601 normal: graph.create_image("rsm-punctual-normal", rsm::normal_target(punctual_extent)),
8602 world: graph.create_image("rsm-punctual-world", rsm::world_target(punctual_extent)),
8603 };
8604 let punctual_depth =
8605 graph.create_image("rsm-punctual-depth", rsm::depth_target(punctual_extent));
8606 let mut punctual_pass = graph
8607 .add_render_pass("rsm-punctual")
8608 // Cleared on the map above's terms, and the world target's clear is
8609 // load-bearing for its reason as well as for one of this map's own:
8610 // the tiles the cascades would hold are drawn into by nothing at
8611 // all, and a coverage flag of zero is what keeps the gather out of
8612 // them.
8613 .clear_color(punctual_targets.albedo, [0.0; 4])
8614 .clear_color(punctual_targets.normal, [0.0; 4])
8615 .clear_color(punctual_targets.world, [0.0; 4])
8616 .clear_depth(punctual_depth)
8617 .read_image(placeholder)
8618 .read_image(reads.occlusion_placeholder)
8619 .read_image(reads.pages.base_color)
8620 .read_image(reads.pages.normal)
8621 .read_image(reads.pages.mro)
8622 .read_image(reads.pages.emissive)
8623 .read_buffer(reads.probes);
8624 if let Some(vertices) = reads.skinned {
8625 punctual_pass = punctual_pass.read_buffer(vertices);
8626 }
8627 // Each face's own cluster-selection buffer, which the mesh path's stages
8628 // write — declared on the atlas pass's terms, and only for the views
8629 // this pass draws.
8630 for face in &punctual {
8631 if let Some(&buffer) = selection.get(face.view) {
8632 punctual_pass = punctual_pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8633 }
8634 }
8635 for draws in &punctual_sources {
8636 punctual_pass = read_draw_sources(punctual_pass, draws, self.emit);
8637 }
8638 let punctual_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
8639 let punctual_recorded = punctual_views.len() as u64
8640 * punctual_partitions
8641 .iter()
8642 .map(BucketDraws::call_count)
8643 .sum::<u64>();
8644 punctual_pass.execute(move |ctx| {
8645 let encoder = ctx.encoder();
8646 // The partition is **outside** the view loop, on the shadow atlas's
8647 // terms: one pipeline bind covers every face of that side.
8648 for partition in &punctual_partitions {
8649 partition.open(encoder);
8650 for (group, tile, draws, region) in &punctual_views {
8651 set_shadow_tile(encoder, *tile);
8652 partition.record_region(encoder, *group, draws, *region);
8653 }
8654 }
8655 });
8656
8657 let images = RsmImages {
8658 sun,
8659 punctual: punctual_targets,
8660 };
8661 (
8662 atlas,
8663 recorded + rsm_recorded + punctual_recorded,
8664 clears,
8665 Some(images),
8666 )
8667 }
8668
8669 /// Which lights hold the atlas's light tiles this frame, and where each
8670 /// map was laid out.
8671 ///
8672 /// **The observable topic 45's priority rung otherwise has
8673 /// none for.** A map's *size* leaves no trace in the picture that a golden
8674 /// can hold anyone to: a light demoted to a quarter of a cell draws a
8675 /// slightly softer shadow, which is a perfectly plausible frame and one a
8676 /// re-bless accepts. [`Selection::atlas_rect`](crate::shadow::Selection)
8677 /// off this is what says which level the allocator actually handed out, and
8678 /// `crates/crcbl/tests/mesh_e2e/shadow_tiles.rs` is what reads it.
8679 ///
8680 /// Named for the selection's own subject rather than for its type, because
8681 /// [`Self::shadow_selection`] above is a *buffer* — the cut a cascade
8682 /// descended to — and two accessors of one name is a caller reaching for
8683 /// the wrong one.
8684 ///
8685 /// It is this frame's answer, written by [`Self::begin_frame`]: before the
8686 /// first frame every slot is free.
8687 /// Whether this frame took the shadow atlas as an earlier frame left it,
8688 /// rather than drawing it again.
8689 ///
8690 /// Topic 45's static-caching rung, read back. True means
8691 /// this frame recorded **no** shadow cull and no shadow pass, and every map
8692 /// sampled through [`Self::shadow_lights`]'s rectangles is the one the last
8693 /// frame that did draw put there — so a caller comparing two frames' pass
8694 /// lists, draw counts or GPU timings has to know which of them redrew.
8695 ///
8696 /// Decided by [`Self::begin_frame`] out of everything each group of the
8697 /// atlas is a function of — see `ForwardRenderer::shadow_group_record` —
8698 /// and it answers `false` before the first frame, because no frame has been
8699 /// opened and so none of them has held anything.
8700 ///
8701 /// **Whole-atlas, and since the cadence rung a frame can be neither.** A
8702 /// frame that redraws one map and holds another answers `false` here and
8703 /// `false` from [`Self::shadow_slot_redrawn`] for the maps it held; the two
8704 /// together are what say which.
8705 #[must_use]
8706 pub const fn shadow_atlas_cached(&self) -> bool {
8707 self.shadow_atlas_cached
8708 }
8709
8710 /// Whether this frame redrew cascade `cascade`'s map, rather than keeping
8711 /// the one an earlier frame put there.
8712 ///
8713 /// Topic 45's cadence rung, read back. **The observable
8714 /// that rung otherwise has none for**: a held map draws a shadow lagging its
8715 /// caster by a frame or two, which is a perfectly plausible picture and one
8716 /// a golden accepts — so nothing but this distinguishes a cadence that is
8717 /// working from one that is not running at all.
8718 ///
8719 /// `false` for a `cascade` past [`shadow::CASCADES`] and before the first
8720 /// frame, which is the same answer for the same reason: no map was drawn
8721 /// there.
8722 #[must_use]
8723 pub fn shadow_cascade_redrawn(&self, cascade: usize) -> bool {
8724 cascade < shadow::CASCADES && self.shadow_group_redrawn[cascade]
8725 }
8726
8727 /// Whether this frame redrew the maps of light slot `slot` —
8728 /// [`shadow::Selection::slots`]' index — rather than keeping the ones an
8729 /// earlier frame put there.
8730 ///
8731 /// [`Self::shadow_cascade_redrawn`]'s answer for the light region, and a
8732 /// point light's [`shadow::POINT_FACES`] faces answer together: they cull
8733 /// once and draw one visible set, so they are redrawn or held as one.
8734 #[must_use]
8735 pub fn shadow_slot_redrawn(&self, slot: usize) -> bool {
8736 slot < shadow::LIGHT_SLOTS && self.shadow_group_redrawn[shadow_cull(slot)]
8737 }
8738
8739 /// How many tiles of the atlas this frame redrew.
8740 ///
8741 /// What [`shadow::r_shadow_faces`] is spent in, read back — so a test can
8742 /// say the budget bound rather than that it was configured. A cascade costs
8743 /// one and a point light's cube costs [`shadow::POINT_FACES`].
8744 #[must_use]
8745 pub const fn shadow_faces_redrawn(&self) -> u32 {
8746 self.shadow_faces_redrawn
8747 }
8748
8749 /// Pins the shadow cadence for this renderer, or hands it back to the
8750 /// console.
8751 ///
8752 /// [`Self::set_effect_request`]'s shape at this knob:
8753 /// [`shadow::r_shadow_cadence`] and [`shadow::r_shadow_faces`] are
8754 /// process-global, so they are the *default* rather than the only answer —
8755 /// an application drawing two views at two qualities, or a test that needs a
8756 /// frame nothing else in the process can move, pins its own.
8757 ///
8758 /// [`None`] hands it back, which is what a renderer starts at.
8759 ///
8760 /// Read once per [`Self::begin_frame`], on `ForwardRenderer::frame_effects`'
8761 /// terms: this call decides it and `add_passes` acts on it.
8762 pub const fn set_shadow_cadence(&mut self, cadence: Option<shadow::Cadence>) {
8763 self.shadow_cadence_request = cadence;
8764 }
8765
8766 /// Whether this frame ignored the cadence for at least one map because the
8767 /// region that map covers had moved out from under it.
8768 ///
8769 /// Topic 45's "a moving light or camera cut resets it",
8770 /// made precise: a map is *reset* rather than merely out of date when the
8771 /// centre it is projected from has moved further than the map's own reach —
8772 /// a light further than its own radius, or a cascade's eye further than the
8773 /// sphere that cascade was fitted to. Holding such a map is not a shadow
8774 /// that lags; it is a shadow of somewhere else.
8775 ///
8776 /// A frame whose atlas was **relaid** — a light gained, lost or resized a
8777 /// tile, or shadows were switched on or off — answers `true` as well, and
8778 /// that frame redraws every map it has: the only clear this seam can make
8779 /// covers the whole image, so there is nothing left to hold.
8780 #[must_use]
8781 pub const fn shadow_cadence_reset(&self) -> bool {
8782 self.shadow_cadence_reset
8783 }
8784
8785 #[must_use]
8786 pub const fn shadow_lights(&self) -> &shadow::Selection {
8787 &self.shadow_lights
8788 }
8789
8790 /// The shadow atlas, for a caller that wants to read it back.
8791 ///
8792 /// **The observable this whole slice can otherwise hide behind.** A shadow
8793 /// pass that renders nothing leaves every texel at
8794 /// [`depth::CLEAR`](crcbl_hal::depth::CLEAR) and produces a frame in which
8795 /// everything is lit — which is a perfectly plausible picture and matches
8796 /// any golden blessed from it. Copying this image back and finding a texel
8797 /// that is not the clear value is what distinguishes the two.
8798 ///
8799 /// It is created with
8800 /// [`ImageUsage::TRANSFER_SRC`](crcbl_hal::ImageUsage::TRANSFER_SRC) for
8801 /// exactly that, and its extent is [`shadow::atlas_extent`].
8802 #[must_use]
8803 pub const fn shadow_atlas(&self) -> crcbl_hal::ImageHandle {
8804 self.shadow_atlas
8805 }
8806
8807 /// The view [`shadow_atlas`](Self::shadow_atlas) is bound and imported
8808 /// through, for a reader importing the atlas into a graph of its own.
8809 #[must_use]
8810 pub const fn shadow_atlas_view(&self) -> ImageViewHandle {
8811 self.shadow_atlas_view
8812 }
8813
8814 /// The base-colour page every material row samples through
8815 /// [`GpuMaterial::base_color_texture`](crcbl_shaders::mesh::GpuMaterial::base_color_texture),
8816 /// as the image and the view [`crate::texture`] uploaded.
8817 ///
8818 /// **What a render-to-texture view copies into.** A second camera drawing
8819 /// into an image is only half of a monitor: the surface that *shows* it
8820 /// samples a page layer, and nothing above this crate can name the image
8821 /// that layer lives in.
8822 ///
8823 /// A caller that wants to *write* it wants
8824 /// [`base_color_page_import`](Self::base_color_page_import) instead: the
8825 /// graph can only order a copy against the draws that sample the page while
8826 /// both are declared, and the two declarations have to agree field for
8827 /// field. This one is the raw handles, for a caller that binds or reads them
8828 /// outside a graph.
8829 ///
8830 /// It is created with
8831 /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST),
8832 /// because the upload that filled it is a copy, so a per-frame copy into it
8833 /// needs no new usage flag. Its extent is
8834 /// [`PageDesc::extent`](crate::scene::PageDesc::extent) of
8835 /// [`PageKind::BaseColor`] squared and it has one layer per
8836 /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of that kind;
8837 /// the description is the caller's, so the caller already knows both. A
8838 /// description naming no base-colour layer gets a 1×1 placeholder instead —
8839 /// see this module's `PAGE_PLACEHOLDER_TEXEL`.
8840 #[must_use]
8841 pub const fn base_color_page(&self) -> UploadedTexture {
8842 self.base_color_page
8843 }
8844
8845 /// What [`add_passes`](Self::add_passes) names the base-colour page in the
8846 /// graph.
8847 ///
8848 /// [`RenderGraph::import_image`] keeps the label of whichever import ran
8849 /// first, so a caller importing the page too passes this rather than a
8850 /// string of its own — otherwise every barrier record and
8851 /// [`dump`](crate::CompiledGraph::dump) line would name the page differently
8852 /// depending on which subsystem got there first.
8853 pub const BASE_COLOR_PAGE_LABEL: &'static str = "base-colour-page";
8854
8855 /// The base-colour page **as this renderer declares it to a graph**.
8856 ///
8857 /// [`add_passes`](Self::add_passes) imports exactly this value under
8858 /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL) and declares a read
8859 /// of it on every pass whose bind group names the page, so a caller that
8860 /// writes the page — a render-to-texture view copied into one layer — gets
8861 /// the graph to order its write against those draws.
8862 ///
8863 /// **A caller that writes it imports this value rather than one of its
8864 /// own.** [`RenderGraph::import_image`] hands the second importer the id the
8865 /// first got, which is what puts the write and the reads on one state
8866 /// tracker, and it does that only while the two declarations agree in every
8867 /// field — a disagreement is [`GraphError::ImportDeclarationConflict`] at
8868 /// [`compile`](RenderGraph::compile). Reading the declaration off the
8869 /// renderer that owns the page is what makes them one answer instead of two
8870 /// constants that have to be kept equal by hand.
8871 ///
8872 /// [`InitialClaim::Tracked`] with [`ResourceState::ShaderRead`] both ways:
8873 /// [`crate::texture`] leaves an uploaded page in that state, and the
8874 /// trailing barrier the `final_state` asks for puts it back there at the end
8875 /// of every frame — so the pool's ledger and this declaration are the same
8876 /// answer, which is what `Tracked` has the graph check.
8877 ///
8878 /// [`GraphError::ImportDeclarationConflict`]: crate::graph::GraphError::ImportDeclarationConflict
8879 #[must_use]
8880 pub const fn base_color_page_import(&self) -> ImportedImage {
8881 ImportedImage {
8882 image: self.base_color_page.image,
8883 view: self.base_color_page.view,
8884 format: BASE_COLOR_PAGE_FORMAT,
8885 extent: self.page_extents[PageKind::BaseColor.index()],
8886 initial: ResourceState::ShaderRead,
8887 claim: InitialClaim::Tracked,
8888 final_state: ResourceState::ShaderRead,
8889 }
8890 }
8891
8892 /// Topic 43 §2's **normal** page, the raw handles.
8893 ///
8894 /// [`base_color_page`](Self::base_color_page)'s counterpart, on every one of
8895 /// its terms: one `D2Array` image, one layer per
8896 /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of
8897 /// [`PageKind::Normal`], at **that kind's own extent**, and created with
8898 /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST) so a
8899 /// per-frame copy into a layer needs no new usage flag. What it is *not* is
8900 /// the same format: it is `Rgba8Unorm`, where the base-colour page is
8901 /// `Rgba8UnormSrgb`, and topic 44's rung 2 is where that
8902 /// is argued.
8903 #[must_use]
8904 pub const fn normal_page(&self) -> UploadedTexture {
8905 self.normal_page
8906 }
8907
8908 /// What [`add_passes`](Self::add_passes) names the normal page in the graph,
8909 /// on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8910 pub const NORMAL_PAGE_LABEL: &'static str = "normal-page";
8911
8912 /// The normal page **as this renderer declares it to a graph**, on
8913 /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly
8914 /// — including that a caller writing a layer imports *this* value rather
8915 /// than one of its own, so the write and the draws land on one state
8916 /// tracker.
8917 #[must_use]
8918 pub const fn normal_page_import(&self) -> ImportedImage {
8919 ImportedImage {
8920 image: self.normal_page.image,
8921 view: self.normal_page.view,
8922 format: NORMAL_PAGE_FORMAT,
8923 extent: self.page_extents[PageKind::Normal.index()],
8924 initial: ResourceState::ShaderRead,
8925 claim: InitialClaim::Tracked,
8926 final_state: ResourceState::ShaderRead,
8927 }
8928 }
8929
8930 /// Topic 43 §2's packed
8931 /// **metallic-roughness-occlusion** page, the raw handles.
8932 ///
8933 /// [`normal_page`](Self::normal_page)'s counterpart, on every one of its
8934 /// terms and at the same `Rgba8Unorm` format: a layer of it is glTF's
8935 /// occlusion, roughness and metallic in `r`, `g` and `b`, which are numbers
8936 /// rather than a colour — see this module's `MRO_PAGE_FORMAT`.
8937 #[must_use]
8938 pub const fn mro_page(&self) -> UploadedTexture {
8939 self.mro_page
8940 }
8941
8942 /// What [`add_passes`](Self::add_passes) names the
8943 /// metallic-roughness-occlusion page in the graph, on
8944 /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8945 pub const MRO_PAGE_LABEL: &'static str = "metallic-roughness-occlusion-page";
8946
8947 /// The metallic-roughness-occlusion page **as this renderer declares it to a
8948 /// graph**, on [`base_color_page_import`](Self::base_color_page_import)'s
8949 /// terms exactly.
8950 #[must_use]
8951 pub const fn mro_page_import(&self) -> ImportedImage {
8952 ImportedImage {
8953 image: self.mro_page.image,
8954 view: self.mro_page.view,
8955 format: MRO_PAGE_FORMAT,
8956 extent: self.page_extents[PageKind::MetallicRoughnessOcclusion.index()],
8957 initial: ResourceState::ShaderRead,
8958 claim: InitialClaim::Tracked,
8959 final_state: ResourceState::ShaderRead,
8960 }
8961 }
8962
8963 /// Topic 43 §2's **emissive** page, the raw
8964 /// handles.
8965 ///
8966 /// [`base_color_page`](Self::base_color_page)'s counterpart down to the
8967 /// format: an emissive texel is a colour, so this image is
8968 /// `Rgba8UnormSrgb` and the sampler decodes it — see this module's
8969 /// `EMISSIVE_PAGE_FORMAT`.
8970 #[must_use]
8971 pub const fn emissive_page(&self) -> UploadedTexture {
8972 self.emissive_page
8973 }
8974
8975 /// What [`add_passes`](Self::add_passes) names the emissive page in the
8976 /// graph, on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8977 pub const EMISSIVE_PAGE_LABEL: &'static str = "emissive-page";
8978
8979 /// The emissive page **as this renderer declares it to a graph**, on
8980 /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly.
8981 #[must_use]
8982 pub const fn emissive_page_import(&self) -> ImportedImage {
8983 ImportedImage {
8984 image: self.emissive_page.image,
8985 view: self.emissive_page.view,
8986 format: EMISSIVE_PAGE_FORMAT,
8987 extent: self.page_extents[PageKind::Emissive.index()],
8988 initial: ResourceState::ShaderRead,
8989 claim: InitialClaim::Tracked,
8990 final_state: ResourceState::ShaderRead,
8991 }
8992 }
8993
8994 /// The model matrix for a cube spinning at `seconds` into the run.
8995 ///
8996 /// Two axes at incommensurable rates, so the animation never repeats and
8997 /// every face comes into view — which is what makes "the cube is spinning"
8998 /// observable rather than a claim about a matrix.
8999 #[must_use]
9000 pub fn spin(seconds: f32) -> Mat4 {
9001 Mat4::from_quat(
9002 Quat::from_axis_angle(Vec3::Y, seconds * 0.9)
9003 * Quat::from_axis_angle(Vec3::X, seconds * 0.55),
9004 )
9005 }
9006
9007 /// The format the tonemap pass renders into.
9008 #[must_use]
9009 pub const fn target_format(&self) -> Format {
9010 self.target_format
9011 }
9012
9013 /// Switches the infinite ground grid on with `style`, or off with [`None`].
9014 ///
9015 /// **Off by default.** Every sample and every golden image predates the
9016 /// grid, so a renderer nobody has called this on records exactly the passes
9017 /// it always did — see [`crate::grid`] for what the pass is and
9018 /// [`add_passes`](Self::add_passes) for where in the frame it lands.
9019 ///
9020 /// The first `Some` builds the pipeline and the uniform ring; later calls
9021 /// only replace the style, and a `None` leaves both built. Releasing them
9022 /// here would mean releasing blocks the frames in flight may still be
9023 /// reading, so they are released by [`destroy`](Self::destroy) alone — the
9024 /// one call that already requires an idle device.
9025 ///
9026 /// # Errors
9027 ///
9028 /// [`HalError`] if the grid's pipeline or its blocks could not be created.
9029 /// Nothing is left switched on when that happens: the grid stays as it was.
9030 pub fn set_ground_grid(
9031 &mut self,
9032 device: &dyn Device,
9033 style: Option<GridStyle>,
9034 ) -> Result<(), HalError> {
9035 let Some(style) = style else {
9036 self.ground_grid_on = false;
9037 return Ok(());
9038 };
9039 let grid = match self.ground_grid.as_mut() {
9040 Some(grid) => grid,
9041 None => {
9042 // Built for the tonemap's target and the scene depth, because
9043 // those are the two attachments the pass is given — see
9044 // `add_passes`. Both are pipeline state, so a renderer whose
9045 // target format changed would need a new `Grid`; nothing in this
9046 // crate changes it after `build`, and `target_format` is kept
9047 // for exactly that reason.
9048 let grid = GroundGrid::new(
9049 device,
9050 self.primary.uniforms.len(),
9051 self.target_format,
9052 SCENE_DEPTH_FORMAT,
9053 )?;
9054 self.ground_grid.insert(grid)
9055 }
9056 };
9057 grid.set_style(style);
9058 self.ground_grid_on = true;
9059 Ok(())
9060 }
9061
9062 /// The debug draw layer's immediate-mode buffer, to append to.
9063 ///
9064 /// The UI's debug item 5 (`docs/notes/tooling.md`): any system appends lines, boxes,
9065 /// spheres and frusta during the frame, and
9066 /// [`begin_frame`](Self::begin_frame) uploads and clears what is there — so
9067 /// a segment lives exactly the frame it was appended in and nothing has to
9068 /// be un-appended. See [`crate::debug_draw`] for where the pass lands and
9069 /// for the console switch that has to be on before anything is drawn.
9070 ///
9071 /// **Appending is free while the layer is off**, but building the geometry
9072 /// is the caller's: a system whose overlay costs something to compute asks
9073 /// [`DebugDraw::enabled`] first.
9074 pub fn debug_draw(&mut self) -> &mut DebugDraw {
9075 &mut self.debug_draw
9076 }
9077
9078 /// How the ground grid is drawn, or [`None`] where it is switched off.
9079 ///
9080 /// The read-back half of [`set_ground_grid`](Self::set_ground_grid), and the
9081 /// observable a test asking "is the grid on" wants: a renderer that built
9082 /// the grid and then switched it off answers [`None`], because what it draws
9083 /// is what the question is about.
9084 #[must_use]
9085 pub fn ground_grid(&self) -> Option<&GridStyle> {
9086 self.ground_grid
9087 .as_ref()
9088 .filter(|_| self.ground_grid_on)
9089 .map(GroundGrid::style)
9090 }
9091
9092 /// Whether this frame adds [`crate::sky_pass`]'s background pass.
9093 ///
9094 /// [`Sky::NONE`] with no atmosphere is the value a renderer nobody called
9095 /// [`set_sky`](Self::set_sky) or
9096 /// [`set_atmosphere`](Self::set_atmosphere) on holds, and it is checked
9097 /// here rather than left to the shader for the reason [`crate::sky_pass`]
9098 /// gives: a black gradient drawn over [`SCENE_CLEAR`] would *change* those
9099 /// frames, where adding no pass leaves them exactly as they were.
9100 fn draws_sky(&self) -> bool {
9101 self.sky != Sky::NONE || self.atmosphere.is_some()
9102 }
9103
9104 /// Brings [`Self::sky_view`] up to the sun this frame has, a stripe of rows
9105 /// per frame.
9106 ///
9107 /// Called once per [`Self::begin_frame`]. The comparison is on the
9108 /// normalised parameters rather than on the [`Atmosphere`] a caller handed
9109 /// over, so re-setting the same sun spelled a different length is not a
9110 /// rebuild — and a caller that sets the same value every frame, which is
9111 /// the ordinary shape of a scene's update, pays the comparison and nothing
9112 /// else.
9113 ///
9114 /// # The first LUT is marched whole; every later one is marched in stripes
9115 ///
9116 /// A renderer that has no LUT has no sky to draw, so the first march after
9117 /// [`set_atmosphere`](Self::set_atmosphere) runs to completion inside this
9118 /// call and a caller that draws a single frame gets that frame's sky. After
9119 /// that there is always a finished LUT to show, so a sun that moved starts
9120 /// a [`SkyViewBuild`] and this steps it [`SKY_VIEW_BUILD_ROWS`] rows per
9121 /// frame — the frames in between keep drawing the LUT the last completed
9122 /// march produced, and no frame pays the whole march.
9123 ///
9124 /// # A sun that moves again restarts the march rather than finishing it
9125 ///
9126 /// The build in flight is kept only while its own sun is still the one the
9127 /// caller wants; a sun that moved during it is a new build from row zero,
9128 /// because finishing the old one would swap in a LUT for a sun that is
9129 /// already wrong and then immediately start marching again. **A sun that
9130 /// moves every frame therefore never completes a build and goes on showing
9131 /// the last one it finished** — a sky frozen at the sun it last caught up
9132 /// with, rather than a sky that stutters at whatever the march last passed.
9133 /// That is the trade this makes: the frame cost is bounded and the sky
9134 /// lags, where the whole-march rebuild it replaced had the sky exact and
9135 /// the frame cost unbounded. A caller that wants the sky exact stops the
9136 /// sun on a value and leaves it there: the march then completes, and the
9137 /// frames it takes are `SKY_VIEW_HEIGHT` over [`SKY_VIEW_BUILD_ROWS`].
9138 ///
9139 /// **The aerial-perspective LUT is marched in the same steps** — see
9140 /// [`SkyViewBuild`] — so the air in front of the scene arrives on the same
9141 /// frame as the sky and lags the sun by the same frames, never a sun apart
9142 /// from it. A change of [`Atmosphere::km_per_unit`] alone is a new march
9143 /// on the same terms, since it is part of the parameters compared.
9144 fn refresh_sky_view(&mut self) {
9145 let Some(atmosphere) = self.atmosphere else {
9146 self.sky_view = None;
9147 self.sky_view_build = None;
9148 return;
9149 };
9150 let parameters = atmosphere.parameters();
9151 if self
9152 .sky_view
9153 .as_ref()
9154 .is_some_and(|presented| presented.parameters == parameters)
9155 {
9156 self.sky_view_build = None;
9157 return;
9158 }
9159 if self.sky_view.is_none() {
9160 self.sky_view_build = None;
9161 self.sky_view = Some(PresentedSky::new(parameters, SkyView::build(¶meters)));
9162 return;
9163 }
9164 let mut build = match self.sky_view_build.take() {
9165 Some(build) if build.atmosphere() == parameters => build,
9166 _ => SkyViewBuild::start(¶meters),
9167 };
9168 if build.step(SKY_VIEW_BUILD_ROWS) {
9169 self.sky_view = Some(PresentedSky::new(parameters, build.finish()));
9170 } else {
9171 self.sky_view_build = Some(build);
9172 }
9173 }
9174
9175 /// Sets the multiplier the tonemap pass applies before its clamp, clamped
9176 /// into [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`].
9177 ///
9178 /// **The default is [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`]**, which is
9179 /// the value `tonemap.slang` held as a compile-time constant until this
9180 /// became a runtime one — so a renderer nobody calls this on draws the frame
9181 /// it always drew, and every golden image is untouched.
9182 ///
9183 /// It takes effect on the next
9184 /// [`begin_frame`](Self::begin_frame), which is what writes the block: a
9185 /// frame already recorded reads the value it was recorded with.
9186 ///
9187 /// **The clamp is here rather than at the call site** so that no caller can
9188 /// reach a picture it cannot get back from, and so that a control which
9189 /// steps by reading this back and setting a multiple of it — which is what
9190 /// [`exposure`](Self::exposure) is for — cannot wind up past the end and
9191 /// then need as many presses to come back.
9192 pub const fn set_exposure(&mut self, exposure: f32) {
9193 // `max` then `min` rather than `f32::clamp`: `clamp` propagates a NaN,
9194 // and a NaN reaching the block is a frame of NaN pixels with no key to
9195 // press to get out of it. `f32::max` returns the bound instead, so a NaN
9196 // lands on `EXPOSURE_MIN` — dark, and one press from being bright again.
9197 self.exposure = exposure.max(EXPOSURE_MIN).min(EXPOSURE_MAX);
9198 }
9199
9200 /// How far auto-exposure may travel toward its measurement in one frame.
9201 ///
9202 /// **[`None`] is the whole distance**, which is what a renderer nobody
9203 /// calls this on does and what the pass did before adaptation existed — so
9204 /// no golden moved when this arrived. A view that wants the roll asks, and
9205 /// asks *every frame*, because [`ExposureAdaptation`] carries that frame's
9206 /// own delta: this crate has no clock, and the frame time lives where the
9207 /// frame loop is.
9208 ///
9209 /// It takes effect on the next [`begin_frame`](Self::begin_frame), which is
9210 /// what writes the block, and it does nothing at all on a frame that did not
9211 /// ask for [`RenderEffects::AUTO_EXPOSURE`] — the passes that read it are
9212 /// the ones that bit adds.
9213 pub const fn set_exposure_adaptation(&mut self, adaptation: Option<ExposureAdaptation>) {
9214 self.exposure_adaptation = adaptation;
9215 }
9216
9217 /// What [`set_exposure_adaptation`](Self::set_exposure_adaptation) was last
9218 /// handed.
9219 #[must_use]
9220 pub const fn exposure_adaptation(&self) -> Option<ExposureAdaptation> {
9221 self.exposure_adaptation
9222 }
9223
9224 /// Which operator the tonemap pass runs on the exposed scene colour.
9225 ///
9226 /// **The ACES fit by default**, because this renderer shades in linear HDR
9227 /// and the roll-off is what that range is for. What a caller asks *for* here
9228 /// is therefore usually the other one: `tonemap.slang`'s clamp is the
9229 /// identity on `0..=1`, so display-referred content reaches the swapchain
9230 /// exactly, and a fixture that predicts a code value from a host model of
9231 /// the shading needs the frame to stay scene-referred. Every 2D sample in
9232 /// this tree draws through `crate::sprite_pass` and `crate::ui_pass`
9233 /// instead, so none of them reaches this pass at all.
9234 ///
9235 /// It takes effect on the next [`begin_frame`](Self::begin_frame), for
9236 /// [`set_exposure`](Self::set_exposure)'s reason: the block is written
9237 /// there, and a frame already recorded reads the value it was recorded
9238 /// with.
9239 ///
9240 /// **There is nothing to refuse and no `supports_` probe beside it.** The
9241 /// selector is a lane of a uniform block read by a branch every device
9242 /// already runs, so unlike the wireframe there is no second pipeline for a
9243 /// device to decline to build.
9244 pub const fn set_tonemap_curve(&mut self, curve: tonemap::TonemapCurve) {
9245 self.tonemap_curve = curve;
9246 }
9247
9248 /// The operator in force, on [`exposure`](Self::exposure)'s terms: the
9249 /// value the next frame will be drawn with.
9250 #[must_use]
9251 pub const fn tonemap_curve(&self) -> tonemap::TonemapCurve {
9252 self.tonemap_curve
9253 }
9254
9255 /// How large the internal render target is as a fraction of the extent
9256 /// [`begin_frame`](Self::begin_frame) is handed, clamped to
9257 /// `MIN_RENDER_SCALE..=1.0`.
9258 ///
9259 /// **This is the largest performance knob this renderer has.** Every pass
9260 /// before the upscale costs what its extent costs, so a scale of `0.7` is
9261 /// roughly half the shading work of `1.0`; the UI is composited onto the
9262 /// target afterwards at native resolution, so text stays sharp while the 3D
9263 /// frame gets cheap. `docs/notes/rendering.md` (_What the deleted
9264 /// 48-post-processing plan left behind_) is where that trade is written down.
9265 ///
9266 /// **`1.0` is not a special case with a fast path, it is the absence of the
9267 /// feature.** At full scale the internal extent *is* the caller's, the post
9268 /// chain writes the target directly, and no upscale pass is recorded — which
9269 /// is what makes a renderer nobody has called this on draw the frame it drew
9270 /// before the knob existed, bit for bit.
9271 ///
9272 /// **Above `1.0` is clamped away rather than supported.** Supersampling
9273 /// wants a box or Lanczos reduction and `upscale.slang` is a Catmull-Rom
9274 /// *reconstruction*; running it as a minification filter would alias, which
9275 /// is the opposite of what a caller asking for it wants. A non-finite scale
9276 /// is clamped to `1.0` for the same reason a `NaN` extent would be refused:
9277 /// the failure it produces is a zero-sized target somewhere downstream.
9278 ///
9279 /// Takes effect on the next [`begin_frame`](Self::begin_frame), on
9280 /// [`set_exposure`](Self::set_exposure)'s terms exactly — a frame already
9281 /// recorded is drawn at the scale it was recorded with.
9282 pub fn set_render_scale(&mut self, scale: f32) {
9283 self.render_scale = if scale.is_finite() {
9284 scale.clamp(MIN_RENDER_SCALE, 1.0)
9285 } else {
9286 1.0
9287 };
9288 }
9289
9290 /// The render scale in force, after the clamp
9291 /// [`set_render_scale`](Self::set_render_scale) applied.
9292 ///
9293 /// The read-back half, on [`exposure`](Self::exposure)'s terms.
9294 #[must_use]
9295 pub const fn render_scale(&self) -> f32 {
9296 self.render_scale
9297 }
9298
9299 /// The anisotropy the base-colour page is sampled with, in force from the
9300 /// next [`begin_frame`](Self::begin_frame).
9301 ///
9302 /// Topic 43's filtering rung, the player's half:
9303 /// [`anisotropy_for`](Self::anisotropy_for) is what a renderer nobody has
9304 /// called this on samples with, and this is what a settings row moves it
9305 /// to. Clamped to `1.0..=max_sampler_anisotropy` where the device was
9306 /// granted [`Features::SAMPLER_ANISOTROPY`] and to exactly `1.0` where it
9307 /// was not — the row can turn the filter off or push it to the device's
9308 /// ceiling, and nothing it asks reaches a `create_sampler` that would
9309 /// refuse it. A value that is not a number is the default, on
9310 /// [`set_render_scale`](Self::set_render_scale)'s terms.
9311 ///
9312 /// **A sampler is a resource a bind group holds by handle**, so a new
9313 /// anisotropy is a new sampler, and every group of the mesh layout has to
9314 /// be rebuilt to name it. That happens per frame slot, at the slot's own
9315 /// `begin_frame`, which is the moment the ring guarantees the slot's
9316 /// previous submission has retired — the guarantee every host write in
9317 /// that call already leans on — so a frame in flight goes on naming the
9318 /// sampler it was recorded with, and the replaced sampler is destroyed once
9319 /// no slot names it. This call creates the sampler and nothing else, and
9320 /// asking for the anisotropy already in force creates nothing.
9321 ///
9322 /// # Errors
9323 ///
9324 /// `create_sampler`'s, and the renderer is unchanged — the sampler in force
9325 /// stays in force.
9326 pub fn set_anisotropy(&mut self, device: &dyn Device, anisotropy: f32) -> Result<(), HalError> {
9327 let caps = device.caps();
9328 let ceiling = if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9329 caps.limits.max_sampler_anisotropy
9330 } else {
9331 1.0
9332 };
9333 let wanted = if anisotropy.is_finite() {
9334 anisotropy.clamp(1.0, ceiling)
9335 } else {
9336 Self::anisotropy_for(&caps)
9337 };
9338 // Bit-equal rather than within an epsilon: both sides came out of the
9339 // same clamp, and a row that lands on the value in force must not
9340 // rebuild every group for it.
9341 if wanted.to_bits() == self.anisotropy.to_bits() {
9342 return Ok(());
9343 }
9344 let sampler = Self::create_page_sampler(device, wanted)?;
9345 self.retired_pages
9346 .push(RetiredPage::Sampler(std::mem::replace(
9347 &mut self.base_color_sampler,
9348 sampler,
9349 )));
9350 self.anisotropy = wanted;
9351 Ok(())
9352 }
9353
9354 /// The anisotropy in force, after the clamp
9355 /// [`set_anisotropy`](Self::set_anisotropy) applied.
9356 ///
9357 /// The read-back half, on [`render_scale`](Self::render_scale)'s terms.
9358 #[must_use]
9359 pub const fn anisotropy(&self) -> f32 {
9360 self.anisotropy
9361 }
9362
9363 /// The anisotropy the base-colour page's sampler is created with on a
9364 /// device of `caps`: [`DEFAULT_ANISOTROPY`] clamped to
9365 /// [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) where
9366 /// [`Features::SAMPLER_ANISOTROPY`] was granted, and `1.0` where it was
9367 /// not.
9368 ///
9369 /// **Granted, not supported.** The feature is optional at every open site
9370 /// — [`Features::GPU_DRIVEN`] does not carry it — and a device opened
9371 /// without asking refuses a sampler above one even on hardware that has
9372 /// it, which is the shape every backend's `create_sampler` documents. So
9373 /// the question is what this device was opened *with*, and a caller that
9374 /// wants the plan's default has to name the feature beside the others it
9375 /// asks for. `crcbl-webgpu` withholds the feature and reports a ceiling of
9376 /// one, so a browser samples isotropically until `docs/backlog.md`'s
9377 /// ceiling decision is taken.
9378 #[must_use]
9379 pub fn anisotropy_for(caps: &DeviceCaps) -> f32 {
9380 if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9381 DEFAULT_ANISOTROPY.min(caps.limits.max_sampler_anisotropy)
9382 } else {
9383 1.0
9384 }
9385 }
9386
9387 /// The base-colour page's sampler at `anisotropy`, which the caller has
9388 /// already held to the device — [`anisotropy_for`](Self::anisotropy_for)
9389 /// at build, [`set_anisotropy`](Self::set_anisotropy)'s clamp after.
9390 ///
9391 /// **Trilinear over the whole chain, anisotropic where the device is** —
9392 /// topic 43's filtering rung: a minified surface
9393 /// reads the level its footprint matches instead of shimmering through
9394 /// level 0, a magnified one blends four texels instead of stepping between
9395 /// them, and a surface at a grazing angle keeps its detail along the long
9396 /// axis of its footprint rather than blurring to the short one. A second
9397 /// sampler object rather than sharing the tonemap's, so a capture names
9398 /// each for what it filters.
9399 ///
9400 /// **`Repeat`, not `ClampToEdge`**, and that is what `mesh.slang`'s
9401 /// `TILING_PHYSICAL` needs: a physical UV runs to `world_extent /
9402 /// tile_metres`, past `0..1` on any face wider than one tile, and only a
9403 /// wrapping address mode makes the page tile across it rather than
9404 /// smearing its edge row. `TILING_AUTHORED` is unaffected — its UV is the
9405 /// vertex's, which the meshes author inside `0..1`, so a wrapped and a
9406 /// clamped read return the same nearest texel for it.
9407 fn create_page_sampler(
9408 device: &dyn Device,
9409 anisotropy: f32,
9410 ) -> Result<SamplerHandle, HalError> {
9411 device.create_sampler(&SamplerDesc {
9412 label: Some("material base colour"),
9413 mag_filter: FilterMode::Linear,
9414 min_filter: FilterMode::Linear,
9415 mip_filter: FilterMode::Linear,
9416 address_mode: [SamplerAddressMode::Repeat; 3],
9417 anisotropy,
9418 ..SamplerDesc::default()
9419 })
9420 }
9421
9422 /// The extent a frame handed `target` is actually drawn at.
9423 ///
9424 /// Rounds rather than truncates, and floors at one texel in each dimension:
9425 /// a zero here would reach a transient image description, and an image of
9426 /// zero extent is a device error rather than a small frame. A caller who
9427 /// minimised the window already hands a zero extent through, and that path
9428 /// is unchanged — `max(1)` on a zero is one either way.
9429 fn internal_extent(&self, target: (u32, u32)) -> (u32, u32) {
9430 if self.render_scale >= 1.0 {
9431 return target;
9432 }
9433 let scale = f64::from(self.render_scale);
9434 (
9435 ((f64::from(target.0) * scale).round() as u32).max(1),
9436 ((f64::from(target.1) * scale).round() as u32).max(1),
9437 )
9438 }
9439
9440 /// The exposure in force, after the clamp
9441 /// [`set_exposure`](Self::set_exposure) applied.
9442 ///
9443 /// The read-back half, on [`ground_grid`](Self::ground_grid)'s terms: what a
9444 /// caller wants is the number the frame is drawn with, not the one it asked
9445 /// for — which is also what makes a multiplicative step land on the end of
9446 /// the range rather than run past it.
9447 #[must_use]
9448 pub const fn exposure(&self) -> f32 {
9449 self.exposure
9450 }
9451
9452 /// Whether `device` can draw the wireframe view at all.
9453 ///
9454 /// The question [`set_wireframe`](Self::set_wireframe) answers with an
9455 /// error, asked **before** anything is switched on — so an application can
9456 /// tell its user that this device has no wireframe rather than binding a key
9457 /// that fails, and can say so once at start-up instead of on every press.
9458 /// WebGPU has no line fill mode at all, so the browser is the case this
9459 /// exists for and not a hypothetical.
9460 ///
9461 /// An associated function rather than a method: it is a fact about the
9462 /// device, and a caller wants it before it has decided anything.
9463 #[must_use]
9464 pub fn supports_wireframe(device: &dyn Device) -> bool {
9465 device.caps().supports(Features::POLYGON_MODE_LINE)
9466 }
9467
9468 /// Asks every camera's cull to drop what is hidden or too small to see —
9469 /// topic 03 §3.3's occlusion cull and its
9470 /// small-feature test. See [`crate::occlusion_cull`].
9471 ///
9472 /// [`OcclusionCulling::occlusion`] **changes no pixel**: the first phase
9473 /// guesses from the previous frame's depth, the second tests every rejected
9474 /// instance against this frame's, and only the second's rejections are
9475 /// dropped. [`OcclusionCulling::small_feature_pixels`] does change pixels,
9476 /// and is off unless a threshold is named.
9477 ///
9478 /// Taken from the next [`begin_frame`](Self::begin_frame), and combined with
9479 /// the `r_occlusion_cull` and `r_small_feature_px` console switches — either
9480 /// side turning a cull on turns it on. A wireframe frame culls by the frustum
9481 /// alone, because a wireframe shows the edges a depth test would hide.
9482 pub fn set_occlusion_culling(&mut self, culling: OcclusionCulling) {
9483 self.occlusion_culling = culling;
9484 }
9485
9486 /// Whether a point light's shadow cull tags each caster with the faces of
9487 /// its cube it reaches, so each face draws only those — **on** by default.
9488 ///
9489 /// Off is the cull this replaced: one test against the light's box, and
9490 /// every caster in it drawn into all six faces for the rasteriser to clip.
9491 /// The two write the same atlas, texel for texel — the six faces' pyramids
9492 /// tile the box, so a caster a face drops has no texel in that face's tile —
9493 /// and the switch exists so a test can hold them against each other and a
9494 /// price can be read off both.
9495 pub fn set_point_face_culls(&mut self, on: bool) {
9496 self.point_face_culls = on;
9497 }
9498
9499 /// **A test hook**: from the next [`begin_frame`](Self::begin_frame),
9500 /// rewrites every block the shadow atlas's depth pass is fed with `tamper`
9501 /// on its way to the GPU, or stops doing so with [`None`] — the default,
9502 /// and the only value a frame outside a test runs under.
9503 ///
9504 /// Applied **after** the atlas cache has read the blocks, so the rewrite is
9505 /// invisible to the decision whether to redraw a map and visible only to the
9506 /// depth pass that draws it. That is what makes it a probe of the shaders:
9507 /// `crcbl`'s `mesh_e2e` `shadow_block_reads` draws the atlas with each
9508 /// [`UniformsReader::ColourOnly`] entry of [`FRAME_UNIFORMS_READERS`]
9509 /// perturbed through here and holds the depth to the untampered frame's, bit
9510 /// for bit. It reaches the atlas's views alone — not the probe updater's
9511 /// shadows-off writes, which draw nothing into the atlas.
9512 pub fn set_shadow_view_tamper(&mut self, tamper: Option<fn(&mut mesh::FrameUniforms)>) {
9513 self.shadow_view_tamper = tamper;
9514 }
9515
9516 /// What [`set_occlusion_culling`](Self::set_occlusion_culling) last asked
9517 /// for, before the console switches and the wireframe are applied.
9518 #[must_use]
9519 pub const fn occlusion_culling(&self) -> OcclusionCulling {
9520 self.occlusion_culling
9521 }
9522
9523 /// The culls the next frame runs: [`occlusion_culling`](Self::occlusion_culling)
9524 /// with the console switches applied, and nothing on a wireframe frame.
9525 #[must_use]
9526 pub fn resolved_occlusion_culling(&self) -> OcclusionCulling {
9527 if self.wireframe_on {
9528 return OcclusionCulling::OFF;
9529 }
9530 let console_pixels = crate::occlusion_cull::r_small_feature_px.get_f32();
9531 OcclusionCulling {
9532 occlusion: self.occlusion_culling.occlusion
9533 || crate::occlusion_cull::r_occlusion_cull.get_bool(),
9534 small_feature_pixels: self
9535 .occlusion_culling
9536 .small_feature_pixels
9537 .or((console_pixels > 0.0).then_some(console_pixels)),
9538 }
9539 }
9540
9541 /// Draws the scene's triangles as lines, or goes back to filling them.
9542 ///
9543 /// **Off by default.** Every sample and every golden image predates the
9544 /// view, so a renderer nobody has called this on records exactly the frame
9545 /// it always did.
9546 ///
9547 /// # What it is, and what it is not
9548 ///
9549 /// The **colour pass** alone changes fill mode. The depth prepass and the
9550 /// shadow cascades keep drawing filled triangles, because they are what the
9551 /// occlusion pair and the shadow lookups read and depth drawn as lines is
9552 /// depth with holes in it. So a wireframe frame is the same geometry, the
9553 /// same shading and the same lights, rasterised as edges: what was inside a
9554 /// triangle becomes the clear colour, and what was on its edge stays lit.
9555 ///
9556 /// # It is built on the first `true`
9557 ///
9558 /// The pipeline is compiled here rather than beside the filled one at
9559 /// [`with_scene`](Self::with_scene), and that is the trade this
9560 /// call makes: one pipeline compile on the first press — a hitch, in a view
9561 /// the user just asked for — against a second compile in the start-up of
9562 /// every sample, golden run and headless test that never asks for one. Later
9563 /// calls only flip the switch, and a `false` leaves the pipeline built, for
9564 /// [`set_ground_grid`](Self::set_ground_grid)'s reason: releasing something
9565 /// the frames in flight may still be recording against is what
9566 /// [`destroy`](Self::destroy) — which already requires an idle device — is
9567 /// for.
9568 ///
9569 /// # Errors
9570 ///
9571 /// [`HalError::UnsupportedFeatures`] naming
9572 /// [`Features::POLYGON_MODE_LINE`](crcbl_hal::Features::POLYGON_MODE_LINE)
9573 /// when `on` is `true` on a device that has not got it — ask
9574 /// [`supports_wireframe`](Self::supports_wireframe) first. Refused rather
9575 /// than quietly filled: a caller who asked for a wireframe and got a solid
9576 /// frame back with no error has no way to tell that from a wireframe of a
9577 /// solid-looking model.
9578 ///
9579 /// [`HalError`] from the pipeline otherwise. **Nothing is left switched on
9580 /// when either happens**: the view stays as it was.
9581 pub fn set_wireframe(&mut self, device: &dyn Device, on: bool) -> Result<(), HalError> {
9582 if !on {
9583 self.wireframe_on = false;
9584 return Ok(());
9585 }
9586 if self.wireframe_pipeline.is_none() {
9587 if !Self::supports_wireframe(device) {
9588 return Err(HalError::UnsupportedFeatures {
9589 missing: Features::POLYGON_MODE_LINE,
9590 });
9591 }
9592 let modules = MeshModules::new(device, self.emit, self.culls_clusters)?;
9593 let [single, double] = MeshModules::sided(|cull| {
9594 modules.color_pipeline(
9595 device,
9596 self.mesh_pipeline_layout,
9597 PolygonMode::Line,
9598 cull,
9599 "wireframe",
9600 )
9601 });
9602 modules.destroy(device);
9603 // **Both or neither.** A caller that got one twin back would draw a
9604 // frame missing every double-sided surface and nothing would say
9605 // so; released here rather than kept, because `destroy` is what
9606 // releases what this field holds and it holds nothing yet.
9607 let pipelines = match (single, double) {
9608 (Ok(single), Ok(double)) => SidedPipelines { single, double },
9609 (Ok(built), Err(error)) | (Err(error), Ok(built)) => {
9610 device.destroy_graphics_pipeline(built);
9611 return Err(error);
9612 }
9613 (Err(error), Err(_)) => return Err(error),
9614 };
9615 self.wireframe_pipeline = Some(pipelines);
9616 }
9617 self.wireframe_on = true;
9618 Ok(())
9619 }
9620
9621 /// Whether the colour pass draws lines instead of filled triangles.
9622 ///
9623 /// The read-back half of [`set_wireframe`](Self::set_wireframe), and the
9624 /// observable a test asking "is this frame a wireframe" wants: a renderer
9625 /// that built the pipeline and then switched it off answers `false`, because
9626 /// what it draws is what the question is about.
9627 #[must_use]
9628 pub const fn wireframe(&self) -> bool {
9629 self.wireframe_on
9630 }
9631
9632 /// Draws each surface's **world-space** normal instead of shading it, so a
9633 /// modeller can see whether the normals a document carries are sane.
9634 ///
9635 /// **Off by default**, on [`set_wireframe`](Self::set_wireframe)'s terms: it
9636 /// is a tool's view of a document, and every sample and every golden image
9637 /// predates it. It takes effect on the next
9638 /// [`begin_frame`](Self::begin_frame), which is what writes the block.
9639 ///
9640 /// # What the colours mean
9641 ///
9642 /// The conventional encoding, `n * 0.5 + 0.5` into RGB: +X reads red, +Y
9643 /// green, +Z blue, and a face whose winding was inverted reads the
9644 /// **complement** of the colour it should have. A missing or degenerate
9645 /// normal reads as whatever the vertex data actually holds rather than as the
9646 /// plausible shading a light would have given it, which is the point.
9647 ///
9648 /// # World space, not view space
9649 ///
9650 /// The two diagnose different things and this one is world space, so a face
9651 /// keeps its colour while the camera orbits: "is this face inverted" is then
9652 /// something a modeller *sees*, instead of inferring it from a picture that
9653 /// re-colours whenever they move. View-space normals answer the other
9654 /// question — is this normal smooth, is this seam split — by re-colouring on
9655 /// purpose, and they are not a thing this block could express anyway: it
9656 /// carries `view_proj` and no separate view matrix, so there is no rotation in
9657 /// the shader to take a normal into eye space with.
9658 ///
9659 /// # It builds nothing and adds no pass
9660 ///
9661 /// Unlike the wireframe, which needs a second pipeline and so a device that
9662 /// can build one: this is one lane of the frame's uniform block — see
9663 /// [`FrameUniforms::NORMALS_VIEW_ON`] — read by a branch in the fragment
9664 /// stage every device already runs. There is nothing to refuse and nothing to
9665 /// release, which is why it cannot fail and there is no `supports_` probe
9666 /// beside it.
9667 ///
9668 /// The tonemap still applies: at
9669 /// [`DEFAULT_EXPOSURE`](crcbl_shaders::tonemap::DEFAULT_EXPOSURE) its operator
9670 /// is the identity on `0..=1` and the encoded normal reaches the swapchain
9671 /// exactly, and at any other exposure the picture is scaled per channel — so
9672 /// which channel dominates a face never changes, but a caller reading exact
9673 /// values wants [`set_exposure`](Self::set_exposure) left alone.
9674 ///
9675 /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
9676 pub const fn set_normals_view(&mut self, on: bool) {
9677 self.normals_view = on;
9678 }
9679
9680 /// Sets the exponential height fog the colour pass composites over every
9681 /// shaded surface.
9682 ///
9683 /// Topic 43 §4's cheapest large win: distance
9684 /// reads as distance, a valley fills while a hilltop stays clear, and it
9685 /// costs four numbers in a block every pipeline already binds.
9686 ///
9687 /// # It adds no pass and cannot fail
9688 ///
9689 /// On [`set_normals_view`](Self::set_normals_view)'s terms exactly — two
9690 /// rows of the frame's uniform block, read by arithmetic in the fragment
9691 /// stage every device already runs. There is nothing to build, so there is
9692 /// nothing to refuse and no `supports_` probe beside it.
9693 ///
9694 /// # Off is exactly off
9695 ///
9696 /// [`Fog::NONE`] is the default and a zero density is an *exact* identity,
9697 /// not an approximate one: the optical depth is zero, its transmittance is
9698 /// exactly one, and `mesh.slang` composites as `lit * t + fog * (1 - t)`
9699 /// rather than as a `lerp`, which at `t == 1` would return
9700 /// `fog + (lit - fog)` and lose the low bits of an HDR radiance far from
9701 /// the fog colour. So this feature moves no frame it is not switched on
9702 /// for.
9703 ///
9704 /// # What it does not fog
9705 ///
9706 /// The screen-space reflections `ssr_blur.slang` adds **after** this pass,
9707 /// which arrive unfogged onto an already-fogged surface — see
9708 /// `docs/backlog.md`. Fog is applied where the radiance is finished, and
9709 /// the reflection composite is one pass later.
9710 pub const fn set_fog(&mut self, fog: Fog) {
9711 self.fog = fog;
9712 }
9713
9714 /// Lights the scene with a gradient sky, on top of whatever ambient and
9715 /// irradiance grid it already has.
9716 ///
9717 /// Topic 43 §8's rung. [`Sky`] is three
9718 /// radiances — zenith, horizon, ground — and what reaches a surface is that
9719 /// gradient projected onto the L1 basis the probe grid already uses, so a
9720 /// surface facing up receives the sky and one facing down the ground's
9721 /// bounce. Three colours, no extra pass.
9722 ///
9723 /// # It adds no pass and cannot fail
9724 ///
9725 /// On [`set_fog`](Self::set_fog)'s terms exactly — three rows of the
9726 /// frame's uniform block and three dot products in a fragment stage every
9727 /// device already runs. Nothing to build, so nothing to refuse and no
9728 /// `supports_` probe beside it.
9729 ///
9730 /// # Off is exactly off
9731 ///
9732 /// [`Sky::NONE`] is the default and a black gradient projects to every
9733 /// coefficient zero — each is a product with a zero factor — so the
9734 /// fragment stage adds `max(0, 0)` and the ambient sum is the one it was
9735 /// before this existed, bit for bit.
9736 ///
9737 /// # What it does not do
9738 ///
9739 /// **Draw anything.** The background is still the scene target's clear
9740 /// colour, and a scene lit by a sky it cannot see is what this rung leaves
9741 /// behind until the pass that draws the gradient lands. The environment
9742 /// `ssr.slang` falls back to on a missed ray is still the probe grid's, so
9743 /// a mirror under a sky still reflects whatever the probes hold.
9744 pub const fn set_sky(&mut self, sky: Sky) {
9745 self.sky = sky;
9746 }
9747
9748 /// Replaces the gradient with Hillaire's atmosphere, or `None` to put the
9749 /// gradient back.
9750 ///
9751 /// Topic 43 §8. A frame with an atmosphere takes
9752 /// it for all three of the things a sky is: the background the sky pass
9753 /// draws, the L1 ambient term `mesh.slang` adds, and the environment
9754 /// `ssr.slang` falls back to when a ray hits nothing. The
9755 /// [`Sky`] a caller may also have set is not read on those frames.
9756 ///
9757 /// # What it costs
9758 ///
9759 /// **A march on the host, not on the device.** The first
9760 /// [`begin_frame`](Self::begin_frame) after this is called marches
9761 /// [`crcbl_shaders::atmosphere::SkyView`] whole, which is tens of
9762 /// milliseconds of CPU — a renderer with no LUT has no sky, so that one is
9763 /// paid where it is asked for. Every later move of the sun is marched
9764 /// [`SKY_VIEW_BUILD_ROWS`] rows per frame with the last finished LUT still
9765 /// drawn, so no frame after the first pays the whole march;
9766 /// `refresh_sky_view` is where that is written down, including what a sun
9767 /// that moves *every* frame gets. A frame whose
9768 /// sun has not moved costs the comparison that finds nothing to do and
9769 /// nothing else: the LUT's two projections are cached beside it. The device
9770 /// pays four buffer loads and a blend, which is what the gradient pays.
9771 ///
9772 /// # Off is exactly off
9773 ///
9774 /// `None` is the default, and a renderer nobody calls this on writes the
9775 /// same block, adds the same passes and draws the same frame it did before
9776 /// this existed — `sky.slang`'s arm is
9777 /// [`crcbl_shaders::sky::ATMOSPHERE_OFF`], which is exactly zero.
9778 ///
9779 /// # What it does not do
9780 ///
9781 /// **Draw the sun.** The LUT holds the scattered sky and not the disc, as
9782 /// the paper's does; the sun itself is the [`DirectionalLight`] the forward
9783 /// pass already shades with, and pointing the two the same way is the
9784 /// caller's job.
9785 ///
9786 /// **Put the air in front of a surface.** That is the paper's third LUT and
9787 /// this engine's froxel column, and neither reads this.
9788 pub fn set_atmosphere(&mut self, atmosphere: Option<Atmosphere>) {
9789 self.atmosphere = atmosphere;
9790 }
9791
9792 /// The bodies of water every view draws — `docs/plan/55-water.md`'s rung 1,
9793 /// and this crate's `water` module for how.
9794 ///
9795 /// Replaces whatever was set before. Each body is meshed here, by
9796 /// [`crcbl_water::surface_mesh`], and the result is uploaded to each frame
9797 /// slot as that slot next begins, so the call touches no device and a frame
9798 /// still in flight keeps the buffers it was submitted with.
9799 ///
9800 /// # Off is exactly off
9801 ///
9802 /// An empty slice is the default, and a renderer with no bodies records no
9803 /// water pass at all: the frame it draws is the one it drew before this
9804 /// existed, bit for bit. Water is content, not a
9805 /// [`RenderEffects`] bit, on [`set_sky`](Self::set_sky)'s terms.
9806 ///
9807 /// # Errors
9808 ///
9809 /// [`crcbl_water::BodyError`] for the first body that cannot be meshed —
9810 /// too few points, a non-finite coordinate, an outline that crosses itself,
9811 /// a negative coefficient — and then **nothing is replaced**: the bodies set
9812 /// before this call go on drawing.
9813 pub fn set_water(
9814 &mut self,
9815 bodies: &[crcbl_water::WaterBody],
9816 ) -> Result<(), crcbl_water::BodyError> {
9817 self.water.set(bodies)
9818 }
9819
9820 /// The bodies of water this renderer draws, as they were last set.
9821 #[must_use]
9822 pub fn water(&self) -> &[crcbl_water::WaterBody] {
9823 self.water.bodies()
9824 }
9825
9826 /// The field of grass every view draws — `docs/plan/57-grass.md`'s rungs G1
9827 /// and G3, and this crate's `grass` module for how.
9828 ///
9829 /// Replaces whatever was set before. The field's ground, cover map, blade
9830 /// table and per-tile blocks are uploaded here, and the buffers a dispatch
9831 /// writes are created here; a field replaced while a frame is in flight
9832 /// leaves its resources alive until the ring has come round, so the call is
9833 /// safe at any point between frames.
9834 ///
9835 /// # Off is exactly off
9836 ///
9837 /// [`None`] is the default, and a renderer with no field records no grass
9838 /// pass at all: the frame it draws is the one it drew before this existed,
9839 /// bit for bit. Grass is content, not a [`RenderEffects`] bit, on
9840 /// [`set_water`](Self::set_water)'s terms.
9841 ///
9842 /// # Errors
9843 ///
9844 /// [`crate::grass::SetError::Field`] for a description the field itself
9845 /// refuses — no tiles, a zero texel scale, an empty blade table — and then
9846 /// **nothing is replaced**: the field set before this call goes on drawing.
9847 /// [`crate::grass::SetError::Hal`] for a seam call that failed, on the same
9848 /// terms.
9849 pub fn set_grass(
9850 &mut self,
9851 device: &dyn Device,
9852 queue: QueueHandle,
9853 field: Option<&crate::grass::GrassField>,
9854 ) -> Result<(), crate::grass::SetError> {
9855 self.grass.set(device, queue, field)
9856 }
9857
9858 /// The field of grass this renderer draws, as it was last set.
9859 #[must_use]
9860 pub fn grass(&self) -> Option<&crate::grass::GrassField> {
9861 self.grass.field()
9862 }
9863
9864 /// The two buffers the grass generation pass writes, or [`None`] for a
9865 /// renderer with no field.
9866 ///
9867 /// What `crcbl`'s `render_e2e` copies back to check the placement blade by
9868 /// blade and to read each slot's instance count, on
9869 /// [`froxel_buffers`](Self::froxel_buffers)' terms — see
9870 /// [`crate::grass::GrassBuffers`] for the layout. They hold whatever the
9871 /// last frame that generated left there, which for a field nobody has drawn
9872 /// yet is undefined rather than empty.
9873 #[must_use]
9874 pub fn grass_buffers(&self) -> Option<crate::grass::GrassBuffers> {
9875 self.grass.buffers()
9876 }
9877
9878 /// The two authored wind layers `docs/plan/56-wind.md`'s decision 1 names,
9879 /// as the GPU copy of the field samples them.
9880 ///
9881 /// [`None`] restores the calm placeholder: one texel of no deflection and
9882 /// one of zero intensity, which is what makes a field with no weather set
9883 /// stand still. A replaced pair waits for the ring exactly as a replaced
9884 /// field does.
9885 ///
9886 /// # Errors
9887 ///
9888 /// [`crate::grass::WindLayerError`] for a layer that is not four bytes a
9889 /// texel of the grid it came with, or a seam call that failed.
9890 pub fn set_wind_layers(
9891 &mut self,
9892 device: &dyn Device,
9893 queue: QueueHandle,
9894 layers: Option<&crate::grass::WindLayers>,
9895 ) -> Result<(), crate::grass::WindLayerError> {
9896 self.grass.set_wind_layers(device, queue, layers)
9897 }
9898
9899 /// The wind's uniform block for the frames from here on —
9900 /// `crcbl_wind::WindField::gpu_params`, which is where the authoritative
9901 /// `f64` formula is narrowed to `f32`.
9902 ///
9903 /// Everything in it is camera-relative or already wrapped, so a caller
9904 /// writes it once per frame from the field's own state and never from a
9905 /// world-scale coordinate. The default is a base speed of zero, which is
9906 /// calm.
9907 pub const fn set_wind(&mut self, params: crcbl_shaders::wind::WindParams) {
9908 self.wind = params;
9909 }
9910
9911 /// The wind block this renderer writes, as it was last set.
9912 #[must_use]
9913 pub const fn wind(&self) -> crcbl_shaders::wind::WindParams {
9914 self.wind
9915 }
9916
9917 /// The atmosphere this renderer draws, if it has one.
9918 #[must_use]
9919 pub const fn atmosphere(&self) -> Option<Atmosphere> {
9920 self.atmosphere
9921 }
9922
9923 /// Draws each cluster tinted by the DAG level it was decimated to, instead
9924 /// of shading it.
9925 ///
9926 /// **The picture cluster LOD's whole claim rests on**: one mesh spanning
9927 /// several levels across its own surface is a statement a test can assert
9928 /// and nobody can see, and this is what makes it visible. The mesh path
9929 /// tints per cluster; the two indirect paths select one level per instance
9930 /// and have no per-cluster level at all, so they draw one flat grey — which
9931 /// is the comparison rather than a shortfall.
9932 ///
9933 /// Costs what [`set_normals_view`](Self::set_normals_view) costs: one lane
9934 /// of the frame's uniform block, read by a branch every device already runs.
9935 /// Nothing to build, nothing to refuse, nothing to release.
9936 ///
9937 /// **Wins over the normals view when both are on**, because the two share a
9938 /// lane and the fragment stage tests this one first.
9939 pub const fn set_lod_view(&mut self, on: bool) {
9940 self.lod_view = on;
9941 }
9942
9943 /// Whether the colour pass tints clusters by their DAG level.
9944 ///
9945 /// **What was asked for, not what is drawn.** The three debug views share
9946 /// one lane and resolve in one order, so a renderer with this and
9947 /// [`set_heatmap`](Self::set_heatmap) both on draws the heatmap and still
9948 /// answers `true` here — the caller's setting is what a caller's toggle has
9949 /// to read back, and [`debug_view`](Self::debug_view) is what says which one
9950 /// the frame actually took.
9951 #[must_use]
9952 pub const fn lod_view(&self) -> bool {
9953 self.lod_view
9954 }
9955
9956 /// Shades each cluster by the **projected screen-space error** the LOD
9957 /// selection judged it on, instead of shading it.
9958 ///
9959 /// The LOD tint's sibling, and the other half of topic 25's
9960 /// pair: [`set_lod_view`](Self::set_lod_view) answers "which level am I
9961 /// looking at", and this answers "how close to the budget is this, and where
9962 /// is the selection about to switch". The number is the one
9963 /// `draw_gen.slang`'s `group_is_expanded` compared against the budget — a
9964 /// cluster's *producing* group's error, projected from this frame's eye at
9965 /// this frame's pixels per unit.
9966 ///
9967 /// # What the colours mean
9968 ///
9969 /// A ramp that climbs in luminance from a cold floor to white, with a hue
9970 /// break at each of the two budgets: the hold budget where the hysteresis
9971 /// band starts, and the expand budget at the top, which is white. So the two
9972 /// budgets draw themselves as contour lines across the surface, and
9973 /// "brighter is closer to switching" reads even in a greyscale screenshot.
9974 /// `mesh_cluster.slang`'s `HEAT_UNDER_LOW` carries the ramp in full, and
9975 /// `crcbl_shaders`' `the_heatmap_ramp_climbs_in_luminance` is what holds it
9976 /// to being readable as an ordering.
9977 ///
9978 /// A cluster nothing simplified — the original surface, at the bottom of the
9979 /// DAG — costs exactly zero and takes the ramp's floor.
9980 ///
9981 /// # Mesh path only, and that is the capability rather than a shortfall
9982 ///
9983 /// A per-cluster error exists only where selection is per cluster.
9984 /// [`GeometryPath::IndirectCount`] and [`GeometryPath::IndirectPerBatch`]
9985 /// choose one level per *instance*, so there is no per-cluster number for
9986 /// them to shade by and `mesh.slang`'s vertex stage writes the same flat grey
9987 /// the LOD tint gets. Standing the two beside each other is the comparison.
9988 ///
9989 /// # It builds nothing and adds no pass
9990 ///
9991 /// One lane of the frame's uniform block, on
9992 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly — plus one
9993 /// storage-buffer read in the mesh stage, which the mesh path's layout
9994 /// already carries. Nothing to build, nothing to refuse, nothing to release.
9995 ///
9996 /// **Wins over both the LOD tint and the normals view when several are on**;
9997 /// see [`debug_view`](Self::debug_view), which is that order stated once.
9998 ///
9999 /// [`GeometryPath::IndirectCount`]: crcbl_hal::GeometryPath::IndirectCount
10000 /// [`GeometryPath::IndirectPerBatch`]: crcbl_hal::GeometryPath::IndirectPerBatch
10001 pub const fn set_heatmap(&mut self, on: bool) {
10002 self.heatmap = on;
10003 }
10004
10005 /// Whether the colour pass shades clusters by their projected error.
10006 ///
10007 /// **What was asked for, not what is drawn**, on
10008 /// [`lod_view`](Self::lod_view)'s terms.
10009 #[must_use]
10010 pub const fn heatmap(&self) -> bool {
10011 self.heatmap
10012 }
10013
10014 /// Draws the ambient-occlusion channel alone, as grey, instead of shading.
10015 ///
10016 /// One is white and fully occluded is black — the buffer the forward pass
10017 /// multiplies its ambient term by, shown as itself. **This is how the AO
10018 /// ladder — GTAO against the eight-tap hemisphere — is compared at all:** a
10019 /// composited frame shows occlusion times albedo times ambient, and a
10020 /// difference in the first is not separable from a difference in the other
10021 /// two by looking at the result.
10022 ///
10023 /// # What it draws with occlusion switched off
10024 ///
10025 /// White, everywhere. A frame without
10026 /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 white image in place of
10027 /// a computed channel, and this view shows that image rather than pretending
10028 /// to a channel nothing computed — "no occlusion was computed" and "nothing
10029 /// occludes here" are the same value to the shading, and the view does not
10030 /// get to disagree with the shading about it.
10031 ///
10032 /// # It builds nothing and adds no pass
10033 ///
10034 /// One lane of the frame's uniform block, on
10035 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly. Unlike the
10036 /// tint and the heatmap it needs nothing from the geometry stage, so it
10037 /// draws on every [`GeometryPath`] rather than on
10038 /// the mesh-shader one alone.
10039 ///
10040 /// **Wins over every other view when several are on**; see
10041 /// [`debug_view`](Self::debug_view), which is that order stated once.
10042 pub const fn set_occlusion_view(&mut self, on: bool) {
10043 self.occlusion_view = on;
10044 }
10045
10046 /// Whether the colour pass draws the occlusion channel instead of shading.
10047 ///
10048 /// **What was asked for, not what is drawn**, on
10049 /// [`lod_view`](Self::lod_view)'s terms.
10050 #[must_use]
10051 pub const fn occlusion_view(&self) -> bool {
10052 self.occlusion_view
10053 }
10054
10055 /// Draws each fragment's motion vector instead of shading it.
10056 ///
10057 /// The two components are stretched by
10058 /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) and centred
10059 /// on grey, into red and green, with blue left at zero. A pixel at rest is
10060 /// grey in both channels to within one half-float step —
10061 /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) says why
10062 /// not exactly — and a surface travelling right and down the screen
10063 /// brightens both.
10064 ///
10065 /// # It is the motion-vector target's only reader today
10066 ///
10067 /// The forward pass writes a motion vector into a third colour attachment on
10068 /// every frame — see [`crate::targets::motion`] — and no pass reads it
10069 /// yet; TAA (`docs/backlog.md`) is the first that will. This
10070 /// view is therefore what says the subtraction behind it is the right one,
10071 /// which is why it exists ahead of a consumer.
10072 ///
10073 /// # It builds nothing and adds no pass
10074 ///
10075 /// One lane of the frame's uniform block, on
10076 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10077 /// the occlusion view it needs nothing from the geometry stage that a
10078 /// shaded frame does not already produce — so it draws on every
10079 /// [`GeometryPath`].
10080 ///
10081 /// **Wins over every other view when several are on**; see
10082 /// [`debug_view`](Self::debug_view), which is that order stated once.
10083 pub const fn set_motion_view(&mut self, on: bool) {
10084 self.motion_view = on;
10085 }
10086
10087 /// Whether the colour pass draws the motion vector instead of shading.
10088 ///
10089 /// **What was asked for, not what is drawn**, on
10090 /// [`lod_view`](Self::lod_view)'s terms.
10091 #[must_use]
10092 pub const fn motion_view(&self) -> bool {
10093 self.motion_view
10094 }
10095
10096 /// Draws the occlusion channel's **bent direction** instead of shading.
10097 ///
10098 /// The three channels beside the visibility scalar, passed through as the
10099 /// colour: the conventional `n * 0.5 + 0.5`, so +X reads red, +Y green and
10100 /// +Z blue, which is the mapping
10101 /// [`set_normals_view`](Self::set_normals_view) already uses for a surface
10102 /// normal. A fragment the occlusion pass had no direction for reads as the
10103 /// mid grey the zero sentinel encodes to.
10104 ///
10105 /// # What it is for
10106 ///
10107 /// The bent direction is what the ambient term is sampled *along*, and a
10108 /// composited frame cannot show it: ambient times albedo times a
10109 /// direction-dependent irradiance is one colour, and a direction that is
10110 /// subtly wrong looks like a lighting choice. This draws the direction
10111 /// alone, which is how a corner that leans the wrong way out of its own
10112 /// wall is a thing a reviewer sees rather than infers.
10113 ///
10114 /// # What it draws with occlusion switched off
10115 ///
10116 /// Mid grey, everywhere. A frame without
10117 /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 placeholder holding
10118 /// [`BENT_NORMAL_NONE`](crcbl_shaders::ssao::BENT_NORMAL_NONE) in those
10119 /// three channels, and this view shows that image rather than pretending to
10120 /// a direction nothing computed — which is the same answer the shading
10121 /// takes, since `mesh.slang` reads that sentinel as "use the shading
10122 /// normal".
10123 ///
10124 /// # It builds nothing and adds no pass
10125 ///
10126 /// One lane of the frame's uniform block, on
10127 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10128 /// the occlusion view it needs nothing from the geometry stage — so it
10129 /// draws on every [`GeometryPath`].
10130 ///
10131 /// **Wins over every other view when several are on**; see
10132 /// [`debug_view`](Self::debug_view), which is that order stated once.
10133 pub const fn set_bent_normal_view(&mut self, on: bool) {
10134 self.bent_normal_view = on;
10135 }
10136
10137 /// Whether the colour pass draws the bent direction instead of shading.
10138 ///
10139 /// **What was asked for, not what is drawn**, on
10140 /// [`lod_view`](Self::lod_view)'s terms.
10141 #[must_use]
10142 pub const fn bent_normal_view(&self) -> bool {
10143 self.bent_normal_view
10144 }
10145
10146 /// Tints the shaded picture by the **cascade** each sun-lit fragment's
10147 /// shadow was sampled from.
10148 ///
10149 /// Topic 45's eighth decision made the cascade switch a
10150 /// band rather than a step, and this is the picture that band is judged in:
10151 /// each fragment's shading multiplied by
10152 /// [`CASCADE_TINTS`](crcbl_shaders::mesh::CASCADE_TINTS) of the cascade it
10153 /// selected, and inside the band by the *blend* of the two — the same weight
10154 /// the visibility itself was mixed with. So the boundary reads as a
10155 /// gradient, and a seam where two cascades disagree shows up as a step in
10156 /// the gradient rather than as a ring somebody has to already suspect.
10157 ///
10158 /// # It keeps the shaded picture, which is why it loses to every other view
10159 ///
10160 /// Every other view replaces the frame; this one multiplies it, so the geometry
10161 /// stays readable underneath and the shadow the cascades produced is still
10162 /// in the picture being coloured. That is also what puts it last in
10163 /// [`debug_view`](Self::debug_view)'s order: with a replacing view on there
10164 /// is no shading left for a tint to reach.
10165 ///
10166 /// # What it draws where no cascade covers a fragment
10167 ///
10168 /// Nothing at all —
10169 /// [`CASCADE_TINT_NONE`](crcbl_shaders::mesh::CASCADE_TINT_NONE) is white.
10170 /// A surface facing away from the sun and one past the last cascade's reach
10171 /// are both that, because neither was sampled through a cascade, and a
10172 /// frame drawn without [`RenderEffects::SHADOWS`](crate::RenderEffects::SHADOWS) is
10173 /// white everywhere for the same reason. Colouring those would be inventing
10174 /// a cascade for a pixel no map covers.
10175 ///
10176 /// # It builds nothing and adds no pass
10177 ///
10178 /// One lane of the frame's uniform block, on
10179 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10180 /// the occlusion view it needs nothing from the geometry stage — so it draws
10181 /// on every [`GeometryPath`].
10182 pub const fn set_cascade_view(&mut self, on: bool) {
10183 self.cascade_view = on;
10184 }
10185
10186 /// Whether the colour pass tints the picture by the sun's cascades.
10187 ///
10188 /// **What was asked for, not what is drawn**, on
10189 /// [`lod_view`](Self::lod_view)'s terms — and here that gap is the usual
10190 /// case rather than the corner one: this view loses to every other one, so a
10191 /// renderer with any of them also on answers `true` here and draws that one.
10192 #[must_use]
10193 pub const fn cascade_view(&self) -> bool {
10194 self.cascade_view
10195 }
10196
10197 /// Draws the **shadow atlas itself** over the finished frame: the
10198 /// `D32Float` image `crate::shadow` budgets, letterboxed at its own aspect,
10199 /// each texel's stored depth as a grey and a border round every occupied
10200 /// slot.
10201 ///
10202 /// Sundial's atlas viewer, and the answer to a
10203 /// question no other view can be asked: which slot holds which map, and
10204 /// which slots hold nothing. A tile that was never rendered into, or
10205 /// rendered at the wrong viewport, lights a scene *fully* — so the frame it
10206 /// produces is plausible and every golden blessed from it passes. Here it is
10207 /// a rectangle that is visibly empty.
10208 ///
10209 /// # It is a pass, and it is the only debug view that is
10210 ///
10211 /// Every other view rides in one lane of the frame's uniform block and is a
10212 /// branch in `mesh.slang`, because every other view is a function of the
10213 /// fragment being shaded. The atlas is not: it is one image the whole frame
10214 /// shares. So this switch adds `crate::atlas_view`'s full-screen pass to
10215 /// the frame instead — after the tonemap, in display space, for that
10216 /// module's reason — and the frame block is byte-identical either way.
10217 ///
10218 /// # Where it resolves, and what it costs when it is off
10219 ///
10220 /// Below every replacing view and above
10221 /// [`set_cascade_view`](Self::set_cascade_view)'s tint — see
10222 /// [`debug_view`](Self::debug_view), which is that order stated once. A
10223 /// frame that resolved anything else records **no pass**, no pipeline bind
10224 /// and no block read, which is what makes the off position bit-identical on
10225 /// `crate::sky_pass`'s terms.
10226 pub const fn set_atlas_view(&mut self, on: bool) {
10227 self.atlas_view = on;
10228 }
10229
10230 /// Whether the frame draws the shadow atlas over the picture.
10231 ///
10232 /// **What was asked for, not what is drawn**, on
10233 /// [`lod_view`](Self::lod_view)'s terms: a renderer with a replacing view
10234 /// also on answers `true` here and draws that one.
10235 #[must_use]
10236 pub const fn atlas_view(&self) -> bool {
10237 self.atlas_view
10238 }
10239
10240 /// Pins the eye topic 25's selection is projected from, so the
10241 /// cut stops following the camera.
10242 ///
10243 /// [`None`] is the default and means "the camera's own eye", which is what
10244 /// every frame before this existed did. `Some(eye)` selects detail for a
10245 /// viewer standing at `eye` while the frame is still drawn, culled and lit
10246 /// from wherever the camera actually is.
10247 ///
10248 /// # What it is for
10249 ///
10250 /// Per-cluster LOD is only checkable from somewhere other than the point
10251 /// that chose it. Looked at from the selecting eye, a cut that is far too
10252 /// coarse and a cut that is exactly right produce the same silhouette —
10253 /// that is what a screen-space error budget *means* — so the one viewpoint
10254 /// where a wrong cut cannot be seen is the viewpoint every unfrozen frame is
10255 /// judged from. Pin the eye and fly away from it, and the boundaries between
10256 /// levels become geometry a reviewer can walk up to and look at edge-on.
10257 ///
10258 /// # Only the selection freezes
10259 ///
10260 /// The frame has three places a viewer position is read, and this moves
10261 /// exactly one of them:
10262 ///
10263 /// * **the selection** — `draw_gen.slang`'s `select_level`, which reads
10264 /// `DrawGenParams::camera_position` and is the only thing that decides the
10265 /// cut. It writes the group hysteresis state that the mesh path's
10266 /// amplification stage then descends, so freezing this one field freezes
10267 /// the cut on the per-cluster path and the two indirect paths alike. This
10268 /// is what moves.
10269 /// * **the frustum culls** — `cull.slang`'s instance test and
10270 /// `mesh_cluster.slang`'s per-cluster one, whose planes are extracted from
10271 /// the frame's own view-projection and never read a camera position at
10272 /// all. Unaffected, and it has to be: a frame culled against a frustum the
10273 /// reviewer has flown out of would draw nothing.
10274 /// * **the normal cone** — `mesh_cluster.slang`'s `cluster_survives`, which
10275 /// reads [`FrameUniforms::camera_position`] and asks which way a cluster
10276 /// faces *relative to the viewer*. That question is about the eye the
10277 /// picture is drawn from, not the eye it was selected for; frozen, a
10278 /// reviewer who flew round to the other side of the face would have every
10279 /// cluster now facing them rejected for facing away from a viewpoint
10280 /// nobody is standing at. It stays live.
10281 ///
10282 /// The split is not new. `DrawGenParams::camera_position` and
10283 /// [`FrameUniforms::camera_position`] are already separate fields carrying
10284 /// different values on a shadow cascade — that one holds the sun while this
10285 /// one stays the camera, because detail is denominated in the camera's
10286 /// pixels and facing is asked about the light. This freezes the same seam
10287 /// from the other side, and needs no new binding, no new shader input and no
10288 /// shader change of any kind.
10289 ///
10290 /// # It freezes the cascades' selection too
10291 ///
10292 /// [`begin_frame`](Self::begin_frame) hands the same eye to every shadow
10293 /// cascade's draw generator, because a cascade selects detail for the
10294 /// *camera* — see [`SHADOW_LOD_BIAS`]. A frozen camera cut over a live
10295 /// shadow cut would be a shadow silhouette sliding under a fixed one, which
10296 /// is a difference in the picture that belongs to neither.
10297 ///
10298 /// # The heatmap reads the live eye, and says so
10299 ///
10300 /// [`set_heatmap`](Self::set_heatmap) shades a cluster by its producing
10301 /// group's projected error, computed in the mesh stage from
10302 /// [`FrameUniforms::camera_position`] — the eye that stays live. So under a
10303 /// frozen selection the two overlays answer different questions: the cut is
10304 /// the one chosen at the pinned eye, and the heat is what the error would be
10305 /// if it were chosen from here now. That is readable — flying towards the
10306 /// face brightens the clusters the frozen cut is not refining, which is the
10307 /// selection's sensitivity made visible — but it does mean the ramp's
10308 /// contours stop coinciding with the level boundaries while frozen.
10309 /// [`set_lod_view`](Self::set_lod_view) is the overlay that composes
10310 /// unconditionally: a cluster's level is a property of the cut and of
10311 /// nothing else.
10312 ///
10313 /// Carrying the pinned eye into the mesh stage as well would need a second
10314 /// position in the frame block, which is a new shader input in every backend
10315 /// for one overlay's benefit; `docs/backlog.md` holds that trade-off.
10316 ///
10317 /// [`FrameUniforms::camera_position`]: crcbl_shaders::mesh::FrameUniforms::camera_position
10318 pub const fn set_frozen_selection_eye(&mut self, eye: Option<Vec3>) {
10319 self.frozen_selection_eye = eye;
10320 }
10321
10322 /// Where the selection is pinned, or [`None`] while it follows the camera.
10323 ///
10324 /// The read-back half of
10325 /// [`set_frozen_selection_eye`](Self::set_frozen_selection_eye), and what a
10326 /// debug panel says "frozen at" out of — "frozen" without the position is a
10327 /// row nobody can act on.
10328 #[must_use]
10329 pub const fn frozen_selection_eye(&self) -> Option<Vec3> {
10330 self.frozen_selection_eye
10331 }
10332
10333 /// Which of the debug views the next frame will actually draw.
10334 ///
10335 /// **The one place the precedence is decided**, and every other statement of
10336 /// it in this crate reads it back from here. The switches ride in one float
10337 /// lane of the frame block — see
10338 /// [`FrameUniforms::HEATMAP_VIEW_ON`](crcbl_shaders::mesh::FrameUniforms::HEATMAP_VIEW_ON)
10339 /// — and the shaders test the outermost threshold first, so a sentinel for
10340 /// an outer view clears every threshold below it. Resolving here rather than
10341 /// letting each caller guess is what stops "which view is on" being answered
10342 /// differently by a menu row, a debug panel and the picture.
10343 #[must_use]
10344 pub const fn debug_view(&self) -> DebugView {
10345 if self.bent_normal_view {
10346 DebugView::BentNormal
10347 } else if self.motion_view {
10348 DebugView::Motion
10349 } else if self.occlusion_view {
10350 DebugView::AmbientOcclusion
10351 } else if self.heatmap {
10352 DebugView::Heatmap
10353 } else if self.lod_view {
10354 DebugView::LodTint
10355 } else if self.normals_view {
10356 DebugView::Normals
10357 } else if self.atlas_view {
10358 // **Below every view above it, and above the tint below.**
10359 //
10360 // Below, because every branch before this one is a question about
10361 // the *picture* — a cluster's error, a surface's normal, the
10362 // occlusion channel — and this one is not a picture of the scene at
10363 // all. A caller who left the atlas up and then asked for normals has
10364 // asked to look at the frame again, and the frame is what the branch
10365 // above draws; the atlas is one keystroke away and is not lost by
10366 // being deferred to.
10367 //
10368 // Above, because the cascade tint multiplies the shaded picture and
10369 // this replaces it: a tint on a frame the atlas overwrote would be a
10370 // tint on the atlas, which is a colour standing for nothing.
10371 DebugView::ShadowAtlas
10372 } else if self.cascade_view {
10373 // **Innermost, and the only view that sits below the others rather
10374 // than above them.** Every branch before this one draws something
10375 // *instead of* the shaded picture and returns before the shading; a
10376 // cascade tint is a multiply on that shading, so there is nothing
10377 // for it to modulate while one of them is showing and a caller with
10378 // both on has asked for the picture the outer one draws. The lane
10379 // says the same thing from the other end — the cascade sentinel is
10380 // negative, so it clears none of the shaders' thresholds — and
10381 // `crcbl_shaders`'
10382 // `the_cascade_view_threshold_lies_below_every_replacing_view` is
10383 // what holds that half.
10384 DebugView::Cascades
10385 } else {
10386 DebugView::Shaded
10387 }
10388 }
10389
10390 /// [`debug_view`](Self::debug_view) as the value the frame block's lane
10391 /// carries.
10392 const fn debug_view_lane(&self) -> f32 {
10393 match self.debug_view() {
10394 DebugView::BentNormal => mesh::FrameUniforms::BENT_NORMAL_VIEW_ON,
10395 DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
10396 DebugView::AmbientOcclusion => mesh::FrameUniforms::OCCLUSION_VIEW_ON,
10397 DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
10398 DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
10399 DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
10400 DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
10401 // **The off sentinel, and it is not an omission.** This view is a
10402 // pass rather than a branch in `mesh.slang` — see
10403 // [`crate::atlas_view`] — so the colour pass draws exactly the
10404 // shaded picture it always drew and the pass afterwards replaces it.
10405 // A lane of its own would be a threshold no shader tests.
10406 DebugView::ShadowAtlas | DebugView::Shaded => mesh::FrameUniforms::NORMALS_VIEW_OFF,
10407 }
10408 }
10409
10410 /// Whether the colour pass draws world-space normals instead of shading.
10411 ///
10412 /// The read-back half of [`set_normals_view`](Self::set_normals_view), on
10413 /// [`wireframe`](Self::wireframe)'s terms: what it draws is what the question
10414 /// is about.
10415 #[must_use]
10416 pub const fn normals_view(&self) -> bool {
10417 self.normals_view
10418 }
10419
10420 /// The cull and draw-argument passes, and the buffers they produce.
10421 ///
10422 /// What a caller reads the culling statistics out of — topic 03 §3.6's
10423 /// delayed readback ring is [`DrawGen::visible_count`] — and what
10424 /// `crcbl-vk`'s end-to-end suite copies back to check the generated
10425 /// arguments against the draws this pass used to record itself.
10426 #[must_use]
10427 pub const fn draws(&self) -> &DrawGen {
10428 &self.primary.draws
10429 }
10430
10431 /// `frame`'s auto-exposure measurement: the bins the histogram pass filled
10432 /// and the exposure the reduce wrote out of them.
10433 ///
10434 /// What `crcbl`'s `mesh_e2e` copies back to check the histogram bin by bin
10435 /// against `crcbl_shaders::exposure`, on [`draws`](Self::draws)' terms — see
10436 /// [`ExposureBuffers`]. Both hold whatever the last frame that measured left
10437 /// there, so a frame drawn without
10438 /// [`RenderEffects::AUTO_EXPOSURE`](crate::RenderEffects::AUTO_EXPOSURE)
10439 /// hands back the frame before it rather than nothing.
10440 ///
10441 /// # Panics
10442 ///
10443 /// If `frame` is not a slot this renderer was built with.
10444 #[must_use]
10445 pub fn exposure_buffers(&self, frame: usize) -> ExposureBuffers {
10446 self.primary.auto_exposure.buffers(frame)
10447 }
10448
10449 /// `frame`'s froxel column: the buffers the froxel volume's
10450 /// three passes write, and the block they read.
10451 ///
10452 /// What `crcbl`'s `mesh_e2e` copies back to check the column froxel by
10453 /// froxel against `crcbl_shaders::volumetric`, on
10454 /// [`draws`](Self::draws)' terms — see [`FroxelBuffers`].
10455 ///
10456 /// # Panics
10457 ///
10458 /// If `frame` is not a slot this renderer was built with.
10459 #[must_use]
10460 pub fn froxel_buffers(&self, frame: usize) -> FroxelBuffers {
10461 self.primary.volumetric.buffers(frame)
10462 }
10463
10464 /// The three layers a caller supplies to the toggle resolution order — see
10465 /// [`crate::effects`].
10466 ///
10467 /// Read back rather than only written, so a caller changing one layer does
10468 /// not have to remember the other two: take this, edit the field it owns,
10469 /// hand it back to [`set_effect_request`](Self::set_effect_request).
10470 #[must_use]
10471 pub const fn effect_request(&self) -> EffectRequest {
10472 self.effect_request
10473 }
10474
10475 /// Replaces all three requested layers, and resolves them at the next
10476 /// [`begin_frame`](Self::begin_frame).
10477 ///
10478 /// **The frame in flight does not move.** `begin_frame` freezes what it
10479 /// resolved and [`add_passes`](Self::add_passes) records that, because the
10480 /// two halves of a frame have to agree about which culls were parametrised:
10481 /// `begin_frame` skips a shadow cull's parameter write when shadows are off
10482 /// and `add_passes` skips its dispatch, and a request landing between the two
10483 /// would dispatch a cull against numbers nothing zeroed.
10484 pub const fn set_effect_request(&mut self, request: EffectRequest) {
10485 self.effect_request = request;
10486 }
10487
10488 /// Replaces the **camera** layer with what `stack` asks for, and leaves the
10489 /// other three where they are.
10490 ///
10491 /// The file half of [`crate::stack`] reaching the renderer: a view that has
10492 /// a render stack writes it here, and the player's `[engine.video]` clamp,
10493 /// the antialiasing rung they picked and any programmatic override are
10494 /// untouched — which is the property that makes the four layers four rather
10495 /// than one. A caller that wants to move more than this layer builds an
10496 /// [`EffectRequest`] and uses
10497 /// [`set_effect_request`](Self::set_effect_request).
10498 ///
10499 /// **The frame in flight does not move**, on `set_effect_request`'s terms
10500 /// and for its reason: this writes the request and
10501 /// [`begin_frame`](Self::begin_frame) is what resolves it.
10502 pub const fn set_camera_stack(&mut self, stack: &CameraStack) {
10503 self.effect_request.camera = stack.compile();
10504 }
10505
10506 /// What the frame the last [`begin_frame`](Self::begin_frame) opened draws.
10507 ///
10508 /// The resolved set, not a layer: every effect in it has survived the
10509 /// camera's stack, the player's quality clamp, any programmatic override and
10510 /// the device — which is the one question a test asking "did this frame have
10511 /// shadows in it" wants answered.
10512 ///
10513 /// [`RenderEffects::all`] before the first frame, which is what a renderer
10514 /// nobody has changed would draw.
10515 #[must_use]
10516 pub const fn effects(&self) -> RenderEffects {
10517 self.frame_effects
10518 }
10519
10520 /// What a frame begun **now** would draw: the whole order applied to the
10521 /// current request.
10522 ///
10523 /// [`effects`](Self::effects)' question one frame earlier, and the one a
10524 /// caller reporting its own configuration wants — a debug panel built at
10525 /// startup has no frame behind it yet, and printing what the last one drew
10526 /// would print a default.
10527 ///
10528 /// **A debug view takes the antialiasing resolve off** — either tier of it
10529 /// — whatever the four layers said. Those views are readouts rather than
10530 /// pictures — a pixel's colour *is* the cluster's projected error or its
10531 /// DAG level, read back against a legend — and a filter that blends two
10532 /// clusters' shades invents a ramp position no cluster occupies.
10533 /// `apps/quarry`'s heatmap and LOD tests are the consumers that count a
10534 /// frame's distinct colours.
10535 #[must_use]
10536 pub fn resolved_effects(&self) -> RenderEffects {
10537 let resolved = self.effect_request.resolve(self.device_effects);
10538 if matches!(self.debug_view(), DebugView::Shaded) {
10539 resolved
10540 } else {
10541 // **Both tiers**, because the slot is what a readout cannot have
10542 // rather than one filter in particular.
10543 resolved.difference(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2))
10544 }
10545 }
10546
10547 /// Which tonemap operator the next frame runs:
10548 /// [`tonemap_curve`](Self::tonemap_curve)'s answer for a shaded frame, and
10549 /// the clamp for a readout.
10550 ///
10551 /// **[`resolved_effects`](Self::resolved_effects)' argument, applied to the
10552 /// operator instead of to the resolve.** A debug view's pixels *are* data —
10553 /// an encoded normal, an occlusion channel, a cascade's colour code — and a
10554 /// curve is a monotone remapping of every one of them. `apps/alcove`'s
10555 /// `--bent-view` reads a normal back and compares it against the geometry's
10556 /// own, which under ACES is 49 code values out; the clamp is the identity on
10557 /// `0..=1`, so it is the operator that leaves a readout readable. A caller
10558 /// that wants a curved readout has none, deliberately: there is no reading
10559 /// it would make easier.
10560 #[must_use]
10561 pub const fn resolved_tonemap_curve(&self) -> tonemap::TonemapCurve {
10562 if matches!(self.debug_view(), DebugView::Shaded) {
10563 self.tonemap_curve
10564 } else {
10565 tonemap::TonemapCurve::Clamp
10566 }
10567 }
10568
10569 /// Which effects this **device** permits, which is the fourth layer and
10570 /// clamps last.
10571 ///
10572 /// Every one of them today — see [`ForwardRenderer::device_effects`], which
10573 /// is where that is argued per effect rather than asserted.
10574 #[must_use]
10575 pub const fn device_effects(&self) -> RenderEffects {
10576 self.device_effects
10577 }
10578
10579 /// Which [`GeometryPath`] this renderer was **built for** — not what the
10580 /// device reports, but what it actually built.
10581 ///
10582 /// The device may prefer a path below its capability ceiling when a higher
10583 /// one uses emulation. This reports the preference actually built, rather
10584 /// than the ceiling: [`GeometryPath::MeshShader`] here means
10585 /// `build` created a mesh pipeline out of `mesh_cluster.slang` and its
10586 /// cluster buffers, and created **no** raster pipeline for the pass to fall
10587 /// back to. So a frame this renderer drew came out of a mesh stage, and a
10588 /// silent degradation is not a state it has — which is the claim a golden
10589 /// image on its own could never make, because a fall-through draws the same
10590 /// picture.
10591 #[must_use]
10592 pub const fn geometry_path(&self) -> GeometryPath {
10593 match self.emit {
10594 EmitTail::Mesh => GeometryPath::MeshShader,
10595 EmitTail::Count => GeometryPath::IndirectCount,
10596 EmitTail::PerBatch => GeometryPath::IndirectPerBatch,
10597 }
10598 }
10599
10600 /// Whether this renderer **built** §3.5's per-cluster cull — an
10601 /// amplification stage in front of the mesh stage, rejecting a surviving
10602 /// instance's back-facing and off-screen clusters.
10603 ///
10604 /// `false` on the two indirect tails, which draw index ranges and have no
10605 /// stage to put it in, and on a device with `Features::MESH_SHADER` and no
10606 /// `Features::TASK_SHADER` — a real and supported state, not a degradation:
10607 /// that device draws every cluster of every surviving instance and the
10608 /// picture is the same one.
10609 ///
10610 /// The instance cull runs on every path either way, and is unaffected by
10611 /// this.
10612 ///
10613 /// It is asked of the renderer rather than of the device for
10614 /// [`ForwardRenderer::geometry_path`]'s reason: this reports what was
10615 /// built, so `true` means
10616 /// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count)'s
10617 /// cluster word is a number the frame produced rather than the zero the
10618 /// clearing pass left.
10619 #[must_use]
10620 pub const fn culls_clusters(&self) -> bool {
10621 self.culls_clusters
10622 }
10623
10624 /// Whether this renderer can choose **which level** of a
10625 /// [`Geometry::Dag`] mesh an object is drawn at, and therefore whether
10626 /// [`ForwardRenderer::add_instance`] may be given one at all.
10627 ///
10628 /// Topic 25's selection happens in the amplification stage where
10629 /// there is one, and in the cull pass where the tail is indirect and a level
10630 /// is an ordinary index range. **One device shape has neither**: a mesh stage
10631 /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
10632 /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) draws through
10633 /// `mesh_cluster.slang`'s un-amplified `meshMain`, which emits every cluster
10634 /// of the bucket — and a DAG's bucket is every level end to end, so the frame
10635 /// is several overlapping copies of one surface. That is a real and supported
10636 /// device state rather than a degradation, so this reports it instead of
10637 /// refusing to build.
10638 ///
10639 /// A [`Geometry::Flat`] mesh is one level and is unaffected: its clusters
10640 /// carry [`ClusterSelect::ALWAYS`] and every path draws it from every camera,
10641 /// which is why this is asked only before placing a DAG.
10642 ///
10643 /// Asked of the renderer rather than of the device for
10644 /// [`ForwardRenderer::culls_clusters`]' reason: it reports what was built.
10645 ///
10646 /// [`ClusterSelect::ALWAYS`]: crcbl_shaders::cluster_select::ClusterSelect::ALWAYS
10647 #[must_use]
10648 pub const fn selects_levels(&self) -> bool {
10649 !self.emit.is_mesh() || self.culls_clusters
10650 }
10651
10652 /// Which frame-in-flight slot the last [`ForwardRenderer::begin_frame`]
10653 /// rotated to, which is the slot every per-frame buffer is indexed by.
10654 #[must_use]
10655 pub const fn frame(&self) -> usize {
10656 self.frame
10657 }
10658
10659 /// What the last [`add_passes`](Self::add_passes) recorded, and what it
10660 /// cannot know.
10661 ///
10662 /// Zero draws until a frame has been built: this reports what was recorded,
10663 /// not what a frame would record.
10664 ///
10665 /// # The triangles are [`None`] here, on every geometry path
10666 ///
10667 /// Every draw this renderer records except the full-screen passes' and the
10668 /// debug draw layer's is **indirect**:
10669 /// the instance count and the index range live in the argument buffer
10670 /// `draw_gen.slang` wrote, so the CPU records the call and learns nothing
10671 /// about what it covered. That is true of
10672 /// [`GeometryPath::MeshShader`] and of
10673 /// both indirect tails alike — the three differ in which call is recorded,
10674 /// not in who decides the counts — so
10675 /// [`FrameCounters::triangles`](crate::counters::FrameCounters::triangles)
10676 /// is [`None`] whatever the device supports. Nothing counts a triangle on
10677 /// the GPU either, and a cluster count times a nominal triangles-per-cluster
10678 /// would read as authoritative and be neither.
10679 ///
10680 /// # The instances drawn come back off the GPU, a few frames late
10681 ///
10682 /// [`FrameCounters::drawn`](crate::counters::FrameCounters::drawn) is
10683 /// `cull.slang`'s survivor count, off [`crate::cull_stats`]'s delayed ring,
10684 /// plus the frame's direct draws — the ones here whose instance the CPU
10685 /// knows about, and the ones that are also in
10686 /// [`instances`](crate::counters::FrameCounters::instances). So the pair is
10687 /// comparable: the same quantity submitted and kept.
10688 ///
10689 /// **The camera's cull alone.** The shadow culls test other frustums and
10690 /// their survivors are counted into buffers of their own; adding them here
10691 /// would give a "drawn" larger than "submitted" on any frame with a shadow
10692 /// in it.
10693 ///
10694 /// It is [`None`] — the row says `indirect` — for the first few frames of a
10695 /// renderer's life, while the ring has not come round, and for good on a
10696 /// device that would not give out a readback.
10697 /// [`cull_frame`](crate::counters::FrameCounters::cull_frame) is which frame
10698 /// the number is about whenever there is one.
10699 ///
10700 /// [`FrameCounters::instances`](crate::counters::FrameCounters::instances)
10701 /// is known and is the plan's "submitted" half: the live instances
10702 /// [`add_passes`](Self::add_passes) hands the cull dispatches, plus the
10703 /// frame's direct draws — every full-screen pass's triangle and the debug
10704 /// draw layer's line list.
10705 #[must_use]
10706 pub fn counters(&self) -> FrameCounters {
10707 if self.recorded_draws == 0 {
10708 return FrameCounters::default();
10709 }
10710 let stats = self.cull_stats();
10711 let direct = self.direct_draws();
10712 FrameCounters {
10713 draws: self.recorded_draws,
10714 instances: self.instances.len() as u64 + direct,
10715 // Each direct draw is submitted and drawn, and none of them is in
10716 // the cull's count — they are draws of one instance, added on both
10717 // sides so the two halves of the row measure the same thing. Off the
10718 // frame that *was* recorded rather than off a constant, so a frame
10719 // with an effect switched off does not count a triangle it never
10720 // submitted.
10721 // Less what the occlusion cull's second phase rejected, which were
10722 // survivors of the frustum and were not drawn.
10723 drawn: stats
10724 .map(|stats| stats.instances.saturating_sub(stats.occlusion.late_rejects) + direct),
10725 triangles: None,
10726 // The survivors alone: the panel row is "clusters drawn", and the
10727 // frustum and cone rejection counts beside them are a different
10728 // question — `CullStats::clusters` carries all three for a caller
10729 // that wants the split, which `apps/quarry`'s own panel row is.
10730 clusters: stats
10731 .and_then(|stats| stats.clusters)
10732 .map(|cull| cull.survivors),
10733 cull_frame: stats.map(|stats| stats.frame),
10734 }
10735 }
10736
10737 /// The draws this renderer records **directly** — the ones whose instance
10738 /// the CPU knows about, as opposed to the indirect calls whose counts live
10739 /// in a buffer a shader wrote.
10740 ///
10741 /// Every full-screen pass's over-sized triangle, plus the debug draw
10742 /// layer's line list on a frame that has one. One instance each, which is
10743 /// why [`counters`](Self::counters) adds this to both halves of its
10744 /// submitted/drawn pair.
10745 fn direct_draws(&self) -> u64 {
10746 self.recorded_fullscreen * FULLSCREEN_DRAWS
10747 + self.recorded_debug_draw
10748 + self.recorded_tile_clears
10749 + self.recorded_water_draws
10750 }
10751
10752 /// What the camera's cull kept, on the frame the ring has reached.
10753 ///
10754 /// Topic 03 §3.6's one permitted readback, and [`None`] until it has come
10755 /// round — see [`crate::cull_stats`] for the latency and for what makes it
10756 /// free of any wait. [`counters`](Self::counters) is where this reaches the
10757 /// panel; it is exposed on its own because the frame number and the cluster
10758 /// word are both things a test asserts about directly.
10759 #[must_use]
10760 pub fn cull_stats(&self) -> Option<crate::cull_stats::CullStats> {
10761 self.cull_stats.as_ref().and_then(CullStatsRing::latest)
10762 }
10763
10764 /// Describes the imported swapchain image the frame ends in.
10765 ///
10766 /// A helper rather than something every caller writes, because getting
10767 /// `initial`/`final_state` wrong is exactly the hand-written barrier this
10768 /// slice removed: an acquired image's contents are undefined, and the
10769 /// compositor may only be handed one in [`ResourceState::Present`].
10770 #[must_use]
10771 pub fn present_target(
10772 image: crcbl_hal::ImageHandle,
10773 view: ImageViewHandle,
10774 format: Format,
10775 extent: (u32, u32),
10776 ) -> ImportedImage {
10777 ImportedImage {
10778 image,
10779 view,
10780 format,
10781 extent,
10782 initial: ResourceState::Undefined,
10783 // The acquire's semaphore, not a barrier, is what orders this frame
10784 // after the last use of the image — which is what makes `Undefined`
10785 // honest here and what makes it uncheckable. See `InitialClaim`.
10786 claim: InitialClaim::Acquired,
10787 final_state: ResourceState::Present,
10788 }
10789 }
10790
10791 /// Releases everything, in dependency order. The device must be idle.
10792 pub fn destroy(self, device: &dyn Device) {
10793 if let Some(stats) = self.cull_stats {
10794 stats.destroy(device);
10795 }
10796 // The cameras first: their groups name the scene's buffers, pages and
10797 // atlas below, and they own nothing the scene's groups name.
10798 for view in self.views.into_iter().flatten() {
10799 view.destroy(device);
10800 }
10801 self.primary.destroy(device);
10802 // After every view, whose grass and water groups name these buffers.
10803 self.grass.destroy(device);
10804 self.water.destroy(device);
10805 device.destroy_sampler(self.sampler);
10806 device.destroy_graphics_pipeline(self.tonemap_pipeline);
10807 device.destroy_pipeline_layout(self.tonemap_pipeline_layout);
10808 device.destroy_bind_group_layout(self.tonemap_layout);
10809
10810 for pipelines in [
10811 self.shadow_pipeline,
10812 self.depth_masked_pipeline,
10813 self.rsm_pipeline,
10814 ] {
10815 device.destroy_graphics_pipeline(pipelines.single);
10816 device.destroy_graphics_pipeline(pipelines.double);
10817 }
10818 device.destroy_graphics_pipeline(self.shadow_clear_pipeline);
10819 for groups in self.shadow_groups {
10820 for group in groups {
10821 device.destroy_bind_group(group);
10822 }
10823 }
10824 for buffers in self.shadow_uniforms {
10825 for buffer in buffers {
10826 device.destroy_buffer(buffer);
10827 }
10828 }
10829 for buffers in self.shadow_selection {
10830 for buffer in buffers {
10831 device.destroy_buffer(buffer);
10832 }
10833 }
10834 for draws in self.shadow_draws {
10835 draws.destroy(device);
10836 }
10837 device.destroy_sampler(self.shadow_sampler);
10838 device.destroy_image_view(self.shadow_atlas_view);
10839 device.destroy_image(self.shadow_atlas);
10840 device.destroy_image_view(self.shadow_placeholder_view);
10841 device.destroy_image(self.shadow_placeholder);
10842
10843 if let Some(grid) = self.ground_grid {
10844 grid.destroy(device);
10845 }
10846 // Nothing to release on a renderer nobody drew a segment through — see
10847 // [`crate::debug_draw`], whose pipeline is built on first use.
10848 self.debug_draw.destroy(device);
10849 self.atlas_viewer.destroy(device);
10850 self.ambient_occlusion_placeholder.destroy(device);
10851 self.contact_shadow_placeholder.destroy(device);
10852 self.probe_visibility_placeholder.destroy(device);
10853 if let Some(captured) = self.probe_visibility {
10854 captured.destroy(device);
10855 }
10856 self.specular_dfg.destroy(device);
10857 self.ltc_table.destroy(device);
10858 self.normal_page.destroy(device);
10859 self.mro_page.destroy(device);
10860 self.emissive_page.destroy(device);
10861
10862 device.destroy_graphics_pipeline(self.mesh_pipeline.single);
10863 device.destroy_graphics_pipeline(self.mesh_pipeline.double);
10864 // The one place the wireframe pair is released — `set_wireframe(.., false)`
10865 // deliberately is not, because this call is the one that requires an
10866 // idle device.
10867 if let Some(pipelines) = self.wireframe_pipeline {
10868 device.destroy_graphics_pipeline(pipelines.single);
10869 device.destroy_graphics_pipeline(pipelines.double);
10870 }
10871 device.destroy_pipeline_layout(self.mesh_pipeline_layout);
10872 device.destroy_bind_group_layout(self.mesh_layout);
10873 self.base_color_page.destroy(device);
10874 device.destroy_sampler(self.base_color_sampler);
10875 for retired in self.retired_pages {
10876 retired.destroy(device);
10877 }
10878 device.destroy_buffer(self.draw_constants);
10879 if let Some(clusters) = self.clusters {
10880 clusters.destroy(device);
10881 }
10882 // Before the probe table, because its bind groups name that table's
10883 // rows — the same ordering the light grid is under above.
10884 if let Some(gather) = self.probe_gather {
10885 gather.destroy(device);
10886 }
10887 self.probes.destroy(device);
10888 self.materials.destroy(device);
10889 self.instances.destroy(device);
10890 self.pool.destroy(device);
10891 }
10892}
10893
10894/// What the shadow pass a frame recorded would leave the image holding, held
10895/// until the frame after can say whether its body ran.
10896///
10897/// Topic 45's static-caching rung, per group: recording a pass
10898/// is not drawing one, so nothing here is believed until
10899/// [`ForwardRenderer::shadow_pass_ran`] carries this [`ShadowCommit::id`] back
10900/// out of the graph.
10901#[derive(Clone, Debug)]
10902struct ShadowCommit {
10903 /// The [`ForwardRenderer::shadow_pass_id`] the body publishes.
10904 id: u64,
10905 /// `[group]`: what the group's entry of
10906 /// [`ForwardRenderer::shadow_group_held`] becomes for every group the pass
10907 /// redraws, and [`None`] for the groups it holds.
10908 groups: Vec<Option<(u64, Vec3, f32)>>,
10909 /// The layout the pass draws under, where it clears the whole attachment —
10910 /// and [`None`] where it loads, because a loading pass leaves every tile it
10911 /// does not redraw exactly as it found it.
10912 layout: Option<Vec<shadow::TileRect>>,
10913}
10914
10915/// The shader modules a mesh pipeline is built from, with its entry points
10916/// already resolved.
10917///
10918/// **A type rather than a run of locals in `build`** because there are now two
10919/// callers: `build`, which makes the colour pipeline and its depth-only twin,
10920/// and [`ForwardRenderer::set_wireframe`], which makes the colour pipeline again
10921/// in [`PolygonMode::Line`] long after `build` released its modules. The
10922/// alternative was a second copy of a descriptor that names two modules, their
10923/// entry points, the colour targets and a depth state — the pair that drifts.
10924///
10925/// Short-lived: created, used to build pipelines, and [`MeshModules::destroy`]ed
10926/// in the same function. A module is not needed once the pipeline exists.
10927struct MeshModules {
10928 /// `mesh.slang`'s module — the vertex stage on the indirect path, and the
10929 /// fragment stage on both.
10930 mesh: ShaderModuleHandle,
10931 /// `vertexMain`, unused on the mesh-shader path.
10932 vertex: &'static str,
10933 /// `depthVertexMain`, which [`MeshModules::depth_pipeline`] takes in
10934 /// [`MeshModules::vertex`]'s place: the same transform off stream 0 of the
10935 /// vertex pool and no attribute region at all. Unused on the mesh-shader
10936 /// path, where the geometry stage is `mesh_cluster.slang`'s either way.
10937 depth_vertex: &'static str,
10938 /// `depthClearVertexMain`, which [`MeshModules::depth_clear_pipeline`]
10939 /// builds the tile clear from: three corners off `SV_VertexID` and no input
10940 /// at all, so it resets one tile of the atlas without reading a vertex.
10941 ///
10942 /// **The same stage on every path**, unlike the two above: a device with a
10943 /// mesh stage still has a vertex stage, and a clear that produced no
10944 /// geometry is a primitive, not a cluster.
10945 depth_clear_vertex: &'static str,
10946 fragment: &'static str,
10947 /// `depthMaskedFragmentMain`, which [`MeshModules::depth_masked_pipeline`]
10948 /// puts *behind* [`MeshModules::vertex`] — the alpha mask and no target at
10949 /// all.
10950 ///
10951 /// **The same stage on both paths**, unlike the two vertex entry points
10952 /// above: it reads `mesh.slang`'s own `VertexOutput`, which is what
10953 /// `vertexMain` writes on the raster path and what `mesh_cluster.slang`'s
10954 /// mesh stage writes on the mesh one. So the cutout is one comparison in one
10955 /// place rather than one per geometry path.
10956 depth_masked_fragment: &'static str,
10957 /// `rsmFragmentMain`, which [`MeshModules::rsm_pipeline`] takes in
10958 /// [`MeshModules::fragment`]'s place: the same geometry stage, three targets
10959 /// describing the surface rather than shading it.
10960 ///
10961 /// **The reason the shaded stage above is looked up by name.** A module with
10962 /// two fragment entry points has no unambiguous one, which is what `entry`
10963 /// answers `None` for.
10964 rsm_fragment: &'static str,
10965 /// `mesh_cluster.slang`'s, on the mesh-shader path alone.
10966 cluster: Option<ClusterStages>,
10967}
10968
10969/// The geometry half of a mesh-shader pipeline: `mesh_cluster.slang`'s module
10970/// and the stages taken out of it.
10971struct ClusterStages {
10972 /// The module the mesh stage is built from, and the one the task stage is,
10973 /// which are **two modules rather than one**.
10974 ///
10975 /// `mesh_cluster.slang` compiles to a combined module carrying every entry
10976 /// point and to one module per stage, and these are the per-stage ones. A
10977 /// module holding a task entry point and its mesh partner carries two
10978 /// `TaskPayloadWorkgroupEXT` variables — the task writes one, the mesh stage
10979 /// reads the other — and an NVIDIA driver then delivers a payload of zeroes,
10980 /// which draws cluster 0 of instance slot 0 of every bucket and nothing
10981 /// else. See `crcbl_shaders::EntryPoint`.
10982 mesh_module: ShaderModuleHandle,
10983 /// The task stage's own module, on the same terms. [`None`] exactly when
10984 /// [`task`](Self::task) is.
10985 task_module: Option<ShaderModuleHandle>,
10986 /// Which of the module's two mesh entry points this path builds — the
10987 /// amplified one where the device has a task stage to feed it.
10988 mesh: &'static str,
10989 /// §3.5's per-cluster cull, where the device has the stage to run it in.
10990 /// [`None`] is not a degradation: `meshMain` draws the same picture out of
10991 /// the same clusters, having rejected none of them, which is what a device
10992 /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
10993 /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) gets.
10994 task: Option<&'static str>,
10995}
10996
10997impl MeshModules {
10998 /// **Three targets, one fragment stage.** `mesh.slang`'s `FragmentOutput`
10999 /// writes the shaded colour, then topic 47's
11000 /// reflectivity channel, then topic 43 §9's motion
11001 /// vector — and both pipeline shapes name that same entry point, so each
11002 /// target is one more element of this array and not a second pipeline, a
11003 /// second entry point or a new interpolant. The refusal the AO section
11004 /// records was about the depth prepass, which has no fragment stage and no
11005 /// colour target at all; it does not reach this array.
11006 ///
11007 /// Element order is `SV_Target` order, and each format is the one the
11008 /// matching `TransientImageDesc` creates: a pipeline built for a format the
11009 /// attachment is not in is a validation error on WebGPU and a silent
11010 /// reinterpretation elsewhere.
11011 const COLOR_TARGETS: [ColorTargetState; 3] = [
11012 ColorTargetState::opaque(Format::Rgba16Float),
11013 ColorTargetState::opaque(Format::Rgba8Unorm),
11014 ColorTargetState::opaque(MOTION_FORMAT),
11015 ];
11016
11017 /// **Three targets again, and a different three.** `mesh.slang`'s
11018 /// `RsmOutput` writes the surface's diffuse albedo, its world normal encoded
11019 /// `n * 0.5 + 0.5`, and its world position with a coverage flag in `w` —
11020 /// which is what the irradiance probes' gather needs of a
11021 /// texel and nothing more.
11022 ///
11023 /// Element order is `SV_Target` order and each format is the one the
11024 /// matching description in [`crate::rsm`] creates: a pipeline built for a
11025 /// format the attachment is not in is a validation error on WebGPU and a
11026 /// silent reinterpretation elsewhere. `the_targets_carry_the_formats_the_shader_writes`
11027 /// in that module is the other half of the pair.
11028 const RSM_TARGETS: [ColorTargetState; 3] = [
11029 ColorTargetState::opaque(Format::Rgba16Float),
11030 ColorTargetState::opaque(Format::Rgba8Unorm),
11031 ColorTargetState::opaque(Format::Rgba32Float),
11032 ];
11033
11034 /// Invocations per mesh workgroup, which is `mesh_cluster.slang`'s
11035 /// `[numthreads(THREADS, 1, 1)]` — and `THREADS` is
11036 /// `MAX_CLUSTER_VERTICES`, one lane per vertex a cluster can hold.
11037 ///
11038 /// Taken from the crate that owns the shader source rather than written
11039 /// out, as
11040 /// [`MeshPipelineDesc::mesh_workgroup_size`](crcbl_hal::MeshPipelineDesc::mesh_workgroup_size)
11041 /// requires: only Metal reads this field, so a literal that disagreed with
11042 /// the shader would launch the wrong number of threads on one backend and
11043 /// nowhere else.
11044 const MESH_WORKGROUP_SIZE: [u32; 3] =
11045 [crcbl_shaders::meshlet::MAX_CLUSTER_VERTICES as u32, 1, 1];
11046
11047 /// Invocations per task workgroup: `taskMain` is
11048 /// `[numthreads(TASK_LANES, 1, 1)]`, one lane per (cluster, instance slot)
11049 /// pair of its chunk. Taken from the crate that owns the shader, on
11050 /// [`MESH_WORKGROUP_SIZE`](Self::MESH_WORKGROUP_SIZE)'s terms.
11051 const TASK_WORKGROUP_SIZE: [u32; 3] = [crcbl_shaders::meshlet::TASK_LANES, 1, 1];
11052
11053 /// Loads whichever modules `emit` needs and resolves their entry points.
11054 ///
11055 /// # Errors
11056 ///
11057 /// [`HalError::ShaderCompilation`] if the committed manifest names no such
11058 /// entry point, and [`HalError`] from either module. A failure after the
11059 /// first module was created releases it rather than leaking it.
11060 fn new(device: &dyn Device, emit: EmitTail, culls_clusters: bool) -> Result<Self, HalError> {
11061 // Entry points resolved before the module exists: a manifest that
11062 // disagreed with the SPIR-V would otherwise fail inside the descriptor
11063 // literal, with the module already created and nothing holding it.
11064 //
11065 // **The vertex stage is named rather than looked up by stage**, for
11066 // `mesh_cluster.slang`'s reason below: since the depth-only stage landed
11067 // this module has two vertex entry points, and a stage lookup answers
11068 // `None` for two matches. Which of the two a pipeline names is the whole
11069 // of what the split-stream vertex pool bought.
11070 let vertex = named_entry(&MESH, "vertexMain", Stage::Vertex)?;
11071 let depth_vertex = named_entry(&MESH, "depthVertexMain", Stage::Vertex)?;
11072 let depth_clear_vertex = named_entry(&MESH, "depthClearVertexMain", Stage::Vertex)?;
11073 // **Named rather than looked up by stage, on the vertex entry points'
11074 // terms exactly.** Since the irradiance probes' updater
11075 // landed, this module has *two* fragment entry points — the shaded one
11076 // and `rsmFragmentMain` — and `entry` answers `None` for two matches, so
11077 // a stage lookup here refuses the build outright with "exposes no
11078 // unambiguous Fragment entry point".
11079 let fragment = named_entry(&MESH, "fragmentMain", Stage::Fragment)?;
11080 let depth_masked_fragment = named_entry(&MESH, "depthMaskedFragmentMain", Stage::Fragment)?;
11081 let rsm_fragment = named_entry(&MESH, "rsmFragmentMain", Stage::Fragment)?;
11082 // **Named rather than looked up by stage**, because the module has two
11083 // mesh entry points and a stage lookup would refuse an ambiguous one —
11084 // see `named_entry`. Which of the two this names is the whole of the
11085 // amplification decision.
11086 let cluster_stages = emit
11087 .is_mesh()
11088 .then(|| {
11089 let mesh = named_entry(
11090 &MESH_CLUSTER,
11091 if culls_clusters {
11092 "amplifiedMeshMain"
11093 } else {
11094 "meshMain"
11095 },
11096 Stage::Mesh,
11097 )?;
11098 let task = culls_clusters
11099 .then(|| named_entry(&MESH_CLUSTER, "taskMain", Stage::Task))
11100 .transpose()?;
11101 Ok::<_, HalError>((mesh, task))
11102 })
11103 .transpose()?;
11104
11105 let mesh = device.create_shader_module(&ShaderModuleDesc {
11106 label: Some("mesh.slang"),
11107 spirv: MESH.spirv(),
11108 wgsl: MESH.wgsl(),
11109 msl: MESH.msl(),
11110 // **Both containers, and still one module.** A DXIL container holds
11111 // exactly one entry point, so this is a list where its three
11112 // neighbours are single artifacts; the backend that consumes it
11113 // picks the container named by the stage it is building. Nothing
11114 // here branches on a backend, and the three that ignore DXIL see
11115 // the same module they always did.
11116 dxil: &MESH.dxil_containers(),
11117 })?;
11118 let cluster = match cluster_stages {
11119 None => None,
11120 Some((cluster_mesh, task)) => {
11121 // **The mesh stage's module is `mesh_cluster.slang`; the
11122 // fragment stage's is still `mesh.slang`'s.** A pipeline takes a
11123 // module per stage, so the shading — Lambert, the GGX lobe, the
11124 // material row, the page sample — is the same code both paths
11125 // run rather than a copy that agrees today.
11126 // `mesh_cluster.slang`'s header carries the argument, and its
11127 // `VertexOutput` is what the two agree through.
11128 // **One module per stage, each carrying that stage's own
11129 // SPIR-V.** Only the SPIR-V differs between them: MSL is one
11130 // artifact per source whatever the stage, and a DXIL container
11131 // is already per entry point, so both are handed over unchanged
11132 // and the backends that read them see what they always did.
11133 let stage_module = |entry_point: &str| {
11134 device.create_shader_module(&ShaderModuleDesc {
11135 label: Some("mesh_cluster.slang"),
11136 // The combined module where this stage has none of its
11137 // own, which is every stage of every other shader.
11138 spirv: MESH_CLUSTER
11139 .spirv_for(entry_point)
11140 .unwrap_or_else(|| MESH_CLUSTER.spirv()),
11141 // `None`, and it is the whole reason this is a second
11142 // file: WGSL cannot express a mesh stage at all.
11143 wgsl: MESH_CLUSTER.wgsl(),
11144 msl: MESH_CLUSTER.msl(),
11145 dxil: &MESH_CLUSTER.dxil_containers(),
11146 })
11147 };
11148 let mesh_module = match stage_module(cluster_mesh) {
11149 Ok(module) => module,
11150 Err(error) => {
11151 device.destroy_shader_module(mesh);
11152 return Err(error);
11153 }
11154 };
11155 let task_module = match task.map(stage_module).transpose() {
11156 Ok(module) => module,
11157 Err(error) => {
11158 device.destroy_shader_module(mesh);
11159 device.destroy_shader_module(mesh_module);
11160 return Err(error);
11161 }
11162 };
11163 Some(ClusterStages {
11164 mesh_module,
11165 task_module,
11166 mesh: cluster_mesh,
11167 task,
11168 })
11169 }
11170 };
11171 Ok(Self {
11172 mesh,
11173 vertex,
11174 depth_vertex,
11175 depth_clear_vertex,
11176 fragment,
11177 depth_masked_fragment,
11178 rsm_fragment,
11179 cluster,
11180 })
11181 }
11182
11183 /// The rasteriser state every pipeline shape here shares, because the only
11184 /// things that differ between them are which stage produces the geometry and
11185 /// which side of it survives.
11186 ///
11187 /// [`CullMode::Back`] is what a single-sided bucket asks for, and it has
11188 /// been on from the first mesh. The cube's winding is asserted by
11189 /// `crcbl-shaders`' own tests, so a face that vanished would be a *test*
11190 /// failure rather than a debugging session — and a mesh drawn without
11191 /// culling would let a winding mistake survive into P7's geometry pool. The
11192 /// mesh stage emits its corner triples in the index buffer's own order, so
11193 /// the winding it produces is the same one.
11194 ///
11195 /// [`CullMode::None`] is what a double-sided bucket asks for — glTF 2.0
11196 /// §3.9.6's first half — and the twin built with it is the only way a back
11197 /// face reaches `mesh.slang` at all. See [`SidedPipelines`].
11198 fn primitive(polygon_mode: PolygonMode, cull_mode: CullMode) -> PrimitiveState {
11199 PrimitiveState {
11200 cull_mode,
11201 polygon_mode,
11202 ..PrimitiveState::default()
11203 }
11204 }
11205
11206 /// What a pipeline built with `cull` adds to its label, so a capture and
11207 /// `crcbl_hal::null`'s recorder tell a [`SidedPipelines::double`] twin from
11208 /// the [`SidedPipelines::single`] it was built beside.
11209 ///
11210 /// Empty for the culling modes, because those pipelines' labels are the ones
11211 /// every existing capture and every test lookup already names.
11212 fn side_label(cull: CullMode) -> &'static str {
11213 match cull {
11214 CullMode::None => " double-sided",
11215 CullMode::Front | CullMode::Back => "",
11216 }
11217 }
11218
11219 /// Both sides of one pipeline shape, single-sided first, **created and not
11220 /// yet unwrapped**.
11221 ///
11222 /// The results rather than the pair, because that is the discipline `build`
11223 /// keeps for every pipeline it makes: everything is created while the
11224 /// modules are alive, the modules are released once, and only then is each
11225 /// successful result handed to rollback before any error is propagated. A
11226 /// helper that unwrapped here would have to drop a handle it had already
11227 /// created when its twin failed, and nothing would ever destroy it.
11228 fn sided(
11229 mut build: impl FnMut(CullMode) -> Result<GraphicsPipelineHandle, HalError>,
11230 ) -> [Result<GraphicsPipelineHandle, HalError>; 2] {
11231 [build(CullMode::Back), build(CullMode::None)]
11232 }
11233
11234 /// Milestone 3's depth test, and the seam's default is already reversed-Z:
11235 /// `Greater` against `D32Float`, writes on. The clear value that agrees with
11236 /// it comes from the graph (`PassBuilder::clear_depth`), and the projection
11237 /// matrix that agrees with **both** comes from [`crate::camera`].
11238 fn depth_stencil() -> Option<DepthStencilState> {
11239 Some(DepthStencilState::default())
11240 }
11241
11242 /// The colour pass's depth state, which is not the same shape as
11243 /// [`MeshModules::depth_stencil`] because the depth prepass has already
11244 /// drawn this geometry.
11245 ///
11246 /// **Filled: [`DepthStencilState::equal_depth_read_only`], so the shading is
11247 /// paid for once per pixel.** The prepass runs the same draws through
11248 /// `depthVertexMain` — or, on the mesh path, through the very same geometry
11249 /// stage — so the depth already in the attachment is this pass's own answer,
11250 /// and a `GreaterOrEqual` test with writes off keeps exactly the fragments
11251 /// that would have won the write. What it removes is the clustered-forward
11252 /// shading of every fragment a nearer one goes on to cover.
11253 ///
11254 /// **Lines: the writing default, because a wireframe is not the geometry the
11255 /// prepass drew.** [`PolygonMode::Line`] rasterises the triangle's edges,
11256 /// and an edge pixel's depth is interpolated along the line rather than
11257 /// across the face, so testing it for equality against a filled prepass
11258 /// rejects most of the wireframe. That frame keeps the pass shape this pass
11259 /// had before the prepass existed — see the colour pass's depth attachment,
11260 /// which branches on the same condition.
11261 fn color_depth_stencil(polygon_mode: PolygonMode) -> Option<DepthStencilState> {
11262 match polygon_mode {
11263 PolygonMode::Fill => Some(DepthStencilState::equal_depth_read_only(Format::D32Float)),
11264 _ => Self::depth_stencil(),
11265 }
11266 }
11267
11268 /// The colour pass's pipeline, filled or wireframe, culling back faces or
11269 /// nothing.
11270 ///
11271 /// `label` names the caller — `"forward"` for the frame's own, `"wireframe"`
11272 /// for [`ForwardRenderer::set_wireframe`]'s — and [`MeshModules::side_label`]
11273 /// names the side, so a capture tells all four apart.
11274 fn color_pipeline(
11275 &self,
11276 device: &dyn Device,
11277 layout: PipelineLayoutHandle,
11278 polygon_mode: PolygonMode,
11279 cull: CullMode,
11280 label: &str,
11281 ) -> Result<GraphicsPipelineHandle, HalError> {
11282 let primitive = Self::primitive(polygon_mode, cull);
11283 let depth_stencil = Self::color_depth_stencil(polygon_mode);
11284 let side = Self::side_label(cull);
11285 let fragment = Some(ShaderEntry {
11286 module: self.mesh,
11287 entry_point: self.fragment,
11288 });
11289 match self.cluster.as_ref() {
11290 Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11291 label: Some(&format!("{label}{side} mesh cluster")),
11292 layout,
11293 task: cluster
11294 .task
11295 .zip(cluster.task_module)
11296 .map(|(entry_point, module)| ShaderEntry {
11297 module,
11298 entry_point,
11299 }),
11300 task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11301 mesh: ShaderEntry {
11302 module: cluster.mesh_module,
11303 entry_point: cluster.mesh,
11304 },
11305 mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11306 fragment,
11307 primitive,
11308 depth_stencil,
11309 multisample: MultisampleState::default(),
11310 color_targets: &Self::COLOR_TARGETS,
11311 }),
11312 None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11313 label: Some(&format!("{label}{side} mesh")),
11314 layout,
11315 vertex: ShaderEntry {
11316 module: self.mesh,
11317 entry_point: self.vertex,
11318 },
11319 fragment,
11320 primitive,
11321 depth_stencil,
11322 multisample: MultisampleState::default(),
11323 color_targets: &Self::COLOR_TARGETS,
11324 }),
11325 }
11326 }
11327
11328 /// The depth-only twin of [`MeshModules::color_pipeline`], built out of the
11329 /// same modules and the same layout: no fragment stage, no colour target,
11330 /// and a vertex stage that fetches stream 0 of the vertex pool alone.
11331 ///
11332 /// **The transform is identical and the fetch is not, which is the point.**
11333 /// Topic 18 asks for a shadow pass "identical on every `GeometryPath` —
11334 /// depth pass plus whatever emit tail the device selected", and what makes
11335 /// that work is a frame block whose `view_proj` is the cascade's matrix
11336 /// rather than a second transform path: a cascade that disagreed with the
11337 /// colour pass about where a vertex is would produce shadows that do not
11338 /// line up with their casters, which is indistinguishable from a bias
11339 /// problem. `depthVertexMain` is that same clip position written the same
11340 /// way, with everything the discarded varyings needed — the attribute
11341 /// region and the previous frame's position — left unread;
11342 /// topic 43 §2 split the pool for exactly this
11343 /// pass, and this is where it is spent.
11344 ///
11345 /// **The mesh-shader path still runs the colour pipeline's geometry
11346 /// stage.** `mesh_cluster.slang` emits one `VertexOutput`, so a depth-only
11347 /// mesh stage is a second entry point in that module and its own rung; a
11348 /// device with a mesh stage goes on reading whole vertices here.
11349 ///
11350 /// Always [`PolygonMode::Fill`]: it fills the shadow atlas and the depth
11351 /// prepass, and depth drawn as lines is depth with holes in it — which the
11352 /// occlusion pair would read as geometry that is not there.
11353 fn depth_pipeline(
11354 &self,
11355 device: &dyn Device,
11356 layout: PipelineLayoutHandle,
11357 cull: CullMode,
11358 ) -> Result<GraphicsPipelineHandle, HalError> {
11359 let primitive = Self::primitive(PolygonMode::Fill, cull);
11360 let side = Self::side_label(cull);
11361 match self.cluster.as_ref() {
11362 Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11363 label: Some(&format!("shadow cascade{side} mesh cluster")),
11364 layout,
11365 task: cluster
11366 .task
11367 .zip(cluster.task_module)
11368 .map(|(entry_point, module)| ShaderEntry {
11369 module,
11370 entry_point,
11371 }),
11372 task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11373 mesh: ShaderEntry {
11374 module: cluster.mesh_module,
11375 entry_point: cluster.mesh,
11376 },
11377 mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11378 fragment: None,
11379 primitive,
11380 depth_stencil: Self::depth_stencil(),
11381 multisample: MultisampleState::default(),
11382 color_targets: &[],
11383 }),
11384 None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11385 label: Some(&format!("shadow cascade{side}")),
11386 layout,
11387 vertex: ShaderEntry {
11388 module: self.mesh,
11389 entry_point: self.depth_vertex,
11390 },
11391 fragment: None,
11392 primitive,
11393 depth_stencil: Self::depth_stencil(),
11394 multisample: MultisampleState::default(),
11395 color_targets: &[],
11396 }),
11397 }
11398 }
11399
11400 /// [`MeshModules::depth_pipeline`] with an alpha mask in it: the same depth
11401 /// state and the same absent colour targets, `depthMaskedFragmentMain`
11402 /// behind the geometry stage, and [`MeshModules::vertex`] in
11403 /// [`MeshModules::depth_vertex`]'s place.
11404 ///
11405 /// Topic 43 §3's cutout, in the two passes that
11406 /// write depth without shading. A masked instance drawn through the pipeline
11407 /// above writes its full silhouette: it occludes itself through the hole it
11408 /// can see through, and it casts the shadow of a leaf that has none.
11409 ///
11410 /// **The vertex stage is the colour pass's, and it has to be.** A cutout
11411 /// needs the UV, which lives in the attribute region `depthVertexMain`
11412 /// exists not to read — so this stage reads a whole vertex, exactly as
11413 /// [`MeshModules::rsm_pipeline`] does beside it and for the same reason.
11414 /// What that buys is one fragment entry point for both geometry paths: the
11415 /// mesh path already emits `mesh.slang`'s `VertexOutput`, so the mask is
11416 /// compared in one place rather than once per path.
11417 ///
11418 /// **Which draws are recorded with it is the bucket's own material mode**,
11419 /// not the frame's — see [`ForwardRenderer::depth_partitions`]. A scene that
11420 /// masks nothing has no bucket in this partition, records through the
11421 /// pipeline above with no fragment stage anywhere, and costs exactly what it
11422 /// cost before this one existed; a scene that masks one mesh pays the
11423 /// fragment stage for that mesh's draws alone.
11424 fn depth_masked_pipeline(
11425 &self,
11426 device: &dyn Device,
11427 layout: PipelineLayoutHandle,
11428 cull: CullMode,
11429 ) -> Result<GraphicsPipelineHandle, HalError> {
11430 let primitive = Self::primitive(PolygonMode::Fill, cull);
11431 let side = Self::side_label(cull);
11432 let fragment = Some(ShaderEntry {
11433 module: self.mesh,
11434 entry_point: self.depth_masked_fragment,
11435 });
11436 match self.cluster.as_ref() {
11437 Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11438 label: Some(&format!("shadow cascade masked{side} mesh cluster")),
11439 layout,
11440 task: cluster
11441 .task
11442 .zip(cluster.task_module)
11443 .map(|(entry_point, module)| ShaderEntry {
11444 module,
11445 entry_point,
11446 }),
11447 task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11448 mesh: ShaderEntry {
11449 module: cluster.mesh_module,
11450 entry_point: cluster.mesh,
11451 },
11452 mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11453 fragment,
11454 primitive,
11455 depth_stencil: Self::depth_stencil(),
11456 multisample: MultisampleState::default(),
11457 color_targets: &[],
11458 }),
11459 None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11460 label: Some(&format!("shadow cascade masked{side}")),
11461 layout,
11462 vertex: ShaderEntry {
11463 module: self.mesh,
11464 entry_point: self.vertex,
11465 },
11466 fragment,
11467 primitive,
11468 depth_stencil: Self::depth_stencil(),
11469 multisample: MultisampleState::default(),
11470 color_targets: &[],
11471 }),
11472 }
11473 }
11474
11475 /// The reflective shadow map's pipeline: the colour pipeline's geometry
11476 /// stage, `rsmFragmentMain` in the shaded stage's place, and
11477 /// [`MeshModules::RSM_TARGETS`] in [`MeshModules::COLOR_TARGETS`]'s.
11478 ///
11479 /// The irradiance probes' updater draws the sun's near
11480 /// cascade a second time through this — see [`crate::rsm`], which owns the
11481 /// attachments, and `ForwardRenderer::add_shadow_pass`, which records the
11482 /// pass out of that cascade's own bind group and its own already-generated
11483 /// draws.
11484 ///
11485 /// **[`MeshModules::vertex`] and not [`MeshModules::depth_vertex`]**, unlike
11486 /// the cascade this rides beside: a fragment stage that writes a world
11487 /// position, a normal and an albedo needs the varyings `depthVertexMain`
11488 /// exists to leave unread. On the mesh path it is the very same geometry
11489 /// stage the colour pass runs, for the reason `depth_pipeline` gives.
11490 ///
11491 /// **Its own depth, written**, rather than the colour pass's read-only
11492 /// equality test: nothing has drawn this view's depth before it, and the
11493 /// pass is what decides which surface a texel of the map holds.
11494 fn rsm_pipeline(
11495 &self,
11496 device: &dyn Device,
11497 layout: PipelineLayoutHandle,
11498 cull: CullMode,
11499 ) -> Result<GraphicsPipelineHandle, HalError> {
11500 let primitive = Self::primitive(PolygonMode::Fill, cull);
11501 let side = Self::side_label(cull);
11502 let fragment = Some(ShaderEntry {
11503 module: self.mesh,
11504 entry_point: self.rsm_fragment,
11505 });
11506 match self.cluster.as_ref() {
11507 Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11508 label: Some(&format!("rsm{side} mesh cluster")),
11509 layout,
11510 task: cluster
11511 .task
11512 .zip(cluster.task_module)
11513 .map(|(entry_point, module)| ShaderEntry {
11514 module,
11515 entry_point,
11516 }),
11517 task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11518 mesh: ShaderEntry {
11519 module: cluster.mesh_module,
11520 entry_point: cluster.mesh,
11521 },
11522 mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11523 fragment,
11524 primitive,
11525 depth_stencil: Self::depth_stencil(),
11526 multisample: MultisampleState::default(),
11527 color_targets: &Self::RSM_TARGETS,
11528 }),
11529 None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11530 label: Some(&format!("rsm{side}")),
11531 layout,
11532 vertex: ShaderEntry {
11533 module: self.mesh,
11534 entry_point: self.vertex,
11535 },
11536 fragment,
11537 primitive,
11538 depth_stencil: Self::depth_stencil(),
11539 multisample: MultisampleState::default(),
11540 color_targets: &Self::RSM_TARGETS,
11541 }),
11542 }
11543 }
11544
11545 /// The pipeline that resets one tile of the shadow atlas, so a pass can keep
11546 /// some tiles and redraw others.
11547 ///
11548 /// Topic 45's cadence rung needs a tile cleared on its own,
11549 /// and the attachment's [`LoadOp`] cannot do it — a clear there covers the
11550 /// whole image, and the region-bounded forms are not portable. This is the
11551 /// portable statement of the same thing: `mesh.slang`'s
11552 /// `depthClearVertexMain` covers the viewport the shadow pass has already
11553 /// set over the tile, and the depth state below writes
11554 /// [`depth::CLEAR`](crcbl_hal::depth) over whatever was there.
11555 ///
11556 /// **[`CompareOp::Always`] and writes on**, which is the pair that makes it a
11557 /// clear rather than a draw: the tile holds the previous frame's depths, and
11558 /// under the engine's [`CompareOp::Greater`] a clear value of zero would
11559 /// fail against every one of them and leave the tile exactly as it was.
11560 ///
11561 /// **[`CullMode::None`]**, unlike [`MeshModules::primitive`]: the triangle
11562 /// is generated from `SV_VertexID` rather than wound by an artist, so a
11563 /// culling rule meant for scene geometry would decide whether the clear
11564 /// happens at all.
11565 ///
11566 /// **A vertex pipeline on every path**, including the mesh-shader one: a
11567 /// device with a mesh stage still has a vertex stage, and the clear has no
11568 /// clusters to descend.
11569 fn depth_clear_pipeline(
11570 &self,
11571 device: &dyn Device,
11572 layout: PipelineLayoutHandle,
11573 ) -> Result<GraphicsPipelineHandle, HalError> {
11574 device.create_graphics_pipeline(&GraphicsPipelineDesc {
11575 label: Some("shadow tile clear"),
11576 // The mesh layout, so binding this pipeline in the middle of the
11577 // shadow pass does not disturb the bind group the draws around it
11578 // are recorded with. The stage reads none of it.
11579 layout,
11580 vertex: ShaderEntry {
11581 module: self.mesh,
11582 entry_point: self.depth_clear_vertex,
11583 },
11584 fragment: None,
11585 primitive: PrimitiveState {
11586 cull_mode: CullMode::None,
11587 polygon_mode: PolygonMode::Fill,
11588 ..PrimitiveState::default()
11589 },
11590 depth_stencil: Some(DepthStencilState {
11591 depth_compare: CompareOp::Always,
11592 ..DepthStencilState::default()
11593 }),
11594 multisample: MultisampleState::default(),
11595 color_targets: &[],
11596 })
11597 }
11598
11599 /// Releases every module. The pipelines built from them stay valid.
11600 fn destroy(self, device: &dyn Device) {
11601 device.destroy_shader_module(self.mesh);
11602 if let Some(cluster) = self.cluster {
11603 device.destroy_shader_module(cluster.mesh_module);
11604 if let Some(task) = cluster.task_module {
11605 device.destroy_shader_module(task);
11606 }
11607 }
11608 }
11609}
11610
11611/// The entry point for `stage`, or an error naming the shader.
11612///
11613/// Unreachable in practice — `crcbl-shaders`' own tests assert both modules
11614/// expose both stages — but the alternative is an `expect` in engine code.
11615fn entry(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&'static str, HalError> {
11616 shader.entry_point(stage).ok_or_else(|| {
11617 HalError::ShaderCompilation(format!(
11618 "{}.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and its \
11619 manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11620 shader.name()
11621 ))
11622 })
11623}
11624
11625/// The entry point called `name`, checked to be `stage`'s.
11626///
11627/// [`entry`] cannot serve `mesh_cluster.slang`: it has **two** mesh entry
11628/// points — one behind the amplification stage and one without it — and a
11629/// lookup by stage answers `None` for two matches rather than picking one, for
11630/// the good reason that picking one would draw the wrong geometry.
11631///
11632/// The stage is still checked rather than taken on trust: a name that resolved
11633/// to the wrong stage would be a pipeline built with an amplification stage in
11634/// its mesh slot, and the failure would arrive as a driver error rather than as
11635/// this sentence.
11636pub(crate) fn named_entry(
11637 shader: &crcbl_shaders::Shader,
11638 name: &'static str,
11639 stage: Stage,
11640) -> Result<&'static str, HalError> {
11641 let found = shader
11642 .entry_points()
11643 .iter()
11644 .find(|entry| entry.name() == name && entry.stage() == stage);
11645 found.map(crcbl_shaders::EntryPoint::name).ok_or_else(|| {
11646 HalError::ShaderCompilation(format!(
11647 "{}.slang exposes no {stage:?} entry point called `{name}`; the committed SPIR-V and \
11648 its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11649 shader.name()
11650 ))
11651 })
11652}
11653
11654// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
11655#[cfg(all(test, not(target_arch = "wasm32")))]
11656mod tests {
11657 mod instance_upload;
11658 mod load_service;
11659 mod page_reload;
11660 mod shadow_reach;
11661
11662 use super::*;
11663 use crate::effects::{Antialiasing, EffectOverride};
11664 use crate::scene::{
11665 DEMO_CUBE, DEMO_DUNES, DEMO_OPEN_BOX, DEMO_PYRAMID, DEMO_TEXTURED, DEMO_TINTED,
11666 DEMO_UNTINTED,
11667 };
11668 use crcbl_hal::null::{Event, NullInstance, ObjectKind, Recorder};
11669 use crcbl_hal::{DeviceDesc, DrawIndirect, Features, Instance, QueueKind};
11670
11671 #[test]
11672 fn refused_mesh_color_pipelines_release_successful_depth_pipelines() {
11673 let recorder = Recorder::new();
11674 let mut limits = crcbl_hal::Limits::desktop();
11675 limits.max_color_attachments = 2;
11676 let features = Features::COMPUTE | Features::MESH_SHADER;
11677 let instance = NullInstance::new(crcbl_hal::DeviceCaps { features, limits })
11678 .with_recorder(recorder.clone());
11679 let device = instance
11680 .create_device(&DeviceDesc {
11681 label: None,
11682 adapter: crcbl_hal::AdapterId(0),
11683 required_features: features,
11684 optional_features: Features::empty(),
11685 compatible_surface: None,
11686 })
11687 .unwrap();
11688 let queue = device.queue(QueueKind::Graphics).unwrap();
11689 let before = recorder.total_live_objects();
11690 let error = ForwardRenderer::with_scene_on_path(
11691 device.as_ref(),
11692 queue,
11693 Format::Rgba8UnormSrgb,
11694 &scene::demo(),
11695 GeometryPath::MeshShader,
11696 )
11697 .expect_err("three-target color pipelines must be refused");
11698 assert!(
11699 error
11700 .to_string()
11701 .contains("3 colour targets exceeds max_color_attachments 2"),
11702 "{error}"
11703 );
11704 assert!(
11705 recorder.events().iter().any(|event| matches!(
11706 event,
11707 Event::Created {
11708 kind: ObjectKind::GraphicsPipeline,
11709 ..
11710 }
11711 )),
11712 "the refusal must exercise cleanup of successful pipelines"
11713 );
11714 assert_eq!(
11715 recorder.total_live_objects(),
11716 before,
11717 "partial pipeline construction leaked resources"
11718 );
11719 recorder.assert_valid();
11720 }
11721
11722 #[test]
11723 fn exact_geometry_path_overrides_preference_and_default_keeps_it() {
11724 let recorder = Recorder::new();
11725 let instance = NullInstance::gpu_driven()
11726 .with_geometry_preference(GeometryPath::IndirectPerBatch)
11727 .with_recorder(recorder.clone());
11728 let device = instance
11729 .create_device(&DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)))
11730 .unwrap();
11731 let queue = device.queue(QueueKind::Graphics).unwrap();
11732 assert_eq!(device.caps().geometry_path(), GeometryPath::IndirectCount);
11733 let default = ForwardRenderer::with_scene(
11734 device.as_ref(),
11735 queue,
11736 Format::Rgba8UnormSrgb,
11737 &scene::demo(),
11738 )
11739 .unwrap();
11740 assert_eq!(default.geometry_path(), GeometryPath::IndirectPerBatch);
11741 default.destroy(device.as_ref());
11742 recorder.clear();
11743 let mut exact = ForwardRenderer::with_scene_on_path(
11744 device.as_ref(),
11745 queue,
11746 Format::Rgba8UnormSrgb,
11747 &scene::demo(),
11748 GeometryPath::IndirectCount,
11749 )
11750 .unwrap();
11751 assert_eq!(exact.geometry_path(), GeometryPath::IndirectCount);
11752 let rendered = frame(device.as_ref(), &mut exact, queue);
11753 let commands = commands_in_pass(&recorder, "forward");
11754 assert!(commands.iter().any(|command| matches!(
11755 command,
11756 crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
11757 )));
11758 assert!(
11759 !commands
11760 .iter()
11761 .any(|command| matches!(command, crcbl_hal::null::Command::DrawIndexedIndirect(_)))
11762 );
11763 rendered.finish(device.as_ref(), exact);
11764 }
11765
11766 /// **A device with a draw index draws a range of buckets per call, and one
11767 /// without it a call per bucket** — both indirect tails, read off the
11768 /// recorded stream of a whole frame.
11769 ///
11770 /// The ranged frame records one bind and one multi-draw per range in the
11771 /// depth prepass, whose draws together cover every bucket exactly once,
11772 /// and no count draw anywhere; the per-bucket frame records the call per
11773 /// bucket it always did. Both frames' counters are what they recorded.
11774 #[test]
11775 fn a_draw_index_puts_the_geometry_passes_on_a_call_per_range() {
11776 use crcbl_hal::null::Command;
11777
11778 for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
11779 for ranged in [false, true] {
11780 let optional = if ranged {
11781 Features::GPU_DRIVEN | Features::DRAW_INDEX
11782 } else {
11783 DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features
11784 };
11785 let (recorder, device, queue) = open_with(optional);
11786 let mut renderer = ForwardRenderer::with_scene_on_path(
11787 device.as_ref(),
11788 queue,
11789 Format::Rgba8UnormSrgb,
11790 &scene::demo(),
11791 path,
11792 )
11793 .expect("the demo scene builds");
11794 assert_eq!(renderer.range_limit.is_some(), ranged, "{path:?}");
11795 let buckets = renderer.bucket_modes.len();
11796 assert!(buckets > 1, "one bucket packs into one call either way");
11797 let rendered = frame(device.as_ref(), &mut renderer, queue);
11798
11799 let commands = commands_in_pass(&recorder, "depth-prepass");
11800 let binds = commands
11801 .iter()
11802 .filter(|command| matches!(command, Command::BindGroup { slot: 0, .. }))
11803 .count();
11804 let draws: Vec<u32> = commands
11805 .iter()
11806 .filter_map(|command| match command {
11807 Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
11808 Command::DrawIndexedIndirectCount(draw) => {
11809 assert!(!ranged, "{path:?}: a ranged pass records no count draw");
11810 assert_eq!(draw.max_draw_count, 1);
11811 Some(1)
11812 }
11813 _ => None,
11814 })
11815 .collect();
11816 assert_eq!(binds, draws.len(), "{path:?}: one bind per call");
11817 assert_eq!(
11818 draws.iter().sum::<u32>() as usize,
11819 buckets,
11820 "{path:?}: every bucket drawn once"
11821 );
11822 if ranged {
11823 assert!(
11824 draws.len() < buckets,
11825 "{path:?}: {draws:?} is a call per bucket over {buckets} buckets"
11826 );
11827 } else {
11828 assert_eq!(draws, vec![1; buckets], "{path:?}");
11829 }
11830 assert!(
11831 !recorder
11832 .commands()
11833 .iter()
11834 .any(|command| ranged
11835 && matches!(command, Command::DrawIndexedIndirectCount(_))),
11836 "{path:?}: a ranged frame records no count draw"
11837 );
11838 assert_eq!(
11839 renderer.counters().draws,
11840 recorded_draws(&recorder) as u64,
11841 "{path:?}, ranged {ranged}"
11842 );
11843 rendered.finish(device.as_ref(), renderer);
11844 recorder.assert_valid();
11845 }
11846 }
11847 }
11848
11849 /// **A scene holding every material mode draws each pipeline's buckets as
11850 /// one ranged call**, because the bucket table is numbered mode-major: the
11851 /// depth prepass records one call per depth pipeline and the colour pass
11852 /// one per sided pipeline, on both indirect tails.
11853 ///
11854 /// Numbered mesh by mesh, the same scene alternates modes bucket by bucket
11855 /// and every partition's runs are one bucket long, so the prepass would
11856 /// record a call per bucket — the counts below are what tell the two
11857 /// numberings apart, and the sums are what say every bucket still drew.
11858 #[test]
11859 fn every_mode_partition_of_a_ranged_frame_is_one_call() {
11860 use crcbl_hal::null::Command;
11861 use crcbl_shaders::mesh::GpuMaterial;
11862
11863 let scene = {
11864 let mut scene = crate::scene::demo();
11865 while scene.materials.len() < 4 {
11866 scene.materials.push(GpuMaterial::UNTINTED);
11867 }
11868 let rows = [
11869 0,
11870 GpuMaterial::ALPHA_MODE_MASK,
11871 GpuMaterial::DOUBLE_SIDED,
11872 GpuMaterial::MODE_MASK,
11873 ];
11874 for (row, flags) in scene.materials.iter_mut().zip(rows) {
11875 row.flags = flags;
11876 }
11877 scene
11878 };
11879 for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
11880 let (recorder, device, queue) = open_with(Features::GPU_DRIVEN | Features::DRAW_INDEX);
11881 let mut renderer = ForwardRenderer::with_scene_on_path(
11882 device.as_ref(),
11883 queue,
11884 Format::Rgba8UnormSrgb,
11885 &scene,
11886 path,
11887 )
11888 .expect("the four-mode demo builds");
11889 assert!(renderer.range_limit.is_some(), "{path:?}");
11890 let buckets = renderer.bucket_modes.len();
11891 let per_mode = buckets / DEPTH_MODES.len();
11892 assert_eq!(
11893 per_mode * DEPTH_MODES.len(),
11894 buckets,
11895 "{path:?}: four twins"
11896 );
11897 assert!(
11898 per_mode > 1,
11899 "{path:?}: a mode of one bucket is one call under either numbering"
11900 );
11901 let rendered = frame(device.as_ref(), &mut renderer, queue);
11902
11903 let draws = |label: &str| -> Vec<u32> {
11904 commands_in_pass(&recorder, label)
11905 .iter()
11906 .filter_map(|command| match command {
11907 Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
11908 _ => None,
11909 })
11910 .collect()
11911 };
11912 let prepass = draws("depth-prepass");
11913 assert_eq!(
11914 prepass,
11915 vec![u32::try_from(per_mode).expect("a few buckets"); DEPTH_MODES.len()],
11916 "{path:?}: one call per depth pipeline, each a whole mode"
11917 );
11918 let forward = draws("forward");
11919 assert_eq!(
11920 forward,
11921 vec![u32::try_from(2 * per_mode).expect("a few buckets"); 2],
11922 "{path:?}: one call per sided pipeline, each two adjacent modes"
11923 );
11924 rendered.finish(device.as_ref(), renderer);
11925 recorder.assert_valid();
11926 }
11927 }
11928
11929 /// **Behind an amplification stage the mesh tail records one flat call per
11930 /// partition, and without one a range of buckets per call on a device with
11931 /// a draw index and a call per bucket without** — read off the recorded
11932 /// stream of a whole frame.
11933 ///
11934 /// The flat calls are [`flat_dispatch_calls`]: one structure each, the
11935 /// colour pass's sided segments in region 0, under the segment's first
11936 /// bucket's block — whatever the bucket count, and whether or not the
11937 /// device granted a draw index, which the flat call does not read. Without
11938 /// the stage the colour pass's calls, unrolled a structure at a time, are
11939 /// exactly the per-bucket dispatches [`mesh_dispatch_calls`] names — every
11940 /// bucket's own extents, each once. Either way the counters are what the
11941 /// frame recorded.
11942 #[test]
11943 fn the_mesh_tail_records_a_flat_call_per_partition_behind_a_task_stage() {
11944 use crcbl_hal::null::Command;
11945
11946 // `None` is the demo scene; `Some(n)` is `n` copies of its cube, one
11947 // bucket each, in one material mode — so one run of `n` buckets.
11948 for cubes in [None, Some(4), Some(33)] {
11949 for task in [Features::TASK_SHADER, Features::empty()] {
11950 for ranged in [false, true] {
11951 let case = format!("{cubes:?} cubes, {task:?}, ranged {ranged}");
11952 let recorder = Recorder::new();
11953 let optional = if ranged {
11954 task | Features::DRAW_INDEX
11955 } else {
11956 task
11957 };
11958 let (device, queue) = open_mesh_path(&recorder, optional);
11959 let mut scene = scene::demo();
11960 if let Some(cubes) = cubes {
11961 scene.meshes = vec![scene.meshes[DEMO_CUBE].clone(); cubes as usize];
11962 scene.capacities.meshes = cubes;
11963 scene.capacities.vertices =
11964 cubes * crcbl_shaders::mesh::CUBE_VERTEX_COUNT as u32;
11965 scene.capacities.indices =
11966 cubes * crcbl_shaders::mesh::CUBE_INDEX_COUNT as u32;
11967 }
11968 let mut renderer = ForwardRenderer::with_scene_on_path(
11969 device.as_ref(),
11970 queue,
11971 Format::Rgba8UnormSrgb,
11972 &scene,
11973 GeometryPath::MeshShader,
11974 )
11975 .expect("the mesh renderer builds");
11976 assert_eq!(renderer.range_limit.is_some(), ranged, "{case}");
11977 assert_eq!(renderer.culls_clusters(), !task.is_empty(), "{case}");
11978 let buckets = renderer.bucket_constants.len();
11979 assert!(buckets > 1, "one bucket packs into one call either way");
11980 let rendered = frame(device.as_ref(), &mut renderer, queue);
11981
11982 let commands = commands_in_pass(&recorder, "forward");
11983 let bound: Vec<u32> = commands
11984 .iter()
11985 .filter_map(|command| match command {
11986 Command::BindGroup {
11987 slot: 0,
11988 dynamic_offsets,
11989 ..
11990 } => Some(dynamic_offsets[0]),
11991 _ => None,
11992 })
11993 .collect();
11994 let calls: Vec<DrawIndirect> = commands
11995 .iter()
11996 .filter_map(|command| match command {
11997 Command::DrawMeshTasksIndirect(draw) => Some(*draw),
11998 Command::DrawMeshTasks { .. }
11999 | Command::DrawIndexedIndirect(_)
12000 | Command::DrawIndexedIndirectCount(_) => {
12001 panic!("{case}: the mesh tail recorded {command:?}")
12002 }
12003 _ => None,
12004 })
12005 .collect();
12006 assert_eq!(bound.len(), calls.len(), "{case}: one bind per call");
12007 assert!(
12008 calls
12009 .iter()
12010 .all(|call| call.stride
12011 == crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32),
12012 "{case}: one structure a bucket, or a flat call's one"
12013 );
12014 if task.is_empty() {
12015 // Each call a structure at a time: what a call per
12016 // bucket would have recorded for the buckets it
12017 // stands for.
12018 let mut unrolled: Vec<DrawIndirect> = calls
12019 .iter()
12020 .flat_map(|call| {
12021 (0..call.draw_count).map(|draw| DrawIndirect {
12022 offset: call.offset + u64::from(draw) * u64::from(call.stride),
12023 draw_count: 1,
12024 ..*call
12025 })
12026 })
12027 .collect();
12028 unrolled.sort_by_key(|draw| draw.offset);
12029 assert_eq!(
12030 unrolled,
12031 mesh_dispatch_calls(&renderer),
12032 "{case}: every bucket's own extents, each once"
12033 );
12034 let counts: Vec<u32> = calls.iter().map(|call| call.draw_count).collect();
12035 match (ranged, cubes) {
12036 (false, _) => assert_eq!(counts, vec![1; buckets], "{case}"),
12037 (true, Some(cubes)) => assert_eq!(counts, vec![cubes], "{case}"),
12038 (true, None) => assert!(
12039 calls.len() < buckets,
12040 "{case}: {counts:?} is a call per bucket over {buckets} buckets"
12041 ),
12042 }
12043 } else {
12044 let (expected, firsts) = flat_dispatch_calls(
12045 &renderer,
12046 crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED,
12047 );
12048 assert_eq!(calls, expected, "{case}: one flat call per sided partition");
12049 assert_eq!(
12050 bound,
12051 firsts
12052 .iter()
12053 .map(|&bucket| renderer.bucket_constants[bucket as usize])
12054 .collect::<Vec<_>>(),
12055 "{case}: each under its segment's first bucket's block"
12056 );
12057 }
12058 assert_eq!(
12059 renderer.counters().draws,
12060 recorded_draws(&recorder) as u64,
12061 "{case}"
12062 );
12063 rendered.finish(device.as_ref(), renderer);
12064 recorder.assert_valid();
12065 }
12066 }
12067 }
12068 }
12069
12070 /// **Draw `d` of a ranged mesh call reads the words bucket `first + d`'s own
12071 /// block carries**, in every draw region.
12072 ///
12073 /// The host half of `mesh_cluster.slang`'s "One call for a range of
12074 /// buckets": a ranged call binds its first bucket's block alone, and the
12075 /// SPIR-V stages add the draw index to its `start_at` and `bucket` and to
12076 /// the two table words it names. So each bucket's block has to sit one word
12077 /// past the one before in all four, and the table words have to hold the
12078 /// bucket's own cluster base and count — read out of the bytes that reached
12079 /// the device, since a block written wrong leaves the renderer's fields
12080 /// right.
12081 #[test]
12082 fn a_mesh_block_names_the_words_a_ranged_draw_reads() {
12083 let recorder = Recorder::new();
12084 let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
12085 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12086 .expect("the mesh renderer builds");
12087 let blocks = recorder
12088 .buffer_bytes(renderer.draw_constants)
12089 .expect("the blocks are live");
12090 let tables = recorder
12091 .buffer_bytes(renderer.primary.draws.tables())
12092 .expect("the tables are live");
12093 let word = |bytes: &[u8], at: usize| {
12094 u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes"))
12095 };
12096 let buckets = renderer.bucket_constants.len();
12097 assert!(buckets > 1, "a range needs two buckets to step between");
12098 let bucket_count = u32::try_from(buckets).expect("a few buckets");
12099 let stride = renderer.bucket_constants[1] - renderer.bucket_constants[0];
12100 let block = |region: u32, bucket: u32| {
12101 let at = ((region * bucket_count + bucket) * stride) as usize;
12102 let field = |index: usize| word(&blocks, at + index * 4);
12103 crcbl_shaders::meshlet::ClusterDrawConstants {
12104 start_at: field(0),
12105 cluster_base: field(1),
12106 cluster_count: field(2),
12107 bucket: field(3),
12108 group_stride: field(4),
12109 level_groups_at: field(5),
12110 cluster_base_at: field(6),
12111 cluster_count_at: field(7),
12112 chunk_starts_at: field(8),
12113 chunk_starts_end: field(9),
12114 }
12115 };
12116 let mut bases = Vec::new();
12117 for region in 0..crcbl_shaders::draw_gen::DRAW_REGIONS {
12118 let first = block(region, 0);
12119 for bucket in 0..bucket_count {
12120 let own = block(region, bucket);
12121 assert_eq!(
12122 word(&tables, own.cluster_base_at as usize * 4),
12123 own.cluster_base,
12124 "region {region} bucket {bucket}: the base word holds the base"
12125 );
12126 assert_eq!(
12127 word(&tables, own.cluster_count_at as usize * 4),
12128 own.cluster_count,
12129 "region {region} bucket {bucket}: the count word holds the count"
12130 );
12131 // What draw `bucket` of a call bound at bucket 0's block reads
12132 // — and a flat call's workgroup that found bucket `bucket` by
12133 // searching the chunk starts from bucket 0's word to the
12134 // region's end.
12135 assert_eq!(
12136 (
12137 first.start_at + bucket,
12138 first.bucket + bucket,
12139 first.cluster_base_at + bucket,
12140 first.cluster_count_at + bucket,
12141 first.group_stride,
12142 first.level_groups_at,
12143 first.chunk_starts_at + bucket,
12144 first.chunk_starts_end,
12145 ),
12146 (
12147 own.start_at,
12148 own.bucket,
12149 own.cluster_base_at,
12150 own.cluster_count_at,
12151 own.group_stride,
12152 own.level_groups_at,
12153 own.chunk_starts_at,
12154 own.chunk_starts_end,
12155 ),
12156 "region {region} bucket {bucket}"
12157 );
12158 assert_eq!(
12159 own.chunk_starts_at,
12160 crcbl_shaders::draw_gen::chunk_start_word(
12161 renderer.primary.draws.visible_capacity(),
12162 bucket_count,
12163 region,
12164 bucket,
12165 ),
12166 "region {region} bucket {bucket}: the word draw_gen writes its chunks' start into"
12167 );
12168 assert_eq!(
12169 own.chunk_starts_end - own.chunk_starts_at,
12170 bucket_count - bucket,
12171 "region {region} bucket {bucket}: the search ends at the region's end word"
12172 );
12173 if region == 0 {
12174 bases.push(own.cluster_base);
12175 }
12176 }
12177 }
12178 assert!(
12179 bases.windows(2).any(|pair| pair[0] != pair[1]),
12180 "the buckets' meshes start at different clusters, so a range reading its \
12181 first bucket's base for every draw would be seen: {bases:?}"
12182 );
12183 renderer.destroy(device.as_ref());
12184 recorder.assert_valid();
12185 }
12186
12187 #[test]
12188 fn exact_geometry_path_builds_supported_tails_and_refuses_missing_features_without_allocating()
12189 {
12190 for features in [
12191 Features::GPU_DRIVEN,
12192 Features::COMPUTE | Features::MESH_SHADER,
12193 ] {
12194 let recorder = Recorder::new();
12195 let instance = NullInstance::new(crcbl_hal::DeviceCaps {
12196 features,
12197 limits: crcbl_hal::Limits::desktop(),
12198 })
12199 .with_recorder(recorder.clone());
12200 let device = instance
12201 .create_device(&DeviceDesc {
12202 label: None,
12203 adapter: crcbl_hal::AdapterId(0),
12204 required_features: Features::COMPUTE,
12205 optional_features: features,
12206 compatible_surface: None,
12207 })
12208 .expect("null device opens");
12209 let queue = device.queue(QueueKind::Graphics).unwrap();
12210 for (path, required) in [
12211 (GeometryPath::IndirectPerBatch, Features::empty()),
12212 (GeometryPath::IndirectCount, Features::DRAW_INDIRECT_COUNT),
12213 (GeometryPath::MeshShader, Features::MESH_SHADER),
12214 ] {
12215 recorder.clear();
12216 let result = ForwardRenderer::with_scene_on_path(
12217 device.as_ref(),
12218 queue,
12219 Format::Rgba8UnormSrgb,
12220 &scene::demo(),
12221 path,
12222 );
12223 if features.contains(required) {
12224 let renderer = result.expect("supported exact tail builds");
12225 assert_eq!(renderer.geometry_path(), path);
12226 renderer.destroy(device.as_ref());
12227 } else {
12228 assert!(
12229 matches!(result, Err(HalError::UnsupportedFeatures { missing }) if missing == required)
12230 );
12231 assert!(
12232 recorder.events().is_empty(),
12233 "unsupported selection must not touch device objects"
12234 );
12235 }
12236 recorder.assert_valid();
12237 }
12238 }
12239 }
12240
12241 pub(super) fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
12242 open_with(DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features)
12243 }
12244
12245 /// [`open`] asking for `optional_features` instead of
12246 /// [`DeviceDesc::for_adapter`]'s.
12247 ///
12248 /// The null preset *has* more than the default request asks for, and a
12249 /// granted feature set is the intersection of the two — so this is how a test
12250 /// reaches a device with something the ordinary one lacks. What it exists for
12251 /// is [`Features::POLYGON_MODE_LINE`]: with the default request, `open`'s
12252 /// device has no line fill mode, which is the other half of the wireframe
12253 /// pair of tests below.
12254 fn open_with(optional_features: Features) -> (Recorder, Box<dyn Device>, QueueHandle) {
12255 let recorder = Recorder::new();
12256 let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
12257 let adapter = instance.adapters().remove(0);
12258 let device = instance
12259 .create_device(&DeviceDesc {
12260 optional_features,
12261 ..DeviceDesc::for_adapter(adapter.id)
12262 })
12263 .expect("the null backend always opens");
12264 let queue = device.queue(QueueKind::Graphics).expect("always present");
12265 (recorder, device, queue)
12266 }
12267
12268 /// Puts one of [`scene::demo`]'s meshes in the frame the way a caller does.
12269 ///
12270 /// **Insertion order is what the caller decides**, and it is load-bearing:
12271 /// the slot an object lands in is topic 25's hysteresis key. So
12272 /// every test below places its objects in the order the frame used to hold
12273 /// them — the cube first, wherever there is one.
12274 fn place_demo(
12275 renderer: &mut ForwardRenderer,
12276 mesh: usize,
12277 material: usize,
12278 transform: Mat4,
12279 ) -> InstanceHandle {
12280 renderer
12281 .add_instance(&InstanceDesc {
12282 mesh,
12283 material,
12284 transform,
12285 })
12286 .expect("a pool of thousands has room for a handful of objects")
12287 }
12288
12289 /// [`scene::demo`]'s cube, placed **first** so it takes the pool slot it has
12290 /// always had.
12291 ///
12292 /// `begin_frame` used to write this object for every caller; the tests below
12293 /// that are about a frame with something in it place it themselves now.
12294 pub(super) fn place_cube(renderer: &mut ForwardRenderer, transform: Mat4) -> InstanceHandle {
12295 place_demo(renderer, DEMO_CUBE, DEMO_UNTINTED, transform)
12296 }
12297
12298 /// The whole renderer builds and tears down against a backend with no
12299 /// driver, which is what makes it testable on every CI leg.
12300 #[test]
12301 fn the_forward_renderer_builds_and_leaks_nothing() {
12302 let (recorder, device, queue) = open();
12303 let before = recorder.total_live_objects();
12304 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12305 .expect("the null backend accepts every descriptor");
12306 assert_eq!(renderer.target_format(), Format::Rgba8UnormSrgb);
12307 assert!(recorder.total_live_objects() > before);
12308 renderer.destroy(device.as_ref());
12309 assert_eq!(
12310 recorder.total_live_objects(),
12311 before,
12312 "every object created must be destroyed"
12313 );
12314 recorder.assert_valid();
12315 }
12316
12317 /// The uniform ring really rotates, or a spinning cube is a
12318 /// read-after-write hazard across submissions.
12319 #[test]
12320 fn the_uniform_ring_rotates() {
12321 let (_, device, queue) = open();
12322 let mut renderer =
12323 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12324 let camera = Camera::default();
12325 let light = DirectionalLight::default();
12326
12327 let mut seen = Vec::new();
12328 for _ in 0..FRAMES_IN_FLIGHT * 2 {
12329 renderer
12330 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12331 .expect("write");
12332 seen.push(renderer.primary.uniforms[renderer.frame]);
12333 }
12334 assert_ne!(
12335 seen[0], seen[1],
12336 "consecutive frames must not share a buffer"
12337 );
12338 assert_eq!(seen[0], seen[FRAMES_IN_FLIGHT], "and the ring must wrap");
12339 renderer.destroy(device.as_ref());
12340 }
12341
12342 /// **The tonemap's block is a ring too, and it carries the exposure the
12343 /// caller set.**
12344 ///
12345 /// The bytes are the observable rather than the field, because the field is
12346 /// what a renderer that never wired the block up would also have: the claim
12347 /// is that the number reaches the buffer `tonemap.slang` reads, and only the
12348 /// null recorder's write log can say so.
12349 ///
12350 /// The default is checked first — a renderer nobody has called
12351 /// [`ForwardRenderer::set_exposure`] on writes the value the shader's
12352 /// `EXPOSURE` constant held, under
12353 /// [`ForwardRenderer::set_tonemap_curve`]'s own default.
12354 #[test]
12355 fn the_tonemap_block_holds_the_exposure_and_rotates_with_the_frame() {
12356 let (recorder, device, queue) = open();
12357 let mut renderer =
12358 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12359 let camera = Camera::default();
12360 let light = DirectionalLight::default();
12361
12362 renderer
12363 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12364 .expect("write");
12365 assert_eq!(
12366 recorder
12367 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12368 .expect("begin_frame wrote the block"),
12369 crcbl_shaders::tonemap::TonemapParams {
12370 exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12371 curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12372 auto_exposure: false,
12373 coverage_alpha: false,
12374 }
12375 .to_bytes(),
12376 "an untouched renderer must write the exposure the constant used to hold, \
12377 under the operator this renderer starts on",
12378 );
12379
12380 // A value that is neither the default nor a bound, so a block left at
12381 // either would fail.
12382 renderer.set_exposure(3.5);
12383 let mut slots = Vec::new();
12384 for _ in 0..FRAMES_IN_FLIGHT * 2 {
12385 renderer
12386 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12387 .expect("write");
12388 slots.push(renderer.primary.tonemap_uniforms[renderer.frame]);
12389 assert_eq!(
12390 recorder
12391 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12392 .expect("begin_frame wrote the block"),
12393 crcbl_shaders::tonemap::TonemapParams {
12394 exposure: 3.5,
12395 curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12396 auto_exposure: false,
12397 coverage_alpha: false,
12398 }
12399 .to_bytes(),
12400 "the frame's own block must carry the exposure in force",
12401 );
12402 }
12403 assert_ne!(
12404 slots[0], slots[1],
12405 "consecutive frames must not share a block"
12406 );
12407 assert_eq!(slots[0], slots[FRAMES_IN_FLIGHT], "and the ring must wrap");
12408
12409 renderer.destroy(device.as_ref());
12410 }
12411
12412 /// **The curve reaches the block, and a caller can move it off the
12413 /// default.**
12414 ///
12415 /// The selector is a lane of the same ring the exposure rides in, and a lane
12416 /// nothing wrote would read as
12417 /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp)
12418 /// whatever a caller asked for — a setter that compiles, a frame that looks
12419 /// right, and a curve that never runs. Since the renderer now *starts* on
12420 /// the fit, that failure would read as a working default, so the check runs
12421 /// in both directions: the untouched block carries the fit, and asking for
12422 /// the clamp changes the bytes on every frame of the ring.
12423 #[test]
12424 fn the_tonemap_block_carries_the_curve_a_caller_selected() {
12425 use crcbl_shaders::tonemap::TonemapCurve;
12426
12427 let (recorder, device, queue) = open();
12428 let mut renderer =
12429 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12430 let camera = Camera::default();
12431 let light = DirectionalLight::default();
12432
12433 assert_eq!(
12434 renderer.tonemap_curve(),
12435 TonemapCurve::Aces,
12436 "a renderer nobody configured must run the operator the goldens were blessed under",
12437 );
12438 renderer
12439 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12440 .expect("write");
12441 let by_default = recorder
12442 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12443 .expect("begin_frame wrote the block");
12444
12445 renderer.set_tonemap_curve(TonemapCurve::Clamp);
12446 assert_eq!(renderer.tonemap_curve(), TonemapCurve::Clamp);
12447 for _ in 0..FRAMES_IN_FLIGHT * 2 {
12448 renderer
12449 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12450 .expect("write");
12451 let written = recorder
12452 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12453 .expect("begin_frame wrote the block");
12454 assert_eq!(
12455 written,
12456 crcbl_shaders::tonemap::TonemapParams {
12457 exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12458 curve: TonemapCurve::Clamp,
12459 auto_exposure: false,
12460 coverage_alpha: false,
12461 }
12462 .to_bytes(),
12463 "every frame of the ring must carry the selected curve",
12464 );
12465 assert_ne!(
12466 written, by_default,
12467 "and it must differ from the block a default renderer writes",
12468 );
12469 }
12470
12471 // **A readout runs the clamp whatever was selected**, and the selection
12472 // survives it: the caller's curve is still the caller's, the frame's is
12473 // the identity, and the shaded frame after gets the curve back. Asked of
12474 // the fit, which is the selection a readout has something to lose under.
12475 renderer.set_tonemap_curve(TonemapCurve::Aces);
12476 renderer.set_normals_view(true);
12477 assert_eq!(renderer.tonemap_curve(), TonemapCurve::Aces);
12478 assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Clamp);
12479 renderer
12480 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12481 .expect("write");
12482 assert_eq!(
12483 recorder
12484 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12485 .expect("begin_frame wrote the block"),
12486 crcbl_shaders::tonemap::TonemapParams {
12487 exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12488 curve: TonemapCurve::Clamp,
12489 auto_exposure: false,
12490 coverage_alpha: false,
12491 }
12492 .to_bytes(),
12493 "a debug view's block must carry the clamp, since its pixels are data",
12494 );
12495 renderer.set_normals_view(false);
12496 assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Aces);
12497
12498 renderer.destroy(device.as_ref());
12499 }
12500
12501 /// **The exposure is clamped where it is set**, so no caller can reach a
12502 /// frame it cannot get back from.
12503 ///
12504 /// Each case is a different way of leaving the range, and the NaN one is the
12505 /// reason [`ForwardRenderer::set_exposure`] does not use `f32::clamp`: that
12506 /// propagates a NaN into the block, which is a frame of NaN pixels with no
12507 /// key to press to escape it.
12508 #[test]
12509 fn the_exposure_setter_clamps_to_a_range_a_caller_can_come_back_from() {
12510 let (_, device, queue) = open();
12511 let mut renderer =
12512 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12513 assert!(
12514 (renderer.exposure() - crcbl_shaders::tonemap::DEFAULT_EXPOSURE).abs() < f32::EPSILON,
12515 "the default is {}",
12516 renderer.exposure(),
12517 );
12518
12519 for (asked, expected) in [
12520 (2.0, 2.0),
12521 (EXPOSURE_MAX * 4.0, EXPOSURE_MAX),
12522 (f32::INFINITY, EXPOSURE_MAX),
12523 (EXPOSURE_MIN / 4.0, EXPOSURE_MIN),
12524 (0.0, EXPOSURE_MIN),
12525 (-8.0, EXPOSURE_MIN),
12526 (f32::NEG_INFINITY, EXPOSURE_MIN),
12527 (f32::NAN, EXPOSURE_MIN),
12528 ] {
12529 renderer.set_exposure(asked);
12530 assert!(
12531 (renderer.exposure() - expected).abs() < f32::EPSILON,
12532 "{asked} was clamped to {}, not {expected}",
12533 renderer.exposure(),
12534 );
12535 }
12536
12537 renderer.destroy(device.as_ref());
12538 }
12539
12540 /// **The debug views resolve in one order, however they are set.**
12541 ///
12542 /// Every one of them rides in one float lane and the shaders test the
12543 /// outermost threshold first, so a renderer with two switches on draws
12544 /// exactly one picture — and which one has to be a rule rather than
12545 /// whichever branch a caller's setter happened to run last. Every
12546 /// combination of the switches is walked, because a precedence written as an
12547 /// `if` chain is right for most of them by accident: a chain in the wrong
12548 /// order agrees with this one on every combination where at most one switch
12549 /// is set.
12550 ///
12551 /// **The two innermost views are the exception the walk is worth most for.**
12552 /// [`DebugView::Cascades`] keeps the shaded picture rather than replacing
12553 /// it, so it resolves *last* and its sentinel runs the other way down the
12554 /// lane; [`DebugView::ShadowAtlas`] resolves just above it and carries the
12555 /// *off* sentinel, because it is a pass rather than a branch. Every
12556 /// combination where either is set beside a replacing view is a combination
12557 /// an order written any other way answers differently, and there is no
12558 /// single-switch case that could tell them apart.
12559 ///
12560 /// [`ForwardRenderer::debug_view`] is asserted beside the lane, so the value
12561 /// a panel reads back and the value the shader branches on cannot drift —
12562 /// they are the same function.
12563 #[test]
12564 fn the_debug_views_resolve_in_one_order_however_they_are_set() {
12565 // `w` of the second `float4` of the block — the lane
12566 // `the_normals_view_moves_the_ambients_last_lane_and_no_other_byte`
12567 // spells out, and for its reason.
12568 const AMBIENT_W: usize = 64 + 16 + 12;
12569
12570 let (recorder, device, queue) = open();
12571 let mut renderer =
12572 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12573 let camera = Camera::default();
12574 let light = DirectionalLight::default();
12575
12576 for bent in [false, true] {
12577 for motion in [false, true] {
12578 for occlusion in [false, true] {
12579 for heatmap in [false, true] {
12580 for lod in [false, true] {
12581 for normals in [false, true] {
12582 for (atlas, cascades) in
12583 [false, true].into_iter().flat_map(|atlas| {
12584 [false, true].map(|cascades| (atlas, cascades))
12585 })
12586 {
12587 renderer.set_bent_normal_view(bent);
12588 renderer.set_motion_view(motion);
12589 renderer.set_occlusion_view(occlusion);
12590 renderer.set_heatmap(heatmap);
12591 renderer.set_lod_view(lod);
12592 renderer.set_normals_view(normals);
12593 renderer.set_atlas_view(atlas);
12594 renderer.set_cascade_view(cascades);
12595 let set = format!(
12596 "bent={bent} motion={motion} occlusion={occlusion} \
12597 heatmap={heatmap} lod={lod} normals={normals} \
12598 atlas={atlas} cascades={cascades}"
12599 );
12600 // Each switch reads back what it was set to, whatever
12601 // the others are: a caller's toggle is about the
12602 // caller's setting, and only `debug_view` is about the
12603 // picture.
12604 assert_eq!(renderer.bent_normal_view(), bent);
12605 assert_eq!(renderer.motion_view(), motion);
12606 assert_eq!(renderer.occlusion_view(), occlusion);
12607 assert_eq!(renderer.heatmap(), heatmap);
12608 assert_eq!(renderer.lod_view(), lod);
12609 assert_eq!(renderer.normals_view(), normals);
12610 assert_eq!(renderer.atlas_view(), atlas);
12611 assert_eq!(renderer.cascade_view(), cascades);
12612
12613 let expected = if bent {
12614 DebugView::BentNormal
12615 } else if motion {
12616 DebugView::Motion
12617 } else if occlusion {
12618 DebugView::AmbientOcclusion
12619 } else if heatmap {
12620 DebugView::Heatmap
12621 } else if lod {
12622 DebugView::LodTint
12623 } else if normals {
12624 DebugView::Normals
12625 } else if atlas {
12626 // **Below every replacing view above and
12627 // above the tint below**, which is the
12628 // half of this order no single-switch
12629 // case reaches: with a replacing view
12630 // also set the frame is that view's, and
12631 // with the tint also set the frame is the
12632 // atlas.
12633 DebugView::ShadowAtlas
12634 } else if cascades {
12635 // **Last, which is the half of this order a
12636 // chain in any other arrangement would get
12637 // right by accident.** The cascade tint is a
12638 // multiply on the shaded picture, so every
12639 // combination that also names a replacing
12640 // view has to resolve to *that* view — and
12641 // those are exactly the combinations an
12642 // `if cascades` written one line higher
12643 // would answer differently.
12644 DebugView::Cascades
12645 } else {
12646 DebugView::Shaded
12647 };
12648 assert_eq!(renderer.debug_view(), expected, "{set}");
12649
12650 renderer
12651 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12652 .expect("write");
12653 let block = recorder
12654 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12655 .expect("begin_frame wrote the block");
12656 let sentinel = match expected {
12657 DebugView::BentNormal => {
12658 mesh::FrameUniforms::BENT_NORMAL_VIEW_ON
12659 }
12660 DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
12661 DebugView::AmbientOcclusion => {
12662 mesh::FrameUniforms::OCCLUSION_VIEW_ON
12663 }
12664 DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
12665 DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
12666 DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
12667 DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
12668 // **The atlas view carries the *off*
12669 // sentinel**, which is what makes this
12670 // assertion say something rather than
12671 // restate `debug_view_lane`: the colour
12672 // pass draws the shaded picture and
12673 // `crate::atlas_view`'s pass replaces
12674 // it, so a lane of its own here would be
12675 // a threshold no shader tests.
12676 DebugView::ShadowAtlas | DebugView::Shaded => {
12677 mesh::FrameUniforms::NORMALS_VIEW_OFF
12678 }
12679 };
12680 assert_eq!(
12681 &block[AMBIENT_W..AMBIENT_W + 4],
12682 &sentinel.to_le_bytes(),
12683 "{set} resolved to {expected:?}, and the lane says otherwise"
12684 );
12685 // And the resolve comes off for every one of them:
12686 // these frames are read back as data, so their colours
12687 // have to stay the ones the shader wrote — see
12688 // `resolved_effects`. The whole slot rather than one
12689 // tier of it, because which tier the default carries
12690 // is not what this is about.
12691 assert_eq!(
12692 renderer.effects().intersects(Antialiasing::SLOT),
12693 expected == DebugView::Shaded,
12694 "{set}"
12695 );
12696 }
12697 }
12698 }
12699 }
12700 }
12701 }
12702 }
12703
12704 renderer.destroy(device.as_ref());
12705 }
12706
12707 /// **The atlas viewer records one pass, and only on the frame it is the view
12708 /// showing.**
12709 ///
12710 /// The mechanism no other check in this file can see. Every other debug view
12711 /// is a lane of the frame block, so
12712 /// [`the_debug_views_resolve_in_one_order_however_they_are_set`] observes it
12713 /// by reading four bytes; this one is a *pass*, and "the pass was recorded"
12714 /// is a claim about the command stream and about nothing else. A switch that
12715 /// resolved correctly and recorded nothing would satisfy every other
12716 /// assertion in this module and draw the frame unchanged.
12717 ///
12718 /// Three arms, and the third is the one that makes the first two mean
12719 /// something:
12720 ///
12721 /// * off — no pass at all, which is what makes the off position
12722 /// bit-identical for every golden in this workspace;
12723 /// * on — the pass, with the full-screen triangle in it;
12724 /// * on **beside a replacing view** — no pass, because
12725 /// [`ForwardRenderer::debug_view`] resolved to that view and the atlas is
12726 /// not what this frame draws. That is the half a `self.atlas_view` read at
12727 /// the recording site would get wrong while passing both arms above.
12728 ///
12729 /// [`the_debug_views_resolve_in_one_order_however_they_are_set`]: fn@the_debug_views_resolve_in_one_order_however_they_are_set
12730 /// **The shadow atlas viewer replaces the tonemap and the ground grid, and
12731 /// the draw count follows.**
12732 ///
12733 /// The viewer fills every display pixel with a `DontCare` load, so a
12734 /// tonemapped frame or a grid recorded under it is stored and discarded.
12735 /// The pass counts go red if either comes back; the counter goes red if
12736 /// `counters` still charges the frame for the triangles it no longer
12737 /// records.
12738 #[test]
12739 fn the_atlas_viewer_replaces_the_display_passes_and_the_count_follows() {
12740 let _seam = ssao_split_switch();
12741 let (recorder, device, queue) = open();
12742 let mut renderer =
12743 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12744 renderer
12745 .set_ground_grid(device.as_ref(), Some(GridStyle::default()))
12746 .expect("the null backend builds every pipeline");
12747 renderer.set_atlas_view(true);
12748 assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
12749
12750 let viewing = frame(device.as_ref(), &mut renderer, queue);
12751 let opened = |label: &str| {
12752 recorder
12753 .commands()
12754 .iter()
12755 .filter(|command| {
12756 matches!(command.opens_pass(), Some((_, Some(recorded))) if recorded == label)
12757 })
12758 .count()
12759 };
12760 assert_eq!(opened(crate::atlas_view::LABEL), 1);
12761 assert_eq!(opened("tonemap"), 0, "the viewer discards the tonemap");
12762 assert_eq!(opened("grid"), 0, "and the grid drawn over it");
12763 assert_eq!(
12764 renderer.counters().draws,
12765 recorded_draws(&recorder) as u64,
12766 "the counter charges the frame for exactly the draws it recorded"
12767 );
12768 viewing.finish(device.as_ref(), renderer);
12769 }
12770
12771 #[test]
12772 fn the_atlas_viewer_records_its_pass_only_when_it_is_the_view_showing() {
12773 use crcbl_hal::null::Command;
12774
12775 let (recorder, device, queue) = open();
12776 let device = device.as_ref();
12777 let mut renderer =
12778 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
12779 let (camera, sun) = (Camera::default(), DirectionalLight::default());
12780
12781 // How many times the viewer's pass was opened since `from`, which is
12782 // where the previous arm's commands ended.
12783 let opened = |from: usize| {
12784 recorder.commands()[from..]
12785 .iter()
12786 .filter(|command| {
12787 matches!(
12788 command.opens_pass(),
12789 Some((_, Some(recorded))) if recorded == crate::atlas_view::LABEL
12790 )
12791 })
12792 .count()
12793 };
12794
12795 let shaded = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12796 assert_eq!(
12797 opened(0),
12798 0,
12799 "a frame drawing the shaded picture recorded the atlas viewer's pass"
12800 );
12801 let after_shaded = recorder.commands().len();
12802 shaded.release(device);
12803
12804 renderer.set_atlas_view(true);
12805 assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
12806 let viewing = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12807 assert_eq!(
12808 opened(after_shaded),
12809 1,
12810 "the atlas viewer is on and its pass was not recorded exactly once"
12811 );
12812 // And what it recorded is the over-sized triangle and nothing else: a
12813 // pass that bound a pipeline and drew no vertices would open above and
12814 // leave the frame the tonemap wrote.
12815 let drawn: Vec<(u32, u32)> = commands_in_pass(&recorder, crate::atlas_view::LABEL)
12816 .into_iter()
12817 .filter_map(|command| match command {
12818 Command::Draw {
12819 vertices,
12820 instances,
12821 } => Some((
12822 vertices.end - vertices.start,
12823 instances.end - instances.start,
12824 )),
12825 _ => None,
12826 })
12827 .collect();
12828 assert_eq!(drawn, vec![(crate::atlas_view::FULLSCREEN_VERTICES, 1)]);
12829 let after_viewing = recorder.commands().len();
12830 viewing.release(device);
12831
12832 // The switch left on, and a replacing view asked for over the top of it.
12833 renderer.set_normals_view(true);
12834 assert_eq!(
12835 renderer.debug_view(),
12836 DebugView::Normals,
12837 "the atlas view does not lose to a replacing view, so the arm below asks nothing"
12838 );
12839 let normals = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12840 assert_eq!(
12841 opened(after_viewing),
12842 0,
12843 "the frame resolved to the normals view and still recorded the atlas viewer's \
12844 pass over the top of it"
12845 );
12846 normals.release(device);
12847
12848 renderer.destroy(device);
12849 }
12850
12851 /// **The heatmap moves the ambient's last lane and no other byte**, and
12852 /// switching it off puts the block back.
12853 ///
12854 /// The normals view's assertion below, for the outermost of the three: the
12855 /// overlay costs one lane, so every golden image ever blessed is untouched
12856 /// by the feature existing. The `lod_params` row the heatmap reads is
12857 /// written every frame whether it is on or not — it is the numbers the
12858 /// selection used — so this compares two frames of the *same* camera and
12859 /// budget, where that row is equal on both sides and any byte outside the
12860 /// lane is a real difference.
12861 #[test]
12862 fn the_heatmap_moves_the_ambients_last_lane_and_no_other_byte() {
12863 const AMBIENT_W: usize = 64 + 16 + 12;
12864
12865 // Held for the whole comparison, and it is not this check's own knob:
12866 // `r_shadow_filter` and `r_shadow_split` land in the block's
12867 // `shadow_filter` row on every `begin_frame`, and the filter checks in
12868 // this module move them under this lock while `cargo test` runs the
12869 // module's checks as threads of one process. Two frames read either side
12870 // of such a move differ at that row, which is outside every lane below —
12871 // one run in twelve, measured 2026-09-04.
12872 let _filter = shadow_filter_switch();
12873 let (recorder, device, queue) = open();
12874 let mut renderer =
12875 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12876 let camera = Camera::default();
12877 let light = DirectionalLight::default();
12878 let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
12879 renderer
12880 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12881 .expect("write");
12882 recorder
12883 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12884 .expect("begin_frame wrote the block")
12885 };
12886
12887 assert!(
12888 !renderer.heatmap(),
12889 "the heatmap has to be off in a renderer nobody has asked",
12890 );
12891 let shaded = block(&mut renderer);
12892 assert_eq!(
12893 &shaded[AMBIENT_W..AMBIENT_W + 4],
12894 &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
12895 "an untouched renderer must write the value every golden image was blessed with",
12896 );
12897
12898 renderer.set_heatmap(true);
12899 let heatmap = block(&mut renderer);
12900 assert_eq!(
12901 &heatmap[AMBIENT_W..AMBIENT_W + 4],
12902 &mesh::FrameUniforms::HEATMAP_VIEW_ON.to_le_bytes(),
12903 "the switch has to reach the lane the mesh stage branches on",
12904 );
12905 let outside: Vec<usize> = shaded
12906 .iter()
12907 .zip(heatmap.iter())
12908 .enumerate()
12909 .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
12910 .map(|(at, _)| at)
12911 .collect();
12912 assert!(
12913 outside.is_empty(),
12914 "the frame block changed at {outside:?}, which is outside the heatmap's own lane",
12915 );
12916
12917 renderer.set_heatmap(false);
12918 assert_eq!(
12919 block(&mut renderer),
12920 shaded,
12921 "switching the view off has to put the block back, not just stop reporting it",
12922 );
12923
12924 renderer.destroy(device.as_ref());
12925 }
12926
12927 /// **The normals view moves one lane of the frame block and nothing else.**
12928 ///
12929 /// The mechanism, at the level a null device can observe it: which bytes of
12930 /// the buffer `mesh.slang` reads changed. A field on the renderer would say
12931 /// only that a flag moved; the block is what the shader actually branches on.
12932 ///
12933 /// Four claims, and each rules out a different way of passing wrongly:
12934 ///
12935 /// * an untouched renderer writes [`FrameUniforms::NORMALS_VIEW_OFF`] — which
12936 /// is what makes every golden image untouched by this feature;
12937 /// * switching on writes [`FrameUniforms::NORMALS_VIEW_ON`] into the lane the
12938 /// shader reads, at the offset `std140` puts it at rather than at one this
12939 /// test picked;
12940 /// * **those four bytes are the only ones that moved**, so the switch did not
12941 /// come at the cost of the ambient colour beside it or of any matrix;
12942 /// * and switching off puts the block back exactly, so the view is a toggle
12943 /// rather than a one-way door.
12944 ///
12945 /// [`FrameUniforms::NORMALS_VIEW_OFF`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_OFF
12946 /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
12947 #[test]
12948 fn the_normals_view_moves_the_ambients_last_lane_and_no_other_byte() {
12949 // `w` of the second `float4` of the block: one `float4x4`, one `float4`,
12950 // then three floats of ambient colour. Spelled as the sum rather than as
12951 // `92` so that a member arriving before it is a compile-time question
12952 // about `FrameUniforms`' own layout and not a silent read of a matrix.
12953 const AMBIENT_W: usize = 64 + 16 + 12;
12954
12955 // Held for the whole comparison, and it is not this check's own knob:
12956 // `r_shadow_filter` and `r_shadow_split` land in the block's
12957 // `shadow_filter` row on every `begin_frame`, and the filter checks in
12958 // this module move them under this lock while `cargo test` runs the
12959 // module's checks as threads of one process. Two frames read either side
12960 // of such a move differ at that row, which is outside every lane below —
12961 // one run in twelve, measured 2026-09-04.
12962 let _filter = shadow_filter_switch();
12963 let (recorder, device, queue) = open();
12964 let mut renderer =
12965 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12966 let camera = Camera::default();
12967 let light = DirectionalLight::default();
12968 let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
12969 renderer
12970 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12971 .expect("write");
12972 recorder
12973 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12974 .expect("begin_frame wrote the block")
12975 };
12976
12977 assert!(
12978 !renderer.normals_view(),
12979 "the normals view has to be off in a renderer nobody has asked",
12980 );
12981 let shaded = block(&mut renderer);
12982 assert_eq!(
12983 &shaded[AMBIENT_W..AMBIENT_W + 4],
12984 &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
12985 "an untouched renderer must write the value every golden image was blessed with",
12986 );
12987
12988 renderer.set_normals_view(true);
12989 assert!(renderer.normals_view());
12990 let normals = block(&mut renderer);
12991 assert_eq!(
12992 &normals[AMBIENT_W..AMBIENT_W + 4],
12993 &mesh::FrameUniforms::NORMALS_VIEW_ON.to_le_bytes(),
12994 "the switch has to reach the lane the fragment stage branches on",
12995 );
12996 // The bytes that moved, and they all have to be inside the lane — not
12997 // *all* of the lane, because `0.0f` and `1.0f` share their two low bytes
12998 // and an equality against the whole range would be a test about IEEE 754
12999 // rather than about the block.
13000 let outside: Vec<usize> = shaded
13001 .iter()
13002 .zip(normals.iter())
13003 .enumerate()
13004 .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
13005 .map(|(at, _)| at)
13006 .collect();
13007 assert!(
13008 outside.is_empty(),
13009 "the frame block changed at {outside:?}, which is outside the normals view's own lane",
13010 );
13011
13012 renderer.set_normals_view(false);
13013 assert!(!renderer.normals_view());
13014 assert_eq!(
13015 block(&mut renderer),
13016 shaded,
13017 "switching the view off has to put the block back, not just stop reporting it",
13018 );
13019
13020 renderer.destroy(device.as_ref());
13021 }
13022
13023 /// **A frame uploads the instances a caller moved, and a frame nobody moved
13024 /// anything in uploads nothing at all.**
13025 ///
13026 /// The second half is the stronger claim and it is the one that needed the
13027 /// cube to become an ordinary instance: `begin_frame` used to take the
13028 /// cube's transform as an argument and write it into the pool every frame,
13029 /// so that slot was dirty in every ring slot forever and a motionless scene
13030 /// paid a spinning one's transfer. The bytes were identical, so no golden
13031 /// image could ever have shown it — the recorder's write log is the only
13032 /// place the difference is visible.
13033 ///
13034 /// The pyramid is here so that "only the one that moved" is a claim about a
13035 /// choice: with one instance in the array, uploading it and uploading
13036 /// everything are the same event.
13037 #[test]
13038 fn only_the_instance_that_moved_is_uploaded() {
13039 let (recorder, device, queue) = open();
13040 let mut renderer =
13041 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13042 let instance_buffers = renderer.instances.buffers().to_vec();
13043 let cube = place_cube(&mut renderer, Mat4::IDENTITY);
13044 place_demo(
13045 &mut renderer,
13046 DEMO_PYRAMID,
13047 DEMO_UNTINTED,
13048 Mat4::from_translation(Vec3::X),
13049 );
13050
13051 // Both instances are dirty in *every* slot when they are inserted, so
13052 // the first frames upload both however well delta upload works. The ring
13053 // has to be walked right through before an upload is evidence about the
13054 // delta rather than about initialisation.
13055 let frame = |renderer: &mut ForwardRenderer| {
13056 renderer
13057 .begin_frame(
13058 device.as_ref(),
13059 &Camera::default(),
13060 &DirectionalLight::default(),
13061 (64, 48),
13062 )
13063 .expect("write");
13064 };
13065 for _ in 0..FRAMES_IN_FLIGHT {
13066 frame(&mut renderer);
13067 }
13068 let instance_writes = |from: usize| -> Vec<(u64, usize)> {
13069 recorder
13070 .events()
13071 .into_iter()
13072 .skip(from)
13073 .filter_map(|event| match event {
13074 crcbl_hal::null::Event::BufferWritten {
13075 buffer,
13076 offset,
13077 len,
13078 } if instance_buffers.contains(&buffer) => Some((offset, len)),
13079 _ => None,
13080 })
13081 .collect()
13082 };
13083
13084 let before = recorder.events().len();
13085 frame(&mut renderer);
13086 assert_eq!(
13087 instance_writes(before),
13088 [],
13089 "a frame in which nothing moved must upload no instance bytes at all"
13090 );
13091
13092 let before = recorder.events().len();
13093 let model = ForwardRenderer::spin(1.25);
13094 renderer.set_instance(
13095 cube,
13096 &InstanceDesc {
13097 mesh: DEMO_CUBE,
13098 material: DEMO_UNTINTED,
13099 transform: model,
13100 },
13101 );
13102 frame(&mut renderer);
13103 assert_eq!(
13104 renderer
13105 .instances
13106 .get(cube)
13107 .expect("the cube is live")
13108 .transform,
13109 model.to_cols_array(),
13110 "the model matrix must land in the instance, not the uniform block"
13111 );
13112 let cube_at = u64::from(renderer.instances.index(cube).expect("the cube is live"))
13113 * crcbl_shaders::mesh::INSTANCE_STRIDE as u64;
13114 assert_eq!(
13115 instance_writes(before),
13116 [(cube_at, crcbl_shaders::mesh::INSTANCE_STRIDE)],
13117 "a steady-state frame must upload exactly the one instance that changed"
13118 );
13119
13120 renderer.destroy(device.as_ref());
13121 recorder.assert_valid();
13122 }
13123
13124 /// **An object takes one pool slot, a rewrite keeps it, and a removal gives
13125 /// it back for the next object to reuse.**
13126 ///
13127 /// The three-call bookkeeping every caller of the instance API depends on,
13128 /// checked on the pool rather than on the recorder. A `set_instance` that
13129 /// inserted instead would take a fresh slot per call — the pool exhausted in
13130 /// a few thousand frames of a caller that writes a transform per frame, which
13131 /// is what every sample does — and every slot it abandoned would stay
13132 /// **live**, so the frame would draw a copy of the object at each transform
13133 /// it had ever been given. Neither is something a golden image would show
13134 /// until the pool ran out.
13135 ///
13136 /// `only_the_instance_that_moved_is_uploaded` is the delta half of this and
13137 /// reads the recorder; this is the bookkeeping half and reads the pool, which
13138 /// is where an abandoned slot would still be counted.
13139 ///
13140 /// Run over every mesh of [`scene::demo`], because the DAG is the one whose
13141 /// slot carries topic 25's hysteresis state — the reuse below is
13142 /// exactly what [`ForwardRenderer::add_instance`] documents as inheriting a
13143 /// previous occupant's expanded groups.
13144 #[test]
13145 fn an_object_takes_one_slot_and_a_removal_gives_it_back() {
13146 for mesh in [DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES] {
13147 let (recorder, device, queue) = open();
13148 let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
13149 .expect("built");
13150 // The null backend takes an indirect tail, so the DAG is placeable
13151 // here; the arm that cannot select a level refuses before an
13152 // application ever calls this.
13153 assert!(
13154 renderer.selects_levels(),
13155 "an indirect tail chooses a level for every mesh, DAG included"
13156 );
13157 // What the pool holds before anything is placed, which is nothing: a
13158 // renderer places no object of its own any more.
13159 let resident = renderer.instances.len();
13160 assert_eq!(resident, 0, "a fresh renderer holds no objects");
13161
13162 let first = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
13163 let handle = place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13164 assert_eq!(
13165 renderer.instances.len(),
13166 resident + 1,
13167 "mesh {mesh}: add_instance takes one slot"
13168 );
13169
13170 // The rewrite is the whole test: the same handle, the same slot
13171 // count, and the new transform in it.
13172 let second = Mat4::from_translation(Vec3::new(-4.0, 5.0, -6.0));
13173 renderer.set_instance(
13174 handle,
13175 &InstanceDesc {
13176 mesh,
13177 material: DEMO_UNTINTED,
13178 transform: second,
13179 },
13180 );
13181 assert_eq!(
13182 renderer.instances.len(),
13183 resident + 1,
13184 "mesh {mesh}: set_instance must rewrite its instance, not insert a second"
13185 );
13186 assert_eq!(
13187 renderer.instances.slot_count(),
13188 u32::try_from(resident + 1).expect("a handful of instances"),
13189 "mesh {mesh}: set_instance must not have reached past the slot it holds"
13190 );
13191 assert_eq!(
13192 renderer
13193 .instances
13194 .get(handle)
13195 .unwrap_or_else(|| panic!("mesh {mesh}: the instance is live"))
13196 .transform,
13197 second.to_cols_array(),
13198 "mesh {mesh}: set_instance must have written the second transform"
13199 );
13200
13201 // And a removal gives the slot back, so a caller toggling an object
13202 // is not a leak either.
13203 renderer.remove_instance(handle);
13204 assert_eq!(
13205 renderer.instances.len(),
13206 resident,
13207 "mesh {mesh}: remove_instance must free the slot rather than hide the object"
13208 );
13209 place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13210 assert_eq!(
13211 renderer.instances.slot_count(),
13212 u32::try_from(resident + 1).expect("a handful of instances"),
13213 "mesh {mesh}: the object after a removal must reuse the freed slot"
13214 );
13215
13216 renderer.destroy(device.as_ref());
13217 recorder.assert_valid();
13218 }
13219 }
13220
13221 /// **The description resolves to the ids the renderer used to hand itself**:
13222 /// one table entry per description mesh, in description order, with the DAG
13223 /// occupying one per level after them — and every level's vertex base
13224 /// measured from level 0's, which is zero.
13225 ///
13226 /// Upload order is what decides a mesh id, and `cull.slang` reads a bounding
13227 /// box out of the entry the *instance* names. So a description walked in
13228 /// another order, or a DAG whose levels landed among the flat meshes, would
13229 /// leave every instance naming a mesh that is not its own: the cube culled
13230 /// against the pyramid's box, the dunes patch drawn as an open box. Every
13231 /// one of those is a frame that still looks like a frame.
13232 ///
13233 /// The bases are asserted against the table bytes rather than against
13234 /// `ResidentMesh`, because the table is what the GPU reads.
13235 #[test]
13236 fn the_description_resolves_to_the_ids_it_was_written_in() {
13237 let (recorder, device, queue) = open();
13238 let renderer =
13239 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13240
13241 assert_eq!(
13242 renderer.mesh_ids,
13243 [0, 1, 2, 3],
13244 "the four description meshes take the first four table entries, in order"
13245 );
13246
13247 // The DAG's coarser levels follow level 0, so a cut that spans them
13248 // reads entries the flat meshes never occupied.
13249 let scene = scene::demo();
13250 let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13251 panic!("the demo description's fourth mesh is the DAG");
13252 };
13253 let level_ids: Vec<u32> = (0..dag.levels.len())
13254 .map(|level| renderer.mesh_ids[DEMO_DUNES] + level as u32)
13255 .collect();
13256 assert!(
13257 level_ids
13258 .iter()
13259 .all(|&id| id > renderer.mesh_ids[DEMO_OPEN_BOX]),
13260 "every dunes level is past the flat residents: {level_ids:?}"
13261 );
13262
13263 // **Level 0 is at the pool's own first vertex**, which is what makes
13264 // every `ClusterSelect::vertex_base` a non-negative offset from it — the
13265 // sum the mesh stage forms with the instance's own base.
13266 let entries: Vec<crcbl_shaders::mesh::GpuMesh> = level_ids
13267 .iter()
13268 .map(|&id| mesh_entry(&recorder, &renderer, id))
13269 .collect();
13270 let level_zero = entries[0].base_vertex;
13271 assert_eq!(
13272 level_zero,
13273 mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_OPEN_BOX]).base_vertex
13274 + crcbl_shaders::mesh::OPEN_BOX_VERTEX_COUNT as u32,
13275 "the DAG starts where the last flat resident ends"
13276 );
13277 let bases: Vec<u32> = entries
13278 .iter()
13279 .map(|entry| {
13280 entry
13281 .base_vertex
13282 .checked_sub(level_zero)
13283 .expect("a level below level 0 would wrap the offset a cluster carries")
13284 })
13285 .collect();
13286 assert_eq!(
13287 bases[0], 0,
13288 "level 0 is the base every other is measured from"
13289 );
13290 assert!(
13291 bases.windows(2).all(|pair| pair[0] < pair[1]),
13292 "each level starts past the one below it: {bases:?}"
13293 );
13294
13295 renderer.destroy(device.as_ref());
13296 recorder.assert_valid();
13297 }
13298
13299 /// **A description that is not [`scene::demo`]: five meshes and two DAGs.**
13300 ///
13301 /// [`ForwardRenderer::with_scene`] is written for any mesh count and any
13302 /// number of DAGs, and until this nothing had put either through it — every
13303 /// golden image and every end-to-end run is `scene::demo()`, whose four
13304 /// meshes hold one DAG between them.
13305 ///
13306 /// What only a second DAG exercises is the **concatenation**: `level_groups`
13307 /// is every DAG's groups laid end to end and a DAG reaches its own run
13308 /// through the `first_group` offset handed to `ClusterDag::selection_records`,
13309 /// which is zero for the first one and therefore invisible while there is
13310 /// only one. A second DAG whose records still named the first's groups would
13311 /// descend a hierarchy belonging to another surface — a cut that is a
13312 /// plausible picture and matches no assertion the CPU makes about the frame.
13313 ///
13314 /// On the mesh path, because that is where the offset is *used*: an indirect
13315 /// tail takes a uniform cut and builds no [`ClusterSelect`] records at all.
13316 ///
13317 /// [`ClusterSelect`]: crcbl_shaders::cluster_select::ClusterSelect
13318 #[test]
13319 fn a_second_dag_reaches_its_own_groups_and_not_the_first_s() {
13320 use crcbl_shaders::cluster_select::{CLUSTER_SELECT_STRIDE, ClusterSelect};
13321
13322 let recorder = Recorder::new();
13323 let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
13324
13325 // The engine has one DAG, so a second one is a second copy of it. That
13326 // is the whole point: two DAGs whose *groups* are alike is the case
13327 // where reaching the wrong run still produces a cut, and so the case a
13328 // frame comparison could never catch.
13329 let mut scene = scene::demo();
13330 let mut again = scene.meshes[DEMO_DUNES].clone();
13331 again.label = "dunes again".into();
13332 scene.meshes.push(again);
13333 // Room for the second copy. Doubling rather than measuring, because the
13334 // number that matters is that the description carries its own sizes at
13335 // all — see `Capacities`, which is the caller's to choose.
13336 scene.capacities.vertices *= 2;
13337 scene.capacities.indices *= 2;
13338 let second_dag = scene.meshes.len() - 1;
13339
13340 let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13341 panic!("the demo description's fourth mesh is the DAG");
13342 };
13343 let levels = dag.levels.len();
13344 let groups = dag.level_groups().len();
13345 assert!(groups > 0, "a DAG with no groups would select nothing");
13346
13347 let mut renderer =
13348 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13349 .expect("a five-mesh description with two DAGs is one this can make resident");
13350
13351 // Every level of both is its own table entry, laid down in description
13352 // order, so the second DAG's level 0 is a whole hierarchy past the
13353 // first's.
13354 assert_eq!(
13355 renderer.mesh_ids.len(),
13356 scene.meshes.len(),
13357 "one id per description mesh, whatever the count"
13358 );
13359 assert_eq!(
13360 renderer.mesh_ids[second_dag],
13361 renderer.mesh_ids[DEMO_DUNES] + levels as u32,
13362 "the second DAG's level 0 starts past every level of the first"
13363 );
13364
13365 // **The hysteresis state is per instance per resident group**, and
13366 // `group_stride` is what says how many groups that is. One DAG made this
13367 // number a single hierarchy's; two is what tells a stride that sums from
13368 // one that took the first answer it found.
13369 assert_eq!(
13370 renderer.primary.draws.group_stride(),
13371 u32::try_from(groups * 2).expect("a few dozen groups per DAG"),
13372 "every resident DAG's groups are in the stride, not just the first's"
13373 );
13374
13375 // The records themselves: which group each cluster produces and which
13376 // contains it, as the amplification stage reads them.
13377 let clusters = renderer
13378 .clusters
13379 .as_ref()
13380 .expect("the mesh path builds a cluster pool");
13381 let selection = recorder
13382 .buffer_bytes(clusters.selection())
13383 .expect("the selection records are live");
13384 // Entries are laid down in description order, a flat mesh taking one and
13385 // a DAG one per level — so the second DAG's start a hierarchy past the
13386 // first's, which start past the three flat residents.
13387 let first_entry = DEMO_DUNES;
13388 let record = |entry: usize| -> Vec<ClusterSelect> {
13389 let range = clusters.range(entry).expect("one range per entry");
13390 (range.base..range.base + range.count)
13391 .map(|cluster| {
13392 let at = cluster as usize * CLUSTER_SELECT_STRIDE;
13393 ClusterSelect::from_bytes(
13394 selection[at..at + CLUSTER_SELECT_STRIDE]
13395 .try_into()
13396 .expect("one whole record"),
13397 )
13398 })
13399 .collect()
13400 };
13401 // The named group of every record that has one, per DAG — and the count,
13402 // because a comparison over an empty set is a check that cannot fail.
13403 let named = |base: usize| -> Vec<u32> {
13404 (base..base + levels)
13405 .flat_map(record)
13406 .flat_map(|select| {
13407 let producer = (select.flags & ClusterSelect::HAS_PRODUCER != 0)
13408 .then_some(select.producer_group);
13409 let container = (select.flags & ClusterSelect::HAS_CONTAINER != 0)
13410 .then_some(select.container_group);
13411 producer.into_iter().chain(container)
13412 })
13413 .collect()
13414 };
13415 let boundary = u32::try_from(groups).expect("a few dozen groups per DAG");
13416 let first = named(first_entry);
13417 let second = named(first_entry + levels);
13418 assert!(
13419 !first.is_empty() && first.len() == second.len(),
13420 "the two copies must name the same number of groups: {} against {}",
13421 first.len(),
13422 second.len()
13423 );
13424 assert!(
13425 first.iter().all(|&group| group < boundary),
13426 "the first DAG's records stay inside its own run: {first:?}"
13427 );
13428 assert!(
13429 second
13430 .iter()
13431 .all(|&group| (boundary..boundary * 2).contains(&group)),
13432 "the second DAG's records must name the groups past the first's, and \
13433 `first_group` is the only thing that puts them there: {second:?}"
13434 );
13435
13436 // And both are placeable through the runtime API, which is what a
13437 // description of a shape no `set_*` method names is *for*.
13438 let place = |renderer: &mut ForwardRenderer, mesh: usize, x: f32| {
13439 renderer
13440 .add_instance(&InstanceDesc {
13441 mesh,
13442 material: DEMO_UNTINTED,
13443 transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)),
13444 })
13445 .expect("the pool has room")
13446 };
13447 let near = place(&mut renderer, DEMO_DUNES, -64.0);
13448 let far = place(&mut renderer, second_dag, 64.0);
13449 let index = |handle| {
13450 renderer
13451 .instances
13452 .index(handle)
13453 .expect("a just-added instance is live")
13454 };
13455 assert_ne!(
13456 index(near),
13457 index(far),
13458 "two instances take two slots, and the index is the hysteresis key"
13459 );
13460 assert_eq!(
13461 renderer.instances.get(far).expect("live").mesh,
13462 renderer.mesh_ids[second_dag],
13463 "an InstanceDesc's mesh index resolves through the description, not through \
13464 a table id the caller cannot know"
13465 );
13466
13467 renderer.destroy(device.as_ref());
13468 recorder.assert_valid();
13469 }
13470
13471 /// **A description the renderer cannot make resident is refused before the
13472 /// first device object exists**, so a rejection leaks nothing.
13473 ///
13474 /// `build` hands the geometry pool and the material table to the rollback
13475 /// and then creates a dozen objects with `?` between them. A check that ran
13476 /// part way down that list would be a new early exit on the wrong side of a
13477 /// handover, and the pool would go with it — which is exactly the leak
13478 /// `Rollback` exists to prevent and which
13479 /// `the_forward_renderer_builds_and_leaks_nothing` cannot see, because it
13480 /// only walks the happy path.
13481 ///
13482 /// Each arm below is a *different* refusal, so a check that stopped running
13483 /// would show up as one arm leaking rather than as all of them — and each
13484 /// names a fragment of the message it must be refused *with*, or an arm
13485 /// would pass on some other check's answer.
13486 /// **A description with no meshes is refused by name**, before anything
13487 /// is created, rather than reaching the mesh table's sizing with nothing
13488 /// to size it from.
13489 #[test]
13490 fn a_scene_with_no_meshes_is_refused_by_name() {
13491 let (recorder, device, queue) = open();
13492 let before = recorder.total_live_objects();
13493 let mut scene = scene::demo();
13494 scene.meshes.clear();
13495 let error =
13496 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13497 .expect_err("a scene of no meshes must be refused");
13498 assert!(
13499 error.to_string().contains("at least one mesh"),
13500 "the refusal says what is missing: {error}"
13501 );
13502 assert_eq!(
13503 recorder.total_live_objects(),
13504 before,
13505 "the refusal created something"
13506 );
13507 }
13508
13509 #[test]
13510 fn a_refused_description_creates_nothing_at_all() {
13511 /// One way of writing a description the renderer cannot build, and the
13512 /// words that say it was this refusal rather than another.
13513 type Break = (&'static str, fn(&mut SceneDesc<'static>), &'static str);
13514
13515 let cases: [Break; 9] = [
13516 (
13517 "a row naming a layer the page has not got",
13518 |scene| {
13519 scene.materials[DEMO_TEXTURED].base_color_texture = 7;
13520 },
13521 "material row 2 samples base-colour page layer 7",
13522 ),
13523 // And the same on the two kinds rung 3 added, because `check_scene`
13524 // reads a different column of the row for each: a check written per
13525 // kind is only worth what its arms cover, and a column nobody broke
13526 // here could be read out of the wrong material field for ever.
13527 // `demo` names no layer of either, so any index at all is past the
13528 // end.
13529 (
13530 "a row naming a packed-page layer the page has not got",
13531 |scene| {
13532 scene.materials[DEMO_TEXTURED].metallic_roughness_occlusion_texture = 3;
13533 },
13534 "material row 2 samples metallic-roughness-occlusion page layer 3",
13535 ),
13536 (
13537 "a row naming an emissive layer the page has not got",
13538 |scene| {
13539 scene.materials[DEMO_TEXTURED].emissive_texture = 3;
13540 },
13541 "material row 2 samples emissive page layer 3",
13542 ),
13543 // The one page refusal a caller can actually spell: `push_layer`
13544 // takes bytes it cannot measure against the extent.
13545 (
13546 "a page layer of the wrong length",
13547 |scene| {
13548 scene.page = scene::PageDesc::empty();
13549 scene
13550 .page
13551 .set_extent(PageKind::BaseColor, scene::PAGE_EXTENT);
13552 scene.page.push_layer(PageKind::BaseColor, vec![0x00; 4]);
13553 scene.materials[DEMO_TEXTURED].base_color_texture = scene::CHECKER_LAYER;
13554 },
13555 "base-colour page layer 0 carries 4 bytes",
13556 ),
13557 (
13558 "a DAG level with no vertices",
13559 |scene| {
13560 let Geometry::Dag { levels, .. } = &mut scene.meshes[DEMO_DUNES].geometry
13561 else {
13562 panic!("the demo description's fourth mesh is the DAG");
13563 };
13564 levels.pop();
13565 },
13566 "vertex array(s) for a DAG of",
13567 ),
13568 // The four capacities, each of which is a pool a caller sized and
13569 // a description outgrew. Written as a capacity the description is
13570 // too large for rather than as a description too large for the
13571 // default, because that is the shape of the mistake: the numbers on
13572 // `Capacities` are the ones an application picks.
13573 (
13574 "more vertices than the pool holds",
13575 |scene| {
13576 scene.capacities.vertices = 1;
13577 },
13578 "the vertex pool holds 1 and the description needs",
13579 ),
13580 (
13581 "more indices than the pool holds",
13582 |scene| {
13583 scene.capacities.indices = 1;
13584 },
13585 "the index pool holds 1 and the description needs",
13586 ),
13587 (
13588 "more meshes than the table holds",
13589 |scene| {
13590 scene.capacities.meshes = 1;
13591 },
13592 "the mesh table holds 1 and the description needs",
13593 ),
13594 (
13595 "more material rows than the table holds",
13596 |scene| {
13597 scene.capacities.materials = 2;
13598 },
13599 "the material table holds 2 and the description needs 3",
13600 ),
13601 ];
13602
13603 for (what, break_it, says) in cases {
13604 let (recorder, device, queue) = open();
13605 let before = recorder.total_live_objects();
13606 let mut scene = scene::demo();
13607 break_it(&mut scene);
13608 let error =
13609 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13610 .expect_err(&format!("{what} must be refused"));
13611 assert!(
13612 matches!(error, HalError::InvalidDescriptor(_)),
13613 "{what} must be refused as an invalid descriptor, not as {error:?}"
13614 );
13615 assert!(
13616 error.to_string().contains(says),
13617 "{what} must be refused with a message saying so, and this one says {error}"
13618 );
13619 assert_eq!(
13620 recorder.total_live_objects(),
13621 before,
13622 "{what} was refused after something had been created, and the rollback \
13623 is the only thing that could have released it"
13624 );
13625 recorder.assert_valid();
13626 }
13627
13628 // **And the refusal that is not free**, which is the half of the
13629 // handover every arm above walks past: `check_scene` settles what the
13630 // whole description says, and what one mesh's *bytes* say is the pool's,
13631 // which only sees them one upload at a time. Vertex bytes that are not a
13632 // whole number of vertices reach `MeshPool::upload` — so the third of
13633 // the four meshes is refused with the pool created, two device-local
13634 // buffers in it and the first two meshes already staged into them.
13635 // `build_geometry` is what releases that, and it can only do so because
13636 // the pool is not the rollback's until it has returned.
13637 let (recorder, device, queue) = open();
13638 let before = recorder.total_live_objects();
13639 // So the count below is this build's and not `open`'s.
13640 recorder.clear();
13641 let mut scene = scene::demo();
13642 let Geometry::Flat { vertices, .. } = &mut scene.meshes[DEMO_OPEN_BOX].geometry else {
13643 panic!("the demo description's third mesh is flat");
13644 };
13645 vertices.to_mut().push(0);
13646 let error =
13647 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13648 .expect_err("a mesh of part of a vertex must be refused");
13649 assert!(
13650 error.to_string().contains("is not a whole number of"),
13651 "the pool's own refusal reaches the caller with its numbers, and this \
13652 one says {error}"
13653 );
13654 assert!(
13655 recorder
13656 .events()
13657 .iter()
13658 .any(|event| matches!(event, crcbl_hal::null::Event::Created { .. })),
13659 "this arm is evidence about the rollback only if the refusal came after \
13660 something had been created"
13661 );
13662 assert_eq!(
13663 recorder.total_live_objects(),
13664 before,
13665 "a mesh refused part way through the list left the geometry pool behind, \
13666 which is exactly what `build_geometry` being self-cleaning is for"
13667 );
13668 recorder.assert_valid();
13669 }
13670
13671 /// **The one capacity a description cannot be checked against, and the one
13672 /// an application is expected to handle while it runs.**
13673 ///
13674 /// Every other number on [`scene::Capacities`] sizes something the
13675 /// description fills once, so `check_scene` refuses an over-large one before
13676 /// a device object exists. Objects are placed at any point in a renderer's
13677 /// life, so the only honest answer for that one is the error
13678 /// [`ForwardRenderer::add_instance`] returns — and it returns
13679 /// [`InstancePoolError`] rather than a [`HalError`], so the capacity and
13680 /// what is in it survive to the caller that chose them.
13681 ///
13682 /// It also gives [`Capacities::instances`](scene::Capacities::instances) a
13683 /// value of its own rather than the default, which is what makes the pool
13684 /// fillable at all: a renderer that ignored the number the description
13685 /// carries and reserved the default would draw every frame in the tree
13686 /// identically and refuse nothing here.
13687 #[test]
13688 fn a_full_instance_pool_reaches_the_application_that_sized_it() {
13689 let (recorder, device, queue) = open();
13690 let mut scene = scene::demo();
13691 scene.capacities.instances = 2;
13692 let mut renderer =
13693 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13694 .expect("a scene with room for two objects builds");
13695 let place = |renderer: &mut ForwardRenderer| {
13696 renderer.add_instance(&InstanceDesc {
13697 mesh: DEMO_CUBE,
13698 material: DEMO_UNTINTED,
13699 transform: Mat4::IDENTITY,
13700 })
13701 };
13702 place(&mut renderer).expect("the first of two");
13703 place(&mut renderer).expect("the second of two");
13704 let error = place(&mut renderer).expect_err("a third object has no slot to go in");
13705 assert!(
13706 matches!(
13707 error,
13708 InstancePoolError::PoolFull {
13709 capacity: 2,
13710 in_use: 2
13711 }
13712 ),
13713 "a full pool must reach the caller as a full pool, with the capacity it \
13714 chose; this arrived as {error}"
13715 );
13716 renderer.destroy(device.as_ref());
13717 recorder.assert_valid();
13718 }
13719
13720 /// **One mesh and one material row is a scene, and it draws.**
13721 ///
13722 /// The floor is gone. `with_scene` used to refuse anything shorter than
13723 /// [`scene::demo`] — four meshes and three rows — because the five `set_*`
13724 /// demo wrappers named those entries by position, and the renderer's own
13725 /// `dunes_clusters` and `dunes_level_buckets` indexed the description at
13726 /// `DEMO_DUNES` besides. So an application's own description was not merely
13727 /// refused: with the check removed it would have panicked out of `build`.
13728 ///
13729 /// A frame is recorded rather than only a build, because that is where the
13730 /// positional indexing was: the bucket table, the cluster ranges and the
13731 /// draw-argument blocks are all one-per-description-mesh, and a renderer that
13732 /// still assumed four would come apart here rather than at `with_scene`.
13733 #[test]
13734 fn a_description_smaller_than_the_demo_is_a_scene() {
13735 use std::borrow::Cow;
13736
13737 let scene = SceneDesc {
13738 meshes: vec![scene::MeshDesc {
13739 label: Cow::Borrowed("the only mesh"),
13740 geometry: Geometry::Flat {
13741 vertices: Cow::Owned(crcbl_shaders::mesh::cube_vertex_bytes()),
13742 uv_range: crcbl_shaders::mesh::demo_uv_range(),
13743 indices: Cow::Owned(crcbl_shaders::mesh::cube_indices()),
13744 clusters: crcbl_shaders::meshlet::cube_clusters(),
13745 flags: 0,
13746 },
13747 }],
13748 materials: vec![mesh::GpuMaterial::UNTINTED],
13749 page: scene::PageDesc::empty(),
13750 probes: scene::ProbeGrid::default(),
13751 capacities: scene::Capacities::default(),
13752 };
13753 assert!(
13754 scene.meshes.len() < scene::demo().meshes.len()
13755 && scene.materials.len() < scene::demo().materials.len(),
13756 "this description must be smaller than the demo's in both, or it says nothing \
13757 about the floor"
13758 );
13759
13760 let (recorder, device, queue) = open();
13761 let mut renderer =
13762 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13763 .expect("one mesh and one row is a description the renderer can hold");
13764 assert_eq!(
13765 renderer.mesh_ids,
13766 [0],
13767 "the one description mesh takes the one table entry"
13768 );
13769 assert_eq!(
13770 renderer.bucket_constants.len(),
13771 1,
13772 "one bucket per description mesh, and there is one"
13773 );
13774 renderer
13775 .add_instance(&InstanceDesc {
13776 mesh: 0,
13777 material: 0,
13778 transform: Mat4::IDENTITY,
13779 })
13780 .expect("an empty pool has room for the only object");
13781 let recorded = frame(device.as_ref(), &mut renderer, queue);
13782 assert_eq!(
13783 commands_in_pass(&recorder, "forward")
13784 .into_iter()
13785 .filter(|command| matches!(
13786 command,
13787 crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
13788 ))
13789 .count(),
13790 1,
13791 "a one-mesh scene records the one bucket's indirect call"
13792 );
13793 recorded.finish(device.as_ref(), renderer);
13794 }
13795
13796 /// **A description that exactly fills what it reserved is built, not
13797 /// refused.**
13798 ///
13799 /// The other side of the capacity check, and the side nothing else in the
13800 /// tree can fail on: every other scene reserves far more than it holds, so a
13801 /// comparison written `>=` instead of `>` would pass the whole suite and
13802 /// refuse only the application that had sized its pools exactly right.
13803 ///
13804 /// The two capacities asserted here are the two a caller can size without
13805 /// re-deriving anything the renderer knows: one mesh table entry per
13806 /// [`Geometry::levels`], which is what that method is documented to answer,
13807 /// and one row per material. The four rows share one comparison, so they
13808 /// stand or fall together.
13809 #[test]
13810 fn a_description_that_exactly_fits_its_capacities_is_built() {
13811 let (recorder, device, queue) = open();
13812 let mut scene = scene::demo();
13813 scene.capacities.meshes = scene
13814 .meshes
13815 .iter()
13816 .map(|desc| u32::try_from(desc.geometry.levels()).expect("a few levels"))
13817 .sum();
13818 scene.capacities.materials =
13819 u32::try_from(scene.materials.len()).expect("a few material rows");
13820 let renderer =
13821 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13822 .expect("a description that fits exactly is not too large for itself");
13823 renderer.destroy(device.as_ref());
13824 recorder.assert_valid();
13825 }
13826
13827 /// **The level tables cover every mesh-table slot an instance can name**,
13828 /// not only the slots the description filled.
13829 ///
13830 /// `draw_gen.slang`'s `mesh_levels_of` reads `gen.mesh_levels_at + mesh *
13831 /// MESH_LEVELS_WORDS` with no bound, and says in its own doc comment that
13832 /// "every entry an instance can name is filled". An instance's mesh id is a
13833 /// bare table index, so a table sized to the description alone makes that
13834 /// read land in whatever the packer put next for any slot the description
13835 /// left empty.
13836 ///
13837 /// Growing the capacity by a known number of slots grows the tables buffer
13838 /// by exactly what those slots occupy: one `MeshLevels` record and one
13839 /// `level_meshes` word each. The arithmetic is the assertion, so nothing
13840 /// here is a number to keep in step by hand.
13841 #[test]
13842 fn the_level_tables_cover_every_slot_the_mesh_table_has() {
13843 const EXTRA: u32 = 4;
13844
13845 let sized = |extra: u32| {
13846 let (recorder, device, queue) = open();
13847 let mut scene = scene::demo();
13848 scene.capacities.meshes += extra;
13849 let renderer =
13850 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13851 .expect("a description with room to spare");
13852 let size = recorder
13853 .buffer_bytes(renderer.primary.draws.tables())
13854 .expect("the table buffer is live")
13855 .len();
13856 renderer.destroy(device.as_ref());
13857 recorder.assert_valid();
13858 size
13859 };
13860
13861 let grown = sized(EXTRA) - sized(0);
13862 let want = EXTRA as usize * (crcbl_shaders::level_select::MESH_LEVELS_STRIDE + 4);
13863 assert_eq!(
13864 grown, want,
13865 "{EXTRA} more table slots must add {EXTRA} more selection records and {EXTRA} more \
13866 level words, and added {grown} bytes"
13867 );
13868 }
13869
13870 /// The property the whole arrangement exists for: the pool's second
13871 /// resident is **not** at base vertex zero, so a frame containing it is a
13872 /// frame that fails if the base is lost between the pool and the shader.
13873 ///
13874 /// Read out of the **mesh table** rather than out of a renderer field,
13875 /// because the table is where a generated draw's index range comes from:
13876 /// `draw_gen.slang` builds every argument structure out of these bytes and
13877 /// nothing on the CPU is consulted.
13878 ///
13879 /// Without this the pass is back where it started — one mesh, base 0, and a
13880 /// base-vertex bug that no picture can show.
13881 #[test]
13882 fn the_second_mesh_lands_past_the_first() {
13883 let (recorder, device, queue) = open();
13884 let renderer =
13885 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13886 let cube = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_CUBE]);
13887 let pyramid = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_PYRAMID]);
13888
13889 assert_eq!(cube.base_vertex, 0, "the cube is first");
13890 assert_eq!(
13891 pyramid.base_vertex as usize,
13892 crcbl_shaders::mesh::CUBE_VERTEX_COUNT,
13893 "the pyramid must start where the cube ends, or the pools are not \
13894 suballocating at all"
13895 );
13896 assert_eq!(
13897 pyramid.index_count as usize,
13898 crcbl_shaders::mesh::PYRAMID_INDEX_COUNT,
13899 "and the entry carries the whole range, which is what the draw-argument \
13900 pass builds its arguments out of"
13901 );
13902 // And the two buckets read different constant blocks, or both would walk
13903 // the same run of instances.
13904 assert_ne!(
13905 renderer.bucket_constants[DEMO_CUBE], renderer.bucket_constants[DEMO_PYRAMID],
13906 "each bucket needs a block of its own"
13907 );
13908 renderer.destroy(device.as_ref());
13909 }
13910
13911 /// **Each bucket's block points at that bucket's own run**, and the runs do
13912 /// not overlap.
13913 ///
13914 /// This is what replaced "the block names an instance": a draw covers
13915 /// however many instances survived culling, so what it can say for itself is
13916 /// only where to find its slice of the survivors. Two buckets naming one
13917 /// start word would draw each other's objects — with the *right* geometry,
13918 /// because the index range comes from the arguments, which is exactly the
13919 /// kind of plausible wrong picture a golden image struggles with.
13920 ///
13921 /// Read out of the bytes that reached the device rather than out of the
13922 /// renderer's own fields, because the failure is a block written wrong and
13923 /// the field would still be right.
13924 #[test]
13925 fn each_bucket_walks_its_own_run_of_survivors() {
13926 let (recorder, device, queue) = open();
13927 let renderer =
13928 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13929 let blocks = recorder
13930 .buffer_bytes(renderer.draw_constants)
13931 .expect("the blocks are live");
13932 let start_word_at = |offset: u32| {
13933 let at = offset as usize;
13934 u32::from_le_bytes(blocks[at..at + 4].try_into().expect("four bytes"))
13935 };
13936
13937 let draws = &renderer.primary.draws;
13938 let cube = start_word_at(renderer.bucket_constants[DEMO_CUBE]);
13939 let pyramid = start_word_at(renderer.bucket_constants[DEMO_PYRAMID]);
13940 // **Behind the survivors, their routes and the runs**, which share the
13941 // buffer: a block naming a word inside the runs would have the draw read
13942 // an instance index as its start, and one inside the survivor list or
13943 // the routes a start that is the same instances in a different order, or
13944 // a bucket number — both of which draw a plausible picture.
13945 assert_eq!(
13946 cube,
13947 draws.runs_at() + draws.visible_capacity(),
13948 "the first bucket's start word is the first word past one capacity of runs"
13949 );
13950 assert_eq!(
13951 pyramid,
13952 cube + (DEMO_PYRAMID - DEMO_CUBE) as u32,
13953 "and the second's is a word later — a start per bucket, not a run per bucket"
13954 );
13955 assert_eq!(
13956 cube,
13957 draws.bucket_start_word(DEMO_CUBE as u32),
13958 "the block carries what `DrawGen::bucket_start_word` says, because a reader \
13959 copying a run back uses that accessor and the shader uses this block"
13960 );
13961 renderer.destroy(device.as_ref());
13962 }
13963
13964 /// **An instance's record carries its material's mode**, in the bits
13965 /// `draw_gen.slang` routes by.
13966 ///
13967 /// The host half of the per-bucket split, and the half no picture and no
13968 /// pipeline bind can show: the bucket table can be perfectly twinned and
13969 /// every partition bound to the right pipeline while every instance still
13970 /// answers mode zero, in which case the masked twins are empty, the cutout
13971 /// partition draws nothing, and a cutout casts a solid shadow. The record is
13972 /// where that is decided.
13973 ///
13974 /// Both directions, so the check is shown to discriminate: the opaque
13975 /// instance's mode bits have to be **clear**, or a writer that set them
13976 /// unconditionally would satisfy a one-sided assertion. And the two records
13977 /// are asserted to differ in `flags` and nothing else, so this is about the
13978 /// mode rather than about two unrelated instances.
13979 #[test]
13980 fn an_instances_record_carries_its_materials_mode() {
13981 let masked_scene = {
13982 let mut scene = crate::scene::demo();
13983 scene.materials[DEMO_TINTED].flags = crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
13984 scene
13985 };
13986 let (recorder, device, queue) = open();
13987 let device = device.as_ref();
13988 let mut renderer =
13989 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &masked_scene)
13990 .expect("the null backend accepts the demo description");
13991 let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
13992 let opaque = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
13993 let masked = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
13994
13995 let record = |handle: InstanceHandle| {
13996 renderer
13997 .instances
13998 .get(handle)
13999 .expect("the instance was inserted and is live")
14000 };
14001 let opaque = record(opaque);
14002 let masked = record(masked);
14003 assert_eq!(
14004 opaque.material_mode(),
14005 0,
14006 "an opaque material's instance carries no mode bits, or every instance in the tree \
14007 routes to a cutout bucket"
14008 );
14009 assert_eq!(
14010 masked.material_mode(),
14011 crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK,
14012 "and a masked material's instance carries its mode, or it scatters into the opaque \
14013 twin and the depth passes write its full silhouette"
14014 );
14015 assert_eq!(
14016 mesh::GpuInstance {
14017 flags: opaque.flags,
14018 material: opaque.material,
14019 ..masked
14020 },
14021 opaque,
14022 "the two records differ in the mode bits and the material id and in nothing else"
14023 );
14024
14025 renderer.destroy(device);
14026 recorder.assert_valid();
14027 }
14028
14029 /// **A scene whose materials are all opaque gets exactly the bucket table
14030 /// it had before material modes existed** — one bucket per (mesh, level),
14031 /// and no twin.
14032 ///
14033 /// The zero-cost half of the per-bucket split, and the one a null device can
14034 /// state exactly. A bucket is not free: every pass records one indirect call
14035 /// per bucket per view, and every generator holds a run start per bucket. So
14036 /// a table that twinned unconditionally would double the recorded draws of
14037 /// every demo and every golden in this tree, none of which mask anything.
14038 ///
14039 /// The oracle is [`level_buckets`](ForwardRenderer::level_buckets), which is
14040 /// built from a mesh's own level count rather than from the table's length —
14041 /// so a build that emitted a twin per mesh has more buckets than levels and
14042 /// this says so. And the twinned scenes below are asserted to be exactly as
14043 /// many times as long as they hold modes, or the comparison would pass on a
14044 /// renderer that had stopped twinning at all.
14045 ///
14046 /// # A twin per mode the scene **holds**, not per mode that exists
14047 ///
14048 /// [`DEPTH_MODES`] has four entries and a bucket is not free — every pass
14049 /// records one indirect call per bucket — so the rule that matters is which
14050 /// values the description's own materials carry. Two rows of two modes are
14051 /// two twins whichever two they are, and the pair below says so both ways:
14052 /// three modes across three rows is three, and three rows collapsed onto two
14053 /// *values* is two even though between them they set both mode bits.
14054 #[test]
14055 fn an_all_opaque_scene_keeps_one_bucket_per_mesh_level() {
14056 use crcbl_shaders::mesh::GpuMaterial;
14057
14058 let (recorder, device, queue) = open();
14059 let device = device.as_ref();
14060 let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
14061 // The uniform-cut path, where a DAG is one bucket per level. The mesh
14062 // path folds a DAG into one bucket and reports no level buckets at all,
14063 // which would leave the oracle below empty.
14064 assert!(
14065 !renderer.emit.is_mesh(),
14066 "this preset built a mesh-shader path, whose level buckets are empty"
14067 );
14068 let levels: usize = (0..crate::scene::demo().meshes.len())
14069 .map(|mesh| renderer.level_buckets(mesh).len())
14070 .sum();
14071 assert!(levels > 0, "the demo has meshes, so it has levels");
14072 assert_eq!(
14073 renderer.bucket_constants.len(),
14074 levels,
14075 "an all-opaque scene's bucket table is one bucket per (mesh, level) and no mode \
14076 twin: {levels} level(s) against {} bucket(s)",
14077 renderer.bucket_constants.len()
14078 );
14079 assert_eq!(
14080 renderer.bucket_modes,
14081 vec![0; levels],
14082 "and every one of them draws the OPAQUE mode"
14083 );
14084 let opaque_meshes = renderer.draw_tables.bucket_meshes.clone();
14085 let opaque_level_buckets: Vec<Vec<u32>> = (0..crate::scene::demo().meshes.len())
14086 .map(|mesh| renderer.level_buckets(mesh).to_vec())
14087 .collect();
14088 renderer.destroy(device);
14089 recorder.assert_valid();
14090
14091 // Every arrangement worth stating, as the modes its material rows carry
14092 // and the number of twins that has to produce. The demo has three rows;
14093 // a fourth is appended where four distinct modes are wanted, which
14094 // nothing instances and which therefore changes nothing but the mode
14095 // set.
14096 for (rows, modes, what) in [
14097 (
14098 vec![GpuMaterial::ALPHA_MODE_MASK, 0, 0],
14099 2,
14100 "one masked row beside two opaque ones",
14101 ),
14102 (
14103 vec![GpuMaterial::DOUBLE_SIDED, 0, 0],
14104 2,
14105 "one double-sided row beside two opaque ones",
14106 ),
14107 (
14108 vec![GpuMaterial::ALPHA_MODE_MASK, GpuMaterial::DOUBLE_SIDED, 0],
14109 3,
14110 "a masked row, a double-sided one and an opaque one",
14111 ),
14112 (
14113 vec![
14114 GpuMaterial::ALPHA_MODE_MASK,
14115 GpuMaterial::DOUBLE_SIDED,
14116 GpuMaterial::ALPHA_MODE_MASK,
14117 ],
14118 2,
14119 "three rows carrying two mode values between them — both mode bits are set \
14120 somewhere and neither row is opaque, so a rule counting bits rather than \
14121 values would say three",
14122 ),
14123 (
14124 vec![
14125 0,
14126 GpuMaterial::ALPHA_MODE_MASK,
14127 GpuMaterial::DOUBLE_SIDED,
14128 GpuMaterial::MODE_MASK,
14129 ],
14130 4,
14131 "one row of each mode, which is the only arrangement that pays for four",
14132 ),
14133 ] {
14134 let scene = {
14135 let mut scene = crate::scene::demo();
14136 while scene.materials.len() < rows.len() {
14137 scene.materials.push(GpuMaterial::UNTINTED);
14138 }
14139 for (row, flags) in scene.materials.iter_mut().zip(&rows) {
14140 row.flags = *flags;
14141 }
14142 scene
14143 };
14144 let (recorder, device, queue) = open();
14145 let device = device.as_ref();
14146 let twinned =
14147 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
14148 .expect("the null backend accepts the demo description");
14149 assert_eq!(
14150 twinned.bucket_constants.len(),
14151 modes * levels,
14152 "{what}: {modes} mode(s) over {levels} level(s) is {} bucket(s), and the table \
14153 has {}",
14154 modes * levels,
14155 twinned.bucket_constants.len()
14156 );
14157 // The modes present, as a set — which is the claim, since the order
14158 // is `DEPTH_MODES`' and the count above already pins the length.
14159 let held: std::collections::BTreeSet<u32> =
14160 twinned.bucket_modes.iter().copied().collect();
14161 let want: std::collections::BTreeSet<u32> = rows.iter().copied().collect();
14162 assert_eq!(
14163 held, want,
14164 "{what}: the table twins the modes its materials carry and no others"
14165 );
14166 for mode in &held {
14167 assert_eq!(
14168 twinned
14169 .bucket_modes
14170 .iter()
14171 .filter(|held| *held == mode)
14172 .count(),
14173 levels,
14174 "{what}: every mode present gets every mesh's levels once"
14175 );
14176 }
14177 // **Mode-major**: each held mode is one contiguous run of the
14178 // all-opaque table, in `DEPTH_MODES` order, so a pipeline's
14179 // partition is one range of buckets.
14180 let held_in_order: Vec<u32> = DEPTH_MODES
14181 .into_iter()
14182 .filter(|mode| held.contains(mode))
14183 .collect();
14184 assert_eq!(
14185 twinned.bucket_modes,
14186 held_in_order
14187 .iter()
14188 .flat_map(|mode| std::iter::repeat_n(*mode, levels))
14189 .collect::<Vec<_>>(),
14190 "{what}: every bucket of one mode is contiguous, modes in DEPTH_MODES order"
14191 );
14192 assert_eq!(
14193 twinned.draw_tables.bucket_meshes,
14194 opaque_meshes.repeat(held_in_order.len()),
14195 "{what}: each mode's run is the all-opaque table, mesh by mesh"
14196 );
14197 for (mesh, opaque) in opaque_level_buckets.iter().enumerate() {
14198 assert_eq!(
14199 twinned.level_buckets(mesh),
14200 opaque.as_slice(),
14201 "{what}: mesh {mesh}'s level buckets are the first mode's run"
14202 );
14203 }
14204 // And the `(mesh, mode) → bucket` lookup the scatter routes through
14205 // sends every key to its mode's run, at the mesh's own offset.
14206 let lookup = crcbl_shaders::draw_gen::bucket_lookup(
14207 &twinned.draw_tables.bucket_meshes,
14208 &twinned.bucket_modes,
14209 )
14210 .expect("a small lookup");
14211 for (slot, mode) in held_in_order.iter().enumerate() {
14212 for (offset, mesh) in opaque_meshes.iter().enumerate() {
14213 let key = 1 + (*mesh * crcbl_shaders::draw_gen::MATERIAL_MODES + *mode);
14214 assert_eq!(
14215 lookup[key as usize] as usize,
14216 slot * levels + offset,
14217 "{what}: mesh {mesh} in mode {mode}"
14218 );
14219 }
14220 }
14221 twinned.destroy(device);
14222 recorder.assert_valid();
14223 }
14224 }
14225
14226 /// **The two pyramids differ in exactly one field, and it is the material
14227 /// id — which names a row holding a different colour and a different
14228 /// roughness.**
14229 ///
14230 /// The whole of what §3.2's table buys, stated as the two things that have
14231 /// to be true at once. Placed at the *same* transform, so "differ only in
14232 /// material" is literal rather than nearly: same mesh id, same matrix, same
14233 /// flags, and a `GpuInstance` comparison that would fail on any other
14234 /// field. And the ids they carry name rows the device actually holds —
14235 /// asserted on the bytes in the buffer, because a table the renderer agrees
14236 /// with itself about is not a table a shader can read.
14237 ///
14238 /// The two rows are asserted to differ, or the pair would be evidence of
14239 /// nothing: two instances naming two rows of the same colour draw the same
14240 /// picture whether or not either id was ever used.
14241 #[test]
14242 fn the_two_pyramids_differ_only_in_their_material() {
14243 let (recorder, device, queue) = open();
14244 let mut renderer =
14245 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14246 let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14247 let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14248 let tinted_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14249
14250 let instance = |handle: InstanceHandle| {
14251 renderer
14252 .instances
14253 .get(handle)
14254 .expect("the instance was inserted and is live")
14255 };
14256 let plain = instance(plain_handle);
14257 let tinted = instance(tinted_handle);
14258 assert_ne!(
14259 plain.material, tinted.material,
14260 "the two pyramids must not share a material row"
14261 );
14262 assert_eq!(
14263 mesh::GpuInstance {
14264 material: tinted.material,
14265 ..plain
14266 },
14267 tinted,
14268 "the two instances must differ in the material id and in nothing else"
14269 );
14270
14271 let bytes = recorder
14272 .buffer_bytes(renderer.materials.buffer())
14273 .expect("the table is live");
14274 let row = |index: u32| {
14275 let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14276 mesh::GpuMaterial::from_bytes(
14277 bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14278 .try_into()
14279 .expect("one row"),
14280 )
14281 };
14282 assert_eq!(
14283 row(plain.material),
14284 mesh::GpuMaterial::UNTINTED,
14285 "the plain pyramid's row must be the factor that changes nothing"
14286 );
14287 assert_eq!(
14288 row(tinted.material),
14289 mesh::GpuMaterial {
14290 base_color: scene::PYRAMID_TINT,
14291 roughness: scene::PYRAMID_ROUGHNESS,
14292 ..mesh::GpuMaterial::UNTINTED
14293 },
14294 "the tinted pyramid's row must be the tint and the tighter lobe"
14295 );
14296 // The shading half of that row, on its own: a roughness equal to the
14297 // neutral row's would leave `crcbl`'s render e2e comparing one lobe
14298 // against itself, and that test would go green on a shader that had
14299 // never read the column.
14300 assert_ne!(
14301 row(plain.material).roughness,
14302 row(tinted.material).roughness,
14303 "the two rows must differ in roughness, or the highlight the render e2e measures \
14304 is not attributable to the material"
14305 );
14306 assert_ne!(
14307 row(plain.material),
14308 row(tinted.material),
14309 "two rows holding the same colour would make the pair prove nothing"
14310 );
14311 // And the tint is the *only* thing that differs between them: a row that
14312 // also changed its page layer would make this pair evidence about two
14313 // columns at once, which is what the third pyramid exists to avoid.
14314 assert_eq!(
14315 row(plain.material).base_color_texture,
14316 row(tinted.material).base_color_texture,
14317 "the factor pair must sample the same page layer"
14318 );
14319
14320 // And the second pyramid leaves the frame the way the first does: the
14321 // instance is removed, not a draw skipped.
14322 renderer.remove_instance(tinted_handle);
14323 assert!(
14324 renderer.instances.get(tinted_handle).is_none(),
14325 "the instance must be given back, or an object nobody asked for stays in the scene"
14326 );
14327
14328 renderer.destroy(device.as_ref());
14329 }
14330
14331 /// **The same claim one column along: the plain and textured pyramids
14332 /// differ in exactly one field, and the rows it names differ in exactly one
14333 /// column — the base-colour page layer.**
14334 ///
14335 /// [`the_two_pyramids_differ_only_in_their_material`]'s argument for §3.2's
14336 /// *texture indices* rather than its *factors*. The factors of the two rows
14337 /// are asserted **equal** here, which is the half that makes the pair
14338 /// evidence about the texture at all: a textured row that also carried a
14339 /// tint would draw a different picture for a reason the frame could not
14340 /// distinguish from the tinted pyramid's.
14341 ///
14342 /// The layer numbers are asserted against the page the renderer actually
14343 /// uploaded, so a row naming a layer that does not exist is caught here
14344 /// rather than as an out-of-range sample on a device.
14345 #[test]
14346 fn the_textured_pyramid_differs_only_in_its_page_layer() {
14347 let (recorder, device, queue) = open();
14348 let mut renderer =
14349 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14350 let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14351 let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14352 let textured_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TEXTURED, at);
14353
14354 let instance = |handle: InstanceHandle| {
14355 renderer
14356 .instances
14357 .get(handle)
14358 .expect("the instance was inserted and is live")
14359 };
14360 let plain = instance(plain_handle);
14361 let textured = instance(textured_handle);
14362 assert_ne!(
14363 plain.material, textured.material,
14364 "the two pyramids must not share a material row"
14365 );
14366 assert_eq!(
14367 mesh::GpuInstance {
14368 material: textured.material,
14369 ..plain
14370 },
14371 textured,
14372 "the two instances must differ in the material id and in nothing else"
14373 );
14374
14375 let bytes = recorder
14376 .buffer_bytes(renderer.materials.buffer())
14377 .expect("the table is live");
14378 let row = |index: u32| {
14379 let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14380 mesh::GpuMaterial::from_bytes(
14381 bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14382 .try_into()
14383 .expect("one row"),
14384 )
14385 };
14386 assert_eq!(
14387 row(plain.material).base_color,
14388 row(textured.material).base_color,
14389 "the texture pair must share a factor, or the pair is evidence about both columns"
14390 );
14391 assert_eq!(
14392 row(plain.material).base_color_texture,
14393 mesh::GpuMaterial::NO_PAGE
14394 );
14395 assert_eq!(
14396 row(textured.material).base_color_texture,
14397 scene::CHECKER_LAYER
14398 );
14399 assert_ne!(
14400 row(plain.material),
14401 row(textured.material),
14402 "two rows naming the same layer would make the pair prove nothing"
14403 );
14404 // The layer that number names is a layer the page has, and it is not
14405 // one flat colour — a checker of one repeated texel would pass every
14406 // assertion above and draw the picture the untextured row draws.
14407 let page = scene::demo().page;
14408 let layers = page.layers(PageKind::BaseColor);
14409 assert!(
14410 (scene::CHECKER_LAYER as usize) < layers.len(),
14411 "layer {} is past the end of a {}-layer page, which is an out-of-range sample \
14412 nothing below the seam would report",
14413 scene::CHECKER_LAYER,
14414 layers.len()
14415 );
14416 let checker = &layers[scene::CHECKER_LAYER as usize];
14417 assert!(
14418 checker
14419 .as_chunks::<4>()
14420 .0
14421 .iter()
14422 .any(|texel| texel != &checker[..4]),
14423 "a flat checker layer would shade the textured row exactly as the untextured \
14424 one shades, and the pair would prove nothing"
14425 );
14426
14427 renderer.remove_instance(textured_handle);
14428 assert!(
14429 renderer.instances.get(textured_handle).is_none(),
14430 "the instance must be given back, or an object nobody asked for stays in the scene"
14431 );
14432
14433 renderer.destroy(device.as_ref());
14434 }
14435
14436 /// **A [`PageKind`] nothing names costs one texel**, not `extent² × 4` bytes
14437 /// and a third again for its chain.
14438 ///
14439 /// This is what row (d) bought, and it is the half of it no picture can
14440 /// show: the frame a scene with no normal map draws is byte-identical either
14441 /// way, because `mesh.slang` returns before it fetches. What changes is the
14442 /// image the renderer created, and the copies into it are where that is
14443 /// visible. `crcbl/tests/mesh_e2e/normal_map.rs`'s
14444 /// `no_normal_map_returns_the_surface_normal_exactly_and_the_neutral_texel_does_not`
14445 /// is the device-side half saying the frame did not move.
14446 ///
14447 /// [`scene::demo`] is the scene: every one of its rows carries
14448 /// [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) in the normal column, and it is
14449 /// the description every golden in this tree is a variation of.
14450 ///
14451 /// # Sabotage
14452 ///
14453 /// The empty-kind arm of the upload loop uploading a full 64² neutral layer
14454 /// and its chain instead of the placeholder — the shape this replaced. Red
14455 /// on 2026-09-06 with `"a description with no normal map must upload the
14456 /// one-texel placeholder, and this copied 7 level(s) at [Extent3d { width:
14457 /// 64, height: 64, depth_or_layers: 1 }, … ] — a burned neutral layer costs
14458 /// extent² × 4 bytes and a third again for its chain, on every scene in the
14459 /// tree"`.
14460 #[test]
14461 fn a_page_kind_nothing_names_costs_one_texel() {
14462 use crcbl_hal::null::Command;
14463
14464 let scene = scene::demo();
14465 assert!(
14466 scene
14467 .materials
14468 .iter()
14469 .all(|row| row.normal_texture == mesh::GpuMaterial::NO_PAGE),
14470 "a row naming a normal layer would make the description one that *does* name \
14471 the page, and this test would be about the other case"
14472 );
14473 assert!(
14474 scene.page.layers(PageKind::Normal).is_empty()
14475 && scene.page.extent(PageKind::BaseColor) > 1,
14476 "the description must name no normal layer while naming base-colour ones, or \
14477 a placeholder-sized copy says nothing about which page it landed in"
14478 );
14479
14480 let (recorder, device, queue) = open();
14481 let renderer =
14482 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14483 .expect("a description naming no normal page is one this can make resident");
14484
14485 let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14486 .commands()
14487 .into_iter()
14488 .filter_map(|command| match command {
14489 Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14490 Some(copy)
14491 }
14492 _ => None,
14493 })
14494 .collect();
14495 let extents: Vec<crcbl_hal::Extent3d> =
14496 copies.iter().map(|copy| copy.image_extent).collect();
14497 assert_eq!(
14498 extents,
14499 vec![crcbl_hal::Extent3d::d2(1, 1)],
14500 "a description with no normal map must upload the one-texel placeholder, and \
14501 this copied {} level(s) at {extents:?} — a burned neutral layer costs \
14502 extent² × 4 bytes and a third again for its chain, on every scene in the tree",
14503 copies.len()
14504 );
14505
14506 // The placeholder is one layer, and the graph declaration says so: a
14507 // caller importing this page to write a layer of its own would get
14508 // `ImportDeclarationConflict` against an extent that was not 1×1.
14509 assert_eq!(
14510 renderer.normal_page_import().extent,
14511 (1, 1),
14512 "the declaration names the placeholder's extent, not the base-colour page's"
14513 );
14514 renderer.destroy(device.as_ref());
14515 }
14516
14517 /// **A page and a material table that are the caller's own, not
14518 /// [`scene::demo`]'s**: a different extent per kind, more layers than the
14519 /// demo page holds, a normal page the demo does not have at all, and rows
14520 /// past the three the demo writes.
14521 ///
14522 /// Every other scene in the tree is `scene::demo()` — with a mesh appended,
14523 /// at most — so until this nothing had put an app-supplied *layer* or an
14524 /// app-supplied *row* through [`ForwardRenderer::with_scene`] at all. A
14525 /// build that uploaded the demo's two layers and stopped, or that inserted
14526 /// its three rows and stopped, would leave every golden byte-identical and
14527 /// pass every other assertion in this module: the demo scene cannot tell a
14528 /// table filled from the description from one filled up to the description's
14529 /// third row.
14530 ///
14531 /// Read off the recorder rather than off the description, because the
14532 /// description is the input. The copies are what reached the image and the
14533 /// table buffer is what the shader indexes, and neither is a restatement of
14534 /// what was handed in.
14535 #[test]
14536 fn an_app_page_and_table_reach_the_device_whole() {
14537 use crcbl_hal::null::Command;
14538
14539 /// Not [`scene::PAGE_EXTENT`], so an extent that had been compiled in
14540 /// rather than read off the page shows up as a copy of the wrong size.
14541 const APP_EXTENT: u32 = 4;
14542
14543 /// **Not [`APP_EXTENT`]**, which is the whole of what row (d)'s per-kind
14544 /// extent bought: a renderer that still sized the normal page from the
14545 /// base-colour page's number would copy this layer at 4² and the copy
14546 /// list below would say so.
14547 const APP_NORMAL_EXTENT: u32 = 2;
14548 let layer_bytes = APP_EXTENT as usize * APP_EXTENT as usize * 4;
14549
14550 // Three base-colour layers, each flat and each a value of its own: a
14551 // build that uploaded one layer twice, or that stopped short, is a
14552 // different sequence of copies. Then one normal layer at the other
14553 // extent, which the demo scene has no page for at all.
14554 let mut page = scene::PageDesc::empty();
14555 page.set_extent(PageKind::BaseColor, APP_EXTENT);
14556 page.set_extent(PageKind::Normal, APP_NORMAL_EXTENT);
14557 let app_layers: Vec<u32> = [0x11_u8, 0x22, 0x33]
14558 .into_iter()
14559 .map(|value| page.push_layer(PageKind::BaseColor, vec![value; layer_bytes]))
14560 .collect();
14561 let app_normal = page.push_layer(
14562 PageKind::Normal,
14563 scene::PageDesc::NEUTRAL_NORMAL
14564 .repeat(APP_NORMAL_EXTENT as usize * APP_NORMAL_EXTENT as usize),
14565 );
14566
14567 let mut scene = scene::demo();
14568 scene.page = page;
14569 // One row per appended layer, and each with a factor of its own as well,
14570 // so a row that landed at another row's id is not a row that happens to
14571 // look like it. The last of them names the normal layer too, so the
14572 // table carries a row through both pages.
14573 for (nth, &layer) in app_layers.iter().enumerate() {
14574 let shade = 0.25 * (nth as f32 + 1.0);
14575 let last = nth + 1 == app_layers.len();
14576 scene.materials.push(mesh::GpuMaterial {
14577 base_color: [shade, shade, shade, 1.0],
14578 base_color_texture: layer,
14579 normal_texture: if last {
14580 app_normal
14581 } else {
14582 mesh::GpuMaterial::NO_PAGE
14583 },
14584 ..mesh::GpuMaterial::UNTINTED
14585 });
14586 }
14587 assert!(
14588 scene.materials.len() > scene::demo().materials.len()
14589 && scene.page.layers(PageKind::BaseColor).len()
14590 > scene::demo().page.layers(PageKind::BaseColor).len(),
14591 "the description under test must exceed the demo's in both, or this is a \
14592 demo test wearing another name"
14593 );
14594 assert_eq!(
14595 scene::demo().page.extent(PageKind::Normal),
14596 0,
14597 "the demo scene must name no normal page, or the normal copies below are \
14598 evidence about the demo's page rather than the caller's"
14599 );
14600
14601 let (recorder, device, queue) = open();
14602 let mut renderer =
14603 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14604 .expect("a page and a table of the caller's own are ones this can make resident");
14605
14606 // The page, layer by layer. Filtered by image because the build uploads
14607 // the ambient-occlusion placeholder through the same path.
14608 let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14609 .commands()
14610 .into_iter()
14611 .filter_map(|command| match command {
14612 Command::CopyBufferToImage(copy)
14613 if copy.image == renderer.base_color_page.image =>
14614 {
14615 Some(copy)
14616 }
14617 _ => None,
14618 })
14619 .collect();
14620 // Every layer goes up with its chain — three levels for this extent —
14621 // so the copies are layer-major, level-minor, each at its level's own
14622 // extent.
14623 let levels = crcbl_hal::Extent3d::d2(APP_EXTENT, APP_EXTENT)
14624 .full_mip_levels(crcbl_hal::ImageType::D2);
14625 assert_eq!(levels, 3, "a 4² page has three levels down to one texel");
14626 let layer_count = u32::try_from(scene.page.layers(PageKind::BaseColor).len())
14627 .expect("a page of a few layers");
14628 assert_eq!(
14629 copies
14630 .iter()
14631 .map(|copy| (
14632 copy.image_subresource.base_layer,
14633 copy.image_subresource.mip
14634 ))
14635 .collect::<Vec<(u32, u32)>>(),
14636 (0..layer_count)
14637 .flat_map(|layer| (0..levels).map(move |level| (layer, level)))
14638 .collect::<Vec<(u32, u32)>>(),
14639 "every level of every layer the description carries must be copied into the page, \
14640 in order"
14641 );
14642 assert!(
14643 copies.iter().all(|copy| {
14644 let side = crate::mip::level_extent(APP_EXTENT, copy.image_subresource.mip);
14645 copy.image_extent == crcbl_hal::Extent3d::d2(side, side)
14646 }),
14647 "the page is the extent the caller wrote, not the demo's, halved per level: \
14648 {copies:?}"
14649 );
14650
14651 // The normal page, at **its own** extent. One layer, two levels for a
14652 // 2² image, and every copy sized from `APP_NORMAL_EXTENT` — a renderer
14653 // that carried one extent for both kinds would put this layer up at 4².
14654 let normal_copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14655 .commands()
14656 .into_iter()
14657 .filter_map(|command| match command {
14658 Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14659 Some(copy)
14660 }
14661 _ => None,
14662 })
14663 .collect();
14664 let normal_levels = crcbl_hal::Extent3d::d2(APP_NORMAL_EXTENT, APP_NORMAL_EXTENT)
14665 .full_mip_levels(crcbl_hal::ImageType::D2);
14666 assert_eq!(
14667 normal_copies
14668 .iter()
14669 .map(|copy| (
14670 copy.image_subresource.base_layer,
14671 copy.image_subresource.mip,
14672 copy.image_extent
14673 ))
14674 .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14675 (0..normal_levels)
14676 .map(|level| {
14677 let side = crate::mip::level_extent(APP_NORMAL_EXTENT, level);
14678 (0, level, crcbl_hal::Extent3d::d2(side, side))
14679 })
14680 .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14681 "the normal page is the extent the caller wrote for *that* kind, halved per \
14682 level: {normal_copies:?}"
14683 );
14684 assert_eq!(
14685 renderer.normal_page_import().extent,
14686 (APP_NORMAL_EXTENT, APP_NORMAL_EXTENT),
14687 "the graph declaration names the normal page's own extent, or a caller \
14688 importing it to write a layer gets ImportDeclarationConflict"
14689 );
14690 assert_eq!(
14691 renderer.base_color_page_import().extent,
14692 (APP_EXTENT, APP_EXTENT),
14693 "and the base-colour declaration names its own, which is a different number"
14694 );
14695
14696 // The table, row by row, out of the buffer `mesh.slang` indexes.
14697 let bytes = recorder
14698 .buffer_bytes(renderer.materials.buffer())
14699 .expect("the table is live");
14700 let row = |id: u32| {
14701 let at = id as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14702 mesh::GpuMaterial::from_bytes(
14703 bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14704 .try_into()
14705 .expect("one row"),
14706 )
14707 };
14708 assert_eq!(
14709 renderer.material_ids.len(),
14710 scene.materials.len(),
14711 "one id per description row, whatever the count"
14712 );
14713 for (index, wrote) in scene.materials.iter().enumerate() {
14714 assert_eq!(
14715 &row(renderer.material_ids[index]),
14716 wrote,
14717 "description row {index} must be the row its id names"
14718 );
14719 }
14720
14721 // And a caller can place an object through a row only its own
14722 // description has, which is the whole point of the rows being the
14723 // caller's.
14724 let last = scene.materials.len() - 1;
14725 let handle = renderer
14726 .add_instance(&InstanceDesc {
14727 mesh: DEMO_CUBE,
14728 material: last,
14729 transform: Mat4::IDENTITY,
14730 })
14731 .expect("an empty pool of thousands has room for one object");
14732 assert_eq!(
14733 renderer
14734 .instances
14735 .get(handle)
14736 .expect("a just-added instance is live")
14737 .material,
14738 renderer.material_ids[last],
14739 "an InstanceDesc's material index resolves through the description, not \
14740 through a table id the caller cannot know"
14741 );
14742
14743 renderer.destroy(device.as_ref());
14744 recorder.assert_valid();
14745 }
14746
14747 /// **The frame records two compute dispatches and exactly one indirect draw
14748 /// per bucket — whatever is in the scene.**
14749 ///
14750 /// The property topic 03 opens with, checked on the recorded command stream:
14751 /// adding the pyramid adds an instance and changes no command. A pass that
14752 /// had kept a draw per object would record one command here and two there,
14753 /// which is what this used to assert and what the indirect path replaced.
14754 ///
14755 /// It also pins the arguments each call names: bucket `n` reads the `n`-th
14756 /// argument structure and the `n`-th count, at the stride every API fixed.
14757 /// Two calls pointing at one structure is a frame that draws one object
14758 /// twice.
14759 #[test]
14760 fn the_frame_records_one_indirect_call_per_bucket_whatever_the_scene_holds() {
14761 use crcbl_hal::null::Command;
14762
14763 for pyramid in [None, Some(Mat4::from_translation(Vec3::X))] {
14764 let (recorder, device, queue) = open();
14765 let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
14766 .expect("built");
14767 // The cube in both scenes, so the difference between them is the
14768 // pyramid alone. It also keeps both frames non-empty, and an empty
14769 // one would be a weaker comparison than this claims: `cull`'s
14770 // dispatch covers no workgroups when the pool is empty, and the pass
14771 // records nothing rather than a dispatch of zero — see
14772 // [`DrawGen::add_passes`].
14773 place_cube(&mut renderer, Mat4::IDENTITY);
14774 if let Some(at) = pyramid {
14775 place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14776 }
14777 let frame = frame(device.as_ref(), &mut renderer, queue);
14778
14779 let stride = crcbl_shaders::draw_gen::DRAW_ARGS_SIZE as u32;
14780 let expected: Vec<(u32, u64, u64)> = (0..renderer.bucket_constants.len())
14781 .map(|bucket| {
14782 (
14783 renderer.bucket_constants[bucket],
14784 bucket as u64 * u64::from(stride),
14785 bucket as u64 * 4,
14786 )
14787 })
14788 .collect();
14789
14790 // The dynamic offset last bound before each draw, paired with the
14791 // offsets that draw read its arguments and its count from.
14792 let mut offset = None;
14793 let mut seen: Vec<(u32, u64, u64)> = Vec::new();
14794 let mut dispatches = 0;
14795 for command in recorder.commands() {
14796 if matches!(command, Command::Dispatch { .. }) {
14797 dispatches += 1;
14798 }
14799 }
14800 for command in commands_in_pass(&recorder, "forward") {
14801 match command {
14802 Command::BindGroup {
14803 slot: 0,
14804 dynamic_offsets,
14805 ..
14806 } => offset = dynamic_offsets.first().copied(),
14807 Command::DrawIndexedIndirectCount(draw) => {
14808 assert_eq!(draw.stride, stride, "sizeof(VkDrawIndexedIndirectCommand)");
14809 assert_eq!(
14810 draw.max_draw_count, 1,
14811 "one argument structure per bucket, so one is the ceiling"
14812 );
14813 seen.push((
14814 offset.expect("a draw is preceded by its constant block"),
14815 draw.args_offset,
14816 draw.count_offset,
14817 ));
14818 }
14819 Command::DrawIndexed { .. } => {
14820 panic!("the forward pass must not record a CPU-counted draw any more")
14821 }
14822 _ => {}
14823 }
14824 }
14825 assert_eq!(
14826 dispatches,
14827 DrawGen::DISPATCHES as usize * (1 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
14828 "the clearing pass, the cull pass and the draw-argument pass's three, in \
14829 front of the draws — once for the camera and once per shadow cascade — plus \
14830 topic 18's one clustering dispatch, which is the camera's alone because a \
14831 cascade shades nothing, plus the resolve's own"
14832 );
14833 assert_eq!(
14834 seen, expected,
14835 "with pyramid = {pyramid:?}, the pass must record one indirect call per \
14836 bucket, each pointing at its own arguments, its own count and its own \
14837 block"
14838 );
14839
14840 frame.finish(device.as_ref(), renderer);
14841 }
14842 }
14843
14844 /// **The two `GeometryPath` arms record different calls and nothing else
14845 /// differs.**
14846 ///
14847 /// A device with a GPU-side count takes it from GPU memory; one without —
14848 /// Metal, whose API has multi-draw-indirect and no count buffer — reads each
14849 /// bucket's one argument structure unconditionally. Same buckets, same
14850 /// arguments, same block: the tail is the only thing that moves, which is
14851 /// what topic 03 means by "the lesser path is
14852 /// a constraint on data layout, not a separate renderer".
14853 ///
14854 /// Both presets are run here rather than only the one this machine has,
14855 /// because the arm a device never selects is the arm nothing tests.
14856 #[test]
14857 fn each_geometry_path_records_its_own_indirect_call() {
14858 use crcbl_hal::null::Command;
14859
14860 for (preset, path, counted) in [
14861 (
14862 NullInstance::gpu_driven(),
14863 GeometryPath::IndirectCount,
14864 true,
14865 ),
14866 (
14867 NullInstance::portable(),
14868 GeometryPath::IndirectPerBatch,
14869 false,
14870 ),
14871 ] {
14872 let recorder = Recorder::new();
14873 let instance = preset.with_recorder(recorder.clone());
14874 let adapter = instance.adapters().remove(0);
14875 assert_eq!(
14876 instance
14877 .adapter_caps(adapter.id)
14878 .expect("the null backend describes its adapter")
14879 .geometry_path(),
14880 path,
14881 "the preset must select the path this arm is about"
14882 );
14883 // `DeviceDesc::for_adapter` requires a timeline semaphore, which the
14884 // portable preset does not have; the forward pass does not need one
14885 // either, so this asks for what it uses. The optional set matters:
14886 // a device is opened with the features it *asked* for, and the path
14887 // is derived from those rather than from the adapter's.
14888 let device = instance
14889 .create_device(&DeviceDesc {
14890 label: None,
14891 adapter: adapter.id,
14892 required_features: Features::COMPUTE,
14893 optional_features: Features::GPU_DRIVEN,
14894 compatible_surface: None,
14895 })
14896 .expect("the null backend always opens");
14897 assert_eq!(
14898 device.caps().geometry_path(),
14899 path,
14900 "and the opened device still selects it"
14901 );
14902 let queue = device.queue(QueueKind::Graphics).expect("always present");
14903 let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
14904 .expect("built");
14905 let frame = frame(device.as_ref(), &mut renderer, queue);
14906
14907 let mut counted_calls = 0;
14908 let mut per_batch_calls = 0;
14909 for command in commands_in_pass(&recorder, "forward") {
14910 match command {
14911 Command::DrawIndexedIndirectCount(_) => counted_calls += 1,
14912 Command::DrawIndexedIndirect(draw) => {
14913 assert_eq!(
14914 draw.draw_count, 1,
14915 "one argument structure per bucket, read unconditionally"
14916 );
14917 per_batch_calls += 1;
14918 }
14919 _ => {}
14920 }
14921 }
14922 let buckets = renderer.bucket_constants.len();
14923 let (expected_counted, expected_per_batch) =
14924 if counted { (buckets, 0) } else { (0, buckets) };
14925 assert_eq!(
14926 (counted_calls, per_batch_calls),
14927 (expected_counted, expected_per_batch),
14928 "{path:?} must record one call of its own kind per bucket and none of the other"
14929 );
14930
14931 frame.finish(device.as_ref(), renderer);
14932 }
14933 }
14934
14935 /// Serialises the two checks that move
14936 /// [`r_debug_draw`](crate::debug_draw::r_debug_draw), and puts it back
14937 /// afterwards.
14938 ///
14939 /// A [`ConVar`](crcbl_console::ConVar) is process-global by design, and
14940 /// `cargo test` runs a crate's tests as threads of *one* process: two checks
14941 /// that move the switch are then two writers to one cell, which shows up as
14942 /// a flake rather than as a failure anybody can read.
14943 /// `crcbl::debug_view::for_test` is the same shape one crate up and there
14944 /// for the same reason; this one is smaller because nothing outside these
14945 /// two tests ever writes the cell.
14946 fn debug_draw_switch() -> DebugDrawSwitch {
14947 let guard = DEBUG_DRAW_SWITCH
14948 .lock()
14949 .unwrap_or_else(std::sync::PoisonError::into_inner);
14950 let switch = DebugDrawSwitch { _guard: guard };
14951 switch.set(false);
14952 switch
14953 }
14954
14955 /// What [`debug_draw_switch`] hands back: the switch is this thread's until
14956 /// it drops, and it goes back off when it does.
14957 struct DebugDrawSwitch {
14958 _guard: std::sync::MutexGuard<'static, ()>,
14959 }
14960
14961 impl DebugDrawSwitch {
14962 /// Moves the switch.
14963 fn set(&self, on: bool) {
14964 crate::debug_draw::r_debug_draw
14965 .set(&crcbl_console::Value::Bool(on))
14966 .expect("`r_debug_draw` is a writable bool");
14967 }
14968 }
14969
14970 impl Drop for DebugDrawSwitch {
14971 fn drop(&mut self) {
14972 // Off at both ends, so a check that panicked mid-way does not hand
14973 // the next holder a switched-on layer.
14974 self.set(false);
14975 }
14976 }
14977
14978 /// [`debug_draw_switch`]'s lock.
14979 ///
14980 /// **First of the two**, when a test takes this and [`ssao_blur_switch`]
14981 /// both — see that function for what the opposite order cost.
14982 static DEBUG_DRAW_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
14983
14984 /// Takes `r_ssao_blur_passes` for this thread and puts it back at its
14985 /// default when the guard drops.
14986 ///
14987 /// [`debug_draw_switch`]'s shape exactly, for its reason: a plain
14988 /// `cargo test` run shares one process between tests, and a variable this
14989 /// one left moved is a frame the next test did not ask for.
14990 ///
14991 /// **Every test whose assertion depends on the shape of a frame takes this,
14992 /// not only the one that moves the count.** The variable is a process
14993 /// global and `cargo test` runs this module's tests on threads that share
14994 /// it, so a frame built while
14995 /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] holds two blurs
14996 /// carries an `ssao-blur-2` pass, a full-screen triangle and a pipeline bind
14997 /// that the test building it never asked for. Taking the guard both
14998 /// serialises against that test and pins the count for the frames this one
14999 /// builds.
15000 ///
15001 /// Two shapes need it, and the second is easy to miss. A test comparing a
15002 /// frame against a **literal pass list** breaks whenever the count is two.
15003 /// A test comparing **two frames it built itself** — a difference in draws,
15004 /// an equality between pass lists, a "one pass longer" claim — breaks only
15005 /// when the count *moves between them*, which is a narrower window and why
15006 /// this reproduced at roughly one run in eight rather than every run.
15007 ///
15008 /// Both were established by experiment on 2026-09-01 rather than by
15009 /// reading: pinning the count at two reddens the first shape, and making
15010 /// `crate::ssao::blur_passes` alternate reddens the second.
15011 ///
15012 /// **A test taking this and [`debug_draw_switch`] takes that one first.**
15013 /// These are two plain mutexes with no ordering between them, so two tests
15014 /// acquiring both in opposite orders deadlock — which is not a hazard this
15015 /// comment is guessing at: adding the guard to the two debug-draw tests
15016 /// above their existing one did exactly that on 2026-09-01, and turned a
15017 /// 0.2 second suite into one that had not finished in ten minutes. It is
15018 /// invisible in a single-threaded run, where the same suite passes in a
15019 /// second, so `--test-threads=1` is not a check for it.
15020 ///
15021 /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`]: fn@a_second_occlusion_blur_is_a_pass_the_frame_records
15022 pub(super) fn ssao_blur_switch() -> SsaoBlurSwitch {
15023 let guard = SSAO_BLUR_SWITCH
15024 .lock()
15025 .unwrap_or_else(std::sync::PoisonError::into_inner);
15026 let switch = SsaoBlurSwitch { _guard: guard };
15027 switch.set(1);
15028 switch
15029 }
15030
15031 /// What [`ssao_blur_switch`] hands back.
15032 pub(super) struct SsaoBlurSwitch {
15033 _guard: std::sync::MutexGuard<'static, ()>,
15034 }
15035
15036 impl SsaoBlurSwitch {
15037 /// Asks for `passes` of them.
15038 fn set(&self, passes: i64) {
15039 crate::ssao::r_ssao_blur_passes
15040 .set(&crcbl_console::Value::Int(passes))
15041 .expect("`r_ssao_blur_passes` is a writable int in range");
15042 }
15043 }
15044
15045 impl Drop for SsaoBlurSwitch {
15046 fn drop(&mut self) {
15047 // Back to the shipping count at both ends, so a check that panicked
15048 // mid-way does not hand the next holder a three-pass frame.
15049 self.set(1);
15050 }
15051 }
15052
15053 /// [`ssao_blur_switch`]'s lock.
15054 static SSAO_BLUR_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15055
15056 /// Takes `r_ssao_split` for this thread and puts it back when the guard
15057 /// drops.
15058 ///
15059 /// [`ssao_blur_switch`]'s shape exactly, for its reason. The seam is what
15060 /// makes the occlusion chain record its second march, so a test about the
15061 /// widest frame a renderer can produce has to hold this as well as the blur
15062 /// count — see `crate::ssao`'s `r_ssao_split`.
15063 pub(super) fn ssao_split_switch() -> SsaoSplitSwitch {
15064 let guard = SSAO_SPLIT_SWITCH
15065 .lock()
15066 .unwrap_or_else(std::sync::PoisonError::into_inner);
15067 let switch = SsaoSplitSwitch { _guard: guard };
15068 switch.set(0.0);
15069 switch
15070 }
15071
15072 /// What [`ssao_split_switch`] hands back.
15073 pub(super) struct SsaoSplitSwitch {
15074 _guard: std::sync::MutexGuard<'static, ()>,
15075 }
15076
15077 impl SsaoSplitSwitch {
15078 /// Asks for a seam at `at`, or for none at zero.
15079 fn set(&self, at: f32) {
15080 crate::ssao::r_ssao_split
15081 .set(&crcbl_console::Value::Float(at))
15082 .expect("`r_ssao_split` is a writable float in range");
15083 }
15084 }
15085
15086 impl Drop for SsaoSplitSwitch {
15087 fn drop(&mut self) {
15088 // Back to the default at both ends, so a check that panicked
15089 // mid-way does not hand the next holder a comparing frame.
15090 self.set(0.0);
15091 }
15092 }
15093
15094 /// [`ssao_split_switch`]'s lock.
15095 static SSAO_SPLIT_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15096
15097 /// Takes `r_shadow_filter` and `r_shadow_split` for this thread and puts
15098 /// them both back at their defaults when the guard drops.
15099 ///
15100 /// [`ssao_split_switch`]'s shape, with two variables under one lock because
15101 /// they are read into one row of one block — `crate::shadow::FILTER_SWITCH`
15102 /// is where that is argued, and why the lock lives there rather than beside
15103 /// this function: `crate::shadow`'s own tests move the same two.
15104 fn shadow_filter_switch() -> ShadowFilterSwitch {
15105 let guard = crate::shadow::FILTER_SWITCH
15106 .lock()
15107 .unwrap_or_else(std::sync::PoisonError::into_inner);
15108 let switch = ShadowFilterSwitch { _guard: guard };
15109 switch.reset();
15110 switch
15111 }
15112
15113 /// What [`shadow_filter_switch`] hands back.
15114 struct ShadowFilterSwitch {
15115 _guard: std::sync::MutexGuard<'static, ()>,
15116 }
15117
15118 impl ShadowFilterSwitch {
15119 /// Asks for `filter` on the near side of the seam.
15120 fn filter(&self, filter: shadow::Filter) {
15121 crate::shadow::r_shadow_filter
15122 .set(&crcbl_console::Value::Enum(filter.label()))
15123 .expect("`r_shadow_filter` is a writable enum in the set");
15124 }
15125
15126 /// Asks for a seam at `at`, or for none at zero.
15127 fn seam(&self, at: f32) {
15128 crate::shadow::r_shadow_split
15129 .set(&crcbl_console::Value::Float(at))
15130 .expect("`r_shadow_split` is a writable float in range");
15131 }
15132
15133 /// Asks for `texels` of constant bias.
15134 fn bias(&self, texels: f32) {
15135 crate::shadow::r_shadow_bias
15136 .set(&crcbl_console::Value::Float(texels))
15137 .expect("`r_shadow_bias` is a writable float in range");
15138 }
15139
15140 /// Asks for `texels` of normal offset.
15141 fn offset(&self, texels: f32) {
15142 crate::shadow::r_shadow_normal_offset
15143 .set(&crcbl_console::Value::Float(texels))
15144 .expect("`r_shadow_normal_offset` is a writable float in range");
15145 }
15146
15147 /// Back to the frame every golden was blessed as.
15148 fn reset(&self) {
15149 self.filter(shadow::shipped_filter());
15150 self.seam(0.0);
15151 self.bias(shipped_float(&crate::shadow::r_shadow_bias));
15152 self.offset(shipped_float(&crate::shadow::r_shadow_normal_offset));
15153 }
15154 }
15155
15156 /// The float `var` declares as its default — what a frame nobody typed at
15157 /// is drawn with, read off the variable rather than written down here.
15158 fn shipped_float(var: &crcbl_console::ConVar) -> f32 {
15159 match var.default() {
15160 crcbl_console::Value::Float(shipped) => *shipped,
15161 other => panic!("`{}` defaults to {other:?}, not to a float", var.name()),
15162 }
15163 }
15164
15165 impl Drop for ShadowFilterSwitch {
15166 fn drop(&mut self) {
15167 // Back to the defaults at both ends, so a check that panicked
15168 // mid-way does not hand the next holder a comparing frame.
15169 self.reset();
15170 }
15171 }
15172
15173 /// Takes `r_ssao_slices` for this thread and puts it back at its default
15174 /// when the guard drops.
15175 ///
15176 /// [`ssao_blur_switch`]'s shape exactly, for its reason: a plain
15177 /// `cargo test` run shares one process between tests, and a variable this
15178 /// one left moved is a frame the next test did not ask for.
15179 fn ssao_slice_switch() -> SsaoSliceSwitch {
15180 let guard = SSAO_SLICE_SWITCH
15181 .lock()
15182 .unwrap_or_else(std::sync::PoisonError::into_inner);
15183 let switch = SsaoSliceSwitch { _guard: guard };
15184 switch.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15185 switch
15186 }
15187
15188 /// What [`ssao_slice_switch`] hands back.
15189 struct SsaoSliceSwitch {
15190 _guard: std::sync::MutexGuard<'static, ()>,
15191 }
15192
15193 impl SsaoSliceSwitch {
15194 /// Asks each pixel for `slices` of them.
15195 fn set(&self, slices: i64) {
15196 crate::ssao::r_ssao_slices
15197 .set(&crcbl_console::Value::Int(slices))
15198 .expect("`r_ssao_slices` is a writable int in range");
15199 }
15200 }
15201
15202 impl Drop for SsaoSliceSwitch {
15203 fn drop(&mut self) {
15204 // Back to the shipping count at both ends, so a check that panicked
15205 // mid-way does not hand the next holder a four-slice frame — which
15206 // is a frame every golden in this workspace was blessed without.
15207 self.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15208 }
15209 }
15210
15211 /// [`ssao_slice_switch`]'s lock.
15212 static SSAO_SLICE_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15213
15214 /// Takes `r_ssao_technique` for this thread and puts it back at its default
15215 /// when the guard drops.
15216 ///
15217 /// [`ssao_blur_switch`]'s shape exactly, for its reason — and this one moves
15218 /// a **pipeline** rather than a lane of a uniform block, so a frame that
15219 /// picked it up from another thread's test gathers through a shader that
15220 /// test never selected.
15221 ///
15222 /// **Its lock lives in `crate::ssao`** rather than beside this function, and
15223 /// it is the one switch here whose does: `ssao`'s own
15224 /// `the_seams_other_side_is_the_technique_that_ships` moves the same
15225 /// variable, and a second mutex would serialise neither against the other.
15226 /// See `crate::ssao::TECHNIQUE_SWITCH` for where it sits in the order.
15227 fn ssao_technique_switch() -> SsaoTechniqueSwitch {
15228 let guard = crate::ssao::TECHNIQUE_SWITCH
15229 .lock()
15230 .unwrap_or_else(std::sync::PoisonError::into_inner);
15231 let switch = SsaoTechniqueSwitch { _guard: guard };
15232 switch.set(shipped_technique_name());
15233 switch
15234 }
15235
15236 /// The technique name the chain ships, and the one
15237 /// [`ssao_technique_switch`] restores.
15238 ///
15239 /// **Read off the variable rather than written down**, which is
15240 /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
15241 /// rule about the slice count and for its reason: which value ships is a
15242 /// thing that moves, and a test naming the wrong one would be comparing the
15243 /// shipped configuration against itself.
15244 ///
15245 /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
15246 fn shipped_technique_name() -> &'static str {
15247 match crate::ssao::r_ssao_technique.default() {
15248 crcbl_console::Value::Enum(name) => name,
15249 other => panic!("`r_ssao_technique` defaults to {other:?}, not to a technique name"),
15250 }
15251 }
15252
15253 /// A name from the variable's own set that is **not** the one it ships.
15254 ///
15255 /// [`shipped_technique_name`]'s clause from the other side: the tests below
15256 /// need a technique to move the console to, and picking it out of the
15257 /// declared set is what keeps them from naming one the variable does not
15258 /// offer — or, if a third arrived, from silently going on comparing the
15259 /// same two.
15260 fn other_technique_name() -> &'static str {
15261 let crcbl_console::Kind::Enum(names) = crate::ssao::r_ssao_technique.kind() else {
15262 panic!("`r_ssao_technique` is an enum variable");
15263 };
15264 let ships = shipped_technique_name();
15265 names
15266 .iter()
15267 .copied()
15268 .find(|name| *name != ships)
15269 .expect("`r_ssao_technique` offers a technique other than the one it ships")
15270 }
15271
15272 /// What [`ssao_technique_switch`] hands back.
15273 struct SsaoTechniqueSwitch {
15274 _guard: std::sync::MutexGuard<'static, ()>,
15275 }
15276
15277 impl SsaoTechniqueSwitch {
15278 /// Asks for the gather `name` selects.
15279 fn set(&self, name: &'static str) {
15280 crate::ssao::r_ssao_technique
15281 .set(&crcbl_console::Value::Enum(name))
15282 .expect("`r_ssao_technique` is a writable enum in the set");
15283 }
15284 }
15285
15286 impl Drop for SsaoTechniqueSwitch {
15287 fn drop(&mut self) {
15288 // Back to what ships at both ends, so a check that panicked mid-way
15289 // does not hand the next holder a frame gathered through the cheap
15290 // tier — which is a frame no golden in this workspace was blessed
15291 // on.
15292 self.set(shipped_technique_name());
15293 }
15294 }
15295
15296 /// Every draw the recorded stream holds, whichever call recorded it.
15297 ///
15298 /// Not scoped to a pass, unlike [`commands_in_pass`]: what
15299 /// [`ForwardRenderer::counters`] claims is a count over the *whole* frame, so
15300 /// the thing to compare it against is the whole frame.
15301 fn recorded_draws(recorder: &Recorder) -> usize {
15302 use crcbl_hal::null::Command;
15303
15304 recorder
15305 .commands()
15306 .into_iter()
15307 .filter(|command| {
15308 matches!(
15309 command,
15310 Command::Draw { .. }
15311 | Command::DrawIndexed { .. }
15312 | Command::DrawIndirect(_)
15313 | Command::DrawIndexedIndirect(_)
15314 | Command::DrawIndirectCount(_)
15315 | Command::DrawIndexedIndirectCount(_)
15316 | Command::DrawMeshTasks { .. }
15317 | Command::DrawMeshTasksIndirect(_)
15318 )
15319 })
15320 .count()
15321 }
15322
15323 /// **The draw count is what the frame recorded, and the two GPU-side
15324 /// counters are `None` rather than a guess.**
15325 ///
15326 /// Both halves matter and both are checked here against something that
15327 /// moves. The draws are compared with the recorded stream, so a count that
15328 /// forgot the shadow pass's share or the tonemap's triangle fails. The
15329 /// instances are read before and after a pyramid is put in the pool, so a
15330 /// counter wired to a constant — or to the pool's *capacity*, which does not
15331 /// move — fails too.
15332 ///
15333 /// `drawn` and `triangles` are asserted [`None`] **on the frames this test
15334 /// runs**, which are inside [`CULL_STATS_FLOOR`]: nothing has come
15335 /// back off the GPU yet, and a `drawn` that was `Some` here would be a
15336 /// number invented before any readback landed. That is the assertion that
15337 /// catches the tempting version of this method: an instance count taken from
15338 /// the pool and reported as "drawn" would read as a culling win of exactly
15339 /// zero on every frame, which is the number the whole cull exists to change.
15340 /// What happens once the ring *has* come round is the test below.
15341 #[test]
15342 fn the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know() {
15343 let _blurs = ssao_blur_switch();
15344 let (recorder, device, queue) = open();
15345 let mut renderer =
15346 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15347
15348 // Before any frame: nothing recorded, and said as a known zero.
15349 assert_eq!(renderer.counters(), FrameCounters::default());
15350
15351 let first = frame(device.as_ref(), &mut renderer, queue);
15352 let counters = renderer.counters();
15353 assert_eq!(
15354 counters.draws,
15355 recorded_draws(&recorder) as u64,
15356 "the counter and the frame's recorded draws disagree",
15357 );
15358 // Derived from what the frame resolved rather than from a constant, so
15359 // this is still the every-effect frame's count and would follow a frame
15360 // that switched one off.
15361 let fullscreen = fullscreen_passes(
15362 renderer.effects(),
15363 TEST_EXTENT,
15364 false,
15365 renderer.frame_ssao_blurs,
15366 ) * FULLSCREEN_DRAWS;
15367 assert!(
15368 counters.draws > fullscreen,
15369 "a frame that recorded only its full-screen passes drew no scene",
15370 );
15371 assert_eq!(
15372 counters.instances,
15373 renderer.instances.len() as u64 + fullscreen,
15374 );
15375 assert_eq!(
15376 counters.drawn, None,
15377 "the ring has not come round, so there is no survivor count yet",
15378 );
15379 assert_eq!(counters.cull_frame, None, "and no frame to stamp it with");
15380 assert_eq!(counters.triangles, None);
15381 first.release(device.as_ref());
15382
15383 // A second scene: one more instance in the pool, and the counter moves
15384 // with it. The draws do not — one call per bucket whatever the scene
15385 // holds is what §3.3 is about, and this is where that shows.
15386 place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, Mat4::IDENTITY);
15387 recorder.clear();
15388 let second = frame(device.as_ref(), &mut renderer, queue);
15389 let richer = renderer.counters();
15390 assert_eq!(
15391 richer.instances,
15392 counters.instances + 1,
15393 "an instance added to the pool must move the counter",
15394 );
15395 assert_eq!(
15396 richer.draws, counters.draws,
15397 "the recorded call count is independent of what the scene holds",
15398 );
15399 assert_eq!(richer.draws, recorded_draws(&recorder) as u64);
15400
15401 second.finish(device.as_ref(), renderer);
15402 }
15403
15404 /// **Once the ring has come round, `drawn` is a number and it says which
15405 /// frame it is from.**
15406 ///
15407 /// The other half of the test above: `indirect` while the readback is in
15408 /// flight, a count afterwards, and a `cull_frame` naming a frame several
15409 /// behind the one just recorded. The null backend executes no copy, so the
15410 /// *value* here is the full-screen passes' own draws and nothing else — what the cull
15411 /// really kept is asserted against a real GPU, in the umbrella crate's
15412 /// `tests/draw_gen_e2e/`, where a scene is culled on purpose.
15413 ///
15414 /// The frame number is the assertion with teeth here: a ring that read the
15415 /// slot it had just written would report the frame it is on, and a
15416 /// `cull_frame` left at `None` would put a latent number on the panel with
15417 /// nothing to say how old it is.
15418 #[test]
15419 fn the_culling_counters_arrive_a_few_frames_late_and_say_which_frame() {
15420 let (_recorder, device, queue) = open();
15421 let mut renderer =
15422 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15423
15424 let mut frames = Vec::new();
15425 for _ in 0..CULL_STATS_FLOOR {
15426 frames.push(frame(device.as_ref(), &mut renderer, queue));
15427 assert_eq!(
15428 renderer.counters().drawn,
15429 None,
15430 "no readback has even been polled yet, so there is nothing back",
15431 );
15432 }
15433
15434 frames.push(frame(device.as_ref(), &mut renderer, queue));
15435 let counters = renderer.counters();
15436 assert_eq!(
15437 counters.drawn,
15438 Some(
15439 fullscreen_passes(
15440 renderer.effects(),
15441 TEST_EXTENT,
15442 false,
15443 renderer.frame_ssao_blurs,
15444 ) * FULLSCREEN_DRAWS,
15445 ),
15446 "the survivor count the null backend produced is zero, plus one instance per \
15447 full-screen pass — which is on both sides of the row",
15448 );
15449 assert_eq!(
15450 counters.cull_frame,
15451 Some(1),
15452 "the report is the frame whose copy answered, not the frame just recorded",
15453 );
15454 assert_eq!(renderer.cull_stats().expect("a readback answered").frame, 1,);
15455
15456 for frame in frames {
15457 frame.release(device.as_ref());
15458 }
15459 renderer.destroy(device.as_ref());
15460 }
15461
15462 /// The frames a culling counter cannot possibly have arrived in.
15463 ///
15464 /// Two: the copy is recorded on one frame and the readback for it requested
15465 /// on the next, so the earliest frame that can poll anything is the third.
15466 /// A device that answers its first poll — the null backend, and every native
15467 /// one — reports there; a browser answers later, which is why this is a
15468 /// floor rather than a latency. See [`crate::cull_stats`].
15469 const CULL_STATS_FLOOR: usize = 2;
15470
15471 /// **A light that takes a shadow tile moves the draw count**, because the
15472 /// shadow pass records one call per bucket per occupied view.
15473 ///
15474 /// The observable a `recorded_draws` comparison alone would miss: a
15475 /// `counters` that counted only the colour pass and the tonemap agrees with
15476 /// nothing here, and one that hard-coded the cascades agrees with the first
15477 /// frame and not the second.
15478 #[test]
15479 fn a_light_that_takes_a_shadow_tile_moves_the_draw_count() {
15480 let (recorder, device, queue) = open();
15481 let mut renderer =
15482 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15483
15484 let dark = frame(device.as_ref(), &mut renderer, queue);
15485 let without = renderer.counters().draws;
15486 assert_eq!(without, recorded_draws(&recorder) as u64);
15487 dark.release(device.as_ref());
15488
15489 renderer.set_lights(&[shadowable_spot(0.0)]);
15490 recorder.clear();
15491 let lit = frame(device.as_ref(), &mut renderer, queue);
15492 let with = renderer.counters().draws;
15493 assert!(
15494 with > without,
15495 "a shadow-casting light adds a view and therefore draws: {with} against {without}",
15496 );
15497 assert_eq!(
15498 with,
15499 recorded_draws(&recorder) as u64,
15500 "and the counter still matches the stream",
15501 );
15502 lit.finish(device.as_ref(), renderer);
15503 }
15504
15505 /// Opens a null device offering `optional` on top of the mesh path, and
15506 /// asserts it really selected that path.
15507 ///
15508 /// Asked for rather than merely reported, because a device grants what it
15509 /// enabled: leaving mesh shaders out of the optional set opens a device on
15510 /// an indirect tail and tests nothing.
15511 ///
15512 /// The adapter has [`Features::DRAW_INDEX`] too, which a device is granted
15513 /// only where `optional` asks for it — so a test that does not gets the
15514 /// mesh tail's call per bucket.
15515 fn open_mesh_path(recorder: &Recorder, optional: Features) -> (Box<dyn Device>, QueueHandle) {
15516 let caps = crcbl_hal::DeviceCaps {
15517 features: Features::GPU_DRIVEN
15518 | Features::MESH_SHADER
15519 | Features::TASK_SHADER
15520 | Features::DRAW_INDEX,
15521 limits: crcbl_hal::Limits::desktop(),
15522 };
15523 let instance = NullInstance::new(caps).with_recorder(recorder.clone());
15524 let adapter = instance.adapters().remove(0);
15525 assert_eq!(
15526 instance
15527 .adapter_caps(adapter.id)
15528 .expect("the null backend describes its adapter")
15529 .geometry_path(),
15530 GeometryPath::MeshShader,
15531 "a device with mesh shaders selects them, which is the case this is about"
15532 );
15533 let device = instance
15534 .create_device(&DeviceDesc {
15535 label: None,
15536 adapter: adapter.id,
15537 required_features: Features::COMPUTE,
15538 optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER | optional,
15539 compatible_surface: None,
15540 })
15541 .expect("the null backend always opens");
15542 assert_eq!(
15543 device.caps().geometry_path(),
15544 GeometryPath::MeshShader,
15545 "and the opened device still selects it"
15546 );
15547 let queue = device.queue(QueueKind::Graphics).expect("always present");
15548 (device, queue)
15549 }
15550
15551 /// **The four material pages are created with the format their contents
15552 /// call for, and it is only a *colour* that is sRGB.**
15553 ///
15554 /// Topic 44's rung 2 calls this the classic PBR bug and
15555 /// says why it survives review: a base-colour texel and an emissive one are
15556 /// sRGB-encoded *colours*, which is what glTF defines them as, and a normal
15557 /// texel and a packed occlusion-roughness-metallic one are *numbers* — so
15558 /// decoding either of those through the sRGB curve is wrong by a gamma and
15559 /// looks merely like a surface bumpier or shinier than the author drew.
15560 /// Nothing in a frame reports it, no golden comparison can name it, and the
15561 /// four constants sit a few lines apart with the wrong one compiling.
15562 ///
15563 /// So this is the whole guard, and it is three claims rather than one: that
15564 /// each constant is the one it should be, that
15565 /// [`PageKind::format`] — which is what the upload loop actually calls —
15566 /// answers with it, and, the half that would otherwise be a check that
15567 /// cannot fail, that the format each page is *created* with is the format
15568 /// its `ImportedImage` declares. A declaration naming a format the image is
15569 /// not in picks the wrong aspects in a barrier.
15570 #[test]
15571 fn the_page_formats_split_colour_from_number() {
15572 assert_eq!(BASE_COLOR_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15573 assert_eq!(EMISSIVE_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15574 assert_eq!(NORMAL_PAGE_FORMAT, Format::Rgba8Unorm);
15575 assert_eq!(MRO_PAGE_FORMAT, Format::Rgba8Unorm);
15576 // Through the dispatch the upload loop actually calls, rather than the
15577 // constants alone: one loop creates every image now, and a `format` arm
15578 // pointed at the wrong constant is the way that loop gets it wrong.
15579 assert_eq!(PageKind::BaseColor.format(), BASE_COLOR_PAGE_FORMAT);
15580 assert_eq!(PageKind::Normal.format(), NORMAL_PAGE_FORMAT);
15581 assert_eq!(
15582 PageKind::MetallicRoughnessOcclusion.format(),
15583 MRO_PAGE_FORMAT
15584 );
15585 assert_eq!(PageKind::Emissive.format(), EMISSIVE_PAGE_FORMAT);
15586 assert_ne!(
15587 BASE_COLOR_PAGE_FORMAT, NORMAL_PAGE_FORMAT,
15588 "a normal page created sRGB decodes every texel through a gamma it never had"
15589 );
15590 assert_ne!(
15591 EMISSIVE_PAGE_FORMAT, MRO_PAGE_FORMAT,
15592 "a packed roughness page created sRGB shades every surface smoother than authored"
15593 );
15594
15595 let (recorder, device, queue) = open();
15596 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15597 .expect("the forward renderer builds on the null backend");
15598 assert_eq!(
15599 renderer.base_color_page_import().format,
15600 BASE_COLOR_PAGE_FORMAT
15601 );
15602 assert_eq!(renderer.normal_page_import().format, NORMAL_PAGE_FORMAT);
15603 assert_eq!(renderer.mro_page_import().format, MRO_PAGE_FORMAT);
15604 assert_eq!(renderer.emissive_page_import().format, EMISSIVE_PAGE_FORMAT);
15605 // And they really are four images, not one bound four times — which is
15606 // the other way a page could be "linear" and still be sampled through
15607 // the sRGB one.
15608 let created = [
15609 renderer.base_color_page(),
15610 renderer.normal_page(),
15611 renderer.mro_page(),
15612 renderer.emissive_page(),
15613 ];
15614 for (at, page) in created.iter().enumerate() {
15615 for other in &created[at + 1..] {
15616 assert_ne!(page.image, other.image, "two page kinds share one image");
15617 assert_ne!(page.view, other.view, "two page kinds share one view");
15618 }
15619 }
15620 // The labels come off the recorder rather than off the handles, so this
15621 // is evidence about what the device was asked to create.
15622 let images: Vec<String> = recorder
15623 .events()
15624 .into_iter()
15625 .filter_map(|event| match event {
15626 Event::Created {
15627 kind: ObjectKind::Image,
15628 label: Some(label),
15629 } => Some(label),
15630 _ => None,
15631 })
15632 .collect();
15633 for kind in PageKind::ALL {
15634 let page = kind.upload_label();
15635 assert!(
15636 images.iter().any(|label| label == page),
15637 "no image was created for the {page} page, and it is {images:?} that were"
15638 );
15639 }
15640 renderer.destroy(device.as_ref());
15641 }
15642
15643 /// Compare native argument indices from the shipped entry points with the
15644 /// actual renderer layout. A shared fragment buffer must have the same index
15645 /// even when geometry introduces additional resources in another module.
15646 #[test]
15647 fn mesh_pipeline_buffers_match_native_shader_arguments() {
15648 for optional in [Features::TASK_SHADER, Features::empty()] {
15649 let recorder = Recorder::new();
15650 let (device, queue) = open_mesh_path(&recorder, optional);
15651 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15652 .expect("the mesh renderer builds");
15653 let (_, entries) = recorder
15654 .bind_group_layouts_created()
15655 .into_iter()
15656 .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
15657 .expect("the actual mesh layout");
15658 let mut buffers: Vec<_> = entries
15659 .iter()
15660 .filter(|entry| {
15661 matches!(
15662 entry.kind,
15663 BindingKind::UniformBuffer { .. } | BindingKind::StorageBuffer { .. }
15664 )
15665 })
15666 .collect();
15667 buffers.sort_by_key(|entry| entry.binding);
15668 assert_eq!(buffers.len(), 20, "the native buffer budget is unchanged");
15669 for (source, shader, names) in [
15670 (
15671 include_str!("../../crcbl-shaders/shaders/mesh.slang"),
15672 &MESH,
15673 &["fragmentMain"][..],
15674 ),
15675 (
15676 include_str!("../../crcbl-shaders/shaders/mesh_cluster.slang"),
15677 &MESH_CLUSTER,
15678 &["meshMain", "taskMain", "amplifiedMeshMain"][..],
15679 ),
15680 ] {
15681 let declarations: Vec<_> = source.lines().collect();
15682 let bindings: Vec<_> = declarations
15683 .windows(2)
15684 .filter_map(|lines| {
15685 let binding = lines[0]
15686 .trim()
15687 .strip_prefix("[[vk::binding(")?
15688 .split(',')
15689 .next()?
15690 .parse::<u32>()
15691 .ok()?;
15692 // The name is the last word before the D3D12 register.
15693 let name = lines[1]
15694 .split(" D3D12_REGISTER(")
15695 .next()?
15696 .split_whitespace()
15697 .last()?
15698 .trim_end_matches(';');
15699 Some((name, binding))
15700 })
15701 .collect();
15702 for name in names {
15703 let signature = shader
15704 .msl()
15705 .expect("committed native shader")
15706 .lines()
15707 .find(|line| line.starts_with("[[") && line.contains(&format!(" {name}(")))
15708 .expect("native entry signature");
15709 let mut checked = 0;
15710 for argument in signature.split(", ") {
15711 let Some((declaration, tail)) = argument.split_once(" [[buffer(") else {
15712 continue;
15713 };
15714 let native: usize = tail.split(')').next().unwrap().parse().unwrap();
15715 let variable = declaration.split_whitespace().last().unwrap();
15716 let variable = variable.rsplit_once('_').map_or(variable, |(base, _)| base);
15717 let binding = bindings
15718 .iter()
15719 .find(|(candidate, _)| *candidate == variable)
15720 .unwrap_or_else(|| panic!("unknown {name} buffer {variable}"))
15721 .1;
15722 let expected = buffers
15723 .iter()
15724 .position(|entry| entry.binding == binding)
15725 .expect("shader binding exists in the renderer layout");
15726 assert_eq!(
15727 native, expected,
15728 "{name}: {variable}, logical binding {binding}, native shader vs global layout"
15729 );
15730 checked += 1;
15731 }
15732 assert!(
15733 checked >= 10,
15734 "entry parsing must cover the complete buffer interface"
15735 );
15736 }
15737 }
15738 renderer.destroy(device.as_ref());
15739 }
15740 }
15741
15742 #[test]
15743 fn the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage() {
15744 let mut declared: Vec<Vec<(u32, BindingKind)>> = Vec::new();
15745 for optional in [Features::TASK_SHADER, Features::empty()] {
15746 let recorder = Recorder::new();
15747 let (device, queue) = open_mesh_path(&recorder, optional);
15748 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15749 .expect("the forward renderer builds on both device shapes");
15750 assert_eq!(
15751 renderer.culls_clusters(),
15752 optional.contains(Features::TASK_SHADER),
15753 "the two arms must actually differ, or this compares a device with itself"
15754 );
15755 let (label, entries) = recorder
15756 .bind_group_layouts_created()
15757 .into_iter()
15758 .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
15759 .expect("the mesh pass declares its layout by name");
15760 assert_eq!(label.as_deref(), Some(MESH_LAYOUT_LABEL));
15761 declared.push(
15762 entries
15763 .iter()
15764 .map(|entry| (entry.binding, entry.kind))
15765 .collect(),
15766 );
15767 }
15768
15769 let [amplified, plain] = declared
15770 .try_into()
15771 .unwrap_or_else(|_| unreachable!("two arms were run"));
15772 assert_eq!(
15773 amplified, plain,
15774 "the mesh layout's bindings changed with the task stage, which moves every Metal \
15775 argument-table index above the difference"
15776 );
15777 // These mesh declarations remain present without a task stage.
15778 for binding in [
15779 CLUSTER_CULL_BINDING,
15780 CLUSTER_CULL_STATS_BINDING,
15781 CLUSTER_SELECT_BINDING,
15782 CLUSTER_SELECTION_BINDING,
15783 CLUSTER_GROUP_STATE_BINDING,
15784 ] {
15785 assert!(
15786 plain.iter().any(|(number, _)| *number == binding),
15787 "binding {binding} is declared by mesh_cluster.slang and must be in the layout"
15788 );
15789 }
15790 // Logical gaps consume no native slots. The complete shader union must
15791 // remain sorted, and every mesh-only buffer follows the fragment prefix.
15792 let numbers: Vec<u32> = plain.iter().map(|(binding, _)| *binding).collect();
15793 let expected: Vec<u32> = (0..=8).chain(15..=16).chain(20..=40).collect();
15794 assert_eq!(
15795 numbers, expected,
15796 "the complete sparse shader binding union"
15797 );
15798 }
15799
15800 /// **`Features::TASK_SHADER` is what decides whether §3.5's per-cluster cull
15801 /// is built, and a device without it still draws.**
15802 ///
15803 /// The two capabilities are separate, and the adapter above offers both — so
15804 /// asking for one and not the other is a device state a real driver has and
15805 /// this can reach. Neither arm is a skip:
15806 ///
15807 /// * With the task stage, the renderer builds the amplification stage and
15808 /// [`ForwardRenderer::culls_clusters`] says so. The null backend refuses a
15809 /// task stage on a device without the flag, so an arm that computed this
15810 /// wrongly would fail to build rather than pass quietly. It records one
15811 /// flat call per partition — [`flat_dispatch_calls`].
15812 /// * Without it, the renderer builds `meshMain` — the un-amplified entry
15813 /// point — and draws every cluster of every surviving instance, one
15814 /// indirect dispatch per bucket reading its own extents.
15815 #[test]
15816 fn the_task_stage_is_built_only_where_the_device_has_one() {
15817 use crcbl_hal::null::Command;
15818
15819 for (optional, expected) in [(Features::TASK_SHADER, true), (Features::empty(), false)] {
15820 let recorder = Recorder::new();
15821 let (device, queue) = open_mesh_path(&recorder, optional);
15822 let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15823 .expect("the forward renderer builds on both device shapes");
15824 assert_eq!(
15825 device.caps().supports(Features::TASK_SHADER),
15826 expected,
15827 "the device must actually differ between the arms, or both test the same thing"
15828 );
15829 assert_eq!(
15830 renderer.culls_clusters(),
15831 expected,
15832 "the amplification stage is built exactly where the device has one"
15833 );
15834 assert_eq!(
15835 renderer.geometry_path(),
15836 GeometryPath::MeshShader,
15837 "both arms are the mesh path; only the stage in front of it differs"
15838 );
15839
15840 let frame = frame(device.as_ref(), &mut renderer, queue);
15841 // After the frame, because the buffer named is the slot the frame
15842 // rotated to — asking before it names the previous slot's ring
15843 // entry and the comparison is against a buffer nothing drew from.
15844 let expected = if expected {
15845 flat_dispatch_calls(&renderer, crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED).0
15846 } else {
15847 mesh_dispatch_calls(&renderer)
15848 };
15849
15850 let dispatched: Vec<DrawIndirect> = commands_in_pass(&recorder, "forward")
15851 .into_iter()
15852 .filter_map(|command| match command {
15853 Command::DrawMeshTasksIndirect(draw) => Some(draw),
15854 _ => None,
15855 })
15856 .collect();
15857 assert_eq!(
15858 dispatched, expected,
15859 "a flat call per partition behind the stage, and a dispatch per bucket reading \
15860 its own extents without it"
15861 );
15862
15863 frame.finish(device.as_ref(), renderer);
15864 }
15865 }
15866
15867 /// The flat calls a pass splitting the bucket table by the material-mode
15868 /// bits `key` records behind a task stage, in region 0, in partition order
15869 /// — one per segment the table holds buckets of — and each segment's first
15870 /// bucket, whose block the call binds.
15871 ///
15872 /// The offsets from [`crcbl_shaders::draw_gen::flat_args_word`] over the
15873 /// camera generator's own region count rather than from
15874 /// `DrawGen::flat_args_offset`, for [`mesh_dispatch_calls`]' reason.
15875 fn flat_dispatch_calls(renderer: &ForwardRenderer, key: u32) -> (Vec<DrawIndirect>, Vec<u32>) {
15876 let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
15877 let buckets = u32::try_from(renderer.bucket_constants.len()).expect("a few buckets");
15878 let regions = renderer.primary.draws.mode().regions();
15879 let segments = crcbl_shaders::draw_gen::flat_segments(&renderer.bucket_modes);
15880 let values: Vec<u32> = if key == crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED {
15881 vec![0, key]
15882 } else {
15883 DEPTH_MODES.to_vec()
15884 };
15885 values
15886 .into_iter()
15887 .filter(|value| {
15888 renderer
15889 .bucket_modes
15890 .iter()
15891 .any(|mode| mode & key == *value)
15892 })
15893 .map(|value| {
15894 let segment = crcbl_shaders::draw_gen::flat_segment(key, value)
15895 .expect("a split every pass makes");
15896 (
15897 DrawIndirect {
15898 args: renderer.primary.draws.mesh_args(renderer.frame),
15899 offset: u64::from(crcbl_shaders::draw_gen::flat_args_word(
15900 buckets, regions, 0, segment, 0,
15901 )) * 4,
15902 draw_count: 1,
15903 stride,
15904 },
15905 segments[segment as usize].0,
15906 )
15907 })
15908 .unzip()
15909 }
15910
15911 /// The [`DrawIndirect`] the mesh path must record for each bucket, in bucket
15912 /// order.
15913 ///
15914 /// Built from the buffer the draw-argument pass writes and the stride the
15915 /// APIs fixed, so a test comparing against it is asserting that the call
15916 /// reads *this frame's* arguments at *this bucket's* offset — the two ways
15917 /// an indirect dispatch goes wrong while still dispatching something.
15918 ///
15919 /// **The offsets are multiplied out here rather than asked of
15920 /// [`DrawGen::mesh_args_offset`]**, which is the difference between a
15921 /// comparison and a tautology: an offset function that returned zero for
15922 /// every bucket would agree with itself, and three calls onto one structure
15923 /// is a frame that draws one bucket's geometry three times.
15924 fn mesh_dispatch_calls(renderer: &ForwardRenderer) -> Vec<DrawIndirect> {
15925 let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
15926 // The extents share a buffer with the one draw count per bucket that
15927 // precedes them, so every offset is that far in. Written out from the
15928 // bucket count here rather than taken from `DrawGen::mesh_args_offset`,
15929 // for the reason above: a base of zero is exactly the mistake this
15930 // comparison exists to catch, and it would agree with itself.
15931 let counts_bytes = renderer.bucket_constants.len() as u64 * 4;
15932 (0..renderer.bucket_constants.len())
15933 .map(|bucket| DrawIndirect {
15934 args: renderer.primary.draws.mesh_args(renderer.frame),
15935 offset: counts_bytes + bucket as u64 * u64::from(stride),
15936 draw_count: 1,
15937 stride,
15938 })
15939 .collect()
15940 }
15941
15942 /// **A device selecting [`GeometryPath::MeshShader`] draws through a mesh
15943 /// pipeline, and records no indirect draw and no index-buffer bind at all.**
15944 ///
15945 /// The three halves are one claim. That it dispatched says the path is
15946 /// wired; that it recorded *no* `DrawIndexedIndirect` of either kind says it
15947 /// did not quietly fall through to a tail that draws the same picture; and
15948 /// that it bound no index buffer says the geometry really came out of the
15949 /// cluster records rather than out of the index pool. Until 2026-08 this
15950 /// device degraded and logged that it had, which is exactly the shape —
15951 /// "not implemented" arriving as a passing frame — the three together rule
15952 /// out.
15953 ///
15954 /// **The extents are not here to be checked, and that is the point.** They
15955 /// are three words the draw-argument pass writes, so what this can pin is
15956 /// the call reading *this* bucket's structure out of *this* frame's buffer
15957 /// — and the CPU-side half of the x extent, the per-bucket cluster table
15958 /// the host uploaded, which the null backend keeps the bytes of. What the
15959 /// GPU then makes of it needs a GPU: `crcbl-vk`'s
15960 /// `the_mesh_dispatch_extent_is_the_culled_instance_count` reads the
15961 /// arguments back.
15962 #[test]
15963 fn a_mesh_shader_device_draws_through_a_mesh_pipeline() {
15964 use crcbl_hal::null::Command;
15965
15966 let recorder = Recorder::new();
15967 let caps = crcbl_hal::DeviceCaps {
15968 features: Features::GPU_DRIVEN | Features::MESH_SHADER,
15969 limits: crcbl_hal::Limits::desktop(),
15970 };
15971 let instance = NullInstance::new(caps).with_recorder(recorder.clone());
15972 let adapter = instance.adapters().remove(0);
15973 assert_eq!(
15974 instance
15975 .adapter_caps(adapter.id)
15976 .expect("the null backend describes its adapter")
15977 .geometry_path(),
15978 GeometryPath::MeshShader,
15979 "a device with mesh shaders selects them, which is the case this is about"
15980 );
15981 let device = instance
15982 .create_device(&DeviceDesc {
15983 label: None,
15984 adapter: adapter.id,
15985 required_features: Features::COMPUTE,
15986 // Asked for, because a device reports what it enabled: leaving
15987 // mesh shaders out of the optional set would open a device that
15988 // selects an indirect path outright and test nothing.
15989 optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER,
15990 compatible_surface: None,
15991 })
15992 .expect("the null backend always opens");
15993 assert_eq!(
15994 device.caps().geometry_path(),
15995 GeometryPath::MeshShader,
15996 "and the opened device still selects it"
15997 );
15998 let queue = device.queue(QueueKind::Graphics).expect("always present");
15999 let mut renderer =
16000 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16001 assert_eq!(
16002 renderer.geometry_path(),
16003 GeometryPath::MeshShader,
16004 "the renderer must have *built* the mesh path, not merely been offered it"
16005 );
16006 let frame = frame(device.as_ref(), &mut renderer, queue);
16007 let expected = mesh_dispatch_calls(&renderer);
16008 // The table is written once at build, into a host-visible buffer the
16009 // null backend keeps the bytes of — so it is readable whether or not a
16010 // shader ever ran. It shares that buffer with the four other tables the
16011 // draw-argument pass reads, so the region has to be cut out at the
16012 // offset the renderer told the shader about rather than at zero.
16013 let table_bytes = recorder
16014 .buffer_bytes(renderer.primary.draws.tables())
16015 .expect("the table buffer is one of this recorder's buffers");
16016 let clusters_at = renderer.primary.draws.table_offsets().bucket_clusters_at as usize * 4;
16017 let clusters: Vec<u32> = table_bytes[clusters_at..]
16018 .as_chunks::<4>()
16019 .0
16020 .iter()
16021 .take(renderer.bucket_constants.len())
16022 .map(|word| u32::from_le_bytes(*word))
16023 .collect();
16024
16025 let mut dispatched = Vec::new();
16026 let mut index_binds = 0;
16027 for command in commands_in_pass(&recorder, "forward") {
16028 match command {
16029 Command::DrawMeshTasksIndirect(draw) => dispatched.push(draw),
16030 Command::DrawMeshTasks { .. } => panic!(
16031 "the mesh path recorded a CPU-sized dispatch, which is the extent \
16032 the instance cull is supposed to have taken over"
16033 ),
16034 Command::DrawIndexedIndirectCount(_) | Command::DrawIndexedIndirect(_) => {
16035 panic!(
16036 "the mesh path recorded an indirect draw, which is the silent \
16037 fall-through this test exists to rule out"
16038 )
16039 }
16040 Command::BindIndexBuffer { .. } => index_binds += 1,
16041 _ => {}
16042 }
16043 }
16044 assert_eq!(
16045 dispatched, expected,
16046 "one indirect dispatch per bucket, each reading its own argument structure \
16047 out of this frame's buffer"
16048 );
16049 assert_eq!(
16050 clusters.len(),
16051 renderer.bucket_constants.len(),
16052 "one x extent per bucket: {clusters:?}"
16053 );
16054 assert!(
16055 clusters.iter().all(|&count| count > 0),
16056 "a bucket with no clusters dispatches nothing, whatever the arguments say: \
16057 {clusters:?}"
16058 );
16059 // **The x extents are not all the same number**, which is what makes
16060 // the table a statement about each bucket's own mesh. Two
16061 // single-cluster meshes would let a table hard-coded to one cluster
16062 // pass; the open box is five, one per face.
16063 assert_eq!(
16064 clusters[DEMO_OPEN_BOX] as usize,
16065 crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
16066 "the open box dispatches one workgroup per face, and that is the only \
16067 resident whose cluster count is not one: {clusters:?}"
16068 );
16069 assert_eq!(
16070 index_binds, 0,
16071 "a mesh pipeline has no index buffer; binding one would mean the geometry \
16072 came from the index pool after all"
16073 );
16074
16075 frame.finish(device.as_ref(), renderer);
16076 }
16077
16078 /// **The cull pass is told the camera the frame is drawn with**, and how
16079 /// many array elements to walk.
16080 ///
16081 /// Both halves fail silently: a frustum from a different aspect ratio culls
16082 /// geometry that is on screen, and an instance count short of the pool's
16083 /// high-water mark stops testing the instances above a freed slot. Neither
16084 /// is visible in a picture until something disappears from an edge.
16085 #[test]
16086 fn the_cull_pass_gets_this_frame_s_camera_and_every_occupied_slot() {
16087 let (recorder, device, queue) = open();
16088 let mut renderer =
16089 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16090 // The cube first and the pyramid above it, because the second half of
16091 // this test frees the lower slot and asks what the walk still covers.
16092 let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16093 place_demo(
16094 &mut renderer,
16095 DEMO_PYRAMID,
16096 DEMO_UNTINTED,
16097 Mat4::from_translation(Vec3::X),
16098 );
16099
16100 let camera = Camera {
16101 eye: Vec3::new(1.6, 1.2, 2.2),
16102 ..Camera::default()
16103 };
16104 let extent = (256u32, 192u32);
16105 renderer
16106 .begin_frame(
16107 device.as_ref(),
16108 &camera,
16109 &DirectionalLight::default(),
16110 extent,
16111 )
16112 .expect("write");
16113
16114 let aspect = extent.0 as f32 / extent.1 as f32;
16115 let expected = crate::cull::Frustum::from_view_projection(camera.view_projection(aspect));
16116 let written = recorder
16117 .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16118 .expect("this frame's cull parameters are live");
16119 assert_eq!(
16120 &written[..crcbl_shaders::cull::PARAMS_SIZE],
16121 &crcbl_shaders::cull::Params {
16122 planes: expected.planes.map(|plane| plane.to_array()),
16123 instance_count: 2,
16124 capacity: scene::Capacities::default().instances,
16125 hidden_view: ViewId::PRIMARY.hidden_bit(),
16126 ..crcbl_shaders::cull::Params::default()
16127 }
16128 .to_bytes()[..],
16129 "the cull block must carry this frame's own frustum, the pool's whole \
16130 occupied range, and the visible list's capacity"
16131 );
16132
16133 // And the high-water mark is what is written, not the live count: remove
16134 // the cube and the pyramid above it still has to be tested.
16135 renderer.remove_instance(cube);
16136 renderer
16137 .begin_frame(
16138 device.as_ref(),
16139 &camera,
16140 &DirectionalLight::default(),
16141 extent,
16142 )
16143 .expect("write");
16144 let written = recorder
16145 .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16146 .expect("live");
16147 assert_eq!(
16148 u32::from_le_bytes(written[96..100].try_into().expect("four bytes")),
16149 2,
16150 "one live instance, two occupied slots — a walk of one would never \
16151 reach the pyramid"
16152 );
16153
16154 renderer.destroy(device.as_ref());
16155 recorder.assert_valid();
16156 }
16157
16158 /// **Every counter both compute passes add to is zeroed by a pass of its
16159 /// own, before either of them runs.**
16160 ///
16161 /// The two shaders only ever increment, so a counter carrying the previous
16162 /// frame's total makes a bucket's argument structure claim more instances
16163 /// than its run holds — which draws whatever the run's stale tail happens to
16164 /// name.
16165 ///
16166 /// # This once read the bytes back, and no longer can
16167 ///
16168 /// It used to poison every counter with `0xAB` and assert `begin_frame`
16169 /// had written zeroes over them — the poison being the whole test, because
16170 /// the null backend runs no shader and a counter nothing wrote reads as the
16171 /// zero it was created with. The counters are device-local now, so nothing
16172 /// on the host writes them and [`Recorder::buffer_bytes`] holds nothing for
16173 /// them: the zero is a dispatch inside the frame, and a backend that runs no
16174 /// shader cannot observe it at all.
16175 ///
16176 /// So the poison moved to where a shader actually runs — `crcbl-vk`'s
16177 /// `draw_gen` end-to-end fills them with a sentinel and reads back the
16178 /// generated arguments — and what is checkable *here* is the schedule: that
16179 /// the frame contains the clearing pass, that it writes exactly those
16180 /// buffers, and that the graph orders the two accumulating passes after it.
16181 /// Each of the counts below goes red if a buffer is dropped from the
16182 /// clearing pass, and the pass list goes red if the pass leaves the frame.
16183 #[test]
16184 fn every_frame_starts_from_zeroed_counters() {
16185 let (recorder, device, queue) = open();
16186 let mut renderer =
16187 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16188 place_cube(&mut renderer, Mat4::IDENTITY);
16189 let imported = swapchain_image(device.as_ref());
16190 // Twice round the ring, because a slot cleared only on its first use is
16191 // exactly the failure this is about.
16192 for round in 0..FRAMES_IN_FLIGHT * 2 {
16193 renderer
16194 .begin_frame(
16195 device.as_ref(),
16196 &Camera::default(),
16197 &DirectionalLight::default(),
16198 (64, 48),
16199 )
16200 .expect("write");
16201 let mut graph = crate::RenderGraph::new(queue);
16202 let target = graph.import_image("target", imported);
16203 let pool = crate::TransientPool::new();
16204 renderer.add_passes(&mut graph, &pool, target, (64, 48));
16205 let compiled = graph.compile(&pool).expect("a legal frame");
16206
16207 let clear = &compiled.passes()[0];
16208 assert_eq!(
16209 clear.label(),
16210 "clear-counters",
16211 "round {round}: the zero has to be written before anything adds to it"
16212 );
16213 let barriers = &clear.barriers().buffers;
16214 assert_eq!(
16215 barriers.len(),
16216 3,
16217 "round {round}: the survivor count, the draw arguments, and the buffer \
16218 holding both the draw counts and the mesh-dispatch arguments, and \
16219 nothing else: {barriers:?}"
16220 );
16221 assert!(
16222 barriers
16223 .iter()
16224 .all(|barrier| barrier.to == ResourceState::ShaderReadWrite),
16225 "round {round}: every one of them is written by this pass: {barriers:?}"
16226 );
16227 // The ones the frame leaves as indirect arguments are the two a
16228 // driver reads; the survivor count rests in a shader read. That
16229 // split is what names them without a handle to compare.
16230 assert_eq!(
16231 barriers
16232 .iter()
16233 .filter(|barrier| barrier.from == ResourceState::IndirectArgument)
16234 .count(),
16235 2,
16236 "round {round}: out of the state a draw read them in: {barriers:?}"
16237 );
16238
16239 let after = |label: &str| {
16240 compiled
16241 .passes()
16242 .iter()
16243 .find(|pass| pass.label() == label)
16244 .unwrap_or_else(|| panic!("round {round}: no `{label}` pass"))
16245 .barriers()
16246 .buffers
16247 .iter()
16248 .filter(|barrier| {
16249 barrier.from == ResourceState::ShaderReadWrite
16250 && barrier.to == ResourceState::ShaderReadWrite
16251 })
16252 .count()
16253 };
16254 assert_eq!(
16255 after("cull"),
16256 1,
16257 "round {round}: the survivor count reaches the cull pass's atomic behind a \
16258 barrier on the write that zeroed it"
16259 );
16260 assert_eq!(
16261 after("draw-args"),
16262 4,
16263 "round {round}: and so do the draw arguments and the buffer holding the \
16264 draw counts beside the mesh-dispatch arguments — plus the survivor list, \
16265 which the cull pass has just written and this pass reads through the same \
16266 descriptor it scatters the runs into, and `docs/notes/rendering.md`'s \
16267 hysteresis state, which the clearing pass does *not* zero and which is \
16268 behind the same kind of barrier for the opposite reason: it is the one \
16269 buffer here carrying a value out of the previous frame, so what it needs \
16270 ordering against is that frame rather than this one's clear"
16271 );
16272 // **And the prefix sum and the scatter behind barriers of their own**,
16273 // on every buffer the stage before them wrote. This is what orders
16274 // them on a device that runs undeclared commands in any order — see
16275 // `DrawGen::add_passes` — and what three dispatches in one pass
16276 // silently lacked.
16277 for label in ["draw-starts", "draw-scatter"] {
16278 assert_eq!(
16279 after(label),
16280 4,
16281 "round {round}: `{label}` reads what the pass before it wrote, so every \
16282 buffer they share is ordered behind a barrier"
16283 );
16284 }
16285
16286 // The compiled graph borrows the renderer's pass bodies, so it has
16287 // to go before the next frame borrows the renderer again.
16288 drop(compiled);
16289 }
16290 renderer.destroy(device.as_ref());
16291 device.destroy_image_view(imported.view);
16292 device.destroy_image(imported.image);
16293 recorder.assert_valid();
16294 }
16295
16296 /// **A frame with no instances leaves out every generator's cull and
16297 /// scatter passes**, and keeps the clear and the two stages that write each
16298 /// bucket's arguments.
16299 ///
16300 /// An empty pass is not a harmless no-op on Metal: the backend opens an
16301 /// encoder for every graph pass and strict validation rejects ending one
16302 /// with no work — see `DrawGen::add_passes`. Each count below goes red if
16303 /// an empty pass comes back, or if a pass a zero-draw frame needs drops out.
16304 #[test]
16305 fn a_frame_with_no_instances_omits_the_empty_draw_generation_passes() {
16306 let (recorder, device, queue) = open();
16307 let mut renderer =
16308 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16309 renderer
16310 .begin_frame(
16311 device.as_ref(),
16312 &Camera::default(),
16313 &DirectionalLight::default(),
16314 (64, 48),
16315 )
16316 .expect("write");
16317 let imported = swapchain_image(device.as_ref());
16318 let mut graph = crate::RenderGraph::new(queue);
16319 let target = graph.import_image("target", imported);
16320 let pool = crate::TransientPool::new();
16321 renderer.add_passes(&mut graph, &pool, target, (64, 48));
16322 let compiled = graph.compile(&pool).expect("a legal frame");
16323
16324 let count = |label: &str| {
16325 compiled
16326 .passes()
16327 .iter()
16328 .filter(|pass| pass.label() == label)
16329 .count()
16330 };
16331 // The camera's generator and one per shadow cascade.
16332 let generators = 1 + shadow::CASCADES;
16333 for label in ["clear-counters", "draw-args", "draw-starts"] {
16334 assert_eq!(
16335 count(label),
16336 generators,
16337 "`{label}` still has work with nothing to draw: the clear erases the \
16338 previous frame's counts and the argument stages write zero draws"
16339 );
16340 }
16341 for label in ["cull", "draw-scatter"] {
16342 assert_eq!(
16343 count(label),
16344 0,
16345 "`{label}` has no workgroups to dispatch with no instances"
16346 );
16347 }
16348
16349 drop(compiled);
16350 renderer.destroy(device.as_ref());
16351 device.destroy_image_view(imported.view);
16352 device.destroy_image(imported.image);
16353 recorder.assert_valid();
16354 }
16355
16356 /// **The graph transitions the generated arguments into
16357 /// [`ResourceState::IndirectArgument`] before the draws read them**, and the
16358 /// runs into a shader read.
16359 ///
16360 /// The seam calls this the single most important barrier in a GPU-driven
16361 /// frame and says its absence produces "sometimes nothing draws" — which is
16362 /// exactly the failure a golden image on one driver would not catch. It is
16363 /// asserted on the compiled graph, which is pure and needs no device.
16364 #[test]
16365 fn the_graph_barriers_the_arguments_into_place_before_the_draws() {
16366 let _blurs = ssao_blur_switch();
16367 let (recorder, device, queue) = open();
16368 let mut renderer =
16369 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16370 place_cube(&mut renderer, Mat4::IDENTITY);
16371 renderer
16372 .begin_frame(
16373 device.as_ref(),
16374 &Camera::default(),
16375 &DirectionalLight::default(),
16376 (64, 48),
16377 )
16378 .expect("write");
16379
16380 let imported = swapchain_image(device.as_ref());
16381 let mut graph = crate::RenderGraph::new(queue);
16382 let target = graph.import_image("target", imported);
16383 let pool = crate::TransientPool::new();
16384 renderer.add_passes(&mut graph, &pool, target, (64, 48));
16385 let compiled = graph.compile(&pool).expect("a legal frame");
16386
16387 let passes: Vec<String> = compiled
16388 .passes()
16389 .iter()
16390 .map(|pass| pass.label().to_string())
16391 .collect();
16392 // The camera's five compute passes and topic 18's clustering dispatch,
16393 // then five per shadow cascade, then the depth-only pass they feed and
16394 // the colour pass that samples it.
16395 //
16396 // **The clustering pass is after the camera's clearing dispatch**, and
16397 // that is the ordering the overflow counter depends on: the clearing
16398 // pass zeroes the statistics word this one adds to, and both declare
16399 // the same buffer, so the graph is what puts the barrier between them.
16400 let mut expected: Vec<String> = Vec::new();
16401 for cascade in 0..=shadow::CASCADES {
16402 expected.extend(
16403 [
16404 "clear-counters",
16405 "cull",
16406 "draw-args",
16407 "draw-starts",
16408 "draw-scatter",
16409 ]
16410 .into_iter()
16411 .map(str::to_string),
16412 );
16413 if cascade == 0 {
16414 expected.push("light-cluster".to_string());
16415 }
16416 }
16417 // And the culling-statistics copy **last**, after every pass that adds
16418 // to the buffer it reads — the cull dispatch, the clustering pass and
16419 // the amplification stage inside the colour pass.
16420 expected.extend(
16421 [
16422 "shadow",
16423 "depth-prepass",
16424 "ssao",
16425 "ssao-blur",
16426 // The reconstruction that ends the occlusion chain, between the
16427 // blur it reads and the pass that binds what it wrote — see
16428 // [`crate::ssao`]'s header on why the first two run smaller than
16429 // the frame and this one does not.
16430 "ssao-upsample",
16431 "forward",
16432 // The pyramid the march climbs, between the pass that wrote
16433 // level 0 and the pass that reads the chain. Two levels at this
16434 // extent, written out for the reason `crate::bloom`'s chain is
16435 // in the toggle test below: a table generated from
16436 // `crate::hiz::levels_for` could not fail.
16437 "hiz-1",
16438 "hiz-2",
16439 "ssr",
16440 "ssr-blur",
16441 "tonemap",
16442 // The resolve `RenderEffects::DEFAULT_STACK` carries, which is
16443 // CMAA2's three rather than FXAA's one —
16444 // `each_effect_toggle_removes_exactly_the_passes_it_owns` is
16445 // where the swap between the two tiers is pinned.
16446 "cmaa2-edges",
16447 "cmaa2-shapes",
16448 "cmaa2-apply",
16449 "cull-stats-readback",
16450 ]
16451 .into_iter()
16452 .map(str::to_string),
16453 );
16454 assert_eq!(
16455 passes, expected,
16456 "each cull's five compute passes come first, and in that order"
16457 );
16458
16459 // **The depth prepass, not the colour pass**, and that is what says the
16460 // prepass really is the first thing to draw from the camera's cull: it is
16461 // where the draw buffers leave the compute pass's writes. The colour pass
16462 // below then needs none of these, because they are already in the state it
16463 // wants — which is the assertion after it.
16464 let prepass = compiled
16465 .passes()
16466 .iter()
16467 .find(|pass| pass.label() == "depth-prepass")
16468 .expect("the pass list above");
16469 let into_indirect = prepass
16470 .barriers()
16471 .buffers
16472 .iter()
16473 .filter(|barrier| barrier.to == ResourceState::IndirectArgument)
16474 .count();
16475 assert_eq!(
16476 into_indirect,
16477 2,
16478 "the arguments and the count, out of the compute pass's writes and into \
16479 the state a draw reads them in: {:?}",
16480 prepass.barriers().buffers
16481 );
16482 assert!(
16483 prepass.barriers().buffers.iter().any(|barrier| {
16484 barrier.from == ResourceState::ShaderReadWrite
16485 && barrier.to == ResourceState::ShaderRead
16486 }),
16487 "and the runs, which the vertex stage reads: {:?}",
16488 prepass.barriers().buffers
16489 );
16490
16491 let forward = compiled
16492 .passes()
16493 .iter()
16494 .find(|pass| pass.label() == "forward")
16495 .expect("the pass list above");
16496 assert!(
16497 forward
16498 .barriers()
16499 .buffers
16500 .iter()
16501 .all(|barrier| barrier.to != ResourceState::IndirectArgument),
16502 "the prepass draws from the same arguments, so the colour pass finds them \
16503 already in the state it wants — a barrier here would mean something between \
16504 the two put them back: {:?}",
16505 forward.barriers().buffers
16506 );
16507 // What the colour pass *does* still have to be given: the froxel grid,
16508 // which no earlier pass reads.
16509 assert!(
16510 forward.barriers().buffers.iter().any(|barrier| {
16511 barrier.from == ResourceState::ShaderReadWrite
16512 && barrier.to == ResourceState::ShaderRead
16513 }),
16514 "and the froxel grid, which its fragment stage reads: {:?}",
16515 forward.barriers().buffers
16516 );
16517
16518 let draw_args = compiled
16519 .passes()
16520 .iter()
16521 .find(|pass| pass.label() == "draw-args")
16522 .expect("the pass list above");
16523 assert!(
16524 draw_args.barriers().buffers.iter().any(|barrier| {
16525 barrier.from == ResourceState::ShaderReadWrite
16526 && barrier.to == ResourceState::ShaderRead
16527 }),
16528 "and the visible list is ordered after the cull pass wrote it: {:?}",
16529 draw_args.barriers().buffers
16530 );
16531
16532 // The compiled graph borrows the renderer's pass bodies, so it has to go
16533 // before the renderer does.
16534 drop(compiled);
16535 renderer.destroy(device.as_ref());
16536 device.destroy_image_view(imported.view);
16537 device.destroy_image(imported.image);
16538 recorder.assert_valid();
16539 }
16540
16541 /// One more frame than the uniform ring is deep, so at least one lap both
16542 /// reuses a slot and follows a lap that already sampled the atlas.
16543 const SHADOW_LAPS: usize = FRAMES_IN_FLIGHT + 1;
16544
16545 /// **Every frame's first barrier on the shadow atlas names what the previous
16546 /// frame left it in**, and the same for its placeholder.
16547 ///
16548 /// # Why this cannot be read off one frame
16549 ///
16550 /// The atlas is neither a transient nor a swapchain image. The pool never
16551 /// hands one out and has no description to size it from, and no acquire
16552 /// semaphore sits between one frame's use of it and the next — so
16553 /// [`ForwardRenderer::add_passes`] *declares* it, and the declaration is what
16554 /// makes the transition true.
16555 ///
16556 /// What it declares is [`imported_state`], the pool's record of what the
16557 /// last graph to *execute* left the image in, so [`InitialClaim::Tracked`]
16558 /// can only ever find the two agreeing for this one import — deliberately,
16559 /// because a declaration and an audit reading one value cannot drift apart
16560 /// the way a renderer-held copy of it could. The audit still has teeth
16561 /// elsewhere in this frame: `ssao-placeholder` and `probes` declare a
16562 /// constant, and `the_guard_still_catches_an_engine_import_that_lies` is
16563 /// what shows it fires on those.
16564 ///
16565 /// So neither mechanism says anything about the barriers on either side of
16566 /// the declaration — whether the frame that ran actually reached the state
16567 /// the ledger now claims, and whether the next frame's first barrier comes
16568 /// out of it — which is what the stream below is for.
16569 ///
16570 /// Declaring [`ResourceState::Undefined`] on a frame after the first is the
16571 /// failure this catches. It expands to `srcStageMask = NONE,
16572 /// srcAccessMask = NONE` (`crcbl_vk::conv::state_masks`), so the transition
16573 /// into the depth-only pass's attachment state orders against nothing — while
16574 /// the previous frame's colour pass is still sampling the very same image.
16575 /// Vulkan reports it as `SYNC-HAZARD-WRITE-AFTER-READ` with
16576 /// `read_barriers: 0`; every other backend resolves it however the driver
16577 /// likes.
16578 ///
16579 /// # Why the command stream is the observable
16580 ///
16581 /// Nothing above the seam can see a wrong declaration: the frame still
16582 /// renders, the golden still matches, and no state is ever read back. So this
16583 /// replays the recorded stream with a tracker, which is the same check a
16584 /// validation layer performs and needs no GPU at all — the shape
16585 /// `crcbl::screenshot`'s
16586 /// `every_readback_barrier_declares_the_state_the_image_is_actually_in` uses.
16587 /// One difference: `Undefined` is **not** waved through after the first
16588 /// touch. It is true for a swapchain image because the acquire's semaphore
16589 /// makes it true, and there is no such semaphore here.
16590 #[test]
16591 fn the_shadow_atlas_enters_each_frame_in_the_state_the_last_one_left_it() {
16592 use crcbl_hal::null::Command;
16593
16594 let (recorder, device, queue) = open();
16595 let device = device.as_ref();
16596 let mut renderer =
16597 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16598 let atlas = renderer.shadow_atlas();
16599 let placeholder = renderer.shadow_placeholder;
16600 let mut pool = crate::TransientPool::new();
16601 let imported = swapchain_image(device);
16602 let mut recorded = Vec::with_capacity(SHADOW_LAPS);
16603
16604 for lap in 0..SHADOW_LAPS {
16605 renderer
16606 .begin_frame(
16607 device,
16608 &Camera::default(),
16609 // **A different sun each lap**, so every lap redraws the
16610 // atlas: this is a test about the barrier a frame that
16611 // writes the image declares, and a lap that cached would
16612 // record no pass and no transition at all. See
16613 // [`moving_sun`].
16614 &moving_sun(u32::try_from(lap).expect("a handful of laps")),
16615 (64, 48),
16616 )
16617 .expect("write");
16618 let mut graph = crate::RenderGraph::new(queue);
16619 let target = graph.import_image("target", imported);
16620 renderer.add_passes(&mut graph, &pool, target, (64, 48));
16621 let compiled = graph.compile(&pool).expect("a legal frame");
16622 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
16623 label: Some("shadow lap"),
16624 queue,
16625 });
16626 compiled
16627 .execute(device, &mut pool, encoder.as_mut(), None)
16628 .expect("the graph executed");
16629 recorded.push(encoder.finish().expect("recording succeeded"));
16630 }
16631
16632 // The two images the renderer owns across frames. A transient's state is
16633 // the pool's business and the fake swapchain image's is the acquire's, so
16634 // neither belongs in here.
16635 let mut tracked = [
16636 (atlas, ResourceState::Undefined),
16637 (placeholder, ResourceState::Undefined),
16638 ];
16639 let mut atlas_writes = 0usize;
16640 let mut named = 0usize;
16641 for command in recorder.commands() {
16642 let Command::Barrier { images, .. } = command else {
16643 continue;
16644 };
16645 for barrier in images {
16646 let Some((_, state)) = tracked
16647 .iter_mut()
16648 .find(|(handle, _)| *handle == barrier.image)
16649 else {
16650 continue;
16651 };
16652 assert_eq!(
16653 barrier.from, *state,
16654 "a barrier declared {:?} -> {:?} on an image the frame before it left in \
16655 {:?}. `Undefined` carries no source scope, so a transition declaring it \
16656 orders against nothing and the previous frame's sampled read is still in \
16657 flight underneath it.",
16658 barrier.from, barrier.to, *state
16659 );
16660 if barrier.image == atlas && barrier.to == ResourceState::DepthStencilWrite {
16661 atlas_writes += 1;
16662 }
16663 *state = barrier.to;
16664 named += 1;
16665 }
16666 }
16667
16668 // Both halves of the loop above are silent on an empty stream, so the
16669 // shape it walked is asserted rather than assumed: one transition into
16670 // the depth-only pass's attachment state per lap, the last one included.
16671 assert_eq!(
16672 atlas_writes, SHADOW_LAPS,
16673 "{named} barrier(s) named the atlas or its placeholder across {SHADOW_LAPS} laps, \
16674 {atlas_writes} of them taking the atlas into DepthStencilWrite — every lap moved \
16675 the sun, so every lap redraws the atlas, and anything else means the loop above \
16676 asserted on a stream that does not contain the transition it is about"
16677 );
16678 let (_, ended) = tracked[0];
16679 assert_eq!(
16680 ended,
16681 ResourceState::ShaderRead,
16682 "the import promises to hand the atlas back in the state the next frame declares"
16683 );
16684
16685 renderer.destroy(device);
16686 for commands in recorded {
16687 device.destroy_command_buffer(commands);
16688 }
16689 pool.destroy(device);
16690 device.destroy_image_view(imported.view);
16691 device.destroy_image(imported.image);
16692 recorder.assert_valid();
16693 }
16694
16695 /// A renderer with a shadowed spot beside the sun's cascades and a caster
16696 /// for both to draw, which is the smallest scene the atlas cache has
16697 /// anything to say about: without a light tile the only maps are the
16698 /// cascades, and without a caster every tile is a clear.
16699 fn shadow_cache_scene(
16700 device: &dyn Device,
16701 queue: QueueHandle,
16702 ) -> (ForwardRenderer, InstanceHandle) {
16703 let mut renderer =
16704 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16705 // Pinned, on `set_shadow_cadence`'s own terms: the console's two limits
16706 // are process-global and `the_console_moves_both_limits` holds them at
16707 // a four-frame hold and three faces a frame for the length of its
16708 // check. A cache test reading the console inside that window reports
16709 // "did not settle" — seen in the wild on 2026-09-04, and reproduced by
16710 // holding both limits at those values inside the arm's own process,
16711 // which the pin makes harmless.
16712 renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
16713 let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16714 renderer.set_lights(&[shadowable_spot(-1.0)]);
16715 (renderer, cube)
16716 }
16717
16718 /// Draws one frame and answers whether it drew the shadow atlas, **read two
16719 /// ways that have to agree**.
16720 ///
16721 /// [`ForwardRenderer::shadow_atlas_cached`] is the renderer's own claim and
16722 /// the recorded stream is what the device was actually told; either on its
16723 /// own would be satisfied by a renderer that reported one thing and did the
16724 /// other, which is precisely the failure a cache has. `seen` is the cursor
16725 /// into the cumulative recorder, so each call reads its own frame.
16726 fn drew_the_atlas(
16727 recorder: &Recorder,
16728 seen: &mut usize,
16729 device: &dyn Device,
16730 renderer: &mut ForwardRenderer,
16731 queue: QueueHandle,
16732 camera: &Camera,
16733 sun: &DirectionalLight,
16734 ) -> bool {
16735 let drawn = frame_seen_from(device, renderer, queue, camera, sun);
16736 let claimed = renderer.shadow_atlas_cached();
16737 let commands = recorder.commands();
16738 let opened = commands[*seen..].iter().any(|command| {
16739 command
16740 .opens_pass()
16741 .is_some_and(|(_, label)| label == Some("shadow"))
16742 });
16743 *seen = commands.len();
16744 drawn.release(device);
16745 assert_eq!(
16746 opened,
16747 !claimed,
16748 "the renderer reports cached = {claimed} and its frame {} a pass labelled `shadow`",
16749 if opened { "opened" } else { "opened no" }
16750 );
16751 opened
16752 }
16753
16754 #[test]
16755 fn shadow_preparation_retains_empty_scratch_after_redraw_and_cached_frames() {
16756 let (recorder, device, queue) = open();
16757 let device = device.as_ref();
16758 let (mut renderer, _) = shadow_cache_scene(device, queue);
16759 let camera = Camera::default();
16760 let sun = DirectionalLight::default();
16761 let mut seen = 0;
16762 assert!(drew_the_atlas(
16763 &recorder,
16764 &mut seen,
16765 device,
16766 &mut renderer,
16767 queue,
16768 &camera,
16769 &sun
16770 ));
16771 let capacity = (
16772 renderer.shadow_prepare_views.capacity(),
16773 renderer.shadow_prepare_culls.capacity(),
16774 );
16775 assert!(capacity.0 >= SHADOW_VIEWS && capacity.1 >= SHADOW_CULLS);
16776 assert!(renderer.shadow_prepare_views.is_empty());
16777 assert!(renderer.shadow_prepare_culls.is_empty());
16778 for _ in 0..FRAMES_IN_FLIGHT {
16779 assert!(!drew_the_atlas(
16780 &recorder,
16781 &mut seen,
16782 device,
16783 &mut renderer,
16784 queue,
16785 &camera,
16786 &sun
16787 ));
16788 assert!(renderer.shadow_prepare_views.is_empty());
16789 assert!(renderer.shadow_prepare_culls.is_empty());
16790 assert_eq!(
16791 (
16792 renderer.shadow_prepare_views.capacity(),
16793 renderer.shadow_prepare_culls.capacity()
16794 ),
16795 capacity
16796 );
16797 }
16798 for (step, view) in [0, 1, shadow_view(0, 0)].into_iter().enumerate() {
16799 // The spot moves for its own view and the camera for the cascades',
16800 // which are fitted to it: a moved spot alone is no input of theirs.
16801 renderer.set_lights(&[shadowable_spot(-2.0 - step as f32)]);
16802 let camera = Camera {
16803 eye: camera.eye + Vec3::X * 0.1 * (step + 1) as f32,
16804 ..camera
16805 };
16806 let slot = (renderer.frame + 1) % FRAMES_IN_FLIGHT;
16807 let short = device
16808 .create_buffer(&BufferDesc {
16809 label: Some("refused shadow scratch test upload"),
16810 size: std::mem::size_of::<f32>() as u64,
16811 usage: BufferUsage::UNIFORM,
16812 memory: MemoryLocation::HostUpload,
16813 })
16814 .unwrap();
16815 let original = std::mem::replace(&mut renderer.shadow_uniforms[slot][view], short);
16816 let before = recorder.buffer_bytes(short).unwrap();
16817 let result = renderer.begin_frame(device, &camera, &sun, TEST_EXTENT);
16818 renderer.shadow_uniforms[slot][view] = original;
16819 assert!(
16820 matches!(result, Err(HalError::InvalidDescriptor(ref cause)) if cause.contains("exceeds")),
16821 "observe a refused shadow uniform: {result:?}"
16822 );
16823 assert_eq!(recorder.buffer_bytes(short).unwrap(), before);
16824 assert!(!recorder.events().iter().any(
16825 |event| matches!(event, Event::BufferWritten { buffer, .. } if *buffer == short)
16826 ));
16827 assert!(renderer.shadow_prepare_views.is_empty());
16828 assert!(renderer.shadow_prepare_culls.is_empty());
16829 assert_eq!(
16830 (
16831 renderer.shadow_prepare_views.capacity(),
16832 renderer.shadow_prepare_culls.capacity()
16833 ),
16834 capacity
16835 );
16836 let refused_inputs = renderer.shadow_group_inputs.clone();
16837 device.destroy_buffer(short);
16838 recorder.assert_valid();
16839 assert!(drew_the_atlas(
16840 &recorder,
16841 &mut seen,
16842 device,
16843 &mut renderer,
16844 queue,
16845 &camera,
16846 &sun
16847 ));
16848 assert_eq!(renderer.shadow_group_inputs, refused_inputs);
16849 assert!(renderer.shadow_prepare_views.is_empty());
16850 assert!(renderer.shadow_prepare_culls.is_empty());
16851 assert_eq!(
16852 (
16853 renderer.shadow_prepare_views.capacity(),
16854 renderer.shadow_prepare_culls.capacity()
16855 ),
16856 capacity
16857 );
16858 assert!(!drew_the_atlas(
16859 &recorder,
16860 &mut seen,
16861 device,
16862 &mut renderer,
16863 queue,
16864 &camera,
16865 &sun
16866 ));
16867 }
16868 renderer.destroy(device);
16869 recorder.assert_valid();
16870 assert_eq!(recorder.total_live_objects(), 0);
16871 }
16872
16873 /// **A frame over a scene nothing moved in does not draw the shadow atlas
16874 /// again**, and what it saves is the whole of the atlas's work.
16875 ///
16876 /// Topic 45's static-caching rung, and the observable it
16877 /// otherwise has none for: the map a cached frame samples is byte for byte
16878 /// the map the frame before it sampled, so no golden image and no readback
16879 /// can tell the two frames apart. The recorded command stream can — and the
16880 /// dispatch count is the half that says the *culls* went with the pass,
16881 /// rather than the frame still paying for the draws it decided not to
16882 /// record.
16883 #[test]
16884 fn a_frame_over_a_still_scene_does_not_draw_the_shadow_atlas_again() {
16885 use crcbl_hal::null::Command;
16886
16887 // The blur count is a process-global console variable, and the frame's
16888 // draw count below includes the full-screen triangle each blur records
16889 // — so a concurrent test holding `r_ssao_blur_passes` at two would move
16890 // it under this one. Held rather than merely read, which is the
16891 // convention that variable's own test set.
16892 let _blurs = ssao_blur_switch();
16893 let (recorder, device, queue) = open();
16894 let device = device.as_ref();
16895 let (mut renderer, _) = shadow_cache_scene(device, queue);
16896 let camera = Camera::default();
16897 let sun = DirectionalLight::default();
16898
16899 let mut seen = 0usize;
16900 let dispatches = |recorder: &Recorder, from: usize| {
16901 recorder.commands()[from..]
16902 .iter()
16903 .filter(|command| matches!(command, Command::Dispatch { .. }))
16904 .count()
16905 };
16906
16907 let at = seen;
16908 assert!(
16909 drew_the_atlas(
16910 &recorder,
16911 &mut seen,
16912 device,
16913 &mut renderer,
16914 queue,
16915 &camera,
16916 &sun
16917 ),
16918 "the first frame of all has to draw the atlas: nothing has put anything in it"
16919 );
16920 let first = dispatches(&recorder, at);
16921 let drawing_draws = renderer.counters().draws;
16922 let buckets = renderer.bucket_constants.len() as u64;
16923 assert!(
16924 renderer.shadow_lights().base_of(0).is_some(),
16925 "the spot must hold a run for the count below to include a light slot's cull"
16926 );
16927 // The camera's own draw generation and topic 18's clustering dispatch,
16928 // plus a generation per cascade and one for the spot's slot.
16929 assert_eq!(
16930 first,
16931 DrawGen::DISPATCHES as usize * (2 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
16932 "the drawing frame did not record the culls this test is about skipping"
16933 );
16934
16935 for round in 0..3 {
16936 let at = seen;
16937 assert!(
16938 !drew_the_atlas(
16939 &recorder,
16940 &mut seen,
16941 device,
16942 &mut renderer,
16943 queue,
16944 &camera,
16945 &sun
16946 ),
16947 "round {round} redrew an atlas nothing had changed"
16948 );
16949 assert_eq!(
16950 dispatches(&recorder, at),
16951 DrawGen::DISPATCHES as usize + 1 + RESOLVE_DISPATCHES,
16952 "round {round} kept a shadow cull it had no pass to feed"
16953 );
16954 assert_eq!(
16955 drawing_draws - renderer.counters().draws,
16956 (shadow::CASCADES + 1) as u64 * buckets,
16957 "round {round}: the frame's own draw count did not lose exactly the atlas's \
16958 calls — one per bucket per cascade, and one per bucket for the spot's tile"
16959 );
16960 }
16961
16962 renderer.destroy(device);
16963 recorder.assert_valid();
16964 }
16965
16966 /// A cadence that holds every map one rung down for a frame, with the whole
16967 /// atlas's worth of tiles to spend.
16968 ///
16969 /// Pinned through [`ForwardRenderer::set_shadow_cadence`] rather than set on
16970 /// the console: [`shadow::r_shadow_cadence`] is process-global and the
16971 /// shadow pass is in every frame's pass list, so a test that moved it would
16972 /// change the frame every other test in this module draws.
16973 const HOLD_TWO: shadow::Cadence = shadow::Cadence {
16974 hold: 2,
16975 faces: shadow::TILES,
16976 };
16977
16978 /// How the shadow pass loaded its depth attachment, over the commands from
16979 /// `from` on, and [`None`] where the frame recorded no such pass.
16980 ///
16981 /// **The observable the tile clear otherwise has none for.** A frame that
16982 /// kept a tile and a frame that redrew every one of them sample maps that
16983 /// may be identical, so nothing in the picture separates them; this is the
16984 /// declaration that says which the device was told.
16985 fn shadow_pass_depth_load(recorder: &Recorder, from: usize) -> Option<LoadOp> {
16986 use crcbl_hal::null::Command;
16987
16988 recorder.commands()[from..].iter().find_map(|command| {
16989 let Command::BeginRenderPass {
16990 label,
16991 depth_stencil_attachment,
16992 ..
16993 } = command
16994 else {
16995 return None;
16996 };
16997 if label.as_deref() != Some("shadow") {
16998 return None;
16999 }
17000 depth_stencil_attachment
17001 .as_ref()
17002 .map(|attachment| attachment.depth_load)
17003 })
17004 }
17005
17006 /// Direct draws recorded inside the shadow pass, over the commands from
17007 /// `from` on — which is one per tile the pass reset itself, the atlas's
17008 /// geometry being drawn indirectly.
17009 fn tile_clears_in_the_shadow_pass(recorder: &Recorder, from: usize) -> usize {
17010 use crcbl_hal::null::Command;
17011
17012 let mut inside = false;
17013 let mut clears = 0;
17014 for command in &recorder.commands()[from..] {
17015 if let Some((_, label)) = command.opens_pass() {
17016 inside = label == Some("shadow");
17017 continue;
17018 }
17019 if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
17020 inside = false;
17021 continue;
17022 }
17023 if inside && matches!(command, Command::Draw { .. }) {
17024 clears += 1;
17025 }
17026 }
17027 clears
17028 }
17029
17030 /// **The far cascade is redrawn every second frame and the near one every
17031 /// frame**, on a scene where the eye moves and so every map is out of date.
17032 ///
17033 /// Topic 45's cadence rung, and the observable it otherwise
17034 /// has none for: a held map draws a shadow one frame behind its caster,
17035 /// which is a plausible picture and one a golden accepts.
17036 ///
17037 /// The eye moves by a fraction of a cascade's own reach, so no frame is a
17038 /// reset — that is asserted rather than assumed, because a reset would make
17039 /// every frame redraw everything and this test would pass by having
17040 /// switched the cadence off.
17041 #[test]
17042 fn the_far_cascade_is_held_on_the_frames_between_its_turns() {
17043 let _blurs = ssao_blur_switch();
17044 let (recorder, device, queue) = open();
17045 let device = device.as_ref();
17046 let (mut renderer, _) = shadow_cache_scene(device, queue);
17047 let sun = DirectionalLight::default();
17048 renderer.set_shadow_cadence(Some(HOLD_TWO));
17049
17050 const FRAMES: usize = 8;
17051 let mut near = 0;
17052 let mut far = 0;
17053 for step in 0..FRAMES {
17054 #[expect(
17055 clippy::cast_precision_loss,
17056 reason = "a handful of frames, and the step is what is wanted"
17057 )]
17058 let camera = Camera {
17059 eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17060 ..Camera::default()
17061 };
17062 let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17063 assert_eq!(
17064 renderer.shadow_cadence_reset(),
17065 step == 0,
17066 "frame {step}: only the first frame has an atlas to lay out, and a reset \
17067 after it would redraw everything and leave nothing for the cadence to hold"
17068 );
17069 near += usize::from(renderer.shadow_cascade_redrawn(0));
17070 far += usize::from(renderer.shadow_cascade_redrawn(1));
17071 drawn.release(device);
17072 }
17073 assert_eq!(
17074 near, FRAMES,
17075 "the near cascade is fitted to the eye and is on the top rung: every frame"
17076 );
17077 assert_eq!(
17078 far,
17079 FRAMES / 2,
17080 "the far cascade is one rung down, so every second frame"
17081 );
17082
17083 renderer.destroy(device);
17084 recorder.assert_valid();
17085 }
17086
17087 /// **A frame that keeps a tile loads the attachment and resets the tiles it
17088 /// redraws itself**, and a frame that keeps none clears it — which is what
17089 /// shipped.
17090 ///
17091 /// The half of the cadence a redraw count cannot see: holding a tile is only
17092 /// worth anything if the tile survives, and the one clear this seam has
17093 /// covers the whole image. A frame that loaded and reset nothing would draw
17094 /// into tiles still holding the last frame's depths, and under reversed-Z a
17095 /// caster that moved away would go on occluding.
17096 #[test]
17097 fn a_frame_that_keeps_a_tile_loads_the_attachment_and_resets_the_rest() {
17098 let _blurs = ssao_blur_switch();
17099 let (recorder, device, queue) = open();
17100 let device = device.as_ref();
17101 let (mut renderer, _) = shadow_cache_scene(device, queue);
17102 let sun = DirectionalLight::default();
17103
17104 // The first frame lays the atlas out, so it clears and redraws
17105 // everything whatever the console says.
17106 let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17107 first.release(device);
17108 assert_eq!(
17109 shadow_pass_depth_load(&recorder, 0),
17110 Some(LoadOp::Clear),
17111 "the frame that lays the atlas out has nothing to keep"
17112 );
17113 assert_eq!(
17114 tile_clears_in_the_shadow_pass(&recorder, 0),
17115 0,
17116 "and so resets no tile of its own"
17117 );
17118
17119 renderer.set_shadow_cadence(Some(HOLD_TWO));
17120 let mut seen = recorder.commands().len();
17121 let mut loaded = 0;
17122 for step in 1..4 {
17123 #[expect(
17124 clippy::cast_precision_loss,
17125 reason = "a handful of frames, and the step is what is wanted"
17126 )]
17127 let camera = Camera {
17128 eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17129 ..Camera::default()
17130 };
17131 let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17132 let load = shadow_pass_depth_load(&recorder, seen).expect("a shadow pass");
17133 let clears = tile_clears_in_the_shadow_pass(&recorder, seen);
17134 let faces = renderer.shadow_faces_redrawn() as usize;
17135 if load == LoadOp::Load {
17136 loaded += 1;
17137 assert_eq!(
17138 clears, faces,
17139 "frame {step} loaded the attachment and reset {clears} of the {faces} \
17140 tiles it redrew"
17141 );
17142 assert!(
17143 faces < shadow::TILES,
17144 "frame {step} loaded an attachment while redrawing every tile"
17145 );
17146 } else {
17147 assert_eq!(
17148 clears, 0,
17149 "frame {step} cleared the attachment and reset {clears} tiles again"
17150 );
17151 }
17152 seen = recorder.commands().len();
17153 drawn.release(device);
17154 }
17155 assert!(
17156 loaded > 0,
17157 "no frame kept a tile, so nothing here is about the load path"
17158 );
17159
17160 renderer.destroy(device);
17161 recorder.assert_valid();
17162 }
17163
17164 /// A point light costs the budget every face it draws, not one.
17165 ///
17166 /// **The half of the budget its name is about.** `shadow_faces_redrawn` is
17167 /// a sum over the groups a frame redrew of the maps each of them owns, and
17168 /// a point light owns [`shadow::POINT_FACES`] of them. Every other check
17169 /// here is built on the sun and a spot, which own one map each — so a face
17170 /// count that answered `1` for every group would satisfy all of them, and
17171 /// did: collapsing it passed the whole of `crcbl-render` and the mesh e2e
17172 /// suite. This is what binds on the difference.
17173 #[test]
17174 fn a_point_light_costs_the_budget_every_face_it_draws() {
17175 let _blurs = ssao_blur_switch();
17176 let (_recorder, device, queue) = open();
17177 let device = device.as_ref();
17178 let mut renderer =
17179 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17180 let _cube = place_cube(&mut renderer, Mat4::IDENTITY);
17181 renderer.set_lights(&[shadowable_point(-1.0)]);
17182 let sun = DirectionalLight::default();
17183
17184 // Every group is forced on the first frame — the image has held none of
17185 // them — so this counts what a full redraw actually costs.
17186 renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
17187 let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17188 first.release(device);
17189 let point_faces = u32::try_from(shadow::POINT_FACES).expect("a handful of faces");
17190 assert!(
17191 renderer.shadow_lights().base_of(0).is_some(),
17192 "the point must hold a run of tiles, or there is no multi-face group to count"
17193 );
17194 assert!(
17195 renderer.shadow_faces_redrawn() >= point_faces,
17196 "a frame that redrew a point light's whole cube reported {} faces, fewer than the \
17197 {point_faces} it owns — so the budget is counting groups rather than the maps they \
17198 draw, and a cube would slip past a budget of one",
17199 renderer.shadow_faces_redrawn()
17200 );
17201 }
17202
17203 /// **A frame never redraws more tiles than the budget allows**, and every
17204 /// map still gets its turn.
17205 ///
17206 /// The starvation half is what makes this more than an inequality: a
17207 /// schedule that spent the budget on the same maps every frame would satisfy
17208 /// the bound and never draw the rest at all.
17209 #[test]
17210 fn the_face_budget_bounds_a_frame_and_starves_no_map() {
17211 let _blurs = ssao_blur_switch();
17212 let (recorder, device, queue) = open();
17213 let device = device.as_ref();
17214 let (mut renderer, _) = shadow_cache_scene(device, queue);
17215 let sun = DirectionalLight::default();
17216
17217 let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17218 first.release(device);
17219 assert!(
17220 renderer.shadow_lights().base_of(0).is_some(),
17221 "the spot must hold a run, or the budget has only the cascades to bind on"
17222 );
17223
17224 // One tile a frame: the two cascades and the spot's map cannot all fit,
17225 // so something is held on every frame of the run below.
17226 const BUDGET: u32 = 1;
17227 renderer.set_shadow_cadence(Some(shadow::Cadence {
17228 hold: 1,
17229 faces: BUDGET as usize,
17230 }));
17231 const FRAMES: usize = 12;
17232 let mut drew = [0usize; 3];
17233 for step in 1..=FRAMES {
17234 #[expect(
17235 clippy::cast_precision_loss,
17236 reason = "a handful of frames, and the step is what is wanted"
17237 )]
17238 let camera = Camera {
17239 eye: Camera::default().eye + Vec3::X * 0.02 * step as f32,
17240 ..Camera::default()
17241 };
17242 // The spot drifts too: its map is not fitted to the camera, so a
17243 // moving eye alone leaves it up to date and asking for nothing.
17244 #[expect(
17245 clippy::cast_precision_loss,
17246 reason = "a handful of frames, and the step is what is wanted"
17247 )]
17248 renderer.set_lights(&[shadowable_spot(-1.0 + 0.01 * step as f32)]);
17249 let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17250 assert!(
17251 renderer.shadow_faces_redrawn() <= BUDGET,
17252 "frame {step} redrew {} tiles against a budget of {BUDGET}",
17253 renderer.shadow_faces_redrawn()
17254 );
17255 drew[0] += usize::from(renderer.shadow_cascade_redrawn(0));
17256 drew[1] += usize::from(renderer.shadow_cascade_redrawn(1));
17257 drew[2] += usize::from(renderer.shadow_slot_redrawn(0));
17258 drawn.release(device);
17259 }
17260 for (map, count) in drew.iter().enumerate() {
17261 assert!(
17262 *count > 0,
17263 "map {map} was never redrawn in {FRAMES} frames under a budget of \
17264 {BUDGET}: {drew:?}"
17265 );
17266 }
17267
17268 renderer.destroy(device);
17269 recorder.assert_valid();
17270 }
17271
17272 /// **A light that jumps further than its own radius resets the cadence**,
17273 /// and one that drifts inside it does not.
17274 ///
17275 /// Topic 45's "a moving light or camera cut resets it",
17276 /// made precise: a map whose centre has moved past the map's own reach is
17277 /// not a frame out of date, it is about somewhere else — so it is redrawn on
17278 /// the frame that notices rather than when its turn comes round. Both arms,
17279 /// because a reset that fired on every move would be the cadence switched
17280 /// off.
17281 #[test]
17282 fn a_light_that_jumps_past_its_own_radius_resets_the_cadence() {
17283 let _blurs = ssao_blur_switch();
17284 let (recorder, device, queue) = open();
17285 let device = device.as_ref();
17286 let (mut renderer, _) = shadow_cache_scene(device, queue);
17287 let sun = DirectionalLight::default();
17288 let camera = Camera::default();
17289 // The coarsest hold there is, so a redraw of the spot's map on the
17290 // frames below is the reset and not its turn.
17291 renderer.set_shadow_cadence(Some(shadow::Cadence {
17292 hold: 8,
17293 faces: shadow::TILES,
17294 }));
17295
17296 let mut settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17297 settle.release(device);
17298 for _ in 0..2 {
17299 settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17300 settle.release(device);
17301 }
17302 assert!(
17303 !renderer.shadow_cadence_reset(),
17304 "the scene has settled, so nothing is about somewhere else"
17305 );
17306
17307 // A drift well inside the light's own radius: out of date, not moved.
17308 renderer.set_lights(&[shadowable_spot(-1.0 + 0.5)]);
17309 let drifted = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17310 drifted.release(device);
17311 assert!(
17312 !renderer.shadow_cadence_reset(),
17313 "a light that moved a sixteenth of its radius is a map a frame out of date"
17314 );
17315
17316 // And a jump past it. `shadowable_spot`'s radius is what the reach is
17317 // taken from, so this is a light standing where its own map says
17318 // nothing.
17319 renderer.set_lights(&[shadowable_spot(-1.0 + 40.0)]);
17320 let jumped = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17321 jumped.release(device);
17322 assert!(
17323 renderer.shadow_cadence_reset(),
17324 "a light that jumped five times its own radius must not hold its map"
17325 );
17326 assert!(
17327 renderer.shadow_slot_redrawn(0),
17328 "and the reset is only a reset if the map is actually redrawn"
17329 );
17330
17331 renderer.destroy(device);
17332 recorder.assert_valid();
17333 }
17334
17335 /// **A console knob about *sampling* the atlas does not redraw it.**
17336 ///
17337 /// `r_shadow_filter` and `r_shadow_split` decide how the colour pass reads
17338 /// a map, and `r_shadow_bias` and `r_shadow_normal_offset` how far from a
17339 /// receiver it reads — and not one byte of what the depth pass writes into
17340 /// it is any of theirs. Yet the
17341 /// shadow views' blocks are the frame's block spread, and the cache record
17342 /// is those blocks' bytes — so until the views zeroed the row, a person
17343 /// typing `r_shadow_filter box` redrew every map in the atlas for nothing,
17344 /// and in this crate's own test process the filter tests moving that cell
17345 /// redrew the atlas under `each_thing_the_atlas_is_drawn_from_redraws_it`
17346 /// once in every five or six workspace runs on 2026-09-04. Holding the lock
17347 /// here is what makes the move below the only one in flight.
17348 #[test]
17349 fn a_moved_shadow_filter_leaves_a_still_atlas_alone() {
17350 let switch = shadow_filter_switch();
17351 let (recorder, device, queue) = open();
17352 let device = device.as_ref();
17353 let (mut renderer, _) = shadow_cache_scene(device, queue);
17354 let camera = Camera::default();
17355 let sun = DirectionalLight::default();
17356 let mut seen = 0usize;
17357 assert!(
17358 drew_the_atlas(
17359 &recorder,
17360 &mut seen,
17361 device,
17362 &mut renderer,
17363 queue,
17364 &camera,
17365 &sun
17366 ),
17367 "the first frame of all draws the atlas"
17368 );
17369 assert!(
17370 !drew_the_atlas(
17371 &recorder,
17372 &mut seen,
17373 device,
17374 &mut renderer,
17375 queue,
17376 &camera,
17377 &sun
17378 ),
17379 "a still second frame has to hold it, or the move below proves nothing"
17380 );
17381
17382 switch.filter(shadow::Filter::Box);
17383 switch.seam(0.5);
17384 assert!(
17385 !drew_the_atlas(
17386 &recorder,
17387 &mut seen,
17388 device,
17389 &mut renderer,
17390 queue,
17391 &camera,
17392 &sun
17393 ),
17394 "`r_shadow_filter` and `r_shadow_split` moved and the atlas was drawn again: a \
17395 sampling knob reached the record of what the maps were drawn from"
17396 );
17397
17398 // The bias pair sits in a different row of the same block, and the
17399 // second row it reaches is `Cascades::params`, which is rebuilt every
17400 // frame — so this is the arm that says the *whole* row is kept out of
17401 // the record rather than the one lane the filter is in.
17402 switch.bias(8.0);
17403 switch.offset(8.0);
17404 assert!(
17405 !drew_the_atlas(
17406 &recorder,
17407 &mut seen,
17408 device,
17409 &mut renderer,
17410 queue,
17411 &camera,
17412 &sun
17413 ),
17414 "`r_shadow_bias` and `r_shadow_normal_offset` moved and the atlas was drawn again: \
17415 the bias row reached the record of what the maps were drawn from"
17416 );
17417
17418 renderer.destroy(device);
17419 recorder.assert_valid();
17420 }
17421
17422 /// **Every input the atlas is drawn from redraws it**, one at a time.
17423 ///
17424 /// The half that stops "cached everything, for ever" from passing every
17425 /// assertion above. Each arm moves exactly one thing and asserts the next
17426 /// frame draws again — and then holds still and asserts it stops, so an arm
17427 /// cannot pass by having broken the cache outright.
17428 ///
17429 /// The camera is in here because it is not obvious: a shadow map is drawn
17430 /// from a light, not from the eye. But a cascade is fitted to the camera's
17431 /// own frustum, and every shadow cull selects a DAG's detail at the camera's
17432 /// pixels — `SHADOW_LOD_BIAS` — so a moved eye is a different cascade, and a
17433 /// different light map wherever a DAG is in the light's cull.
17434 /// `shadow_reach`'s tests are the other half: what a moved eye or a moved
17435 /// caster must *not* redraw.
17436 ///
17437 /// `settles` is how many still frames it takes to go quiet again, and it is
17438 /// two for exactly one arm: `InstancePool`'s carry-forward puts a moved
17439 /// instance's `previous_transform` back at rest on the frame *after* the
17440 /// move, and that is a write, which is a change this record cannot tell
17441 /// from any other. See `InstancePool::take_written`, which says so.
17442 #[test]
17443 fn each_thing_the_atlas_is_drawn_from_redraws_it() {
17444 let camera = Camera::default();
17445 let sun = DirectionalLight::default();
17446 let moved_camera = Camera {
17447 eye: camera.eye + Vec3::X * 4.0,
17448 ..camera
17449 };
17450 type Change = fn(&mut ForwardRenderer, InstanceHandle);
17451 let arms: [(&str, Change, &Camera, &DirectionalLight, usize); 4] = [
17452 (
17453 "a caster moved",
17454 |renderer, cube| {
17455 renderer.set_instance(
17456 cube,
17457 &InstanceDesc {
17458 mesh: DEMO_CUBE,
17459 material: DEMO_UNTINTED,
17460 transform: Mat4::from_translation(Vec3::X),
17461 },
17462 );
17463 },
17464 &camera,
17465 &sun,
17466 2,
17467 ),
17468 (
17469 "a caster removed",
17470 |renderer, cube| renderer.remove_instance(cube),
17471 &camera,
17472 &sun,
17473 1,
17474 ),
17475 (
17476 "the light moved",
17477 |renderer, _| renderer.set_lights(&[shadowable_spot(1.5)]),
17478 &camera,
17479 &sun,
17480 1,
17481 ),
17482 ("the camera moved", |_, _| {}, &moved_camera, &sun, 1),
17483 ];
17484
17485 for (what, change, camera, sun, settles) in arms {
17486 let (recorder, device, queue) = open();
17487 let device = device.as_ref();
17488 let (mut renderer, cube) = shadow_cache_scene(device, queue);
17489 let mut seen = 0usize;
17490 // Two frames, so the atlas is drawn and then held: the arm's own
17491 // assertion is about a frame that would otherwise have cached.
17492 for round in 0..2 {
17493 let drew = drew_the_atlas(
17494 &recorder,
17495 &mut seen,
17496 device,
17497 &mut renderer,
17498 queue,
17499 &Camera::default(),
17500 &DirectionalLight::default(),
17501 );
17502 assert_eq!(
17503 drew,
17504 round == 0,
17505 "{what}: the still frames before the change did not settle"
17506 );
17507 }
17508
17509 change(&mut renderer, cube);
17510 assert!(
17511 drew_the_atlas(
17512 &recorder,
17513 &mut seen,
17514 device,
17515 &mut renderer,
17516 queue,
17517 camera,
17518 sun
17519 ),
17520 "{what} and the atlas was not drawn again"
17521 );
17522 // And it goes quiet again in exactly `settles` frames, so the arm
17523 // cannot pass by having broken the cache rather than by having
17524 // invalidated it — and a change that started redrawing for ever
17525 // fails here rather than going unnoticed.
17526 for round in 0..settles {
17527 assert_eq!(
17528 drew_the_atlas(
17529 &recorder,
17530 &mut seen,
17531 device,
17532 &mut renderer,
17533 queue,
17534 camera,
17535 sun
17536 ),
17537 round + 1 < settles,
17538 "{what}: the still frames after the change did not settle in {settles}"
17539 );
17540 }
17541
17542 renderer.destroy(device);
17543 recorder.assert_valid();
17544 }
17545 }
17546
17547 /// **A frame with a skinned object in it always redraws the atlas**, and
17548 /// that is a limit written down rather than a gap.
17549 ///
17550 /// A skinned caster's vertices are produced by a compute dispatch into the
17551 /// pool, so there is nothing on the host to compare: the palette a caller
17552 /// hands over is not the geometry, and the geometry is never read back. The
17553 /// honest answer is to redraw, and the dishonest one is a map of a pose the
17554 /// character has left.
17555 #[test]
17556 fn a_frame_with_a_skinned_object_never_caches_the_atlas() {
17557 let (recorder, device, queue) = open();
17558 let device = device.as_ref();
17559 let mut fixture = SkinnedFixture::build(device, queue);
17560 fixture.renderer.set_lights(&[shadowable_spot(-1.0)]);
17561 let imported = swapchain_image_at(device, TEST_EXTENT);
17562 let mut pool = crate::TransientPool::new();
17563
17564 // The same palette and the same plan every lap, so nothing a host-side
17565 // comparison could see has moved.
17566 for lap in 0..3 {
17567 fixture.begin(device);
17568 let mut graph = crate::RenderGraph::new(queue);
17569 let target = graph.import_image("target", imported);
17570 fixture.renderer.add_skinned_passes(
17571 &mut graph,
17572 &pool,
17573 target,
17574 TEST_EXTENT,
17575 &fixture.skinning,
17576 );
17577 let compiled = graph.compile(&pool).expect("a legal frame");
17578 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17579 label: Some("skinned lap"),
17580 queue,
17581 });
17582 compiled
17583 .execute(device, &mut pool, encoder.as_mut(), None)
17584 .expect("the graph executed");
17585 device.destroy_command_buffer(encoder.finish().expect("recording succeeded"));
17586 assert!(
17587 !fixture.renderer.shadow_atlas_cached(),
17588 "lap {lap} held a shadow map of a pose no host-side comparison can vouch for"
17589 );
17590 }
17591
17592 fixture.destroy(device);
17593 pool.destroy(device);
17594 device.destroy_image_view(imported.view);
17595 device.destroy_image(imported.image);
17596 recorder.assert_valid();
17597 }
17598
17599 /// **Switching the shadows off clears the atlas once, and then holds the
17600 /// clear**, which is the same cache answering a frame that draws nothing.
17601 ///
17602 /// The switched-off frame is not itself a cached frame: the pass has to run
17603 /// to write the reversed-Z clear that makes every comparison come back lit,
17604 /// and the image holds the last drawn maps until it does. What *is* cached
17605 /// is every frame after it, and the record for a switched-off frame is
17606 /// deliberately blind to the camera and the casters, because nothing about
17607 /// them reaches an atlas nothing draws into.
17608 #[test]
17609 fn switching_the_shadows_off_clears_the_atlas_once_and_then_holds_it() {
17610 let (recorder, device, queue) = open();
17611 let device = device.as_ref();
17612 let (mut renderer, cube) = shadow_cache_scene(device, queue);
17613 let camera = Camera::default();
17614 let sun = DirectionalLight::default();
17615 let mut seen = 0usize;
17616
17617 assert!(
17618 drew_the_atlas(
17619 &recorder,
17620 &mut seen,
17621 device,
17622 &mut renderer,
17623 queue,
17624 &camera,
17625 &sun
17626 ),
17627 "the first frame draws the maps"
17628 );
17629 renderer.set_effect_request(EffectRequest {
17630 programmatic: EffectOverride::none().force(RenderEffects::SHADOWS, Some(false)),
17631 ..EffectRequest::default()
17632 });
17633 assert!(
17634 drew_the_atlas(
17635 &recorder,
17636 &mut seen,
17637 device,
17638 &mut renderer,
17639 queue,
17640 &camera,
17641 &sun
17642 ),
17643 "the frame that switched the shadows off has to run the pass that clears the maps \
17644 out of the image"
17645 );
17646 assert!(
17647 !drew_the_atlas(
17648 &recorder,
17649 &mut seen,
17650 device,
17651 &mut renderer,
17652 queue,
17653 &camera,
17654 &sun
17655 ),
17656 "a second switched-off frame cleared an atlas that was already clear"
17657 );
17658 // And nothing about the scene reaches a frame that draws no map: the
17659 // caster moves and the atlas is still the clear it was.
17660 renderer.set_instance(
17661 cube,
17662 &InstanceDesc {
17663 mesh: DEMO_CUBE,
17664 material: DEMO_UNTINTED,
17665 transform: Mat4::from_translation(Vec3::X),
17666 },
17667 );
17668 assert!(
17669 !drew_the_atlas(
17670 &recorder,
17671 &mut seen,
17672 device,
17673 &mut renderer,
17674 queue,
17675 &camera,
17676 &sun
17677 ),
17678 "a caster moved with the shadows off, and the frame cleared the atlas over again"
17679 );
17680
17681 renderer.set_effect_request(EffectRequest::default());
17682 assert!(
17683 drew_the_atlas(
17684 &recorder,
17685 &mut seen,
17686 device,
17687 &mut renderer,
17688 queue,
17689 &camera,
17690 &sun
17691 ),
17692 "switching the shadows back on has to draw the maps the clear replaced"
17693 );
17694
17695 renderer.destroy(device);
17696 recorder.assert_valid();
17697 }
17698
17699 /// **A frame the graph refuses leaves the shadow atlas where it was.**
17700 ///
17701 /// [`RenderGraph::compile`] returns a [`Result`], so a frame can be
17702 /// described in full and then thrown away, and
17703 /// [`CompiledGraph::execute`](crate::CompiledGraph::execute) — the only
17704 /// thing that writes the pool's ledger — never runs. That is the case a
17705 /// renderer-held `ResourceState`, stepped forward while the passes were
17706 /// declared, gets wrong: it would already say [`ResourceState::ShaderRead`]
17707 /// for an image no barrier has touched, and [`InitialClaim::Tracked`] cannot
17708 /// object, because with nothing recorded there is nothing to contradict. The
17709 /// guard would be silent on precisely the drift it exists to find, which is
17710 /// why [`imported_state`] reads the ledger instead of a second copy of it.
17711 ///
17712 /// The observable is the first barrier the *next* frame records on the
17713 /// atlas. `Undefined -> DepthStencilWrite` is the transition an image
17714 /// nothing has written needs; `ShaderRead -> DepthStencilWrite` names an old
17715 /// layout the image was never in, which is a layout mismatch on every
17716 /// backend and a discarded image on some.
17717 #[test]
17718 fn a_refused_frame_leaves_the_shadow_atlas_where_it_was() {
17719 use crcbl_hal::null::Command;
17720
17721 let (recorder, device, queue) = open();
17722 let device = device.as_ref();
17723 let mut renderer =
17724 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17725 let atlas = renderer.shadow_atlas();
17726 let placeholder = renderer.shadow_placeholder;
17727 let mut pool = crate::TransientPool::new();
17728 let imported = swapchain_image(device);
17729
17730 // The refused frame: every pass a real frame declares, and beside them
17731 // one transient nothing reads or writes. `compile` answers
17732 // `UnusedTransient` and the whole description — the shadow atlas's
17733 // import included — is dropped without a command being recorded.
17734 renderer
17735 .begin_frame(
17736 device,
17737 &Camera::default(),
17738 &DirectionalLight::default(),
17739 (64, 48),
17740 )
17741 .expect("write");
17742 {
17743 let mut graph = crate::RenderGraph::new(queue);
17744 let target = graph.import_image("target", imported);
17745 renderer.add_passes(&mut graph, &pool, target, (64, 48));
17746 graph.create_image("orphan", crate::targets::scene_color((64, 48)));
17747 let refused = graph
17748 .compile(&pool)
17749 .expect_err("a transient no pass declares");
17750 assert!(
17751 matches!(refused, crate::GraphError::UnusedTransient { .. }),
17752 "the frame has to be refused for the reason this test is about — a graph that \
17753 compiled would go on to execute and the ledger would be written after all: \
17754 {refused:?}"
17755 );
17756 }
17757 assert_eq!(
17758 pool.imported_image_use(atlas),
17759 None,
17760 "nothing executed, so the ledger has nothing to say about the atlas — this is the \
17761 emptiness `InitialClaim::Tracked` cannot check against"
17762 );
17763
17764 // And the frame after it, which does run.
17765 renderer
17766 .begin_frame(
17767 device,
17768 &Camera::default(),
17769 &DirectionalLight::default(),
17770 (64, 48),
17771 )
17772 .expect("write");
17773 let mut graph = crate::RenderGraph::new(queue);
17774 let target = graph.import_image("target", imported);
17775 renderer.add_passes(&mut graph, &pool, target, (64, 48));
17776 let compiled = graph.compile(&pool).expect("a legal frame");
17777 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17778 label: Some("frame after a refusal"),
17779 queue,
17780 });
17781 compiled
17782 .execute(device, &mut pool, encoder.as_mut(), None)
17783 .expect("the graph executed");
17784 let commands = encoder.finish().expect("recording succeeded");
17785
17786 // The first barrier each of the two images gets. Only the refused frame
17787 // ran before this one and it recorded nothing, so these are the frame's
17788 // opening transitions.
17789 let mut opened: Vec<(crcbl_hal::ImageHandle, ResourceState, ResourceState)> = Vec::new();
17790 for command in recorder.commands() {
17791 let Command::Barrier { images, .. } = command else {
17792 continue;
17793 };
17794 for barrier in images {
17795 if barrier.image != atlas && barrier.image != placeholder {
17796 continue;
17797 }
17798 if opened.iter().any(|(image, _, _)| *image == barrier.image) {
17799 continue;
17800 }
17801 opened.push((barrier.image, barrier.from, barrier.to));
17802 }
17803 }
17804 for (image, from, to) in &opened {
17805 assert_eq!(
17806 *from,
17807 ResourceState::Undefined,
17808 "a barrier declared {from:?} -> {to:?} on an image the refused frame never gave a \
17809 layout to. The declaration is what makes the transition true, so one that has \
17810 moved on without an executed frame behind it names a source scope and an old \
17811 layout the image was never in — and the ledger is empty, so nothing refuses it \
17812 either. Image {image:?}"
17813 );
17814 }
17815 // The loop above is silent on an empty list and on a short one, and a
17816 // wrong declaration shortens it: an image declared in the state it is
17817 // wanted in needs no transition, so it drops out of the stream
17818 // altogether rather than appearing with the wrong source.
17819 assert_eq!(
17820 opened.len(),
17821 2,
17822 "the atlas and its placeholder are both imported every frame and both are wanted in a \
17823 state they are not in, so both have to be barriered: {opened:?}"
17824 );
17825 assert!(
17826 opened
17827 .iter()
17828 .any(|(image, _, to)| *image == atlas && *to == ResourceState::DepthStencilWrite),
17829 "and the atlas's is the shadow pass taking it as a depth attachment: {opened:?}"
17830 );
17831
17832 renderer.destroy(device);
17833 device.destroy_command_buffer(commands);
17834 pool.destroy(device);
17835 device.destroy_image_view(imported.view);
17836 device.destroy_image(imported.image);
17837 recorder.assert_valid();
17838 }
17839
17840 /// **The import audit still refuses an engine site whose declaration is
17841 /// wrong**, now that the shadow atlas's is read out of the same ledger it is
17842 /// checked against.
17843 ///
17844 /// That pair is deliberately circular and this test is what keeps it from
17845 /// swallowing the guard whole: `shadow-atlas` and `shadow-placeholder` say
17846 /// what [`imported_state`] just read, so [`InitialClaim::Tracked`] can only
17847 /// ever find them agreeing — their safety comes from there being one answer
17848 /// rather than from the check. Every *other* import in the frame declares a
17849 /// constant, and `ssao-placeholder` is the one this drives a ledger entry
17850 /// away from: uploaded into [`ResourceState::ShaderRead`] at build and
17851 /// declared so on every frame, so a graph that leaves it somewhere else is a
17852 /// declaration the next `compile` has to refuse.
17853 #[test]
17854 fn the_guard_still_catches_an_engine_import_that_lies() {
17855 let (recorder, device, queue) = open();
17856 let device = device.as_ref();
17857 let mut renderer =
17858 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17859 let mut pool = crate::TransientPool::new();
17860 let imported = swapchain_image(device);
17861 let occlusion = renderer.ambient_occlusion_placeholder.image;
17862
17863 // A graph of this test's own, which moves the renderer's occlusion
17864 // placeholder somewhere `add_passes` does not expect. Same image handle,
17865 // so the entry it leaves in the ledger is the one the next `compile`
17866 // reads for `ssao-placeholder`.
17867 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17868 label: Some("move the placeholder"),
17869 queue,
17870 });
17871 {
17872 let mut graph = crate::RenderGraph::new(queue);
17873 let moved = graph.import_image(
17874 "moved-placeholder",
17875 ImportedImage {
17876 image: occlusion,
17877 view: renderer.ambient_occlusion_placeholder.view,
17878 format: Format::Rgba8Unorm,
17879 extent: (1, 1),
17880 initial: ResourceState::ShaderRead,
17881 claim: InitialClaim::Tracked,
17882 final_state: ResourceState::TransferSrc,
17883 },
17884 );
17885 graph
17886 .add_copy_pass("read the placeholder")
17887 .use_image(moved, ResourceState::TransferSrc)
17888 .execute(|_| {});
17889 graph
17890 .compile(&pool)
17891 .expect("a legal frame")
17892 .execute(device, &mut pool, encoder.as_mut(), None)
17893 .expect("the graph executed");
17894 }
17895 let commands = encoder.finish().expect("recording succeeded");
17896 assert_eq!(
17897 pool.imported_image_use(occlusion),
17898 Some(ResourceState::TransferSrc),
17899 "the ledger has to have moved for the frame below to have anything to disagree with"
17900 );
17901
17902 renderer
17903 .begin_frame(
17904 device,
17905 &Camera::default(),
17906 &DirectionalLight::default(),
17907 (64, 48),
17908 )
17909 .expect("write");
17910 let mut graph = crate::RenderGraph::new(queue);
17911 let target = graph.import_image("target", imported);
17912 renderer.add_passes(&mut graph, &pool, target, (64, 48));
17913 let refused = graph
17914 .compile(&pool)
17915 .expect_err("`ssao-placeholder` declares a constant the ledger no longer agrees with");
17916 let crate::GraphError::ImportStateMismatch {
17917 resource,
17918 declared,
17919 left,
17920 } = &refused
17921 else {
17922 panic!("the audit has to name the import it refused, not merely fail: {refused:?}");
17923 };
17924 assert_eq!(resource, "ssao-placeholder");
17925 assert_eq!(*declared, ResourceState::ShaderRead);
17926 assert_eq!(*left, ResourceState::TransferSrc);
17927
17928 renderer.destroy(device);
17929 device.destroy_command_buffer(commands);
17930 pool.destroy(device);
17931 device.destroy_image_view(imported.view);
17932 device.destroy_image(imported.image);
17933 recorder.assert_valid();
17934 }
17935
17936 /// Compiles one frame and names the passes it turned out to be, in order.
17937 ///
17938 /// Compiled and not executed: what a pass costs is not the question here,
17939 /// only which of them the frame declared. Names rather than a count since
17940 /// the toggles landed — a count says a frame lost two passes and a list says
17941 /// *which* two, which is the difference between "the switch did something"
17942 /// and "the switch did the thing it is for".
17943 fn passes_in_a_frame(
17944 device: &dyn Device,
17945 queue: QueueHandle,
17946 renderer: &mut ForwardRenderer,
17947 imported: ImportedImage,
17948 pool: &crate::TransientPool,
17949 extent: (u32, u32),
17950 ) -> Vec<String> {
17951 renderer
17952 .begin_frame(
17953 device,
17954 &Camera::default(),
17955 &DirectionalLight::default(),
17956 extent,
17957 )
17958 .expect("write");
17959 let mut graph = crate::RenderGraph::new(queue);
17960 let target = graph.import_image("target", imported);
17961 renderer.add_passes(&mut graph, pool, target, extent);
17962 graph
17963 .compile(pool)
17964 .expect("a legal frame")
17965 .passes()
17966 .iter()
17967 .map(|pass| pass.label().to_string())
17968 .collect()
17969 }
17970
17971 /// A spot at `x` that [`shadow::Selection`] will give a tile: finite, a
17972 /// radius, a direction and a cone well inside the widest one allowed.
17973 /// A shadowed point light, which is [`shadow::POINT_FACES`] maps rather
17974 /// than one.
17975 ///
17976 /// The spot beside it is one tile and one face, so a scene built only from
17977 /// spots cannot tell a budget counting **faces** from one counting groups —
17978 /// which is what this exists to give a check something to bind on.
17979 fn shadowable_point(x: f32) -> Light {
17980 Light::Point(crate::light::PointLight {
17981 position: Vec3::new(x, 2.0, 0.0),
17982 radius: 8.0,
17983 color: Vec3::ONE,
17984 fill: false,
17985 })
17986 }
17987
17988 fn shadowable_spot(x: f32) -> Light {
17989 Light::Spot(crate::light::SpotLight {
17990 position: Vec3::new(x, 2.0, 0.0),
17991 radius: 8.0,
17992 color: Vec3::ONE,
17993 direction: -Vec3::Y,
17994 inner_angle: 0.3,
17995 outer_angle: 0.6,
17996 fill: false,
17997 })
17998 }
17999
18000 /// The page's anisotropy is the plan's default clamped to the device, and
18001 /// one on a device that was not granted the feature — whatever its limit
18002 /// says.
18003 ///
18004 /// The last arm is the one worth having: `gate_limits_on_features` narrows
18005 /// a declined feature's limit on `crcbl-vk`, but a backend that did not
18006 /// would report sixteen beside an absent feature, and a clamp that read the
18007 /// limit alone would ask for a sampler the device refuses.
18008 #[test]
18009 fn the_anisotropy_is_the_default_clamped_to_what_the_device_granted() {
18010 let caps = |features: Features, max_sampler_anisotropy: f32| DeviceCaps {
18011 features,
18012 limits: crcbl_hal::Limits {
18013 max_sampler_anisotropy,
18014 ..crcbl_hal::Limits::desktop()
18015 },
18016 };
18017 let granted = Features::SAMPLER_ANISOTROPY;
18018 assert!(
18019 (ForwardRenderer::anisotropy_for(&caps(granted, 16.0)) - DEFAULT_ANISOTROPY).abs()
18020 < f32::EPSILON,
18021 "a device above the default gets the default"
18022 );
18023 assert!(
18024 (ForwardRenderer::anisotropy_for(&caps(granted, 4.0)) - 4.0).abs() < f32::EPSILON,
18025 "a device below the default gets its own limit"
18026 );
18027 assert!(
18028 (ForwardRenderer::anisotropy_for(&caps(Features::empty(), 16.0)) - 1.0).abs()
18029 < f32::EPSILON,
18030 "a device that was not granted the feature gets one, whatever its limit says"
18031 );
18032 }
18033
18034 /// A new anisotropy is a new sampler, and every slot moves onto it at its
18035 /// own frame — the old one living until the last slot has left it.
18036 ///
18037 /// Counted on the null recorder rather than looked at: the sampler count
18038 /// rises by one at the call, holds through every slot's frame but the
18039 /// last, and falls back there, while the live group count never moves at
18040 /// all — every rebuilt group replaced one. A rebuild that leaked, one that
18041 /// destroyed a group a slot in flight still held, and one that never
18042 /// happened each move one of those counts; a second lap of the ring
18043 /// creating any group at all would be a rebuild that did not know it was
18044 /// done.
18045 #[test]
18046 fn a_new_anisotropy_moves_each_slot_at_its_own_frame_and_retires_the_old() {
18047 let (recorder, device, queue) =
18048 open_with(Features::GPU_DRIVEN.union(Features::SAMPLER_ANISOTROPY));
18049 let device = device.as_ref();
18050 let mut renderer =
18051 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18052 assert!(
18053 (renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON,
18054 "a renderer nobody has called the setter on samples at the default"
18055 );
18056 let samplers = recorder.live_objects(ObjectKind::Sampler);
18057 let groups = recorder.live_objects(ObjectKind::BindGroup);
18058 let groups_created = || {
18059 recorder
18060 .events()
18061 .iter()
18062 .filter(|event| {
18063 matches!(
18064 event,
18065 Event::Created {
18066 kind: ObjectKind::BindGroup,
18067 ..
18068 }
18069 )
18070 })
18071 .count()
18072 };
18073
18074 renderer
18075 .set_anisotropy(device, DEFAULT_ANISOTROPY)
18076 .expect("the device allows it");
18077 assert_eq!(
18078 recorder.live_objects(ObjectKind::Sampler),
18079 samplers,
18080 "the value in force creates nothing"
18081 );
18082
18083 renderer
18084 .set_anisotropy(device, 4.0)
18085 .expect("the device allows it");
18086 assert!((renderer.anisotropy() - 4.0).abs() < f32::EPSILON);
18087 assert_eq!(
18088 recorder.live_objects(ObjectKind::Sampler),
18089 samplers + 1,
18090 "the new sampler stands beside the one every slot still names"
18091 );
18092 assert_eq!(
18093 recorder.live_objects(ObjectKind::BindGroup),
18094 groups,
18095 "no group moves until its slot's frame"
18096 );
18097
18098 for round in 0..FRAMES_IN_FLIGHT {
18099 renderer
18100 .begin_frame(
18101 device,
18102 &Camera::default(),
18103 &DirectionalLight::default(),
18104 (64, 48),
18105 )
18106 .expect("write");
18107 let expected = if round + 1 < FRAMES_IN_FLIGHT {
18108 samplers + 1
18109 } else {
18110 samplers
18111 };
18112 assert_eq!(
18113 recorder.live_objects(ObjectKind::Sampler),
18114 expected,
18115 "round {round}: the replaced sampler lives until the last slot has left it"
18116 );
18117 assert_eq!(
18118 recorder.live_objects(ObjectKind::BindGroup),
18119 groups,
18120 "round {round}: every rebuilt group replaced one"
18121 );
18122 }
18123 let created = groups_created();
18124 for _ in 0..FRAMES_IN_FLIGHT {
18125 renderer
18126 .begin_frame(
18127 device,
18128 &Camera::default(),
18129 &DirectionalLight::default(),
18130 (64, 48),
18131 )
18132 .expect("write");
18133 }
18134 assert_eq!(
18135 groups_created(),
18136 created,
18137 "a slot already on the sampler in force rebuilds nothing"
18138 );
18139
18140 // The clamp: the device's ceiling above it, off below one, the default
18141 // for a value that is not a number.
18142 let ceiling = device.caps().limits.max_sampler_anisotropy;
18143 renderer
18144 .set_anisotropy(device, ceiling * 4.0)
18145 .expect("clamped to what the device allows");
18146 assert!((renderer.anisotropy() - ceiling).abs() < f32::EPSILON);
18147 renderer
18148 .set_anisotropy(device, 0.0)
18149 .expect("one is the value that turns it off");
18150 assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18151 renderer
18152 .set_anisotropy(device, f32::NAN)
18153 .expect("the default is a sampler the device allows");
18154 assert!((renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON);
18155
18156 recorder.assert_valid();
18157 renderer.destroy(device);
18158 assert_eq!(
18159 recorder.live_objects(ObjectKind::Sampler),
18160 0,
18161 "the samplers no slot ever adopted went with the renderer"
18162 );
18163 }
18164
18165 /// A device without the feature samples isotropically whatever is asked:
18166 /// the ceiling is one, so the clamp lands on the value already in force and
18167 /// no sampler is created that `create_sampler` would refuse.
18168 #[test]
18169 fn a_device_without_the_feature_keeps_the_page_isotropic_whatever_is_asked() {
18170 let (recorder, device, queue) = open();
18171 let device = device.as_ref();
18172 assert!(
18173 !device
18174 .caps()
18175 .features
18176 .contains(Features::SAMPLER_ANISOTROPY),
18177 "the default request does not name the feature"
18178 );
18179 let mut renderer =
18180 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18181 assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18182 let samplers = recorder.live_objects(ObjectKind::Sampler);
18183
18184 renderer
18185 .set_anisotropy(device, DEFAULT_ANISOTROPY)
18186 .expect("asks for nothing the device lacks");
18187 assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18188 assert_eq!(recorder.live_objects(ObjectKind::Sampler), samplers);
18189 renderer.destroy(device);
18190 }
18191
18192 /// The knob clamps to the range it documents, in both directions and on a
18193 /// value that is neither.
18194 ///
18195 /// **The `NaN` arm is the one worth having.** A slider that divided by a
18196 /// zero, or a settings file that carried a nonsense string, reaches this
18197 /// with a value that fails every comparison it is put through — so a naive
18198 /// `clamp` would keep it, `internal_extent` would multiply by it, and the
18199 /// `as u32` below would produce a zero extent and a device error a long way
18200 /// from here.
18201 #[test]
18202 fn the_render_scale_is_clamped_to_the_range_it_documents() {
18203 let (recorder, device, queue) = open();
18204 let device = device.as_ref();
18205 let mut renderer =
18206 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18207
18208 assert!(
18209 (renderer.render_scale() - 1.0).abs() < f32::EPSILON,
18210 "a renderer nobody has called the setter on draws at full scale"
18211 );
18212
18213 renderer.set_render_scale(0.5);
18214 assert!((renderer.render_scale() - 0.5).abs() < f32::EPSILON);
18215
18216 // Above one is supersampling, which this filter is the wrong one for.
18217 renderer.set_render_scale(2.0);
18218 assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18219
18220 renderer.set_render_scale(0.01);
18221 assert!((renderer.render_scale() - MIN_RENDER_SCALE).abs() < f32::EPSILON);
18222
18223 renderer.set_render_scale(f32::NAN);
18224 assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18225 renderer.set_render_scale(f32::INFINITY);
18226 assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18227
18228 renderer.destroy(device);
18229 recorder.assert_valid();
18230 }
18231
18232 /// The internal extent is the target rounded, never zero, and is the target
18233 /// itself at full scale.
18234 ///
18235 /// **The floor is not decoration.** A transient image of zero extent is a
18236 /// device error rather than a small frame, and a 4×3 target at the minimum
18237 /// scale is exactly the arithmetic that would produce one.
18238 #[test]
18239 fn the_internal_extent_rounds_and_never_reaches_zero() {
18240 let (recorder, device, queue) = open();
18241 let device = device.as_ref();
18242 let mut renderer =
18243 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18244
18245 assert_eq!(
18246 renderer.internal_extent((1920, 1080)),
18247 (1920, 1080),
18248 "full scale is the absence of the feature, not a resize by one"
18249 );
18250
18251 renderer.set_render_scale(0.5);
18252 assert_eq!(renderer.internal_extent((1920, 1080)), (960, 540));
18253
18254 // Rounds rather than truncating: 1920 * 0.7 is 1344, and 1080 * 0.7 is
18255 // 756 — both exact — so a target that does *not* divide evenly is what
18256 // shows the rounding. 1281 * 0.7 = 896.7.
18257 renderer.set_render_scale(0.7);
18258 assert_eq!(renderer.internal_extent((1281, 1080)), (897, 756));
18259
18260 renderer.set_render_scale(MIN_RENDER_SCALE);
18261 assert_eq!(renderer.internal_extent((4, 3)), (1, 1));
18262 assert_eq!(
18263 renderer.internal_extent((0, 0)),
18264 (1, 1),
18265 "a minimised window is the caller's zero extent, and this may not \
18266 pass it through as one"
18267 );
18268
18269 renderer.destroy(device);
18270 recorder.assert_valid();
18271 }
18272
18273 /// **The upscale is a pass below full scale and is not there above it**, and
18274 /// the frame is otherwise the same list.
18275 ///
18276 /// This is the observable the knob is: everything else about it — the
18277 /// clamps, the rounding — is arithmetic that could be right while the frame
18278 /// went on being drawn at the caller's extent. What says the feature works
18279 /// is that the pass appears, that it appears **last**, and that switching it
18280 /// off leaves the frame that was there before it existed.
18281 #[test]
18282 fn the_upscale_is_the_last_pass_and_only_below_full_scale() {
18283 let _blurs = ssao_blur_switch();
18284 let (recorder, device, queue) = open();
18285 let device = device.as_ref();
18286 let mut renderer =
18287 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18288 let imported = swapchain_image_at(device, TEST_EXTENT);
18289 let pool = crate::TransientPool::new();
18290
18291 let full = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18292 assert!(
18293 !full.contains(&"upscale".to_string()),
18294 "a frame at full scale has no upscale in it: {full:?}"
18295 );
18296
18297 renderer.set_render_scale(0.5);
18298 let scaled = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18299 assert_eq!(
18300 scaled.iter().filter(|label| *label == "upscale").count(),
18301 1,
18302 "a scaled frame records exactly one upscale: {scaled:?}"
18303 );
18304 // Last of the passes that draw. The statistics copy is genuinely after
18305 // it and says so — see the comment on `add_copy_pass`'s placement.
18306 let upscale = scaled
18307 .iter()
18308 .position(|label| label == "upscale")
18309 .expect("the assertion above");
18310 let tonemap = scaled
18311 .iter()
18312 .position(|label| label == "tonemap")
18313 .expect("every frame tonemaps");
18314 assert!(
18315 upscale > tonemap,
18316 "the upscale carries what the post chain ended with: {scaled:?}"
18317 );
18318
18319 // **The pyramid gets shorter, and that is the evidence the rest of the
18320 // frame really is smaller.** Everything above this is about the last
18321 // pass; a knob that added an upscale while going on rendering at the
18322 // caller's extent would pass every one of those assertions and save
18323 // nothing. `crate::hiz`'s chain is as long as the extent allows, so the
18324 // level count is a number read out of the frame that can only be the
18325 // internal extent's.
18326 let levels = |passes: &[String]| {
18327 passes
18328 .iter()
18329 .filter(|label| label.starts_with("hiz-"))
18330 .count()
18331 };
18332 let internal = renderer.internal_extent(TEST_EXTENT);
18333 assert_eq!(levels(&full), crate::hiz::levels_for(TEST_EXTENT) as usize);
18334 assert_eq!(levels(&scaled), crate::hiz::levels_for(internal) as usize);
18335 assert!(
18336 levels(&scaled) < levels(&full),
18337 "at this extent the halved frame has to lose a level, or this \
18338 assertion is not looking at anything: {scaled:?}"
18339 );
18340
18341 // And nothing else moved: an upscale is a pass added to the frame, not a
18342 // frame rebuilt around one. The pyramid is the one part that is a
18343 // function of the extent, so it is compared by the count above and
18344 // dropped from the list here.
18345 let without_hiz = |passes: &[String]| -> Vec<String> {
18346 passes
18347 .iter()
18348 .filter(|label| !label.starts_with("hiz-") && *label != "upscale")
18349 .cloned()
18350 .collect()
18351 };
18352 assert_eq!(
18353 without_hiz(&scaled),
18354 without_hiz(&full),
18355 "the scaled frame is the full-scale frame, one pass longer and one \
18356 pyramid shorter"
18357 );
18358
18359 renderer.set_render_scale(1.0);
18360 let back = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18361 assert_eq!(
18362 back, full,
18363 "the knob goes back, which is what a settings slider does"
18364 );
18365
18366 renderer.destroy(device);
18367 device.destroy_image_view(imported.view);
18368 device.destroy_image(imported.image);
18369 recorder.assert_valid();
18370 }
18371
18372 /// **A skinned-frame overlay receives the display and depth images at the
18373 /// internal extent, before either resolve reconstructs the target.**
18374 ///
18375 /// The callback's own pass attaches the display and depth it received. That
18376 /// makes matching dimensions a graph invariant rather than a comparison of
18377 /// numbers the callback could have been handed without ever using the
18378 /// images; changing either id to a target-sized image makes compilation
18379 /// refuse the mismatched attachments.
18380 #[test]
18381 fn an_overlay_uses_the_internal_display_and_depth_before_the_resolves() {
18382 let (recorder, device, queue) = open();
18383 let device = device.as_ref();
18384 let mut fixture = SkinnedFixture::build(device, queue);
18385 fixture.renderer.set_render_scale(0.5);
18386 fixture.renderer.set_effect_request(EffectRequest {
18387 antialiasing: Some(Antialiasing::Fxaa),
18388 ..EffectRequest::default()
18389 });
18390 fixture.begin(device);
18391 let internal_extent = fixture.renderer.internal_extent(TEST_EXTENT);
18392
18393 let imported = swapchain_image_at(device, TEST_EXTENT);
18394 let mut pool = crate::TransientPool::new();
18395 {
18396 let mut graph = crate::RenderGraph::new(queue);
18397 let target = graph.import_image("target", imported);
18398 let mut received = None;
18399 fixture.renderer.add_skinned_passes_with_overlay(
18400 &mut graph,
18401 &pool,
18402 target,
18403 TEST_EXTENT,
18404 &fixture.skinning,
18405 |graph, targets| {
18406 received = Some(targets);
18407 graph
18408 .add_render_pass("overlay-probe")
18409 .color(
18410 targets.display,
18411 LoadOp::Load,
18412 StoreOp::Store,
18413 crcbl_hal::ClearValue::default(),
18414 )
18415 .depth_read(targets.depth)
18416 .execute(|_| {});
18417 },
18418 );
18419 let received = received.expect("the overlay callback runs while the frame is built");
18420 assert_eq!(
18421 received.internal_extent, internal_extent,
18422 "the overlay receives the extent its display and depth attachments have"
18423 );
18424
18425 let compiled = graph.compile(&pool).expect("the shared attachments match");
18426 let labels: Vec<&str> = compiled.passes().iter().map(|pass| pass.label()).collect();
18427 let overlay = labels
18428 .iter()
18429 .position(|label| *label == "overlay-probe")
18430 .expect("the callback's pass is part of the frame");
18431 let fxaa = labels
18432 .iter()
18433 .position(|label| *label == "fxaa")
18434 .expect("the requested resolve is part of the frame");
18435 let upscale = labels
18436 .iter()
18437 .position(|label| *label == "upscale")
18438 .expect("the half-scale frame reconstructs its target");
18439 assert!(
18440 overlay < fxaa && overlay < upscale,
18441 "the overlay must write display before its resolve and upscale: {labels:?}"
18442 );
18443 }
18444
18445 fixture.destroy(device);
18446 pool.destroy(device);
18447 device.destroy_image_view(imported.view);
18448 device.destroy_image(imported.image);
18449 recorder.assert_valid();
18450 }
18451
18452 /// **[`ForwardRenderer::MAX_PASSES`] bounds the frame, and lands on it.**
18453 ///
18454 /// It is what a caller sizes [`PassTimers`](crate::PassTimers) with, so both
18455 /// halves matter: a bound under the widest frame times part of it and drops
18456 /// the rest, and a bound well over it buys query sets nothing ever writes.
18457 /// A shadowable spot per light slot fills every one of them, which is the
18458 /// most culls a frame can run and so the widest frame there is — it must land
18459 /// exactly on the constant, and the frame with no shadowed light at all must
18460 /// be short of it by exactly the culls those slots would have added.
18461 ///
18462 /// The ground grid is switched on for **both** frames, because the widest
18463 /// frame is the one that has it: it is off by default and not a
18464 /// [`RenderEffects`] bit, so nothing else here would put its pass in. The
18465 /// debug draw layer is on for both frames for the same reason, and it needs
18466 /// a segment appended before each rather than one switch, because
18467 /// [`begin_frame`](ForwardRenderer::begin_frame) clears its buffer.
18468 ///
18469 /// **And the frames are drawn at [`WIDEST_EXTENT`] rather than at
18470 /// [`TEST_EXTENT`], with every effect forced on and the render scale off
18471 /// full.** The bloom chain's length is a function of the extent the frame is
18472 /// drawn at — see [`crate::bloom`] — so the widest frame this renderer
18473 /// records is a *large* one, and a bound checked against a 64×48 frame would
18474 /// sit six passes above what that frame runs and this assertion would have
18475 /// to be a `<=`. It is an `==` on purpose: a bound well over the widest
18476 /// frame buys query sets nothing writes, and only an exact comparison
18477 /// notices.
18478 ///
18479 /// **The render scale is what makes those two requirements compose.** The
18480 /// upscale is a pass only below full scale, and below full scale the chain
18481 /// runs at the *internal* extent — so a frame with both is one whose
18482 /// internal extent is the longest chain's, and whose target is larger than
18483 /// that. Halving a target of 2048×1024 is what arranges it, and the two
18484 /// assertions below check the arrangement rather than trusting it.
18485 ///
18486 /// [`WIDEST_EXTENT`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
18487 #[test]
18488 fn the_pass_bound_is_the_widest_frame_the_renderer_records() {
18489 /// The extent whose bloom chain is the longest [`crate::bloom`] will
18490 /// build: six halvings of 512 leave sixteen by eight, which is still at
18491 /// or above that module's floor. The widest frame is drawn at this,
18492 /// which is why it is the internal one and not the target.
18493 const WIDEST_INTERNAL: (u32, u32) = (1024, 512);
18494 /// Half, so the frame records an upscale and draws at
18495 /// [`WIDEST_INTERNAL`].
18496 const WIDEST_SCALE: f32 = 0.5;
18497 /// The caller's extent: twice [`WIDEST_INTERNAL`] in each dimension.
18498 const WIDEST_EXTENT: (u32, u32) = (WIDEST_INTERNAL.0 * 2, WIDEST_INTERNAL.1 * 2);
18499
18500 let (recorder, device, queue) = open();
18501 let device = device.as_ref();
18502 // **A scene whose probes ask to be updated**, because the widest frame
18503 // is the one with every pass in it and
18504 // the irradiance probes' two are recorded by a volume
18505 // rather than by an effect bit — the ground grid's argument exactly. A
18506 // renderer built on the demo's empty grid records neither, and the bound
18507 // would then be checked against a frame that could not reach it.
18508 let mut scene = scene::demo();
18509 scene.capacities.probes = 1;
18510 scene.probes = scene::ProbeGrid {
18511 volume: crcbl_shaders::probe::ProbeVolume {
18512 origin: [0.0; 3],
18513 inv_spacing: [1.0; 3],
18514 counts: [1, 1, 1],
18515 levels: 1,
18516 steps: crcbl_shaders::probe::ProbeSteps::default(),
18517 },
18518 probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
18519 update: ProbeUpdate::EveryFrame,
18520 };
18521 let mut renderer =
18522 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
18523 .expect("built");
18524 // A maximum-width graph must include actual instances to cull.
18525 place_cube(&mut renderer, Mat4::IDENTITY);
18526 renderer
18527 .set_ground_grid(device, Some(GridStyle::default()))
18528 .expect("the null backend builds every pipeline");
18529 // **And the occlusion cull**, whose late prepass, farthest pyramid and
18530 // three late compute passes are the ground grid's kind of pass: off
18531 // unless a caller asks, and in the widest frame when one does.
18532 renderer.set_occlusion_culling(OcclusionCulling {
18533 occlusion: true,
18534 small_feature_pixels: None,
18535 });
18536 // **A body of water**, on the ground grid's terms: content rather than
18537 // an effect bit, so the widest frame is one a caller gave water to, and
18538 // `Water::PASSES` is in the bound for it.
18539 renderer
18540 .set_water(&[crcbl_water::WaterBody {
18541 outline: vec![[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]],
18542 level: 0.0,
18543 medium: crcbl_water::Medium {
18544 absorption: [0.4, 0.1, 0.05],
18545 scattering: [0.01, 0.01, 0.01],
18546 },
18547 }])
18548 .expect("a square meshes");
18549 // **A field of grass**, on the water body's terms exactly: content
18550 // rather than an effect bit, so the widest frame is one a caller gave a
18551 // field to and `Grass::PASSES` is in the bound for it.
18552 renderer
18553 .set_grass(
18554 device,
18555 queue,
18556 Some(
18557 &crate::grass::GrassField::new(
18558 [1, 1],
18559 4.0,
18560 [-2.0, -2.0],
18561 50.0,
18562 crate::grass::Heightfield {
18563 texels: [4, 4],
18564 metres_per_texel: 1.0,
18565 origin: [-2.0, -2.0],
18566 heights: vec![0.0; 16],
18567 },
18568 crate::grass::CoverMap {
18569 texels: [4, 4],
18570 metres_per_texel: 1.0,
18571 origin: [-2.0, -2.0],
18572 cover: vec![[255, 0]; 16],
18573 },
18574 // A shell row and a mesh blade row, so the widest
18575 // frame records every look's draw the grass pass has.
18576 [
18577 crate::grass::BladeLook::Shells,
18578 crate::grass::BladeLook::Blades,
18579 ]
18580 .map(|look| crate::grass::BladeType {
18581 root_color: [0.05, 0.1, 0.02],
18582 tip_color: [0.3, 0.5, 0.1],
18583 height: 0.3,
18584 half_width: 0.03,
18585 height_spread: 0.3,
18586 width_spread: 0.2,
18587 look,
18588 style: crate::grass::BladeStyle::PLAIN,
18589 shape: crate::grass::BladeShape::STRAIGHT,
18590 clumping: crate::grass::Clumping::NONE,
18591 })
18592 .to_vec(),
18593 )
18594 .expect("a real field"),
18595 ),
18596 )
18597 .expect("the null backend uploads every map");
18598 renderer.set_render_scale(WIDEST_SCALE);
18599 assert_eq!(
18600 renderer.internal_extent(WIDEST_EXTENT),
18601 WIDEST_INTERNAL,
18602 "the scale has to take the target to the extent whose chain is the \
18603 longest one, or the bound below is checked against a frame that \
18604 could not reach it"
18605 );
18606 // **Both post effects forced on.** Neither is in the default camera
18607 // stack — see [`RenderEffects::DEFAULT_STACK`], which leaves the lens out
18608 // for one reason and the resolve out for another — and the widest frame
18609 // is the one that has every effect in it, the ground grid's argument
18610 // exactly.
18611 renderer.set_effect_request(EffectRequest {
18612 programmatic: EffectOverride::none().force(OUTSIDE_THE_DEFAULT, Some(true)),
18613 ..EffectRequest::default()
18614 });
18615 let imported = swapchain_image_at(device, WIDEST_EXTENT);
18616 let mut pool = crate::TransientPool::new();
18617
18618 // The debug draw layer on for both frames below, because it is a pass
18619 // the bound counts and no effect bit switches on — the ground grid's
18620 // argument again. A segment before each, since `begin_frame` clears the
18621 // buffer: the layer is immediate mode.
18622 let switch = debug_draw_switch();
18623 switch.set(true);
18624 // And the occlusion pair's second blur, for exactly that reason: it is a
18625 // pass [`Ssao::MAX_PASSES`] counts and no effect bit switches on, so a
18626 // frame at the shipping count comes one short of the bound and this test
18627 // would be asserting the bound against a frame that could not reach it.
18628 let blurs = ssao_blur_switch();
18629 blurs.set(i64::from(Ssao::MAX_BLUR_PASSES));
18630 // And the comparison seam, which is the occlusion chain's other
18631 // conditional pass — see `crate::ssao`'s `r_ssao_split`. Held for the
18632 // same reason the blur count is: the bound counts a frame that compares,
18633 // so a frame that does not could never reach it.
18634 let split = ssao_split_switch();
18635 split.set(0.5);
18636 renderer
18637 .debug_draw()
18638 .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18639 let bare =
18640 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18641 assert_eq!(
18642 crate::bloom::mips_for(WIDEST_INTERNAL),
18643 crate::bloom::MAX_MIPS,
18644 "the widest frame has to be one whose chain is the longest one there \
18645 is, or the bound below is checked against a frame that could not \
18646 reach it"
18647 );
18648 assert!(
18649 bare < ForwardRenderer::MAX_PASSES as usize,
18650 "a frame with no shadowed light runs {bare} passes, which is already the \
18651 bound of {} — then the bound does not cover the slots this scene left free",
18652 ForwardRenderer::MAX_PASSES
18653 );
18654
18655 // One spot per slot, spaced so no two of them share an influence — the
18656 // list has to fill every slot or the bound below is checked against a
18657 // frame that could not reach it.
18658 #[expect(
18659 clippy::cast_precision_loss,
18660 reason = "a handful of slots, and the value is only a position"
18661 )]
18662 let spots: Vec<Light> = (0..shadow::LIGHT_SLOTS)
18663 .map(|slot| shadowable_spot(1.0 + slot as f32))
18664 .collect();
18665 renderer.set_lights(&spots);
18666 renderer
18667 .debug_draw()
18668 .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18669 let widest =
18670 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18671 assert_eq!(
18672 renderer.shadow_lights.slots().iter().flatten().count(),
18673 shadow::LIGHT_SLOTS,
18674 "the spots must actually hold every slot, or this is the bare frame again \
18675 under another name"
18676 );
18677 assert_eq!(
18678 widest,
18679 ForwardRenderer::MAX_PASSES as usize,
18680 "the widest frame is what the bound is for"
18681 );
18682 assert_eq!(
18683 widest - bare,
18684 DrawGen::MAX_PASSES as usize * shadow::LIGHT_SLOTS,
18685 "a filled slot costs a cull's passes and nothing else"
18686 );
18687
18688 renderer.destroy(device);
18689 pool.destroy(device);
18690 device.destroy_image_view(imported.view);
18691 device.destroy_image(imported.image);
18692 recorder.assert_valid();
18693 }
18694
18695 /// **A toggle reaches the recorded frame, and takes exactly its own passes
18696 /// with it.**
18697 ///
18698 /// The observable is the compiled pass list, because the thing that could
18699 /// otherwise be true is that the switch is stored and read by nothing: a
18700 /// renderer holding `SHADOWS` clear and recording every shadow cull anyway
18701 /// draws a frame that looks right, reports the right effect set, and has not
18702 /// switched anything off.
18703 ///
18704 /// So each arm compares the whole list rather than its length. Two passes
18705 /// fewer is satisfied by removing the wrong two, and it is satisfied by a
18706 /// frame that lost its tonemap.
18707 ///
18708 /// The shadow arm is the one that cannot be written by name — a cascade's
18709 /// cull passes are labelled exactly as the camera's are — so it is written as
18710 /// its two halves instead: the count moves by a cull's worth per cascade and
18711 /// per filled light slot, and everything from the `shadow` pass onwards is
18712 /// unchanged. The `shadow` pass itself **stays**, because it is what writes
18713 /// the clear that reads as "fully lit".
18714 #[test]
18715 fn each_effect_toggle_removes_exactly_the_passes_it_owns() {
18716 let _blurs = ssao_blur_switch();
18717 let (recorder, device, queue) = open();
18718 let device = device.as_ref();
18719 let mut renderer =
18720 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18721 place_cube(&mut renderer, Mat4::IDENTITY);
18722 // One shadowed light beside the cascades, so the shadow arm below covers
18723 // a light slot's cull as well as a cascade's.
18724 renderer.set_lights(&[shadowable_spot(-1.0)]);
18725 let imported = swapchain_image(device);
18726 let mut pool = crate::TransientPool::new();
18727
18728 // [`OUTSIDE_THE_DEFAULT`] forced on and then `off` forced off, on
18729 // [`frame_switching_off`]'s terms exactly: the default camera stack
18730 // leaves both of them out — see [`RenderEffects::DEFAULT_STACK`] — so a
18731 // control built on the default alone would have nothing for their arms
18732 // to remove. `force` clears the other side, so an arm whose `off` is one
18733 // of them still resolves to off.
18734 //
18735 // [`frame_switching_off`]: fn@frame_switching_off
18736 let without = |renderer: &mut ForwardRenderer, off: RenderEffects| {
18737 renderer.set_effect_request(EffectRequest {
18738 programmatic: EffectOverride::none()
18739 .force(OUTSIDE_THE_DEFAULT, Some(true))
18740 .force(off, Some(false)),
18741 ..EffectRequest::default()
18742 });
18743 passes_in_a_frame(device, queue, renderer, imported, &pool, TEST_EXTENT)
18744 };
18745
18746 let all_on = without(&mut renderer, RenderEffects::empty());
18747 assert_eq!(
18748 renderer.effects(),
18749 RenderEffects::all(),
18750 "the control frame has to be the every-effect one"
18751 );
18752 assert_eq!(
18753 renderer.shadow_lights.slots().iter().flatten().count(),
18754 1,
18755 "the spot must actually hold a slot, or the shadow arm below is only about cascades"
18756 );
18757
18758 // **None of the three leaves anything behind it**, and for the same
18759 // reason: nothing reads what it would have written. The occlusion pair's
18760 // reader binds the 1×1 white placeholder instead — `mesh.slang` clamps
18761 // its `Load` into it — and the reflection pair's and the chain's readers
18762 // both tonemap whatever image they would have read anyway.
18763 //
18764 // The chain's labels are written out rather than built from
18765 // `crate::bloom`'s arithmetic, because a table generated from the code
18766 // under test cannot fail: it is `TEST_EXTENT`'s two levels — two
18767 // downsamples, the one upsample between them, and the composite — and if
18768 // that extent moves this is the assertion that says so.
18769 for (off, gone) in [
18770 (
18771 RenderEffects::AMBIENT_OCCLUSION,
18772 ["ssao", "ssao-blur", "ssao-upsample"].as_slice(),
18773 ),
18774 (
18775 RenderEffects::CONTACT_SHADOWS,
18776 // One pass and no blur — `crate::contact_shadows`'s header says
18777 // why the occlusion pair's second pass has no counterpart here.
18778 ["contact-shadows"].as_slice(),
18779 ),
18780 (
18781 RenderEffects::REFLECTIONS,
18782 // **The pyramid goes with the march**, which is the whole of
18783 // what makes it an optimisation rather than a resource: it is
18784 // recorded on the frames that reflect and on no others. Two
18785 // levels at `TEST_EXTENT`, written out on the chain's terms
18786 // above.
18787 ["hiz-1", "hiz-2", "ssr", "ssr-blur"].as_slice(),
18788 ),
18789 (
18790 RenderEffects::BLOOM,
18791 [
18792 "bloom-down-1",
18793 "bloom-down-2",
18794 "bloom-up-1",
18795 "bloom-composite",
18796 ]
18797 .as_slice(),
18798 ),
18799 (
18800 RenderEffects::AUTO_EXPOSURE,
18801 // All three go together and the tonemap stays: the pass reads
18802 // the measurement only when the block says to, and the block
18803 // says so on exactly the frames these three ran on.
18804 ["exposure-clear", "exposure-histogram", "exposure-reduce"].as_slice(),
18805 ),
18806 ] {
18807 let labels = without(&mut renderer, off);
18808 assert_eq!(
18809 renderer.effects(),
18810 RenderEffects::all().difference(off),
18811 "{off:?}: the frame must have resolved to the set the request asked for"
18812 );
18813 // **The control frame has to contain what this arm removes**, and
18814 // that is not a restatement of the comparison below: the comparison
18815 // builds `expected` by filtering `gone` out of `all_on`, so an arm
18816 // naming a pass the control never recorded filters nothing, matches,
18817 // and passes whether the effect draws anything or not. Removing the
18818 // resolve pass entirely left this loop green until this assertion
18819 // existed.
18820 for label in gone {
18821 assert!(
18822 all_on.iter().any(|recorded| recorded == label),
18823 "{off:?}: the every-effect frame does not record `{label}`, so removing it \
18824 below proves nothing: {all_on:#?}"
18825 );
18826 }
18827 let expected: Vec<String> = all_on
18828 .iter()
18829 .filter(|label| !gone.contains(&label.as_str()))
18830 .cloned()
18831 .collect();
18832 assert_eq!(
18833 labels, expected,
18834 "{off:?}: the frame must lose {gone:?}, gain nothing in their place, and keep \
18835 every other pass"
18836 );
18837 }
18838
18839 // **The two antialiasing tiers share one resolve slot**, so neither is
18840 // a plain removal and neither belongs in the loop above: switching
18841 // CMAA2 off while FXAA stays on swaps three passes for one rather than
18842 // losing three, and the loop's "gain nothing in their place" comparison
18843 // is exactly what that violates. Three frames say it instead.
18844 let both = all_on.clone();
18845 let cheap = without(&mut renderer, RenderEffects::CMAA2);
18846 let neither = without(
18847 &mut renderer,
18848 RenderEffects::CMAA2.union(RenderEffects::ANTIALIASING),
18849 );
18850 const CMAA2_PASSES: [&str; 3] = ["cmaa2-edges", "cmaa2-shapes", "cmaa2-apply"];
18851 let resolve_of = |labels: &[String]| -> Vec<String> {
18852 labels
18853 .iter()
18854 .filter(|label| *label == "fxaa" || CMAA2_PASSES.contains(&label.as_str()))
18855 .cloned()
18856 .collect()
18857 };
18858 let without_resolve = |labels: &[String]| -> Vec<String> {
18859 labels
18860 .iter()
18861 .filter(|label| *label != "fxaa" && !CMAA2_PASSES.contains(&label.as_str()))
18862 .cloned()
18863 .collect()
18864 };
18865 assert_eq!(
18866 resolve_of(&both),
18867 CMAA2_PASSES.map(str::to_string).to_vec(),
18868 "with both bits set the higher tier takes the slot and the cheap one \
18869 records nothing"
18870 );
18871 assert_eq!(
18872 resolve_of(&cheap),
18873 vec!["fxaa".to_string()],
18874 "with only the cheap bit set the slot is FXAA's"
18875 );
18876 assert!(
18877 resolve_of(&neither).is_empty(),
18878 "with neither bit set the frame has no resolve at all: {neither:#?}"
18879 );
18880 // And nothing else moved: the tiers swap in one slot rather than
18881 // rebuilding the frame around themselves.
18882 assert_eq!(without_resolve(&both), without_resolve(&cheap));
18883 assert_eq!(without_resolve(&both), without_resolve(&neither));
18884 // The slot is where the ordering argument puts it — directly after the
18885 // last pass that writes the display image, which at this extent is the
18886 // tonemap.
18887 for labels in [&both, &cheap] {
18888 let at = labels
18889 .iter()
18890 .position(|label| label == "tonemap")
18891 .expect("a frame has to reach the swapchain");
18892 assert_eq!(
18893 &labels[at + 1..=at + resolve_of(labels).len()],
18894 resolve_of(labels).as_slice(),
18895 "the resolve must follow the tonemap: {labels:#?}"
18896 );
18897 }
18898
18899 let no_shadows = without(&mut renderer, RenderEffects::SHADOWS);
18900 assert_eq!(
18901 renderer.effects(),
18902 RenderEffects::all().difference(RenderEffects::SHADOWS),
18903 );
18904 assert_eq!(
18905 all_on.len() - no_shadows.len(),
18906 DrawGen::MAX_PASSES as usize * (shadow::CASCADES + 1),
18907 "shadows off must drop a cull's passes per cascade and per filled slot"
18908 );
18909 let from_the_atlas = |labels: &[String]| {
18910 let at = labels
18911 .iter()
18912 .position(|label| label == "shadow")
18913 .expect("the atlas pass is recorded whether or not anything draws into it");
18914 labels[at..].to_vec()
18915 };
18916 assert_eq!(
18917 from_the_atlas(&no_shadows),
18918 from_the_atlas(&all_on),
18919 "only the culls go: the atlas pass and everything after it are unchanged"
18920 );
18921
18922 renderer.destroy(device);
18923 pool.destroy(device);
18924 device.destroy_image_view(imported.view);
18925 device.destroy_image(imported.image);
18926 recorder.assert_valid();
18927 }
18928
18929 /// **The contact march is a pass a frame records only when it was asked
18930 /// for, and the mask it writes is what the forward pass then reads.**
18931 ///
18932 /// Two observables, because either alone is satisfied by a mistake the other
18933 /// one catches:
18934 ///
18935 /// * **The compiled pass list.** `contact-shadows` appears between the
18936 /// prepass whose depth it marches and the forward pass that binds it, and
18937 /// appears at all only on the frame that asked. The toggle test above
18938 /// already says a frame loses this pass and nothing else; what is added
18939 /// here is *where* it sits, which is the half a set comparison cannot see
18940 /// — a march recorded after the pass that reads it compiles and draws a
18941 /// mask nothing ever looks at.
18942 /// * **The forward pass's own barriers.** On the frame that marched, one
18943 /// more image is transitioned into [`ResourceState::ShaderRead`] before
18944 /// the forward pass opens than on the frame that did not — which is the
18945 /// mask leaving the colour attachment it was written as. That is what says
18946 /// the pass's output reaches the shading, rather than being written into a
18947 /// transient and dropped while the shader goes on reading the 1×1
18948 /// placeholder. The placeholder is imported in `ShaderRead` already and
18949 /// needs no transition, so it contributes nothing to this count and the
18950 /// difference is exactly the mask.
18951 ///
18952 /// [`RenderEffects::CONTACT_SHADOWS`] is out of the default camera stack
18953 /// while its re-bless is pending — see that constant — so the `on` frame has
18954 /// to force it and the `off` frame is what a view saying nothing draws.
18955 #[test]
18956 fn the_contact_march_is_recorded_only_when_asked_and_its_mask_reaches_the_forward_pass() {
18957 let (recorder, device, queue) = open();
18958 let device = device.as_ref();
18959 let mut renderer =
18960 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18961 let imported = swapchain_image(device);
18962 let mut pool = crate::TransientPool::new();
18963
18964 let frame = |renderer: &mut ForwardRenderer, on: bool| -> (Vec<String>, usize) {
18965 renderer.set_effect_request(EffectRequest {
18966 programmatic: EffectOverride::none()
18967 .force(RenderEffects::CONTACT_SHADOWS, Some(on)),
18968 ..EffectRequest::default()
18969 });
18970 renderer
18971 .begin_frame(
18972 device,
18973 &Camera::default(),
18974 &DirectionalLight::default(),
18975 TEST_EXTENT,
18976 )
18977 .expect("write");
18978 let mut graph = crate::RenderGraph::new(queue);
18979 let target = graph.import_image("target", imported);
18980 renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
18981 let compiled = graph.compile(&pool).expect("a legal frame");
18982 let labels: Vec<String> = compiled
18983 .passes()
18984 .iter()
18985 .map(|pass| pass.label().to_string())
18986 .collect();
18987 let readable = compiled
18988 .passes()
18989 .iter()
18990 .find(|pass| pass.label() == "forward")
18991 .expect("every frame draws its geometry")
18992 .barriers()
18993 .images
18994 .iter()
18995 .filter(|barrier| barrier.to == ResourceState::ShaderRead)
18996 .count();
18997 (labels, readable)
18998 };
18999
19000 let (marched, marched_reads) = frame(&mut renderer, true);
19001 assert!(
19002 renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19003 "the forced frame has to have resolved with the bit set"
19004 );
19005 let (bare, bare_reads) = frame(&mut renderer, false);
19006 assert!(
19007 !renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19008 "and the control frame without it"
19009 );
19010
19011 assert!(
19012 !bare.iter().any(|label| label == "contact-shadows"),
19013 "a frame that did not ask must record no march at all: {bare:#?}"
19014 );
19015 let at = |labels: &[String], wanted: &str| {
19016 labels
19017 .iter()
19018 .position(|label| label == wanted)
19019 .unwrap_or_else(|| panic!("no `{wanted}` pass in {labels:#?}"))
19020 };
19021 let march = at(&marched, "contact-shadows");
19022 assert!(
19023 march > at(&marched, "depth-prepass"),
19024 "the march reads the prepass's depth, so it cannot precede it: {marched:#?}"
19025 );
19026 assert!(
19027 march < at(&marched, "forward"),
19028 "and the forward pass binds what it wrote, so it cannot follow it: {marched:#?}"
19029 );
19030
19031 assert_eq!(
19032 marched_reads,
19033 bare_reads + 1,
19034 "the forward pass has to take one more image into `ShaderRead` on the frame that \
19035 marched — the mask. Equal counts mean the pass wrote a transient the shading \
19036 never reads."
19037 );
19038
19039 renderer.destroy(device);
19040 pool.destroy(device);
19041 device.destroy_image_view(imported.view);
19042 device.destroy_image(imported.image);
19043 recorder.assert_valid();
19044 }
19045
19046 /// **The ground grid is off until a caller asks, and then it is the last
19047 /// pass of the frame — after the tonemap.**
19048 ///
19049 /// Three claims and each is a separate way to get this wrong. Off by default
19050 /// is what keeps every sample and every golden image where they were. *After
19051 /// the tonemap* is the placement decision: added a line earlier it would
19052 /// draw into the HDR scene colour and be tonemapped like geometry, which
19053 /// compiles, draws a grid, and gives it a colour that moves with the
19054 /// exposure. And switching it off again has to remove the pass, not merely
19055 /// stop reporting it.
19056 ///
19057 /// The whole list is compared rather than its length, for the reason the
19058 /// effect-toggle test gives: one more pass is satisfied by gaining the wrong
19059 /// one.
19060 #[test]
19061 fn the_ground_grid_is_opt_in_and_lands_after_the_tonemap() {
19062 let _blurs = ssao_blur_switch();
19063 let (recorder, device, queue) = open();
19064 let device = device.as_ref();
19065 let mut renderer =
19066 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19067 let imported = swapchain_image(device);
19068 let mut pool = crate::TransientPool::new();
19069
19070 let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19071 assert!(
19072 renderer.ground_grid().is_none(),
19073 "a renderer nobody asked has no grid"
19074 );
19075 assert!(
19076 !off.contains(&"grid".to_string()),
19077 "the grid must not be in a frame nobody asked for it in: {off:#?}"
19078 );
19079
19080 renderer
19081 .set_ground_grid(device, Some(GridStyle::default()))
19082 .expect("the null backend builds every pipeline");
19083 assert_eq!(renderer.ground_grid(), Some(&GridStyle::default()));
19084 let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19085
19086 let mut expected = off.clone();
19087 // The statistics copy is added after every render pass and stays last —
19088 // see `add_passes`. So the grid goes in front of it, which is directly
19089 // after the tonemap.
19090 let tonemap = expected
19091 .iter()
19092 .position(|label| label == "tonemap")
19093 .expect("a frame has to reach the swapchain");
19094 expected.insert(tonemap + 1, "grid".to_string());
19095 assert_eq!(
19096 on, expected,
19097 "the grid must be the one pass gained, and it must sit after the tonemap"
19098 );
19099
19100 renderer
19101 .set_ground_grid(device, None)
19102 .expect("switching off builds nothing");
19103 assert!(renderer.ground_grid().is_none());
19104 assert_eq!(
19105 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
19106 off,
19107 "switching the grid off has to remove its pass, not just stop reporting it"
19108 );
19109
19110 renderer.destroy(device);
19111 pool.destroy(device);
19112 device.destroy_image_view(imported.view);
19113 device.destroy_image(imported.image);
19114 recorder.assert_valid();
19115 }
19116
19117 /// **A second occlusion blur is a pass the frame records, an image it takes
19118 /// out of the pool, and a triangle its counter reports** — or it is a switch
19119 /// that does nothing.
19120 ///
19121 /// `crcbl`'s `forward_e2e::occlusion` measures what the second blur is worth
19122 /// by driving the pipelines itself, so nothing there would notice that a
19123 /// real frame never records it. The three things below are what a frame has
19124 /// to do differently, and each of them fails silently on its own: a missing
19125 /// pass draws a slightly rougher picture, a missing image is a bind of the
19126 /// wrong one, and a counter short by one is a number nobody reads until it
19127 /// is quoted.
19128 ///
19129 /// **This test owns `r_ssao_blur_passes` for its duration**, through
19130 /// [`ssao_blur_switch`] and for [`debug_draw_switch`]'s reason.
19131 /// The id [`Ssao::add_passes`] hands back is the reconstruction's target,
19132 /// whichever blur ran into it.
19133 ///
19134 /// **The one thing about that chain no other check can see.** The pass list
19135 /// is identical either way, the graph accepts a written-and-never-read
19136 /// transient without complaint, and every golden is at one blur where the
19137 /// two blur answers coincide — so a frame bound to the wrong image draws
19138 /// something nobody would question, which is exactly what the function's
19139 /// own doc warns about. Verified 2026-08-31 by returning `blurred` from the
19140 /// two-blur arm: `crcbl-render`'s unit tests, the forward and mesh e2e
19141 /// suites and lantern's golden all stayed green.
19142 ///
19143 /// **Since the halving it is a second silent failure and a louder one.**
19144 /// Every working image is [`crate::ssao::half_extent`] of the frame, so a
19145 /// returned working id is not merely a rougher channel — it is an image a
19146 /// quarter of the size bound where `mesh.slang` reads at `SV_Position`,
19147 /// which its clamp turns into occlusion smeared over the top-left quarter of
19148 /// the frame rather than into an error.
19149 #[test]
19150 fn the_occlusion_id_handed_back_is_the_reconstruction_target() {
19151 let (_recorder, device, queue) = open();
19152 let device = device.as_ref();
19153 let mut ssao = Ssao::new(device, 1, ForwardRenderer::build_fullscreen).expect("built");
19154 let gathered = crate::ssao::half_extent(TEST_EXTENT);
19155
19156 let one = {
19157 let mut graph = crate::RenderGraph::new(queue);
19158 let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19159 let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19160 let blurred =
19161 graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19162 let upsampled = graph.create_image(
19163 "ssao-upsampled",
19164 crate::targets::ambient_occlusion(TEST_EXTENT),
19165 );
19166 let got = ssao.add_passes(
19167 &mut graph,
19168 0,
19169 TEST_EXTENT,
19170 depth,
19171 crate::ssao::OcclusionImages {
19172 raw,
19173 blurred,
19174 again: None,
19175 upsampled,
19176 },
19177 );
19178 (got == upsampled, got == blurred || got == raw)
19179 };
19180 assert!(one.0, "one blur finishes in the reconstruction's image");
19181 assert!(
19182 !one.1,
19183 "and never in one of the half-extent images the chain worked in"
19184 );
19185
19186 let two = {
19187 let mut graph = crate::RenderGraph::new(queue);
19188 let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19189 let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19190 let blurred =
19191 graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19192 let again = graph.create_image(
19193 "ssao-blurred-2",
19194 crate::targets::ambient_occlusion(gathered),
19195 );
19196 let upsampled = graph.create_image(
19197 "ssao-upsampled",
19198 crate::targets::ambient_occlusion(TEST_EXTENT),
19199 );
19200 let got = ssao.add_passes(
19201 &mut graph,
19202 0,
19203 TEST_EXTENT,
19204 depth,
19205 crate::ssao::OcclusionImages {
19206 raw,
19207 blurred,
19208 again: Some(again),
19209 upsampled,
19210 },
19211 );
19212 (got == upsampled, got == again || got == blurred)
19213 };
19214 assert!(
19215 two.0,
19216 "two blurs finish in the reconstruction's image as well, which is the id the forward \
19217 pass binds"
19218 );
19219 assert!(
19220 !two.1,
19221 "and not in a blur's own image -- a frame bound to one of those is a frame nobody \
19222 would question"
19223 );
19224 }
19225
19226 /// **The gather runs at half the frame and the reconstruction runs at all
19227 /// of it** — or the halving is a description nobody rendered into.
19228 ///
19229 /// The pass list cannot see this: three passes with the right labels in the
19230 /// right order is exactly what a chain that halved nothing would record. The
19231 /// **render area** is where the halving is observable, and the graph derives
19232 /// it from each pass's colour attachment — so this is the check that the
19233 /// transients [`ForwardRenderer::add_passes`] created are the ones
19234 /// [`crate::ssao::half_extent`] sized, and that the reconstruction was given
19235 /// the frame-sized one.
19236 ///
19237 /// Neither mistake is an error anywhere else. Working images at the frame's
19238 /// extent are four times the march and a reconstruction reading the corner
19239 /// of its input; a frame-sized image handed to the march and a half-sized
19240 /// one to the forward pass is occlusion smeared over a quarter of the
19241 /// picture by `mesh.slang`'s clamp. Both are pictures.
19242 ///
19243 /// **This test owns `r_ssao_blur_passes` for its duration**, through
19244 /// [`ssao_blur_switch`] and for that function's second reason: it looks the
19245 /// occlusion chain's passes up by name, and a second blur arriving from
19246 /// another thread's switch is a pass this frame did not ask for.
19247 #[test]
19248 fn the_occlusion_chain_gathers_at_half_the_frame_and_reconstructs_at_all_of_it() {
19249 let _switch = ssao_blur_switch();
19250
19251 let (recorder, device, queue) = open();
19252 let device = device.as_ref();
19253 let mut renderer =
19254 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19255 let imported = swapchain_image(device);
19256 let mut pool = crate::TransientPool::new();
19257 renderer
19258 .begin_frame(
19259 device,
19260 &Camera::default(),
19261 &DirectionalLight::default(),
19262 TEST_EXTENT,
19263 )
19264 .expect("write");
19265 let mut graph = crate::RenderGraph::new(queue);
19266 let target = graph.import_image("target", imported);
19267 renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19268 let compiled = graph.compile(&pool).expect("a legal frame");
19269 let area_of = |label: &str| {
19270 let pass = compiled
19271 .passes()
19272 .iter()
19273 .find(|pass| pass.label() == label)
19274 .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
19275 let area = pass.render_area();
19276 (area.width, area.height)
19277 };
19278
19279 let gathered = crate::ssao::half_extent(TEST_EXTENT);
19280 assert_ne!(
19281 gathered, TEST_EXTENT,
19282 "the fixture extent has to halve to something else, or every assertion below holds \
19283 of a chain that halved nothing"
19284 );
19285 assert_eq!(
19286 area_of("ssao"),
19287 gathered,
19288 "the march has to run over the gather extent"
19289 );
19290 assert_eq!(
19291 area_of("ssao-blur"),
19292 gathered,
19293 "and so does the blur over what the march wrote"
19294 );
19295 assert_eq!(
19296 area_of("ssao-upsample"),
19297 TEST_EXTENT,
19298 "the reconstruction writes the channel `mesh.slang` reads at `SV_Position`, so it \
19299 runs at the frame's own extent"
19300 );
19301
19302 drop(compiled);
19303 renderer.destroy(device);
19304 pool.destroy(device);
19305 device.destroy_image_view(imported.view);
19306 device.destroy_image(imported.image);
19307 recorder.assert_valid();
19308 }
19309
19310 /// [`ssr_resolution_switch`]'s lock.
19311 static SSR_RESOLUTION_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
19312
19313 /// Takes `r_ssr_resolution` for this thread and puts full resolution back
19314 /// when the guard drops, on [`ssao_blur_switch`]'s terms.
19315 fn ssr_resolution_switch() -> std::sync::MutexGuard<'static, ()> {
19316 SSR_RESOLUTION_SWITCH
19317 .lock()
19318 .unwrap_or_else(std::sync::PoisonError::into_inner)
19319 }
19320
19321 /// **The reflection march runs at its share of the frame and the composite
19322 /// at all of it**, at every share a quality tier writes.
19323 ///
19324 /// On the occlusion chain's terms just above: the pass list is the same at
19325 /// every share, so the **render area** is where the scale is observable. A
19326 /// march image left at the frame's extent would be a march that saved
19327 /// nothing, and a composite at the march's extent would tonemap a truncated
19328 /// frame.
19329 #[test]
19330 fn the_reflection_march_runs_at_its_share_and_composites_at_the_frame() {
19331 let _switch = ssr_resolution_switch();
19332
19333 let (recorder, device, queue) = open();
19334 let device = device.as_ref();
19335 let mut renderer =
19336 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19337 let imported = swapchain_image(device);
19338 let mut pool = crate::TransientPool::new();
19339 for share in [1.0, 0.75, 0.5, 0.25] {
19340 crate::ssr::r_ssr_resolution
19341 .set(&crcbl_console::Value::Float(share))
19342 .expect("every tier's share is in the variable's range");
19343 renderer
19344 .begin_frame(
19345 device,
19346 &Camera::default(),
19347 &DirectionalLight::default(),
19348 TEST_EXTENT,
19349 )
19350 .expect("write");
19351 let mut graph = crate::RenderGraph::new(queue);
19352 let target = graph.import_image("target", imported);
19353 renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19354 let compiled = graph.compile(&pool).expect("a legal frame");
19355 let area_of = |label: &str| {
19356 let pass = compiled
19357 .passes()
19358 .iter()
19359 .find(|pass| pass.label() == label)
19360 .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
19361 let area = pass.render_area();
19362 (area.width, area.height)
19363 };
19364 let marched = crate::ssr::march_extent(TEST_EXTENT, share);
19365 assert_eq!(
19366 area_of("ssr"),
19367 marched,
19368 "at {share} the march has to run over its own share of the frame"
19369 );
19370 assert_eq!(
19371 area_of("ssr-blur"),
19372 TEST_EXTENT,
19373 "at {share} the composite replaces the scene colour, so it runs at the frame's \
19374 own extent"
19375 );
19376 drop(compiled);
19377 }
19378 crate::ssr::r_ssr_resolution
19379 .set(&crcbl_console::Value::Float(1.0))
19380 .expect("full resolution is in range");
19381
19382 renderer.destroy(device);
19383 pool.destroy(device);
19384 device.destroy_image_view(imported.view);
19385 device.destroy_image(imported.image);
19386 recorder.assert_valid();
19387 }
19388
19389 /// **The comparison seam records a second march, scissored to the columns
19390 /// the first one was kept off.**
19391 ///
19392 /// `crate::split`'s geometry, read off the encoder rather than off the code
19393 /// that drove it: two passes, and two `SetScissor` rectangles that tile the
19394 /// gather extent between them.
19395 ///
19396 /// **What this cannot see is which block each march bound.** The reference
19397 /// backend records a bind group as a handle and a layout, not as the
19398 /// resources behind it, so pointing both marches at one buffer leaves this
19399 /// test green — measured, by doing exactly that. The group inequality below
19400 /// is kept because it is free and would catch the two marches sharing a
19401 /// cache, which is a different fault; what covers the blocks is
19402 /// `crate::ssao`'s `the_seams_other_side_is_what_the_chain_ships`, and what
19403 /// is not covered at all is the wiring between them. `docs/backlog.md`
19404 /// carries that gap.
19405 ///
19406 /// **The control is the same frame without a seam**, and it is what makes
19407 /// the assertions mean anything: a chain that scissored unconditionally
19408 /// would satisfy every claim below and change every golden in the workspace,
19409 /// so the frame nobody asked to compare has to record one march and set no
19410 /// rectangle at all.
19411 ///
19412 /// Holds [`ssao_split_switch`] for [`ssao_blur_switch`]'s reason: the seam
19413 /// is process-wide state and a frame that picked one up from another
19414 /// thread's test is a frame with a pass this one did not ask for.
19415 #[test]
19416 fn the_comparison_seam_marches_twice_over_columns_that_tile_the_gather() {
19417 use crcbl_hal::null::Command;
19418
19419 let _blurs = ssao_blur_switch();
19420 let split = ssao_split_switch();
19421 // Third, after the two above: the only other test that takes this one
19422 // takes it alone, so this is the whole order and there is no cycle in
19423 // it. Moved below, because two blocks holding the same scalars are
19424 // equal whatever the seam did.
19425 let slices = ssao_slice_switch();
19426 // The count the seam's far side reads, and one that is not it. Read off
19427 // the variable rather than written down: which end of the range ships
19428 // has changed once already, and a test naming the wrong end would be
19429 // comparing the shipped configuration against itself.
19430 let ships = match crate::ssao::r_ssao_slices.default() {
19431 crcbl_console::Value::Int(count) => *count,
19432 other => panic!("`r_ssao_slices` defaults to {other:?}, which is not a count"),
19433 };
19434 let moved = if ships == i64::from(ssao::SLICE_COUNT_MAX) {
19435 i64::from(ssao::SLICE_COUNT_DEFAULT)
19436 } else {
19437 i64::from(ssao::SLICE_COUNT_MAX)
19438 };
19439 assert_ne!(
19440 ships, moved,
19441 "the two slice counts this compares are one count, so the blocks below would differ \
19442 by nothing whatever the seam did"
19443 );
19444 slices.set(ships);
19445
19446 let gathered = crate::ssao::half_extent(TEST_EXTENT);
19447 // One entry per march the frame recorded: the last rectangle that pass
19448 // left the scissor at, and the group it bound.
19449 //
19450 // **The last and not the only one.** The graph opens every pass with a
19451 // scissor over the whole render area, so a march that sets none of its
19452 // own still records one — which is why "did it scissor at all" is not
19453 // the question and "what did it end up cropped to" is.
19454 let marches = |recorder: &Recorder, from: usize| {
19455 let mut inside = false;
19456 let mut found: Vec<(crcbl_hal::Rect2d, crcbl_hal::BindGroupHandle)> = Vec::new();
19457 let mut rect = None;
19458 let mut group = None;
19459 for command in &recorder.commands()[from..] {
19460 if let Some((_, label)) = command.opens_pass() {
19461 inside = matches!(label, Some("ssao" | "ssao-shipped"));
19462 (rect, group) = (None, None);
19463 continue;
19464 }
19465 if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19466 if let (true, Some(rect), Some(group)) = (inside, rect, group) {
19467 found.push((rect, group));
19468 }
19469 inside = false;
19470 continue;
19471 }
19472 if !inside {
19473 continue;
19474 }
19475 match command {
19476 Command::SetScissor(at) => rect = Some(*at),
19477 Command::BindGroup { group: bound, .. } => group = Some(*bound),
19478 _ => {}
19479 }
19480 }
19481 found
19482 };
19483
19484 let (recorder, device, queue) = open();
19485 let device = device.as_ref();
19486 let mut renderer =
19487 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19488
19489 split.set(0.0);
19490 let alone = frame_seen_from(
19491 device,
19492 &mut renderer,
19493 queue,
19494 &Camera::default(),
19495 &DirectionalLight::default(),
19496 );
19497 let plain = marches(&recorder, 0);
19498 let after = recorder.commands().len();
19499 let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
19500 let (uncompared_console, uncompared_shipped) = (
19501 recorder.buffer_bytes(console).expect("the console's block"),
19502 recorder.buffer_bytes(shipped).expect("the seam's block"),
19503 );
19504 alone.release(device);
19505
19506 split.set(0.5);
19507 slices.set(moved);
19508 let frame = frame_seen_from(
19509 device,
19510 &mut renderer,
19511 queue,
19512 &Camera::default(),
19513 &DirectionalLight::default(),
19514 );
19515 let compared = marches(&recorder, after);
19516 let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
19517 let (compared_console, compared_shipped) = (
19518 recorder.buffer_bytes(console).expect("the console's block"),
19519 recorder.buffer_bytes(shipped).expect("the seam's block"),
19520 );
19521 frame.finish(device, renderer);
19522
19523 assert_eq!(
19524 plain.len(),
19525 1,
19526 "a frame comparing nothing recorded {} march(es); the seam is off, so there is one",
19527 plain.len()
19528 );
19529 assert_eq!(
19530 (
19531 plain[0].0.x,
19532 plain[0].0.y,
19533 plain[0].0.width,
19534 plain[0].0.height
19535 ),
19536 (0, 0, gathered.0, gathered.1),
19537 "a frame comparing nothing left its march cropped to something other than the whole \
19538 gather extent {gathered:?} — so the chain crops whether or not anybody asked it to, \
19539 and every golden in this workspace was blessed on a frame that does not"
19540 );
19541
19542 assert_eq!(
19543 compared.len(),
19544 2,
19545 "a frame comparing two configurations recorded {} march(es)",
19546 compared.len()
19547 );
19548 let (left, right) = (compared[0].0, compared[1].0);
19549 assert_eq!(
19550 (left.x, left.y, right.y),
19551 (0, 0, 0),
19552 "both halves start at the top and the left one at the edge"
19553 );
19554 assert_eq!(
19555 i64::from(right.x),
19556 i64::from(left.width),
19557 "the second march starts where the first one ended, or a column is drawn twice"
19558 );
19559 assert_eq!(
19560 (left.width + right.width, left.height, right.height),
19561 (gathered.0, gathered.1, gathered.1),
19562 "the two rectangles have to cover the gather extent {gathered:?} exactly"
19563 );
19564 assert!(
19565 left.width < gathered.0 && right.width < gathered.0,
19566 "one half covers the whole extent, so the other draws over it and the seam is a \
19567 rectangle that crops nothing"
19568 );
19569 assert_ne!(
19570 compared[0].1, compared[1].1,
19571 "the two marches bound one group, so they cannot be reading two blocks"
19572 );
19573
19574 // How far the reference backend can follow the far side. It will say
19575 // what bytes a buffer holds and it will not say which buffer a group
19576 // names, so the two together are "there are two blocks, and they differ
19577 // by the knob that was moved" — not "the right march read the right
19578 // one". Pointing both marches at one buffer still passes; see this
19579 // module's entry in `docs/backlog.md`.
19580 assert_eq!(
19581 uncompared_console, uncompared_shipped,
19582 "the console sat at its defaults and the two blocks still differ, so the seam's far \
19583 side is not this frame with the shipped scalars — it is another frame"
19584 );
19585 assert_ne!(
19586 compared_console, compared_shipped,
19587 "one slice count was moved off the shipped one and both blocks still hold the same \
19588 bytes, so a comparison shows the same picture twice"
19589 );
19590
19591 recorder.assert_valid();
19592 }
19593
19594 /// Every gather pipeline the frame bound, in the order the marches ran.
19595 ///
19596 /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
19597 /// `marches` closure asking the other question of the same stream: that one
19598 /// reads the scissor and the group, and this one reads the pipeline. Only
19599 /// the `ssao` and `ssao-shipped` passes are looked at, because every other
19600 /// pass in the chain binds a pipeline too and a filter over the whole stream
19601 /// would be counting blurs.
19602 ///
19603 /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
19604 fn gathers_bound(recorder: &Recorder, from: usize) -> Vec<crcbl_hal::GraphicsPipelineHandle> {
19605 use crcbl_hal::null::Command;
19606
19607 let mut inside = false;
19608 let mut found = Vec::new();
19609 for command in &recorder.commands()[from..] {
19610 if let Some((_, label)) = command.opens_pass() {
19611 inside = matches!(label, Some("ssao" | "ssao-shipped"));
19612 continue;
19613 }
19614 if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19615 inside = false;
19616 continue;
19617 }
19618 if let (true, Command::BindGraphicsPipeline(pipeline)) = (inside, command) {
19619 found.push(*pipeline);
19620 }
19621 }
19622 found
19623 }
19624
19625 /// **`r_ssao_technique` decides which shader the gather runs**, read off the
19626 /// pipeline the `ssao` pass bound.
19627 ///
19628 /// The observable `docs/backlog.md` says the uniform block cannot have. The
19629 /// reference backend records a bind group as a handle and a layout rather
19630 /// than as the resources behind it, so nothing can ask which *block* a march
19631 /// read — but a pipeline is recorded as itself, so which *technique* a march
19632 /// ran is a question this backend answers. `Ssao::gathers` is what names the
19633 /// two, so this is an equality against the pipeline built from each shader
19634 /// rather than an inequality that any two handles would satisfy.
19635 ///
19636 /// **The default arm is the load-bearing half.** A selector that read the
19637 /// wrong variable, or a `pipeline_for` whose arms were swapped, would still
19638 /// change the frame when the console moved; what would go with it is every
19639 /// golden in this workspace, which is blessed on the technique that ships.
19640 ///
19641 /// Holds [`ssao_blur_switch`] for its own reason and
19642 /// [`ssao_technique_switch`] third, after it and [`ssao_split_switch`] —
19643 /// see `crate::ssao::TECHNIQUE_SWITCH` on the order.
19644 #[test]
19645 fn the_occlusion_technique_picks_the_gathers_pipeline() {
19646 let _blurs = ssao_blur_switch();
19647 let _seam = ssao_split_switch();
19648 let technique = ssao_technique_switch();
19649 // The name to move to, taken out of the variable's own set — see
19650 // `other_technique_name`.
19651 let other = other_technique_name();
19652
19653 let (recorder, device, queue) = open();
19654 let device = device.as_ref();
19655 let mut renderer =
19656 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19657 let (ships, cheap) = renderer.primary.ssao.gathers();
19658 assert_ne!(
19659 ships, cheap,
19660 "the renderer built one gather pipeline for both techniques, so nothing below can \
19661 tell them apart"
19662 );
19663
19664 let shipped = frame_seen_from(
19665 device,
19666 &mut renderer,
19667 queue,
19668 &Camera::default(),
19669 &DirectionalLight::default(),
19670 );
19671 let by_default = gathers_bound(&recorder, 0);
19672 let after = recorder.commands().len();
19673 shipped.release(device);
19674
19675 technique.set(other);
19676 let moved_frame = frame_seen_from(
19677 device,
19678 &mut renderer,
19679 queue,
19680 &Camera::default(),
19681 &DirectionalLight::default(),
19682 );
19683 let moved = gathers_bound(&recorder, after);
19684 moved_frame.finish(device, renderer);
19685
19686 assert_eq!(
19687 by_default,
19688 vec![ships],
19689 "a frame nobody has touched the console on gathered through something other than \
19690 `ssao.slang`'s pipeline, which is what every golden in this workspace was blessed on"
19691 );
19692 assert_eq!(
19693 moved,
19694 vec![cheap],
19695 "`r_ssao_technique {other}` left the frame gathering through the pipeline \
19696 it gathered through before, so the selector reaches nothing"
19697 );
19698 recorder.assert_valid();
19699 }
19700
19701 /// **The comparison seam's two marches run two techniques**, which is what
19702 /// the seam was built for.
19703 ///
19704 /// Alcove's second milestone is SSAO and GTAO in
19705 /// one frame, and this is that claim as a pair of pipeline handles: with the
19706 /// technique moved the near side runs the cheap tier and the far side the
19707 /// one that ships, and with it at its default both marches run the same
19708 /// shader and the seam separates nothing.
19709 ///
19710 /// **The control is the frame at the default**, and it is what makes the
19711 /// first half mean anything: a far side that always ran `ssao.slang` would
19712 /// satisfy the inequality below whatever `shipped_technique` did, and a
19713 /// chain that had simply forgotten to pass the far side a pipeline of its
19714 /// own would too.
19715 #[test]
19716 fn the_comparison_seam_marches_through_two_techniques() {
19717 let _blurs = ssao_blur_switch();
19718 let seam = ssao_split_switch();
19719 let technique = ssao_technique_switch();
19720 let other = other_technique_name();
19721
19722 let (recorder, device, queue) = open();
19723 let device = device.as_ref();
19724 let mut renderer =
19725 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19726 let (ships, cheap) = renderer.primary.ssao.gathers();
19727
19728 seam.set(0.5);
19729 let compared = frame_seen_from(
19730 device,
19731 &mut renderer,
19732 queue,
19733 &Camera::default(),
19734 &DirectionalLight::default(),
19735 );
19736 let one_technique = gathers_bound(&recorder, 0);
19737 let after = recorder.commands().len();
19738 compared.release(device);
19739
19740 technique.set(other);
19741 let frame = frame_seen_from(
19742 device,
19743 &mut renderer,
19744 queue,
19745 &Camera::default(),
19746 &DirectionalLight::default(),
19747 );
19748 let two_techniques = gathers_bound(&recorder, after);
19749 frame.finish(device, renderer);
19750
19751 assert_eq!(
19752 one_technique,
19753 vec![ships, ships],
19754 "a seam with the technique at its default has to march the shipped gather twice — \
19755 both sides read `shipped`'s configuration, and the picture is one technique either \
19756 side of a line"
19757 );
19758 assert_eq!(
19759 two_techniques,
19760 vec![cheap, ships],
19761 "with `r_ssao_technique {other}` the near side has to run the cheap tier \
19762 and the far side what ships; the far side follows the variable's *default*, exactly \
19763 as the four scalars do"
19764 );
19765 recorder.assert_valid();
19766 }
19767
19768 /// **The frame block carries the console's shadow filter on the near side
19769 /// of the seam, the shipped one on the far side, and the column
19770 /// [`crate::split::halves`] counted.**
19771 ///
19772 /// [`the_comparison_seam_marches_through_two_techniques`]'s claim for the
19773 /// other seam, and it has to be a claim about *bytes* rather than about
19774 /// pass handles: the occlusion chain compares two pipelines and this
19775 /// compares two arms of one, so there is nothing in the pass list to look
19776 /// at. What a person sees is decided entirely by the row this asserts.
19777 ///
19778 /// **The frame at the default is the control**, and it is what makes the
19779 /// rest mean anything: a block that always wrote the shipped filter into
19780 /// both lanes would satisfy the third case's far side whatever
19781 /// `shipped_filter` did, and one that copied the near lane into the far one
19782 /// would satisfy the first two.
19783 ///
19784 /// The column is compared against `halves`' own answer rather than against
19785 /// a number written here, which is the seam module's whole point: a test
19786 /// that multiplied the fraction by the width itself would be a second
19787 /// opinion about the rounding, and the floor is exactly what that module's
19788 /// `the_seam_takes_the_floor_of_the_column_it_asks_for` exists to pin.
19789 ///
19790 /// [`the_comparison_seam_marches_through_two_techniques`]: fn@the_comparison_seam_marches_through_two_techniques
19791 #[test]
19792 fn the_frame_block_carries_a_shadow_filter_for_each_side_of_the_seam() {
19793 let switch = shadow_filter_switch();
19794
19795 let (recorder, device, queue) = open();
19796 let device = device.as_ref();
19797 let mut renderer =
19798 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19799
19800 // The seam is counted over the extent the scene is *drawn* at, which is
19801 // what `SV_Position.x` is denominated in — not the caller's window.
19802 let internal = renderer.internal_extent(TEST_EXTENT);
19803 let (left, _) = crate::split::halves(internal, 0.5).expect("a seam down the middle");
19804 assert!(
19805 left.width > 0,
19806 "a seam with no columns on one side would make every assertion below hold of a \
19807 frame that compares nothing"
19808 );
19809
19810 let ships = shadow::shipped_filter();
19811 let other = shadow::Filter::Box;
19812 assert_ne!(
19813 other.mode(),
19814 ships.mode(),
19815 "the filter this test moves the console to is the one that ships, so the seam it \
19816 asks for compares one kernel against itself"
19817 );
19818
19819 let draw = |renderer: &mut ForwardRenderer| {
19820 renderer
19821 .begin_frame(
19822 device,
19823 &Camera::default(),
19824 &DirectionalLight::default(),
19825 TEST_EXTENT,
19826 )
19827 .expect("write");
19828 let bytes = recorder
19829 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
19830 .expect("this frame's uniform block is live");
19831 let at = mesh::FRAME_UNIFORMS_SIZE - 16;
19832 core::array::from_fn(|lane| {
19833 u32::from_le_bytes(
19834 bytes[at + lane * 4..at + lane * 4 + 4]
19835 .try_into()
19836 .expect("four bytes"),
19837 )
19838 })
19839 };
19840
19841 let shipped: [u32; 4] = draw(&mut renderer);
19842 assert_eq!(
19843 shipped,
19844 [ships.mode(), ships.mode(), 0, 0],
19845 "a frame nobody has touched the console on must carry the shipped filter in both \
19846 lanes and no column, which is the row every golden in this workspace was blessed \
19847 under"
19848 );
19849
19850 switch.filter(other);
19851 let unsplit: [u32; 4] = draw(&mut renderer);
19852 assert_eq!(
19853 unsplit,
19854 [other.mode(), other.mode(), 0, 0],
19855 "`r_shadow_filter {}` with no seam has to reach every pixel, so both lanes carry it",
19856 other.label()
19857 );
19858
19859 switch.seam(0.5);
19860 let compared: [u32; 4] = draw(&mut renderer);
19861 assert_eq!(
19862 compared,
19863 [other.mode(), ships.mode(), left.width, 0],
19864 "a seam at 0.5 has to put the console's filter left of `halves`' column and the \
19865 shipped one right of it; the far side follows the variable's *default*, exactly \
19866 as the occlusion chain's does"
19867 );
19868
19869 renderer.destroy(device);
19870 recorder.assert_valid();
19871 }
19872
19873 #[test]
19874 fn a_second_occlusion_blur_is_a_pass_the_frame_records() {
19875 let switch = ssao_blur_switch();
19876
19877 let (recorder, device, queue) = open();
19878 let device = device.as_ref();
19879 let mut renderer =
19880 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19881 let imported = swapchain_image(device);
19882 let pool = crate::TransientPool::new();
19883
19884 let once = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19885 let counted_once = renderer.counters().instances;
19886 assert!(
19887 once.contains(&"ssao-blur".to_string()),
19888 "the shipping frame has to blur once, or the arm below is about a frame with no \
19889 occlusion in it at all: {once:#?}"
19890 );
19891 assert!(
19892 !once.contains(&"ssao-blur-2".to_string()),
19893 "a frame nobody moved the switch for must record one blur: {once:#?}"
19894 );
19895
19896 switch.set(2);
19897 let twice = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19898 let counted_twice = renderer.counters().instances;
19899 assert!(
19900 twice.contains(&"ssao-blur-2".to_string()),
19901 "`r_ssao_blur_passes 2` must put a second blur in the frame: {twice:#?}"
19902 );
19903 assert_eq!(
19904 twice.len(),
19905 once.len() + 1,
19906 "the second blur is the only pass that may join the frame: {twice:#?}"
19907 );
19908 assert_eq!(
19909 counted_twice,
19910 counted_once + FULLSCREEN_DRAWS,
19911 "the frame recorded a full-screen triangle its counter did not report"
19912 );
19913
19914 // The pass has to write somewhere the forward pass then reads, and the
19915 // graph is what would refuse a frame that bound an image nothing wrote.
19916 // `passes_in_a_frame` compiles rather than executes, so this is the
19917 // check that the third transient was requested at all.
19918 assert!(
19919 twice.iter().any(|pass| pass == "forward"),
19920 "the frame still has to reach its forward pass: {twice:#?}"
19921 );
19922 recorder.assert_valid();
19923 }
19924
19925 /// Every host-written buffer at the end of a whole ring of frames, keyed by
19926 /// the handle written and holding what that handle last held.
19927 ///
19928 /// A whole ring rather than one frame, because the blocks a frame writes are
19929 /// themselves rings — a buffer per frame in flight, [`Ssao`]'s among them —
19930 /// so one frame touches one slot of each and two single-frame batches would
19931 /// be comparing different buffers. A ring writes every slot, so two batches'
19932 /// keys line up and a difference between them is a difference in *bytes*.
19933 ///
19934 /// Only the events this call appends are read, so a caller can take one
19935 /// batch after another off the same recorder.
19936 fn host_buffers_over_a_ring(
19937 recorder: &Recorder,
19938 device: &dyn Device,
19939 renderer: &mut ForwardRenderer,
19940 queue: QueueHandle,
19941 ) -> std::collections::BTreeMap<u64, Vec<u8>> {
19942 let from = recorder.events().len();
19943 for _ in 0..FRAMES_IN_FLIGHT {
19944 frame(device, renderer, queue).release(device);
19945 }
19946 recorder.events()[from..]
19947 .iter()
19948 .filter_map(|event| match event {
19949 Event::BufferWritten { buffer, .. } => Some(*buffer),
19950 _ => None,
19951 })
19952 .map(|buffer| {
19953 let bytes = recorder
19954 .buffer_bytes(buffer)
19955 .expect("the stream only names buffers this recorder created");
19956 (buffer.to_bits(), bytes)
19957 })
19958 .collect()
19959 }
19960
19961 /// **`r_ssao_slices` reaches the block `ssao.slang` reads, on every frame of
19962 /// the ring, and moves nothing else in the frame.**
19963 ///
19964 /// The device test drives the two occlusion pipelines directly and
19965 /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] moves the *blur*
19966 /// count, so until this the slice count was a variable with a `get_i64` and
19967 /// no evidence that a rendered frame ever carried it: `slice_count` could
19968 /// have returned its default unconditionally and every check in this
19969 /// workspace would still be green.
19970 ///
19971 /// So the observable is the bytes, taken off the null recorder's write log
19972 /// after a whole ring of frames at each setting and compared **by handle**.
19973 /// Two claims come out of that comparison and both are load-bearing:
19974 ///
19975 /// * **Some block moved** — every ring slot, in fact, which is what says the
19976 /// count reaches the frame at all rather than only the slot the last frame
19977 /// happened to land in.
19978 /// * **Every block that moved, moved only there.** A frame is a few dozen
19979 /// host writes and the slice count has business with exactly one word of
19980 /// one of them; a setting that perturbed a matrix, an instance or a shadow
19981 /// view would be drawing a different frame for a reason nobody asked for,
19982 /// and the "at least one differs" half alone would pass on it happily.
19983 ///
19984 /// **Holds every switch whose row is in a block it compares**, in the lock
19985 /// order: the two batches are compared byte for byte over every host
19986 /// buffer the frame writes, so any console row another test moves between
19987 /// them — the blur count, the seam, the technique, the shadow filter, or
19988 /// `crate::ssao`'s own mover of the params block — reads here as "some
19989 /// other write moving". [`ssao_technique_switch`] is the one that
19990 /// serialises against that mover.
19991 #[test]
19992 fn four_slices_reach_the_frame_the_shader_reads() {
19993 let _blurs = ssao_blur_switch();
19994 let _seam = ssao_split_switch();
19995 let switch = ssao_slice_switch();
19996 let _technique = ssao_technique_switch();
19997 let _filter = shadow_filter_switch();
19998
19999 let (recorder, device, queue) = open();
20000 let device = device.as_ref();
20001 let mut renderer =
20002 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20003
20004 // A ring rendered before either batch is taken, because the two below
20005 // are compared by handle and the renderer's opening frame writes blocks
20006 // no later frame writes again: it fills a cold shadow atlas, so the
20007 // shadow views' uniform blocks and the draw-generation blocks of the
20008 // cascades that were drawn are written once and never again while the
20009 // cache holds. Those would be in the first batch and missing from the
20010 // second, and a key that is only in one of them is a difference this
20011 // test cannot say anything about.
20012 for _ in 0..FRAMES_IN_FLIGHT {
20013 frame(device, &mut renderer, queue).release(device);
20014 }
20015 let shipping = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
20016 switch.set(i64::from(ssao::SLICE_COUNT_MAX));
20017 let asked = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
20018 assert_eq!(
20019 shipping.keys().collect::<Vec<_>>(),
20020 asked.keys().collect::<Vec<_>>(),
20021 "the two batches must write the same buffers, or they are not comparable",
20022 );
20023
20024 // Which bytes moving the count alone is allowed to move, asked of
20025 // `SsaoParams::to_bytes` rather than written here as an offset: the
20026 // block's layout is `crcbl_shaders::ssao`'s, and a field inserted ahead
20027 // of the count would leave a number spelled here pointing at the radius.
20028 let block_of = |slices| {
20029 ssao::SsaoParams {
20030 inv_proj: [0.0; 16],
20031 proj: [0.0; 16],
20032 inv_view: [0.0; 16],
20033 radius: 0.0,
20034 slices,
20035 intensity: ssao::INTENSITY_DEFAULT,
20036 bent_normals: crate::ssao::bent_normals(),
20037 }
20038 .to_bytes()
20039 };
20040 let at_shipping = block_of(ssao::SLICE_COUNT_DEFAULT);
20041 let at_max = block_of(ssao::SLICE_COUNT_MAX);
20042 let count_word: Vec<usize> = (0..ssao::PARAMS_SIZE)
20043 .filter(|at| at_shipping[*at] != at_max[*at])
20044 .collect();
20045
20046 let mut moved = 0;
20047 for (handle, before) in &shipping {
20048 let after = &asked[handle];
20049 if before == after {
20050 continue;
20051 }
20052 moved += 1;
20053 let mut only_the_count = before.clone();
20054 for at in &count_word {
20055 assert_eq!(
20056 before[*at], at_shipping[*at],
20057 "buffer {handle} differs between the batches but did not go in holding the \
20058 shipping slice count, so this is some other write moving",
20059 );
20060 only_the_count[*at] = at_max[*at];
20061 }
20062 assert_eq!(
20063 after, &only_the_count,
20064 "buffer {handle} moved somewhere other than the slice count's word: the setting \
20065 is perturbing a block it has no business in",
20066 );
20067 }
20068 assert_eq!(
20069 moved, FRAMES_IN_FLIGHT,
20070 "`r_ssao_slices 4` must reach every slot of the occlusion ring; a count that moved \
20071 none of them is a console variable no rendered frame reads",
20072 );
20073
20074 renderer.destroy(device);
20075 recorder.assert_valid();
20076 }
20077
20078 /// **The debug draw layer costs a frame nothing until something is appended
20079 /// *and* the console switch is on, and then it is the pass immediately
20080 /// before the tonemap.**
20081 ///
20082 /// Four claims, and each is a separate way to get this wrong.
20083 ///
20084 /// * **Off by default** is what keeps every golden image in the workspace
20085 /// where it was blessed.
20086 /// * **A segment appended while the switch is off records nothing**, so a
20087 /// system may append unconditionally.
20088 /// * **The switch on with an empty buffer records nothing either** — this is
20089 /// the "costs nothing when empty" claim as a check rather than a sentence:
20090 /// the compiled pass list is compared whole against the frame drawn before
20091 /// the layer was switched on, so a pass that clears, blits or barriers
20092 /// anything would show up here.
20093 /// * **Before the tonemap**, which is
20094 /// `docs/plan/18-render-features.md`'s interaction rule and the opposite of
20095 /// the ground grid above. Recorded a line later it would draw into the
20096 /// display-space target and be free of the exposure, which compiles and
20097 /// draws lines and is the wrong picture.
20098 ///
20099 /// And the fifth, which is what "immediate mode" means: the frame *after*
20100 /// the one that appended records nothing again, because
20101 /// [`ForwardRenderer::begin_frame`] cleared the buffer.
20102 ///
20103 /// The whole list is compared rather than its length, for the ground grid
20104 /// test's reason: one more pass is satisfied by gaining the wrong one.
20105 ///
20106 /// **This test owns `r_debug_draw` for its duration**, through
20107 /// [`debug_draw_switch`]: a plain `cargo test` run shares one process
20108 /// between tests, so the two checks here that move it have to take turns.
20109 /// `cargo nextest`, which CI runs, gives each a process of its own and needs
20110 /// none of it.
20111 #[test]
20112 fn the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap() {
20113 let switch = debug_draw_switch();
20114 let _blurs = ssao_blur_switch();
20115
20116 let (recorder, device, queue) = open();
20117 let device = device.as_ref();
20118 let mut renderer =
20119 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20120 let imported = swapchain_image(device);
20121 let mut pool = crate::TransientPool::new();
20122
20123 assert!(
20124 !crate::DebugDraw::enabled(),
20125 "the layer must be off before anything switches it on, or every claim below is \
20126 about a different default"
20127 );
20128 let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20129 assert!(
20130 !off.contains(&"debug-draw".to_string()),
20131 "the layer must not be in a frame nobody switched it on for: {off:#?}"
20132 );
20133
20134 renderer
20135 .debug_draw()
20136 .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20137 assert_eq!(
20138 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20139 off,
20140 "a segment appended while the switch is off must record no pass"
20141 );
20142
20143 switch.set(true);
20144 assert_eq!(
20145 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20146 off,
20147 "the switch on with an empty buffer must record the frame the layer's absence would"
20148 );
20149
20150 renderer
20151 .debug_draw()
20152 .aabb(-Vec3::ONE, Vec3::ONE, [0.0, 1.0, 0.0, 1.0]);
20153 let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20154 let mut expected = off.clone();
20155 let tonemap = expected
20156 .iter()
20157 .position(|label| label == "tonemap")
20158 .expect("a frame has to reach the swapchain");
20159 expected.insert(tonemap, "debug-draw".to_string());
20160 assert_eq!(
20161 on, expected,
20162 "the layer must be the one pass gained, and it must sit before the tonemap"
20163 );
20164
20165 assert_eq!(
20166 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20167 off,
20168 "the buffer is immediate mode: the frame after the one that appended must record \
20169 nothing"
20170 );
20171
20172 switch.set(false);
20173 renderer.destroy(device);
20174 pool.destroy(device);
20175 device.destroy_image_view(imported.view);
20176 device.destroy_image(imported.image);
20177 recorder.assert_valid();
20178 }
20179
20180 /// **The debug draw layer's own call is counted in the frame's draws.**
20181 ///
20182 /// [`ForwardRenderer::counters`]' draw count is compared against the
20183 /// commands the null backend actually recorded, which is the same instrument
20184 /// `the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know`
20185 /// uses — so a layer whose line list was recorded and not counted fails here
20186 /// rather than quietly making every panel's draw row one short.
20187 ///
20188 /// Both directions are asserted: the frame that drew a segment records one
20189 /// more draw than the frame before it, *and* the counter moved by the same
20190 /// one. A count wired to a constant satisfies neither.
20191 ///
20192 /// It owns `r_debug_draw` for its duration, on
20193 /// `the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap`'s
20194 /// terms.
20195 #[test]
20196 fn the_debug_draw_layers_call_is_counted_in_the_frames_draws() {
20197 let switch = debug_draw_switch();
20198 let _blurs = ssao_blur_switch();
20199
20200 let (recorder, device, queue) = open();
20201 let device = device.as_ref();
20202 let mut renderer =
20203 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20204
20205 // A different sun in each of the two frames, so both of them redraw the
20206 // shadow atlas: the claim below is that the layer's own call is the one
20207 // draw the second frame gained, and a second frame that cached its
20208 // atlas would have lost the atlas's draws at the same time. See
20209 // [`moving_sun`].
20210 let quiet = frame_moving_the_sun(device, &mut renderer, queue, 0);
20211 let without = renderer.counters().draws;
20212 assert_eq!(
20213 without,
20214 recorded_draws(&recorder) as u64,
20215 "the counter and the frame's recorded draws disagree before the layer draws at all"
20216 );
20217 quiet.release(device);
20218
20219 switch.set(true);
20220 renderer
20221 .debug_draw()
20222 .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20223 let drawn = frame_moving_the_sun(device, &mut renderer, queue, 1);
20224 let with = renderer.counters().draws;
20225 assert_eq!(
20226 with,
20227 without + 1,
20228 "the layer records one draw, so the count has to move by one"
20229 );
20230 assert_eq!(
20231 recorded_draws(&recorder) as u64,
20232 without + with,
20233 "the two frames' recorded draws and the two counts disagree, so the layer's call is \
20234 counted somewhere it was not recorded or recorded somewhere it was not counted"
20235 );
20236
20237 switch.set(false);
20238 drawn.finish(device, renderer);
20239 recorder.assert_valid();
20240 }
20241
20242 /// **The depth-only passes run the depth-only entry point, and the colour
20243 /// pass does not.**
20244 ///
20245 /// Topic 43 §2 split the vertex pool so a pass
20246 /// that wants a clip position and no more could fetch stream 0 alone, and
20247 /// [`MeshModules::depth_pipeline`] naming `mesh.slang`'s `depthVertexMain`
20248 /// is the whole of how that split is spent. **Nothing else in the tree sees
20249 /// it.** `crcbl_shaders::mesh`'s
20250 /// `the_depth_entry_point_fetches_the_position_stream_alone` reads the
20251 /// compiled artifact and would pass with the entry point built and unused;
20252 /// no golden moves, because the two stages compute the same clip position on
20253 /// purpose; the render graph records a legal frame either way; and the
20254 /// measured price says nothing — pointing this pipeline back at `vertexMain`
20255 /// cost the depth prepass about a tenth more on lavapipe and nothing to
20256 /// three figures on an RX 7900 XTX, measured 2026-08-31. So the wiring is
20257 /// asserted here, against the reference backend, which records the entry
20258 /// point a pipeline names precisely so this question has an answer.
20259 ///
20260 /// **Both halves, so the check is shown to discriminate.** A lookup that
20261 /// answered `depthVertexMain` for every pipeline would satisfy the first
20262 /// assertion alone, and the colour pipeline is the one that must *not* have
20263 /// moved. The labels are the descriptors' own and are what the two are told
20264 /// apart by, so a renamed pipeline fails at the `expect` rather than
20265 /// silently matching nothing.
20266 #[test]
20267 fn the_depth_pipeline_names_the_depth_only_vertex_stage_and_the_colour_one_does_not() {
20268 let (recorder, device, queue) = open();
20269 let device = device.as_ref();
20270 let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20271 // A mesh stage has no vertex entry point to name, and this whole rung is
20272 // about the raster arm — see [`MeshModules::depth_pipeline`]. The null
20273 // preset reports no `Features::MESH_SHADER`, so this is what it built;
20274 // asserted rather than assumed, because a preset that grew the feature
20275 // would leave every assertion below looking for pipelines that do not
20276 // exist.
20277 assert_ne!(
20278 renderer.geometry_path(),
20279 crcbl_hal::GeometryPath::MeshShader,
20280 "this device built a mesh-shader path, whose geometry stage names no vertex \
20281 entry point at all"
20282 );
20283
20284 let pipelines = recorder.graphics_pipeline_vertex_entries();
20285 let entry_of = |label: &str| -> String {
20286 let found: Vec<&str> = pipelines
20287 .iter()
20288 .filter(|(name, _)| name.as_deref() == Some(label))
20289 .map(|(_, entry)| entry.as_str())
20290 .collect();
20291 assert_eq!(
20292 found.len(),
20293 1,
20294 "the renderer built {} pipeline(s) labelled `{label}`, out of {pipelines:?}",
20295 found.len()
20296 );
20297 found[0].to_owned()
20298 };
20299
20300 assert_eq!(
20301 entry_of("shadow cascade"),
20302 "depthVertexMain",
20303 "the shadow atlas and the depth prepass share this pipeline, and it is the one \
20304 that reads the position stream alone"
20305 );
20306 assert_eq!(
20307 entry_of("forward mesh"),
20308 "vertexMain",
20309 "the colour pass needs every attribute the depth pass skips, so it is the entry \
20310 point that reads a whole vertex"
20311 );
20312 assert_eq!(
20313 entry_of("shadow cascade masked"),
20314 "vertexMain",
20315 "the cutout twin has to read a whole vertex: the UV it samples the mask from lives \
20316 in the attribute region `depthVertexMain` exists not to read"
20317 );
20318
20319 renderer.destroy(device);
20320 recorder.assert_valid();
20321 }
20322
20323 /// **A masked material moves that mesh's depth draws onto the cutout
20324 /// pipeline, and moves nothing else.**
20325 ///
20326 /// The mechanism is which pipeline handle the recorded stream binds and
20327 /// which buckets' indirect calls follow each bind — the wireframe test's
20328 /// observable, for the same reason: a field saying a mode was read would
20329 /// prove the flag was read, not that the frame changed.
20330 ///
20331 /// Four claims, and each rules out a different way of passing wrongly:
20332 ///
20333 /// * a scene with nothing masked binds the vertex-only pipeline and
20334 /// **never** the cutout one, which is the "an opaque frame costs what it
20335 /// always did" claim at the level a null device can see it;
20336 /// * a scene with one masked row binds **both** in the depth prepass and
20337 /// both in the shadow atlas — a per-frame choice binds one or the other,
20338 /// never the pair;
20339 /// * the calls following each bind are exactly that mode's buckets, in
20340 /// bucket order, read off the argument offsets the draws name. A split
20341 /// that bound both pipelines and drew every bucket under each would
20342 /// satisfy the claim above and double the frame's draws;
20343 /// * and folding the two handles together — then collapsing the runs of
20344 /// equal binds the fold creates — leaves the two frames' bind streams
20345 /// **equal**, so the colour pass, the tile clears and the reflective
20346 /// shadow map are all where they were. A change that had also moved the
20347 /// colour pass would satisfy the first three and fail this.
20348 ///
20349 /// The two scenes differ in one flags word and nothing else.
20350 #[test]
20351 fn a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline() {
20352 use crcbl_hal::null::Command;
20353
20354 // The occlusion blur count is a process-global console variable and a
20355 // frame binds one pipeline per blur, so a concurrent test moving it
20356 // would put a bind in one of these frames and not the other — the
20357 // wireframe test's hazard exactly.
20358 let _blurs = ssao_blur_switch();
20359
20360 let masked_scene = {
20361 let mut scene = crate::scene::demo();
20362 scene.materials[DEMO_UNTINTED].flags =
20363 crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
20364 scene
20365 };
20366
20367 /// What one scene's frame reveals: the bucket count and each bucket's
20368 /// mode, how often each depth pipeline was bound, the (pipeline, bucket)
20369 /// pairs the depth prepass and the shadow atlas recorded, and the whole
20370 /// bind stream with the two depth handles folded into one.
20371 struct Recorded {
20372 modes: Vec<u32>,
20373 cutouts: usize,
20374 plains: usize,
20375 prepass: Vec<(bool, u32)>,
20376 atlas: Vec<(bool, u32)>,
20377 folded: Vec<GraphicsPipelineHandle>,
20378 }
20379
20380 // One frame each, from two renderers rather than two frames from one:
20381 // a bucket table is fixed at build, and two builds keep the frames'
20382 // shadow-atlas state identical — both are a first frame.
20383 let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20384 let (recorder, device, queue) = open();
20385 let device = device.as_ref();
20386 let mut renderer =
20387 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20388 .expect("the null backend accepts the demo description");
20389 place_cube(&mut renderer, Mat4::IDENTITY);
20390 let imported = swapchain_image(device);
20391 let mut pool = crate::TransientPool::new();
20392 renderer
20393 .begin_frame(
20394 device,
20395 &Camera::default(),
20396 &DirectionalLight::default(),
20397 (64, 48),
20398 )
20399 .expect("write");
20400 let mut graph = crate::RenderGraph::new(queue);
20401 let target = graph.import_image("target", imported);
20402 renderer.add_passes(&mut graph, &pool, target, (64, 48));
20403 let compiled = graph.compile(&pool).expect("a legal frame");
20404 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20405 label: Some("alpha mask lap"),
20406 queue,
20407 });
20408 compiled
20409 .execute(device, &mut pool, encoder.as_mut(), None)
20410 .expect("the graph executed");
20411 encoder.finish().expect("recording succeeded");
20412 let plain = renderer.shadow_pipeline.single;
20413 let cutout = renderer.depth_masked_pipeline.single;
20414 assert_ne!(
20415 plain, cutout,
20416 "the two depth pipelines have to be two objects, or nothing below discriminates"
20417 );
20418 // Which bucket a draw is, recovered from the argument offset it
20419 // names — the offsets are the renderer's own accessor, so a call
20420 // pointing at the wrong bucket has no entry here at all.
20421 let bucket_of = |args_offset: u64| -> u32 {
20422 (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
20423 .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
20424 .unwrap_or_else(|| {
20425 panic!("a draw read its arguments at {args_offset}, which is no bucket's")
20426 })
20427 };
20428 // Per depth pass: the pipeline in force at each indirect call and
20429 // the bucket that call drew, in the order they were recorded.
20430 let pass_calls = |label: &str| -> Vec<(bool, u32)> {
20431 let mut current = None;
20432 let mut out = Vec::new();
20433 for command in commands_in_pass(&recorder, label) {
20434 match command {
20435 Command::BindGraphicsPipeline(handle) => current = Some(handle),
20436 Command::DrawIndexedIndirectCount(draw) => {
20437 let handle = current.expect("a draw follows a pipeline bind");
20438 assert!(
20439 handle == plain || handle == cutout,
20440 "a depth pass drew under a pipeline that is neither depth one"
20441 );
20442 out.push((handle == cutout, bucket_of(draw.args_offset)));
20443 }
20444 _ => {}
20445 }
20446 }
20447 out
20448 };
20449 let prepass = pass_calls("depth-prepass");
20450 let atlas = pass_calls("shadow");
20451 let binds: Vec<GraphicsPipelineHandle> = recorder
20452 .commands()
20453 .iter()
20454 .filter_map(|command| match command {
20455 Command::BindGraphicsPipeline(handle) => Some(*handle),
20456 _ => None,
20457 })
20458 .collect();
20459 let cutouts = binds.iter().filter(|handle| **handle == cutout).count();
20460 let plains = binds.iter().filter(|handle| **handle == plain).count();
20461 let mut folded: Vec<GraphicsPipelineHandle> = Vec::with_capacity(binds.len());
20462 for handle in binds {
20463 let handle = if handle == cutout { plain } else { handle };
20464 // The fold turns the masked frame's `plain, cutout` pair into
20465 // `plain, plain`; collapsing a run of equal binds is what makes
20466 // the two streams comparable without hiding a bind of anything
20467 // else, since no pass in either frame binds two *different*
20468 // pipelines that the fold could bring together.
20469 if folded.last() != Some(&handle) {
20470 folded.push(handle);
20471 }
20472 }
20473 let modes = renderer.bucket_modes.clone();
20474 renderer.destroy(device);
20475 recorder.assert_valid();
20476 Recorded {
20477 modes,
20478 cutouts,
20479 plains,
20480 prepass,
20481 atlas,
20482 folded,
20483 }
20484 };
20485
20486 let opaque = bound(&crate::scene::demo());
20487 let masked = bound(&masked_scene);
20488
20489 assert_eq!(
20490 opaque.cutouts, 0,
20491 "a scene with nothing masked must never bind the cutout pipeline"
20492 );
20493 assert!(
20494 opaque.plains > 0,
20495 "a scene with nothing masked must bind the vertex-only pipeline, or the assertion \
20496 above is about a frame with no depth pass in it"
20497 );
20498 assert!(
20499 opaque.modes.iter().all(|mode| *mode == 0),
20500 "and every one of its buckets is opaque: {:?}",
20501 opaque.modes
20502 );
20503 assert_eq!(
20504 opaque.prepass.iter().filter(|(cutout, _)| *cutout).count(),
20505 0,
20506 "so no opaque draw is recorded under the cutout pipeline"
20507 );
20508
20509 assert!(
20510 masked.cutouts > 0 && masked.plains > 0,
20511 "a masked scene must bind **both** depth pipelines — {} cutout and {} plain — or \
20512 the choice is still per frame",
20513 masked.cutouts,
20514 masked.plains
20515 );
20516 // What each depth pass should have recorded: every opaque bucket under
20517 // the plain pipeline in bucket order, then every masked one under the
20518 // cutout, which is the partition order `depth_partitions` lays down.
20519 let want: Vec<(bool, u32)> = [false, true]
20520 .into_iter()
20521 .flat_map(|cutout| {
20522 masked
20523 .modes
20524 .iter()
20525 .enumerate()
20526 .filter(move |(_, mode)| {
20527 (**mode == crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK) == cutout
20528 })
20529 .map(move |(bucket, _)| (cutout, u32::try_from(bucket).expect("a few buckets")))
20530 })
20531 .collect();
20532 assert!(
20533 want.iter().any(|(cutout, _)| *cutout) && want.iter().any(|(cutout, _)| !*cutout),
20534 "the masked demo has to hold buckets of both modes, or this compares one partition \
20535 against itself: {:?}",
20536 masked.modes
20537 );
20538 assert_eq!(
20539 masked.prepass, want,
20540 "the depth prepass must record each bucket once, under the pipeline its own mode \
20541 asked for"
20542 );
20543 // The atlas draws every bucket once per occupied view, and the
20544 // partition is **outside** the view loop — one pipeline bind covers
20545 // every view of that mode — so its stream is each partition's bucket
20546 // list repeated once per view.
20547 let views = masked.atlas.len() / want.len();
20548 assert!(
20549 views > 0 && masked.atlas.len() % want.len() == 0,
20550 "the shadow atlas recorded {} calls over {} buckets, which is not a whole number \
20551 of views",
20552 masked.atlas.len(),
20553 want.len()
20554 );
20555 let mut atlas_want: Vec<(bool, u32)> = Vec::with_capacity(masked.atlas.len());
20556 for cutout in [false, true] {
20557 let partition: Vec<(bool, u32)> = want
20558 .iter()
20559 .copied()
20560 .filter(|(mode, _)| *mode == cutout)
20561 .collect();
20562 for _ in 0..views {
20563 atlas_want.extend_from_slice(&partition);
20564 }
20565 }
20566 assert_eq!(
20567 masked.atlas, atlas_want,
20568 "and every shadow view draws both partitions, each under its own pipeline"
20569 );
20570
20571 assert_eq!(
20572 masked.folded, opaque.folded,
20573 "the frame gained or lost a pipeline bind beyond the cutout twin beside a plain one"
20574 );
20575 }
20576
20577 /// **A double-sided material moves every pass's draws for its own buckets
20578 /// onto the `CullMode::None` twins, and moves nothing else.**
20579 ///
20580 /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]'s
20581 /// claim for glTF's other mode, and it is wider by construction: an alpha
20582 /// mask is cut inside a fragment stage, so only the two depth-only passes
20583 /// route around it, while a cull mode is a pipeline state and **every** pass
20584 /// that draws the surface has to route around it — the colour pass, both
20585 /// depth passes and the two reflective shadow maps.
20586 ///
20587 /// So this walks the whole recorded stream rather than two named passes:
20588 /// every render pass that recorded an indirect draw is read back as the
20589 /// (side, bucket) pairs it recorded, and each of the four claims below is
20590 /// about all of them at once.
20591 ///
20592 /// * a scene with nothing double-sided binds **no** cull-none twin
20593 /// anywhere, which is the "an all-single-sided frame costs what it always
20594 /// did" claim at the level a null device can see it;
20595 /// * a scene with one double-sided row binds a twin in every pass that
20596 /// draws — a frame that had only routed the colour pass would satisfy
20597 /// nothing below, and one that had only routed the depth passes would
20598 /// draw a surface the prepass wrote no depth for;
20599 /// * the calls following each bind are exactly that side's buckets, in
20600 /// bucket order. A split that bound both pipelines and drew every bucket
20601 /// under each would satisfy the claim above and double the frame's draws;
20602 /// * and folding each twin onto the pipeline it is a twin of — then
20603 /// collapsing the runs of equal binds the fold creates — leaves the two
20604 /// frames' bind streams **equal**, so nothing else in the frame moved.
20605 ///
20606 /// The two scenes differ in one flags word and nothing else.
20607 ///
20608 /// [`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
20609 #[test]
20610 fn a_double_sided_material_moves_every_passs_draws_onto_the_cull_none_twins() {
20611 use crcbl_hal::null::Command;
20612
20613 // The occlusion blur count is a process-global console variable and a
20614 // frame binds one pipeline per blur — the masked test's hazard exactly.
20615 let _blurs = ssao_blur_switch();
20616
20617 // **A scene whose probes ask to be updated**, because the reflective
20618 // shadow maps are recorded by a volume rather than by an effect bit —
20619 // and they are two of the five passes this claim is about. The demo's
20620 // empty grid records neither, which would leave the widest half of the
20621 // routing unchecked.
20622 let scene_with_probes = || {
20623 let mut scene = crate::scene::demo();
20624 scene.capacities.probes = 1;
20625 scene.probes = crate::scene::ProbeGrid {
20626 volume: crcbl_shaders::probe::ProbeVolume {
20627 origin: [0.0; 3],
20628 inv_spacing: [1.0; 3],
20629 counts: [1, 1, 1],
20630 levels: 1,
20631 steps: crcbl_shaders::probe::ProbeSteps::default(),
20632 },
20633 probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
20634 update: ProbeUpdate::EveryFrame,
20635 };
20636 scene
20637 };
20638 let single_scene = scene_with_probes();
20639 let double_scene = {
20640 let mut scene = scene_with_probes();
20641 scene.materials[DEMO_UNTINTED].flags = crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED;
20642 scene
20643 };
20644
20645 /// What one scene's frame reveals: each bucket's mode, how often a
20646 /// cull-none twin was bound at all, every drawing pass's (side, bucket)
20647 /// pairs in record order, and the whole bind stream with each twin
20648 /// folded onto the pipeline it twins.
20649 struct Recorded {
20650 modes: Vec<u32>,
20651 twins_bound: usize,
20652 passes: Vec<(String, Vec<(bool, u32)>)>,
20653 folded: Vec<GraphicsPipelineHandle>,
20654 }
20655
20656 // One frame each, from two renderers rather than two frames from one, on
20657 // the masked test's terms: a bucket table is fixed at build, and two
20658 // builds keep both frames a first frame.
20659 let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20660 let (recorder, device, queue) = open();
20661 let device = device.as_ref();
20662 let mut renderer =
20663 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20664 .expect("the null backend accepts the demo description");
20665 assert!(
20666 !renderer.emit.is_mesh(),
20667 "this preset built a mesh-shader path, whose draws carry no argument offset to \
20668 recover a bucket from"
20669 );
20670 place_cube(&mut renderer, Mat4::IDENTITY);
20671 // **One shadowed spot**, so the punctual reflective shadow map has a
20672 // face to draw into: the pass is recorded on every frame but its
20673 // view loop is empty without one, and an empty loop records no draw
20674 // for the claim below to be about.
20675 renderer.set_lights(&[crate::Light::Spot(crate::SpotLight {
20676 position: Vec3::new(0.0, 2.0, 0.0),
20677 radius: 8.0,
20678 color: Vec3::splat(4.0),
20679 direction: Vec3::NEG_Y,
20680 inner_angle: 0.3,
20681 outer_angle: 0.6,
20682 fill: false,
20683 })]);
20684 let imported = swapchain_image(device);
20685 let mut pool = crate::TransientPool::new();
20686 renderer
20687 .begin_frame(
20688 device,
20689 &Camera::default(),
20690 &DirectionalLight::default(),
20691 (64, 48),
20692 )
20693 .expect("write");
20694 let mut graph = crate::RenderGraph::new(queue);
20695 let target = graph.import_image("target", imported);
20696 renderer.add_passes(&mut graph, &pool, target, (64, 48));
20697 let compiled = graph.compile(&pool).expect("a legal frame");
20698 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20699 label: Some("double sided lap"),
20700 queue,
20701 });
20702 compiled
20703 .execute(device, &mut pool, encoder.as_mut(), None)
20704 .expect("the graph executed");
20705 encoder.finish().expect("recording succeeded");
20706
20707 // Every twin and the pipeline it twins, so a bind can be reported as
20708 // a side and folded back. Asserted distinct, or nothing here
20709 // discriminates.
20710 let sided = [
20711 renderer.mesh_pipeline,
20712 renderer.shadow_pipeline,
20713 renderer.depth_masked_pipeline,
20714 renderer.rsm_pipeline,
20715 ];
20716 for pair in sided {
20717 assert_ne!(
20718 pair.single, pair.double,
20719 "a pipeline and its cull-none twin have to be two objects"
20720 );
20721 }
20722 let twin_of = |handle: GraphicsPipelineHandle| -> Option<GraphicsPipelineHandle> {
20723 sided
20724 .iter()
20725 .find(|pair| pair.double == handle)
20726 .map(|pair| pair.single)
20727 };
20728 let bucket_of = |args_offset: u64| -> u32 {
20729 (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
20730 .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
20731 .unwrap_or_else(|| {
20732 panic!("a draw read its arguments at {args_offset}, which is no bucket's")
20733 })
20734 };
20735
20736 let mut passes: Vec<(String, Vec<(bool, u32)>)> = Vec::new();
20737 let mut folded: Vec<GraphicsPipelineHandle> = Vec::new();
20738 let mut twins_bound = 0usize;
20739 let mut current: Option<GraphicsPipelineHandle> = None;
20740 let mut label: Option<String> = None;
20741 let mut calls: Vec<(bool, u32)> = Vec::new();
20742 let commands = recorder.commands();
20743 for command in &commands {
20744 match command {
20745 Command::BeginRenderPass { label: name, .. } => {
20746 label = name.clone();
20747 calls = Vec::new();
20748 }
20749 Command::EndRenderPass => {
20750 if !calls.is_empty() {
20751 passes.push((
20752 label.clone().expect("every pass here is labelled"),
20753 std::mem::take(&mut calls),
20754 ));
20755 }
20756 }
20757 Command::BindGraphicsPipeline(handle) => {
20758 current = Some(*handle);
20759 if twin_of(*handle).is_some() {
20760 twins_bound += 1;
20761 }
20762 // The fold turns a `single, double` pair into
20763 // `single, single`; collapsing a run of equal binds is
20764 // what makes the two streams comparable without hiding
20765 // a bind of anything else.
20766 let folded_handle = twin_of(*handle).unwrap_or(*handle);
20767 if folded.last() != Some(&folded_handle) {
20768 folded.push(folded_handle);
20769 }
20770 }
20771 Command::DrawIndexedIndirectCount(draw) => {
20772 let handle = current.expect("a draw follows a pipeline bind");
20773 calls.push((twin_of(handle).is_some(), bucket_of(draw.args_offset)));
20774 }
20775 Command::DrawIndexedIndirect(draw) => {
20776 let handle = current.expect("a draw follows a pipeline bind");
20777 calls.push((twin_of(handle).is_some(), bucket_of(draw.offset)));
20778 }
20779 _ => {}
20780 }
20781 }
20782 let modes = renderer.bucket_modes.clone();
20783 renderer.destroy(device);
20784 pool.destroy(device);
20785 device.destroy_image_view(imported.view);
20786 device.destroy_image(imported.image);
20787 recorder.assert_valid();
20788 Recorded {
20789 modes,
20790 twins_bound,
20791 passes,
20792 folded,
20793 }
20794 };
20795
20796 let single = bound(&single_scene);
20797 let double = bound(&double_scene);
20798
20799 assert_eq!(
20800 single.twins_bound, 0,
20801 "a scene with nothing double-sided must never bind a cull-none twin"
20802 );
20803 // Named rather than counted, because the claim is that **every** pass
20804 // that draws the surface routes: a frame that had quietly stopped
20805 // recording one of them would satisfy a count and leave that pass's
20806 // routing unchecked for ever.
20807 let drawing: Vec<&str> = single
20808 .passes
20809 .iter()
20810 .map(|(name, _)| name.as_str())
20811 .collect();
20812 for pass in ["shadow", "depth-prepass", "forward", "rsm", "rsm-punctual"] {
20813 assert!(
20814 drawing.contains(&pass),
20815 "`{pass}` drew nothing in this frame, so its routing is unchecked: {drawing:?}"
20816 );
20817 }
20818 assert!(
20819 double.twins_bound > 0,
20820 "a double-sided scene must bind the cull-none twins"
20821 );
20822 assert_eq!(
20823 double
20824 .passes
20825 .iter()
20826 .map(|(name, _)| name)
20827 .collect::<Vec<_>>(),
20828 single
20829 .passes
20830 .iter()
20831 .map(|(name, _)| name)
20832 .collect::<Vec<_>>(),
20833 "the two frames must draw in the same passes, or they are not comparable"
20834 );
20835
20836 // What each drawing pass should have recorded: every single-sided bucket
20837 // under the plain pipeline in bucket order, then every double-sided one
20838 // under the twin — the partition order `sided_partitions` lays down —
20839 // repeated once per view for a pass that draws several.
20840 let want: Vec<(bool, u32)> = [false, true]
20841 .into_iter()
20842 .flat_map(|twin| {
20843 double
20844 .modes
20845 .iter()
20846 .enumerate()
20847 .filter(move |(_, mode)| {
20848 (**mode & crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED != 0) == twin
20849 })
20850 .map(move |(bucket, _)| (twin, u32::try_from(bucket).expect("a few buckets")))
20851 })
20852 .collect();
20853 assert!(
20854 want.iter().any(|(twin, _)| *twin) && want.iter().any(|(twin, _)| !*twin),
20855 "the double-sided demo has to hold buckets of both sides, or this compares one \
20856 partition against itself: {:?}",
20857 double.modes
20858 );
20859 for (name, calls) in &double.passes {
20860 let views = calls.len() / want.len();
20861 assert!(
20862 views > 0 && calls.len() % want.len() == 0,
20863 "`{name}` recorded {} call(s) over {} bucket(s), which is not a whole number of \
20864 views",
20865 calls.len(),
20866 want.len()
20867 );
20868 // The partition is **outside** any view loop — one pipeline bind
20869 // covers every view of that side — so the stream is each partition's
20870 // bucket list repeated once per view.
20871 let mut expected: Vec<(bool, u32)> = Vec::with_capacity(calls.len());
20872 for twin in [false, true] {
20873 let partition: Vec<(bool, u32)> = want
20874 .iter()
20875 .copied()
20876 .filter(|(side, _)| *side == twin)
20877 .collect();
20878 for _ in 0..views {
20879 expected.extend_from_slice(&partition);
20880 }
20881 }
20882 assert_eq!(
20883 *calls, expected,
20884 "`{name}` must record each bucket once per view, under the pipeline its own \
20885 side asked for"
20886 );
20887 }
20888
20889 assert_eq!(
20890 double.folded, single.folded,
20891 "the frame gained or lost a pipeline bind beyond a cull-none twin beside the \
20892 pipeline it twins"
20893 );
20894 }
20895
20896 /// **The wireframe view swaps the colour pass's pipeline and nothing else.**
20897 ///
20898 /// The mechanism, at the level a null device can observe it: which pipeline
20899 /// handle each pass of the recorded stream binds. A field on the renderer
20900 /// would say only that a flag moved — this says the *frame* moved, and says
20901 /// which part of it did.
20902 ///
20903 /// Four claims, and each rules out a different way of passing wrongly:
20904 ///
20905 /// * the filled pipeline is bound on a frame nobody asked, and the wireframe
20906 /// one does not exist;
20907 /// * switching on **removes** the filled pipeline from the stream — a second
20908 /// pipeline that was built and never bound would still leave it there;
20909 /// * every other pipeline the frame binds is unchanged, so the depth prepass
20910 /// and the shadow cascades are still filling triangles;
20911 /// * and switching off puts the stream back exactly, so the view is a toggle
20912 /// rather than a one-way door.
20913 #[test]
20914 fn the_wireframe_view_swaps_the_colour_passs_pipeline_and_no_other() {
20915 use crcbl_hal::null::Command;
20916
20917 // The pipelines a frame binds include one per occlusion blur, and the
20918 // blur count is a process-global console variable — so a concurrent
20919 // test holding `r_ssao_blur_passes` at two adds a bind to one of the
20920 // frames below and not to the others. It reddened this assertion on
20921 // 2026-08-31 under a workspace `cargo test`.
20922 let _blurs = ssao_blur_switch();
20923 let (recorder, device, queue) =
20924 open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
20925 let device = device.as_ref();
20926 assert!(
20927 ForwardRenderer::supports_wireframe(device),
20928 "this test needs the line fill mode, and asked the device for it",
20929 );
20930 let mut renderer =
20931 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20932 place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
20933 let imported = swapchain_image(device);
20934 let mut pool = crate::TransientPool::new();
20935
20936 // The pipelines one frame binds, in record order. Cumulative recorder,
20937 // so each call takes the tail its own frame added.
20938 let mut seen = 0usize;
20939 // A different sun each lap, so the shadow atlas is redrawn in every one
20940 // of them: the comparison below is "which pipelines did this frame
20941 // bind", and a lap that cached its atlas would bind the depth-only
20942 // pipeline one fewer time for a reason that has nothing to do with the
20943 // wireframe. See [`moving_sun`].
20944 let mut lap = 0u32;
20945 let mut pipelines_in_a_frame = |renderer: &mut ForwardRenderer, pool: &mut _| {
20946 lap += 1;
20947 renderer
20948 .begin_frame(device, &Camera::default(), &moving_sun(lap), (64, 48))
20949 .expect("write");
20950 let mut graph = crate::RenderGraph::new(queue);
20951 let target = graph.import_image("target", imported);
20952 renderer.add_passes(&mut graph, pool, target, (64, 48));
20953 let compiled = graph.compile(pool).expect("a legal frame");
20954 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20955 label: Some("wireframe lap"),
20956 queue,
20957 });
20958 compiled
20959 .execute(device, pool, encoder.as_mut(), None)
20960 .expect("the graph executed");
20961 encoder.finish().expect("recording succeeded");
20962 let commands = recorder.commands();
20963 let bound: Vec<GraphicsPipelineHandle> = commands[seen..]
20964 .iter()
20965 .filter_map(|command| match command {
20966 Command::BindGraphicsPipeline(handle) => Some(*handle),
20967 _ => None,
20968 })
20969 .collect();
20970 seen = commands.len();
20971 bound
20972 };
20973
20974 let filled = renderer.mesh_pipeline.single;
20975 let off = pipelines_in_a_frame(&mut renderer, &mut pool);
20976 assert!(
20977 off.contains(&filled),
20978 "a frame nobody asked has to bind the filled pipeline: {off:?}",
20979 );
20980 assert!(!renderer.wireframe());
20981 assert!(
20982 renderer.wireframe_pipeline.is_none(),
20983 "the wireframe pipeline must not be built until it is asked for",
20984 );
20985
20986 renderer
20987 .set_wireframe(device, true)
20988 .expect("a device with the line fill mode builds it");
20989 assert!(renderer.wireframe());
20990 let lines = renderer
20991 .wireframe_pipeline
20992 .expect("switching on is what builds it")
20993 .single;
20994 let on = pipelines_in_a_frame(&mut renderer, &mut pool);
20995 assert!(
20996 !on.contains(&filled),
20997 "the colour pass still bound the filled pipeline: {on:?}",
20998 );
20999 assert_eq!(
21000 on.iter().filter(|handle| **handle == lines).count(),
21001 1,
21002 "the wireframe pipeline has to be bound exactly once — by the colour pass: {on:?}",
21003 );
21004 let substituted: Vec<GraphicsPipelineHandle> = on
21005 .iter()
21006 .map(|handle| if *handle == lines { filled } else { *handle })
21007 .collect();
21008 assert_eq!(
21009 substituted, off,
21010 "the frame gained or lost a pipeline bind beyond the colour pass's: {on:?} against \
21011 {off:?}",
21012 );
21013
21014 renderer
21015 .set_wireframe(device, false)
21016 .expect("switching off builds nothing");
21017 assert!(!renderer.wireframe());
21018 assert_eq!(
21019 pipelines_in_a_frame(&mut renderer, &mut pool),
21020 off,
21021 "switching the view off has to put the filled pipeline back, not just stop reporting \
21022 it",
21023 );
21024
21025 renderer.destroy(device);
21026 pool.destroy(device);
21027 device.destroy_image_view(imported.view);
21028 device.destroy_image(imported.image);
21029 recorder.assert_valid();
21030 }
21031
21032 /// **The colour pass tests against the prepass's depth instead of clearing
21033 /// and rewriting it, so each pixel is shaded once** — and a wireframe frame
21034 /// does the opposite, because lines do not reproduce a filled prepass.
21035 ///
21036 /// Both halves have to hold together or the frame is wrong in one of two
21037 /// ways, so both are asserted here. The attachment alone read-only while the
21038 /// pipeline still wrote would be a pipeline writing to a read-only
21039 /// attachment; the pipeline alone on `GreaterOrEqual` against an attachment
21040 /// this pass had just *cleared* would reject every fragment and draw a black
21041 /// frame. Neither shows up as an error — the first is a validation message
21042 /// on one backend and undefined behaviour on the rest, the second is a
21043 /// picture — which is why the observable is read off the compiled graph and
21044 /// off the pipeline state rather than off a screenshot.
21045 #[test]
21046 fn the_colour_pass_shades_once_per_pixel_against_the_prepasss_depth() {
21047 let (recorder, device, queue) =
21048 open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
21049 let device = device.as_ref();
21050 let mut renderer =
21051 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21052 place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
21053 let imported = swapchain_image(device);
21054 let mut pool = crate::TransientPool::new();
21055
21056 // Each pass's depth attachment, off the graph's own dump: the label it
21057 // was declared under, and the `load`/`store`/`write` triple the backend
21058 // is handed. A pass with no depth attachment contributes nothing, which
21059 // is what makes the lookup below a search rather than an index.
21060 let depth_of = |renderer: &mut ForwardRenderer, pool: &mut _, label: &str| {
21061 renderer
21062 .begin_frame(
21063 device,
21064 &Camera::default(),
21065 &DirectionalLight::default(),
21066 (64, 48),
21067 )
21068 .expect("write");
21069 let mut graph = crate::RenderGraph::new(queue);
21070 let target = graph.import_image("target", imported);
21071 renderer.add_passes(&mut graph, pool, target, (64, 48));
21072 let dump = graph.compile(pool).expect("a legal frame").dump();
21073 let mut pass = String::new();
21074 let mut found = None;
21075 for line in dump.lines() {
21076 if let Some(rest) = line.split(" pass \"").nth(1) {
21077 pass = rest.trim_end_matches('"').to_string();
21078 if let Some((name, _)) = pass.split_once('"') {
21079 pass = name.to_string();
21080 }
21081 }
21082 if pass == label
21083 && let Some(at) = line.find("depth load=")
21084 {
21085 // Without the slot note the dump appends: which physical
21086 // image the transient landed on is aliasing's business, not
21087 // this assertion's.
21088 let role = &line[at..];
21089 let role = role.split_once(" [").map_or(role, |(head, _)| head);
21090 found = Some(role.trim().to_string());
21091 }
21092 }
21093 found.unwrap_or_else(|| panic!("no depth attachment on `{label}`:\n{dump}"))
21094 };
21095
21096 assert_eq!(
21097 depth_of(&mut renderer, &mut pool, "depth-prepass"),
21098 "depth load=Clear store=Store write=yes",
21099 "the prepass is what puts the depth there, so it clears, writes and keeps it",
21100 );
21101 assert_eq!(
21102 depth_of(&mut renderer, &mut pool, "forward"),
21103 "depth load=Load store=Store write=no",
21104 "and the colour pass reads it: a clear here would throw away the prepass and \
21105 pay for the overdraw again, and a write would be a second pass writing the \
21106 same values",
21107 );
21108 assert_eq!(
21109 MeshModules::color_depth_stencil(PolygonMode::Fill),
21110 Some(DepthStencilState {
21111 format: Format::D32Float,
21112 depth_write: false,
21113 depth_compare: CompareOp::GreaterOrEqual,
21114 stencil: None,
21115 bias: DepthBias::default(),
21116 }),
21117 "and the pipeline agrees with the attachment: equality against the prepass, \
21118 reachable only through the `OrEqual` under reversed-Z",
21119 );
21120
21121 renderer
21122 .set_wireframe(device, true)
21123 .expect("this device was asked for the line fill mode");
21124 assert_eq!(
21125 depth_of(&mut renderer, &mut pool, "forward"),
21126 "depth load=Clear store=Store write=yes",
21127 "a wireframe frame keeps the old shape: `PolygonMode::Line` interpolates depth \
21128 along the edge rather than across the face, so testing it against a filled \
21129 prepass rejects most of the wireframe — and *loading* that depth under the \
21130 writing default's `Greater` would reject all of it",
21131 );
21132 assert_eq!(
21133 MeshModules::color_depth_stencil(PolygonMode::Line),
21134 MeshModules::depth_stencil(),
21135 "which is the writing default, the same state the depth-only twin uses",
21136 );
21137
21138 renderer.destroy(device);
21139 pool.destroy(device);
21140 device.destroy_image_view(imported.view);
21141 device.destroy_image(imported.image);
21142 recorder.assert_valid();
21143 }
21144
21145 /// **A device with no line fill mode is refused, not quietly filled.**
21146 ///
21147 /// The failure this rules out is the silent one: a caller who binds a key to
21148 /// this, presses it, and gets the solid frame back with nothing anywhere
21149 /// saying why — which on a model whose silhouette hides its interior is
21150 /// indistinguishable from a wireframe that worked. WebGPU is the real device
21151 /// this happens on; `open`'s null device stands in for it, because
21152 /// [`DeviceDesc::for_adapter`] asks for
21153 /// [`Features::GPU_DRIVEN`] and nothing else.
21154 #[test]
21155 fn a_device_without_the_line_fill_mode_refuses_the_wireframe_rather_than_filling_it() {
21156 let (recorder, device, queue) = open();
21157 let device = device.as_ref();
21158 assert!(
21159 !ForwardRenderer::supports_wireframe(device),
21160 "this device was not asked for the line fill mode, so it must not report it",
21161 );
21162 let mut renderer =
21163 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21164
21165 let refused = renderer
21166 .set_wireframe(device, true)
21167 .expect_err("a device without the feature has to say so");
21168 assert!(
21169 matches!(
21170 refused,
21171 HalError::UnsupportedFeatures { missing } if missing == Features::POLYGON_MODE_LINE
21172 ),
21173 "the refusal has to name the feature to go and look up, and is {refused:?}",
21174 );
21175 assert!(
21176 !renderer.wireframe(),
21177 "a refused request must leave the view off rather than half on",
21178 );
21179 assert!(
21180 renderer.wireframe_pipeline.is_none(),
21181 "nothing may be left behind by a refusal",
21182 );
21183 // And switching *off* is still fine on such a device: it builds nothing.
21184 renderer
21185 .set_wireframe(device, false)
21186 .expect("switching off asks the device for nothing");
21187
21188 renderer.destroy(device);
21189 recorder.assert_valid();
21190 }
21191
21192 /// The grid's own full-screen triangle is counted as submitted, and only
21193 /// while it is on.
21194 ///
21195 /// [`FrameCounters::instances`] is the "submitted" half of the debug panel's
21196 /// row, and every full-screen pass in the frame contributes one — so a grid
21197 /// that drew and was not counted makes that row disagree with the frame by
21198 /// exactly one triangle, silently.
21199 #[test]
21200 fn the_grids_triangle_is_counted_only_while_it_is_on() {
21201 let _blurs = ssao_blur_switch();
21202 let (recorder, device, queue) = open();
21203 let device = device.as_ref();
21204 let mut renderer =
21205 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21206 let imported = swapchain_image(device);
21207 let mut pool = crate::TransientPool::new();
21208
21209 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21210 let off = renderer.counters();
21211
21212 renderer
21213 .set_ground_grid(device, Some(GridStyle::default()))
21214 .expect("the null backend builds every pipeline");
21215 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21216 let on = renderer.counters();
21217
21218 assert_eq!(
21219 on.draws - off.draws,
21220 FULLSCREEN_DRAWS,
21221 "the grid records exactly one draw"
21222 );
21223 assert_eq!(
21224 on.instances - off.instances,
21225 FULLSCREEN_DRAWS,
21226 "and exactly one submitted instance"
21227 );
21228
21229 renderer.destroy(device);
21230 pool.destroy(device);
21231 device.destroy_image_view(imported.view);
21232 device.destroy_image(imported.image);
21233 recorder.assert_valid();
21234 }
21235
21236 /// One frame on a device of its own, under an override switching `off`.
21237 ///
21238 /// **A device of its own per arm**, because a [`Recorder`] accumulates for a
21239 /// device's whole life: asking "did the atlas pass draw" of a recorder that
21240 /// has seen two frames answers about both of them, and the arm that matters
21241 /// most here is the one whose answer must be zero.
21242 ///
21243 /// Returns what the frame reported and what its atlas pass actually drew.
21244 fn frame_switching_off(off: RenderEffects) -> (FrameCounters, u64, usize) {
21245 use crcbl_hal::null::Command;
21246
21247 let recorder = Recorder::new();
21248 let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21249 let adapter = instance.adapters().remove(0);
21250 let opened = instance
21251 .create_device(&DeviceDesc::for_adapter(adapter.id))
21252 .expect("the null backend always opens");
21253 let device = opened.as_ref();
21254 let queue = opened.queue(QueueKind::Graphics).expect("always present");
21255 let mut renderer =
21256 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21257 // A shadowed light beside the cascades, so the atlas pass has draws to
21258 // lose rather than being empty either way.
21259 renderer.set_lights(&[shadowable_spot(-1.0)]);
21260 // **[`OUTSIDE_THE_DEFAULT`] forced on, then `off` forced off.** The default
21261 // camera stack leaves both of them out — see
21262 // [`RenderEffects::DEFAULT_STACK`] — so a control frame built on the
21263 // default alone would be measuring three effects and calling it five,
21264 // and their arms below would be switching off something already off.
21265 // `force` clears the other side, so an arm whose `off` is one of them
21266 // still resolves to off.
21267 renderer.set_effect_request(EffectRequest {
21268 programmatic: EffectOverride::none()
21269 .force(OUTSIDE_THE_DEFAULT, Some(true))
21270 .force(off, Some(false)),
21271 ..EffectRequest::default()
21272 });
21273
21274 let recorded = frame(device, &mut renderer, queue);
21275 assert_eq!(
21276 renderer.effects(),
21277 RenderEffects::all().difference(off),
21278 "the frame must have resolved to the set the request asked for"
21279 );
21280 let counters = renderer.counters();
21281 let instances = renderer.instances.len() as u64;
21282 let atlas_draws = commands_in_pass(&recorder, "shadow")
21283 .into_iter()
21284 .filter(|command| {
21285 matches!(
21286 command,
21287 Command::DrawIndexedIndirect(_)
21288 | Command::DrawIndexedIndirectCount(_)
21289 | Command::DrawMeshTasksIndirect(_)
21290 )
21291 })
21292 .count();
21293 assert_eq!(
21294 counters.draws,
21295 recorded_draws(&recorder) as u64,
21296 "the counter and the frame's own recorded stream must agree, whatever is switched off"
21297 );
21298 recorded.finish(device, renderer);
21299 recorder.assert_valid();
21300 (counters, instances, atlas_draws)
21301 }
21302
21303 /// **A switched-off effect is work the frame did not record**, and a frame
21304 /// that still executes with the placeholder bound in place of what it lost.
21305 ///
21306 /// The other half of the pass-list test above, and the half a pass list
21307 /// cannot make: the `shadow` pass is still *there* with shadows off, so the
21308 /// question is whether it drew. That answer comes off the recorded command
21309 /// stream, which is a different instrument from `recorded_draws` — the number
21310 /// under test.
21311 ///
21312 /// Executed rather than only compiled, because the occlusion switch changes
21313 /// which image the forward pass has bound. A frame that declared a read of a
21314 /// transient it never created, or bound a view the graph never realised,
21315 /// fails here and compiles perfectly.
21316 #[test]
21317 fn a_switched_off_effect_is_work_the_frame_did_not_record() {
21318 let _blurs = ssao_blur_switch();
21319 let (control, instances, atlas_draws) = frame_switching_off(RenderEffects::empty());
21320 assert!(
21321 atlas_draws > 0,
21322 "with shadows on the atlas pass has to draw something, or turning it off means \
21323 nothing"
21324 );
21325 assert_eq!(
21326 control.instances,
21327 instances
21328 + fullscreen_passes(
21329 RenderEffects::all(),
21330 TEST_EXTENT,
21331 false,
21332 crate::ssao::blur_passes(),
21333 ) * FULLSCREEN_DRAWS,
21334 "the control frame submits one triangle per full-screen pass"
21335 );
21336
21337 // Each pair is one full-screen triangle per pass, and the atlas is
21338 // untouched by either.
21339 for (off, fewer) in [
21340 (
21341 RenderEffects::AMBIENT_OCCLUSION,
21342 u64::from(Ssao::passes(crate::ssao::blur_passes())),
21343 ),
21344 // The contact march's one pass, and a constant rather than a
21345 // function of anything: it has no blur behind it and no chain.
21346 (
21347 RenderEffects::CONTACT_SHADOWS,
21348 u64::from(ContactShadows::PASSES),
21349 ),
21350 // The march's two passes and the reductions that feed them, which
21351 // is what makes this arm's number a function of the extent the way
21352 // the chain's below is.
21353 (
21354 RenderEffects::REFLECTIONS,
21355 u64::from(Ssr::PASSES) + u64::from(crate::hiz::levels_for(TEST_EXTENT)),
21356 ),
21357 // Not a constant, unlike the occlusion pair above: the chain's
21358 // length is a function of the extent, and this is what it is at
21359 // `TEST_EXTENT`.
21360 (
21361 RenderEffects::BLOOM,
21362 u64::from(Bloom::passes_for(TEST_EXTENT)),
21363 ),
21364 ] {
21365 let (counters, instances, atlas) = frame_switching_off(off);
21366 assert_eq!(
21367 counters.draws,
21368 control.draws - fewer * FULLSCREEN_DRAWS,
21369 "{off:?}: the frame must record one draw fewer per pass it did not add"
21370 );
21371 assert_eq!(
21372 counters.instances,
21373 instances
21374 + fullscreen_passes(
21375 RenderEffects::all().difference(off),
21376 TEST_EXTENT,
21377 false,
21378 crate::ssao::blur_passes(),
21379 ) * FULLSCREEN_DRAWS,
21380 "{off:?}: and must not report as submitted a triangle it never submitted"
21381 );
21382 assert_eq!(
21383 atlas, atlas_draws,
21384 "{off:?}: a screen-space effect must not touch the shadow atlas"
21385 );
21386 }
21387
21388 // Shadows: the atlas pass survives and draws nothing at all, which is
21389 // the mechanism — a cleared reversed-Z atlas reads as fully lit.
21390 let (counters, _, atlas) = frame_switching_off(RenderEffects::SHADOWS);
21391 assert_eq!(
21392 atlas, 0,
21393 "with shadows off the atlas pass must record its clear and no draw"
21394 );
21395 assert_eq!(
21396 counters.draws,
21397 control.draws - atlas_draws as u64,
21398 "and the frame must record exactly the atlas pass's draws fewer"
21399 );
21400 }
21401
21402 /// **Every pass the frame records gets a row in the report, except the ones
21403 /// that open no scope.**
21404 ///
21405 /// The observable the bound exists for: the samples' hand-picked capacity
21406 /// timed the first eight passes of a fourteen-pass frame and reported eight
21407 /// rows, which reads exactly like a frame that has eight passes. Sized from
21408 /// [`MAX_TIMED_PASSES`](crate::MAX_TIMED_PASSES), the report names every
21409 /// pass the graph compiled, in order — so a bound one short of the frame
21410 /// makes this list short too.
21411 ///
21412 /// A [`PassKind::Copy`](crate::graph::PassKind::Copy) is filtered out of the
21413 /// expectation rather than expected to be missing by accident. The seam
21414 /// takes a timestamp only where a pass opens and closes and a copy opens
21415 /// nothing, so `PassTimers` gives it no query pair and no row — a row
21416 /// reading 0.000 ms would be a measurement nobody made.
21417 #[test]
21418 fn every_pass_of_the_frame_gets_a_timing_row() {
21419 let _blurs = ssao_blur_switch();
21420 // And the comparison seam, so the frame this checks carries the
21421 // occlusion chain's second march: `docs/plan/ROADMAP.md`'s S4D row asks
21422 // for a *per-technique* cost, and what makes that true is this test's
21423 // own claim — every pass that opens a scope gets a row — applied to a
21424 // frame that compares. See `crate::ssao`'s `r_ssao_split`.
21425 let split = ssao_split_switch();
21426 split.set(0.5);
21427 let recorder = Recorder::new();
21428 let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21429 let adapter = instance.adapters().remove(0);
21430 // `TIMESTAMP_QUERY` is not part of `GPU_DRIVEN` — topic 10's browsers
21431 // may lack it — so a device that wants timers has to ask for it, and
21432 // `open` above, which uses `DeviceDesc::for_adapter`, does not.
21433 let opened = instance
21434 .create_device(&DeviceDesc {
21435 label: Some("timed frame"),
21436 adapter: adapter.id,
21437 required_features: Features::GPU_DRIVEN,
21438 optional_features: Features::TIMESTAMP_QUERY,
21439 compatible_surface: None,
21440 })
21441 .expect("the null backend always opens");
21442 let queue = opened.queue(QueueKind::Graphics).expect("always present");
21443 let device = opened.as_ref();
21444 let mut renderer =
21445 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21446 renderer.set_lights(&[shadowable_spot(-1.0), shadowable_spot(1.0)]);
21447 let mut timers = crate::PassTimers::new(device, FRAMES_IN_FLIGHT, crate::MAX_TIMED_PASSES)
21448 .expect("the tier A null adapter has timestamp queries");
21449 let imported = swapchain_image(device);
21450 let mut pool = crate::TransientPool::new();
21451 let mut recorded = Vec::new();
21452 let mut compiled_labels = Vec::new();
21453
21454 // The ring is one slot longer than the frames in flight and resolves a
21455 // slot only when it comes round again, so the first frame's report is
21456 // that many frames behind it — see the [`timing`](crate::timing) docs.
21457 for _ in 0..FRAMES_IN_FLIGHT + 2 {
21458 renderer
21459 .begin_frame(
21460 device,
21461 &Camera::default(),
21462 &DirectionalLight::default(),
21463 (64, 48),
21464 )
21465 .expect("write");
21466 let mut graph = crate::RenderGraph::new(queue);
21467 let target = graph.import_image("target", imported);
21468 renderer.add_passes(&mut graph, &pool, target, (64, 48));
21469 let compiled = graph.compile(&pool).expect("a legal frame");
21470 if compiled_labels.is_empty() {
21471 compiled_labels = compiled
21472 .passes()
21473 .iter()
21474 .filter(|pass| pass.kind() != crate::graph::PassKind::Copy)
21475 .map(|pass| pass.label().to_string())
21476 .collect();
21477 }
21478 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21479 label: Some("timed frame"),
21480 queue,
21481 });
21482 compiled
21483 .execute(device, &mut pool, encoder.as_mut(), Some(&mut timers))
21484 .expect("the graph executed");
21485 recorded.push(encoder.finish().expect("recording succeeded"));
21486 }
21487
21488 let reported: Vec<&str> = timers
21489 .latest()
21490 .passes
21491 .iter()
21492 .map(|timing| timing.label.as_str())
21493 .collect();
21494 // Anti-vacuity for the seam held above: a frame that did not compare
21495 // would satisfy the equality below and say nothing about a
21496 // per-technique cost, because there would be one technique in it.
21497 for label in ["ssao", "ssao-shipped"] {
21498 assert!(
21499 compiled_labels.iter().any(|pass| pass == label),
21500 "the frame compiled no `{label}` pass, so the seam did not reach it and this \
21501 test says nothing about a comparison having a cost per side. Its passes: \
21502 {compiled_labels:?}"
21503 );
21504 }
21505 assert_eq!(
21506 reported,
21507 compiled_labels,
21508 "the report must name every pass the frame compiled that opens a scope, in order \
21509 — {} of {} timed with a capacity of {}",
21510 reported.len(),
21511 compiled_labels.len(),
21512 timers.capacity()
21513 );
21514
21515 timers.destroy(device);
21516 renderer.destroy(device);
21517 for commands in recorded {
21518 device.destroy_command_buffer(commands);
21519 }
21520 pool.destroy(device);
21521 device.destroy_image_view(imported.view);
21522 device.destroy_image(imported.image);
21523 recorder.assert_valid();
21524 }
21525
21526 /// One mesh-table entry, decoded from the bytes that reached the device.
21527 fn mesh_entry(
21528 recorder: &Recorder,
21529 renderer: &ForwardRenderer,
21530 id: u32,
21531 ) -> crcbl_shaders::mesh::GpuMesh {
21532 let table = recorder
21533 .buffer_bytes(renderer.pool.table_buffer())
21534 .expect("the table is live");
21535 let at = id as usize * crcbl_shaders::mesh::MESH_ENTRY_STRIDE;
21536 crcbl_shaders::mesh::GpuMesh::from_bytes(
21537 table[at..at + crcbl_shaders::mesh::MESH_ENTRY_STRIDE]
21538 .try_into()
21539 .expect("one whole entry"),
21540 )
21541 }
21542
21543 // --- skinning: the seam a caller draws a skinned mesh through -----------
21544
21545 /// A renderer with [`scene::demo`]'s cube reserved for skinning, and a
21546 /// [`Skinning`] built against that renderer's own vertex pool.
21547 struct SkinnedFixture {
21548 renderer: ForwardRenderer,
21549 skinning: Skinning,
21550 skinned: SkinnedMesh,
21551 palette: Vec<Mat4>,
21552 bindings: Vec<crcbl_shaders::skinning::SkinBinding>,
21553 }
21554
21555 impl SkinnedFixture {
21556 fn build(device: &dyn Device, queue: QueueHandle) -> Self {
21557 let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
21558 .expect("the null backend accepts every descriptor");
21559 let skinned = renderer
21560 .reserve_skinned(DEMO_CUBE)
21561 .expect("a default pool has room for two halves of a cube");
21562 let skinning = Skinning::new(
21563 device,
21564 &crate::skinning::SkinningDesc {
21565 label: Some("skinned fixture"),
21566 frames: FRAMES_IN_FLIGHT,
21567 ranges: 1,
21568 joints: 1,
21569 bindings: skinned.vertex_count(),
21570 // The renderer's own pool, which is the whole of what makes
21571 // the dispatch's output reachable by its draws.
21572 vertices: renderer.vertex_buffer(),
21573 attribute_base: renderer.attribute_base(),
21574 },
21575 )
21576 .expect("the null backend accepts every descriptor");
21577 let bindings = vec![
21578 crcbl_shaders::skinning::SkinBinding {
21579 joints: [0; crcbl_shaders::skinning::JOINTS_PER_VERTEX],
21580 weights: [1.0, 0.0, 0.0, 0.0],
21581 };
21582 skinned.vertex_count() as usize
21583 ];
21584 Self {
21585 renderer,
21586 skinning,
21587 skinned,
21588 palette: vec![Mat4::IDENTITY],
21589 bindings,
21590 }
21591 }
21592
21593 /// One skinned frame's `begin_skinned_frame`, with this fixture's single
21594 /// range.
21595 fn begin(&mut self, device: &dyn Device) {
21596 let range = self.skinned.skin_range(&self.palette, &self.bindings);
21597 self.renderer
21598 .begin_skinned_frame(
21599 device,
21600 &mut self.skinning,
21601 &[range],
21602 &Camera::default(),
21603 &DirectionalLight::default(),
21604 TEST_EXTENT,
21605 )
21606 .expect("a legal skinning plan");
21607 }
21608
21609 fn destroy(mut self, device: &dyn Device) {
21610 self.renderer.release_skinned(self.skinned);
21611 self.skinning.destroy(device);
21612 self.renderer.destroy(device);
21613 }
21614 }
21615
21616 /// How many times the host wrote the mesh-table entry `id` names.
21617 fn table_writes(recorder: &Recorder, renderer: &ForwardRenderer, id: u32) -> usize {
21618 let table = renderer.pool.table_buffer();
21619 let at = u64::from(id) * crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u64;
21620 recorder
21621 .events()
21622 .into_iter()
21623 .filter(|event| {
21624 matches!(
21625 event,
21626 crcbl_hal::null::Event::BufferWritten { buffer, offset, .. }
21627 if *buffer == table && *offset == at
21628 )
21629 })
21630 .count()
21631 }
21632
21633 /// The record `handle` names, out of the ring buffer **this frame draws
21634 /// from** rather than out of the pool's host mirror.
21635 ///
21636 /// A mirror and a buffer that disagree is exactly the defect a re-pointing
21637 /// design can have, so every claim about a skinned instance's bases is read
21638 /// off the bytes a shader would.
21639 fn instance_record(
21640 recorder: &Recorder,
21641 renderer: &ForwardRenderer,
21642 handle: InstanceHandle,
21643 ) -> mesh::GpuInstance {
21644 let buffer = renderer.instances.buffers()[renderer.frame()];
21645 let bytes = recorder.buffer_bytes(buffer).expect("the ring is live");
21646 let index = renderer
21647 .instances
21648 .index(handle)
21649 .expect("the object is live") as usize;
21650 let at = index * mesh::INSTANCE_STRIDE;
21651 mesh::GpuInstance::from_bytes(
21652 bytes[at..at + mesh::INSTANCE_STRIDE]
21653 .try_into()
21654 .expect("one whole instance"),
21655 )
21656 }
21657
21658 /// **A skinned primitive takes no mesh-table entry of its own, and nothing
21659 /// rewrites the one it draws through.**
21660 ///
21661 /// [`crate::mesh_pool`]'s table is one host-visible buffer rather than a ring
21662 /// precisely because nothing rewrites an entry between frames, so a design
21663 /// that re-pointed an entry at the half a frame writes would be wrong only
21664 /// on the frames that overlap — which is to say invisibly. What alternates
21665 /// instead is a field of the *instance*, and instances go through a ring.
21666 ///
21667 /// So a skinned object draws through the source mesh's own entry: the same
21668 /// id [`add_instance`](ForwardRenderer::add_instance) would give it, still
21669 /// carrying the bind pose's base vertex, still written exactly once after
21670 /// four skinned frames. That shared entry is also what lets one mesh be
21671 /// drawn skinned and unskinned in the same frame.
21672 #[test]
21673 fn a_skinned_mesh_takes_no_table_entry_and_rewrites_none() {
21674 let (recorder, device, queue) = open();
21675 let device = device.as_ref();
21676 let mut fixture = SkinnedFixture::build(device, queue);
21677
21678 let bind_pose_id = fixture.renderer.mesh_ids[DEMO_CUBE];
21679 assert_eq!(
21680 fixture.skinned.mesh_id(),
21681 bind_pose_id,
21682 "a skinned instance names the mesh it was deformed from, so the bucket, the level \
21683 tables and the bounding box all resolve as the bind pose's"
21684 );
21685
21686 let bind_pose = mesh_entry(&recorder, &fixture.renderer, bind_pose_id);
21687 assert_eq!(
21688 bind_pose.base_vertex,
21689 fixture.skinned.input_base(),
21690 "the entry goes on naming the bind pose the dispatch reads, not either half it \
21691 writes"
21692 );
21693 for parity in 0..2 {
21694 assert_ne!(
21695 fixture.skinned.region().base(parity),
21696 bind_pose.base_vertex,
21697 "half {parity} must not be the bind pose, which the kernel reads while it \
21698 writes them"
21699 );
21700 }
21701 assert_ne!(
21702 fixture.skinned.region().base(0),
21703 fixture.skinned.region().base(1),
21704 "the two halves are separate reservations, or the ping-pong is one buffer"
21705 );
21706
21707 // Counted before the frames rather than compared against a literal:
21708 // `MeshPool::new` clears the whole table with one write at offset zero,
21709 // which lands on this entry too, so the number here is the pool's
21710 // start-up and not this test's business. What the loop below has to
21711 // leave alone is whatever it is.
21712 let writes_before = table_writes(&recorder, &fixture.renderer, bind_pose_id);
21713 assert!(
21714 writes_before > 0,
21715 "the entry was written at least once before any frame ran, or the counter below \
21716 is counting nothing and the comparison after the frames is vacuous"
21717 );
21718
21719 // Four frames, which is two of each parity: enough that a design
21720 // rewriting an entry per frame would have written four more times.
21721 let imported = swapchain_image_at(device, TEST_EXTENT);
21722 let mut pool = crate::TransientPool::new();
21723 for _ in 0..4 {
21724 fixture.begin(device);
21725 let mut graph = crate::RenderGraph::new(queue);
21726 let target = graph.import_image("target", imported);
21727 fixture.renderer.add_skinned_passes(
21728 &mut graph,
21729 &pool,
21730 target,
21731 TEST_EXTENT,
21732 &fixture.skinning,
21733 );
21734 graph.compile(&pool).expect("a legal frame");
21735 }
21736
21737 assert_eq!(
21738 table_writes(&recorder, &fixture.renderer, bind_pose_id),
21739 writes_before,
21740 "entry {bind_pose_id} was written again by a skinned frame; the whole reason this \
21741 table is one buffer rather than a ring is that nothing rewrites an entry between \
21742 frames"
21743 );
21744
21745 fixture.destroy(device);
21746 pool.destroy(device);
21747 device.destroy_image_view(imported.view);
21748 device.destroy_image(imported.image);
21749 recorder.assert_valid();
21750 }
21751
21752 /// **A skinned object's recorded base vertex follows the parity of the frame
21753 /// it is drawn in**, and it carries the bit that makes a shader read it.
21754 ///
21755 /// The other half of the design: the table entry never moves, so what has to
21756 /// alternate is a field of the *instance* — and it has to alternate in the
21757 /// buffer the frame actually draws from, which is why this reads the
21758 /// instance ring's bytes rather than the host's mirror.
21759 ///
21760 /// Three claims, and the last two are what stop the first being vacuous. The
21761 /// base must be the one this frame's parity names; the record must carry
21762 /// [`GpuInstance::BASE_VERTEX_OVERRIDE`](mesh::GpuInstance::BASE_VERTEX_OVERRIDE),
21763 /// without which the raster stages read the mesh entry and the field is
21764 /// decoration; and two consecutive frames must have named **different**
21765 /// halves, without which a renderer ignoring the parity entirely would pass.
21766 #[test]
21767 fn a_skinned_draw_carries_the_base_the_frames_dispatch_filled() {
21768 let (recorder, device, queue) = open();
21769 let device = device.as_ref();
21770 let mut fixture = SkinnedFixture::build(device, queue);
21771 let handle = fixture
21772 .renderer
21773 .add_skinned_instance(&SkinnedInstanceDesc {
21774 mesh: &fixture.skinned,
21775 material: DEMO_UNTINTED,
21776 transform: Mat4::IDENTITY,
21777 })
21778 .expect("a pool of thousands has room for one object");
21779
21780 let mut carried = Vec::new();
21781 for _ in 0..2 {
21782 fixture.begin(device);
21783 let parity = fixture.skinning.parity();
21784 let instance = instance_record(&recorder, &fixture.renderer, handle);
21785 assert_eq!(
21786 instance.base_vertex,
21787 fixture.skinned.region().base(parity),
21788 "the buffer this frame draws from must carry the base parity {parity} writes"
21789 );
21790 assert_eq!(
21791 instance.flags & mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
21792 mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
21793 "without the bit the raster stages resolve the mesh entry's base and this \
21794 field is never read"
21795 );
21796 assert_eq!(
21797 instance.mesh, fixture.renderer.mesh_ids[DEMO_CUBE],
21798 "and the record still names the source mesh, which is what its bucket, its \
21799 levels and its bounding box resolve through"
21800 );
21801 carried.push(instance.base_vertex);
21802 }
21803 assert_ne!(
21804 carried[0], carried[1],
21805 "two consecutive frames must have drawn different halves, or a renderer that \
21806 ignored the parity entirely would pass this"
21807 );
21808
21809 fixture.destroy(device);
21810 recorder.assert_valid();
21811 }
21812
21813 /// **A skinned object's record names the half the frame before it filled**,
21814 /// and it starts at rest.
21815 ///
21816 /// The other half of a skinned motion vector. The base above is where a
21817 /// fragment *is*; this is where it *was*, and without it the geometry stages
21818 /// put the previous transform through this frame's deformed vertex — so a
21819 /// limb that swung reports the motion of the body it hangs off. See
21820 /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
21821 ///
21822 /// Four claims, and the first and last are what stop the middle two being a
21823 /// restatement of the parity:
21824 ///
21825 /// * the **first** frame of a fresh object writes the base it draws out of,
21826 /// because the other half holds whatever its reservation came with and a
21827 /// motion vector against undefined vertices is worse than no motion;
21828 /// * the frames after it write
21829 /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base),
21830 /// which must also **differ** from the base they draw out of — a renderer
21831 /// that wrote the current base into both lanes would satisfy every "it is
21832 /// a legal base" reading of this and leave every skinned instance at rest;
21833 /// * and moving the object onto a **different region** puts it back at rest
21834 /// for one frame, because the halves it now names are two runs it has
21835 /// never been drawn out of.
21836 #[test]
21837 fn a_skinned_draw_carries_the_previous_half_and_starts_at_rest() {
21838 let (recorder, device, queue) = open();
21839 let device = device.as_ref();
21840 let mut fixture = SkinnedFixture::build(device, queue);
21841 let handle = fixture
21842 .renderer
21843 .add_skinned_instance(&SkinnedInstanceDesc {
21844 mesh: &fixture.skinned,
21845 material: DEMO_UNTINTED,
21846 transform: Mat4::IDENTITY,
21847 })
21848 .expect("a pool of thousands has room for one object");
21849
21850 for frame in 1..=3u32 {
21851 fixture.begin(device);
21852 let parity = fixture.skinning.parity();
21853 let instance = instance_record(&recorder, &fixture.renderer, handle);
21854 assert_eq!(
21855 instance.base_vertex,
21856 fixture.skinned.region().base(parity),
21857 "frame {frame} must draw out of the half parity {parity} fills"
21858 );
21859 if frame == 1 {
21860 assert_eq!(
21861 instance.previous_base_vertex, instance.base_vertex,
21862 "a fresh object has no previous deformation, so its first frame owes rest \
21863 rather than a half no dispatch has written"
21864 );
21865 } else {
21866 assert_eq!(
21867 instance.previous_base_vertex,
21868 fixture.skinned.region().previous_base(parity),
21869 "frame {frame} must subtract against the half the frame before it filled"
21870 );
21871 assert_ne!(
21872 instance.previous_base_vertex, instance.base_vertex,
21873 "frame {frame} named one half twice, which is every skinned fragment at \
21874 rest however far its surface moved"
21875 );
21876 }
21877 }
21878
21879 // The same object, moved onto a region it has never been drawn out of:
21880 // both halves are runs no dispatch of this object's has filled, so the
21881 // rule that put the first frame at rest applies again.
21882 let second = fixture
21883 .renderer
21884 .reserve_skinned(DEMO_CUBE)
21885 .expect("a default pool has room for two more halves of a cube");
21886 assert_ne!(
21887 second.region().base(0),
21888 fixture.skinned.region().base(0),
21889 "the second reservation is the same two runs as the first, so nothing below is \
21890 about a change of region at all"
21891 );
21892 fixture.renderer.set_skinned_instance(
21893 handle,
21894 &SkinnedInstanceDesc {
21895 mesh: &second,
21896 material: DEMO_UNTINTED,
21897 transform: Mat4::IDENTITY,
21898 },
21899 );
21900
21901 for frame in 1..=2u32 {
21902 fixture.begin(device);
21903 let parity = fixture.skinning.parity();
21904 let instance = instance_record(&recorder, &fixture.renderer, handle);
21905 assert_eq!(
21906 instance.base_vertex,
21907 second.region().base(parity),
21908 "frame {frame} after the move must draw out of the new region"
21909 );
21910 if frame == 1 {
21911 assert_eq!(
21912 instance.previous_base_vertex, instance.base_vertex,
21913 "the first frame on a new region owes rest, exactly as a fresh object does"
21914 );
21915 } else {
21916 assert_eq!(
21917 instance.previous_base_vertex,
21918 second.region().previous_base(parity),
21919 "and the frame after it is subtracting against the new region's other half"
21920 );
21921 }
21922 }
21923
21924 fixture.renderer.release_skinned(second);
21925 fixture.destroy(device);
21926 recorder.assert_valid();
21927 }
21928
21929 /// **A skinned object that moves carries the transform it moved from**, and
21930 /// the frame after it is back at rest.
21931 ///
21932 /// The transform half of a skinned motion vector, and the half the
21933 /// per-frame re-point used to erase: it rewrote the record through
21934 /// [`InstancePool::set`], which fills the previous transform out of the
21935 /// record it overwrites — and that record already held this frame's
21936 /// transform, because
21937 /// [`set_skinned_instance`](ForwardRenderer::set_skinned_instance) had put
21938 /// it there. Every skinned instance then read `previous_transform ==
21939 /// transform` on every frame, so a character that walked contributed
21940 /// nothing to the motion target from the walk, only from its deformation.
21941 /// [`InstancePool::set_bases`] is what the re-point goes through instead.
21942 ///
21943 /// Both frames are the claim. Without the second, a re-point that wrote
21944 /// some *other* stale transform into the field would pass; and the second
21945 /// is the pool's own rest rule reaching a skinned object at all, which a
21946 /// re-point that kept enrolling the element every frame would suppress
21947 /// for ever.
21948 ///
21949 /// Read out of the ring buffer the frame draws from, on
21950 /// [`instance_record`]'s terms.
21951 #[test]
21952 fn a_skinned_instance_that_moves_carries_the_transform_it_moved_from() {
21953 let (recorder, device, queue) = open();
21954 let device = device.as_ref();
21955 let mut fixture = SkinnedFixture::build(device, queue);
21956 let handle = fixture
21957 .renderer
21958 .add_skinned_instance(&SkinnedInstanceDesc {
21959 mesh: &fixture.skinned,
21960 material: DEMO_UNTINTED,
21961 transform: Mat4::IDENTITY,
21962 })
21963 .expect("a pool of thousands has room for one object");
21964
21965 // Two frames standing still, so the history the move is measured
21966 // against is a settled record rather than a fresh one.
21967 fixture.begin(device);
21968 fixture.begin(device);
21969
21970 let moved = Mat4::from_translation(Vec3::new(5.0, 0.0, 0.0));
21971 fixture.renderer.set_skinned_instance(
21972 handle,
21973 &SkinnedInstanceDesc {
21974 mesh: &fixture.skinned,
21975 material: DEMO_UNTINTED,
21976 transform: moved,
21977 },
21978 );
21979 fixture.begin(device);
21980 let instance = instance_record(&recorder, &fixture.renderer, handle);
21981 assert_eq!(
21982 instance.transform,
21983 moved.to_cols_array(),
21984 "the frame that moved the object must draw it where it arrived"
21985 );
21986 assert_eq!(
21987 instance.previous_transform,
21988 Mat4::IDENTITY.to_cols_array(),
21989 "and it must say where from — a previous transform equal to the current one is \
21990 the re-point having overwritten the move"
21991 );
21992
21993 fixture.begin(device);
21994 let settled = instance_record(&recorder, &fixture.renderer, handle);
21995 assert_eq!(
21996 settled.transform,
21997 moved.to_cols_array(),
21998 "nothing moved it again"
21999 );
22000 assert_eq!(
22001 settled.previous_transform, settled.transform,
22002 "so the frame after the move owes rest; a re-point that enrolled the element \
22003 every frame would keep it reporting the move for ever"
22004 );
22005
22006 fixture.destroy(device);
22007 recorder.assert_valid();
22008 }
22009
22010 /// **The graph barriers the skinning dispatch's write before every pass that
22011 /// pulls vertices**, and it does so because `add_skinned_passes` added the
22012 /// dispatch itself rather than trusting a caller to.
22013 ///
22014 /// Pass order alone would not settle it — a dispatch that ran first and was
22015 /// never barriered is the exact defect, and it produces a correct-looking
22016 /// frame on a desktop driver. So the transition out of
22017 /// [`ResourceState::ShaderReadWrite`] is named: there must be exactly one,
22018 /// it must sit after the dispatch, and it must sit at or before the first of
22019 /// the three passes that draw.
22020 #[test]
22021 fn the_skinning_dispatch_is_barriered_before_every_pass_that_draws() {
22022 let (recorder, device, queue) = open();
22023 let device = device.as_ref();
22024 let mut fixture = SkinnedFixture::build(device, queue);
22025 place_cube(&mut fixture.renderer, Mat4::IDENTITY);
22026 fixture
22027 .renderer
22028 .add_skinned_instance(&SkinnedInstanceDesc {
22029 mesh: &fixture.skinned,
22030 material: DEMO_UNTINTED,
22031 transform: Mat4::IDENTITY,
22032 })
22033 .expect("room for one object");
22034 fixture.begin(device);
22035
22036 let imported = swapchain_image_at(device, TEST_EXTENT);
22037 let mut pool = crate::TransientPool::new();
22038 let mut graph = crate::RenderGraph::new(queue);
22039 let target = graph.import_image("target", imported);
22040 // The same node `Skinning::add_pass` imports — one handle is one node —
22041 // so the barriers below can be named rather than guessed at.
22042 let vertices = graph.import_buffer(
22043 "vertex-pool",
22044 ImportedBuffer {
22045 buffer: fixture.renderer.vertex_buffer(),
22046 initial: ResourceState::ShaderRead,
22047 final_state: ResourceState::ShaderRead,
22048 },
22049 );
22050 fixture.renderer.add_skinned_passes(
22051 &mut graph,
22052 &pool,
22053 target,
22054 TEST_EXTENT,
22055 &fixture.skinning,
22056 );
22057 let compiled = graph.compile(&pool).expect("a legal frame");
22058 let labels: Vec<&str> = compiled
22059 .passes()
22060 .iter()
22061 .map(crate::graph::CompiledPass::label)
22062 .collect();
22063
22064 let dispatch = labels
22065 .iter()
22066 .position(|label| *label == "skinning")
22067 .expect("add_skinned_passes adds the dispatch itself");
22068 let drawing: Vec<usize> = ["shadow", "depth-prepass", "forward"]
22069 .into_iter()
22070 .map(|wanted| {
22071 labels
22072 .iter()
22073 .position(|label| *label == wanted)
22074 .unwrap_or_else(|| panic!("the frame draws through {wanted}: {labels:?}"))
22075 })
22076 .collect();
22077 for (label, at) in ["shadow", "depth-prepass", "forward"]
22078 .into_iter()
22079 .zip(&drawing)
22080 {
22081 assert!(
22082 dispatch < *at,
22083 "the dispatch is at {dispatch} and {label} at {at}: {labels:?}"
22084 );
22085 }
22086
22087 // Each drawing pass declares the read for itself, and this is asserted
22088 // per pass rather than left to the single barrier below. The graph
22089 // transitions the region once, before the first reader, and a later
22090 // pass that never declared the read finds it already in the state it
22091 // wanted — so dropping the declaration from `forward` alone changes no
22092 // barrier and moves no label, and every assertion in this test still
22093 // passes. What it does drop is that pass's *dependency* on the
22094 // dispatch, which is the only thing keeping the two in this order.
22095 for (label, at) in ["shadow", "depth-prepass", "forward"]
22096 .into_iter()
22097 .zip(&drawing)
22098 {
22099 assert!(
22100 compiled.passes()[*at].reads_buffer(vertices),
22101 "{label} draws skinned vertices and must declare that it reads them, or \
22102 nothing but declaration order keeps it after the dispatch"
22103 );
22104 }
22105
22106 let released: Vec<usize> = compiled
22107 .passes()
22108 .iter()
22109 .enumerate()
22110 .filter(|(_, pass)| {
22111 pass.barriers().buffers.iter().any(|barrier| {
22112 barrier.buffer == vertices
22113 && barrier.from == ResourceState::ShaderReadWrite
22114 && barrier.to == ResourceState::ShaderRead
22115 })
22116 })
22117 .map(|(at, _)| at)
22118 .collect();
22119 assert_eq!(
22120 released.len(),
22121 1,
22122 "exactly one transition out of the dispatch's write: {released:?} in {labels:?}"
22123 );
22124 let barrier = released[0];
22125 let first_draw = *drawing.iter().min().expect("three passes");
22126 assert!(
22127 dispatch < barrier && barrier <= first_draw,
22128 "the barrier is at {barrier}, the dispatch at {dispatch} and the first pass that \
22129 draws at {first_draw} — a draw that reads the region before the write is made \
22130 visible is the whole defect this seam exists to prevent"
22131 );
22132
22133 drop(compiled);
22134 fixture.destroy(device);
22135 pool.destroy(device);
22136 device.destroy_image_view(imported.view);
22137 device.destroy_image(imported.image);
22138 recorder.assert_valid();
22139 }
22140
22141 /// A frame with nothing to skin adds no dispatch and declares no read, and
22142 /// is the frame [`ForwardRenderer::add_passes`] would have built.
22143 #[test]
22144 fn a_frame_with_no_skinned_range_is_the_frame_add_passes_builds() {
22145 let _blurs = ssao_blur_switch();
22146 let (recorder, device, queue) = open();
22147 let device = device.as_ref();
22148 let mut fixture = SkinnedFixture::build(device, queue);
22149 place_cube(&mut fixture.renderer, Mat4::IDENTITY);
22150
22151 let imported = swapchain_image_at(device, TEST_EXTENT);
22152 let pool = crate::TransientPool::new();
22153 let mut skinned_labels = Vec::new();
22154 for _ in 0..1 {
22155 fixture
22156 .renderer
22157 .begin_skinned_frame(
22158 device,
22159 &mut fixture.skinning,
22160 &[],
22161 &Camera::default(),
22162 &DirectionalLight::default(),
22163 TEST_EXTENT,
22164 )
22165 .expect("an empty plan is a legal one");
22166 let mut graph = crate::RenderGraph::new(queue);
22167 let target = graph.import_image("target", imported);
22168 fixture.renderer.add_skinned_passes(
22169 &mut graph,
22170 &pool,
22171 target,
22172 TEST_EXTENT,
22173 &fixture.skinning,
22174 );
22175 skinned_labels = graph
22176 .compile(&pool)
22177 .expect("a legal frame")
22178 .passes()
22179 .iter()
22180 .map(|pass| pass.label().to_string())
22181 .collect();
22182 }
22183 let plain = passes_in_a_frame(
22184 device,
22185 queue,
22186 &mut fixture.renderer,
22187 imported,
22188 &pool,
22189 TEST_EXTENT,
22190 );
22191 assert_eq!(
22192 skinned_labels, plain,
22193 "a frame with nothing to skin must cost the vertex pool no barrier at all"
22194 );
22195
22196 fixture.destroy(device);
22197 let mut pool = pool;
22198 pool.destroy(device);
22199 device.destroy_image_view(imported.view);
22200 device.destroy_image(imported.image);
22201 recorder.assert_valid();
22202 }
22203
22204 /// One frame recorded end to end: `begin_frame`, the graph, and an encoder
22205 /// the commands land in.
22206 ///
22207 /// Returned rather than cleaned up here because the caller reads the
22208 /// recorder afterwards, and everything below must outlive that.
22209 struct Frame {
22210 imported: ImportedImage,
22211 pool: crate::TransientPool,
22212 commands: crcbl_hal::CommandBufferHandle,
22213 }
22214
22215 impl Frame {
22216 /// Releases the frame and the image it drew into, leaving the renderer
22217 /// alive for another one.
22218 fn release(self, device: &dyn Device) {
22219 device.destroy_command_buffer(self.commands);
22220 let mut pool = self.pool;
22221 pool.destroy(device);
22222 device.destroy_image_view(self.imported.view);
22223 device.destroy_image(self.imported.image);
22224 }
22225
22226 /// Releases the frame, the renderer and the image it drew into.
22227 fn finish(self, device: &dyn Device, renderer: ForwardRenderer) {
22228 self.release(device);
22229 renderer.destroy(device);
22230 }
22231 }
22232
22233 /// Everything one labelled pass recorded, and nothing any other pass did.
22234 ///
22235 /// **Every draw assertion below is scoped through this**, and the reason is
22236 /// topic 18: the frame now records the same indirect call the colour pass
22237 /// records once per shadow cascade as well, out of that cascade's own
22238 /// arguments. A test filtering the whole stream for `DrawIndexedIndirect`
22239 /// would see one per cascade as well as the colour pass's, and could not
22240 /// say which pass any of them belonged to — so "the forward pass records one
22241 /// call per bucket" would become a claim about a total, which a shadow pass
22242 /// recording the wrong thing could satisfy.
22243 /// The compute dispatches a default frame's **resolve** records, which
22244 /// every dispatch count in this module sees and none of them is about.
22245 ///
22246 /// `RenderEffects::DEFAULT_STACK` carries `CMAA2`, whose edge detect and
22247 /// shape classification are dispatches; its apply is a draw and does not
22248 /// count here. `each_effect_toggle_removes_exactly_the_passes_it_owns` is
22249 /// what pins the resolve's pass list itself, so a tier that grew a dispatch
22250 /// fails there first and arrives here as a second red rather than as a
22251 /// silent skew.
22252 const RESOLVE_DISPATCHES: usize = 2;
22253
22254 fn commands_in_pass(
22255 recorder: &crcbl_hal::null::Recorder,
22256 label: &str,
22257 ) -> Vec<crcbl_hal::null::Command> {
22258 use crcbl_hal::null::Command;
22259
22260 let mut inside = false;
22261 let mut out = Vec::new();
22262 for command in recorder.commands() {
22263 if let Some((_, recorded)) = command.opens_pass() {
22264 inside = recorded == Some(label);
22265 continue;
22266 }
22267 if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
22268 inside = false;
22269 continue;
22270 }
22271 if inside {
22272 out.push(command);
22273 }
22274 }
22275 assert!(!out.is_empty(), "no pass labelled `{label}` recorded work");
22276 out
22277 }
22278
22279 /// The extent every helper frame in this module is drawn at.
22280 ///
22281 /// Named since the bloom chain, whose length is a function of it — see
22282 /// [`crate::bloom`] — so a test comparing a pass count against
22283 /// [`fullscreen_passes`] has to ask about the same size the frame was drawn
22284 /// at. Small on purpose: two chain levels is enough for every arm here, and
22285 /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`] is the one
22286 /// test that needs a frame large enough for six.
22287 ///
22288 /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
22289 const TEST_EXTENT: (u32, u32) = (64, 48);
22290
22291 /// The effects a caller has to ask for, because the default stack leaves
22292 /// them out — see [`RenderEffects::DEFAULT_STACK`].
22293 ///
22294 /// Named rather than written out at each of the three sites that force them
22295 /// on, because the point of those sites is "every effect there is" and the
22296 /// bug they exist to catch is a new effect joining the set and one site
22297 /// still measuring the old one while calling it the whole stack. They are
22298 /// held out of the default for different reasons — [`crate::effects`] gives
22299 /// each, and [`RenderEffects::CONTACT_SHADOWS`]'s is the only one that is a
22300 /// pending re-bless rather than a decision — and share only that a test
22301 /// wanting the widest frame must ask.
22302 ///
22303 /// **Named for what it is rather than for what most of it is**: the set held
22304 /// four post passes and a resolve when it was `POST_EFFECTS`, and the contact
22305 /// march is neither.
22306 const OUTSIDE_THE_DEFAULT: RenderEffects = RenderEffects::BLOOM
22307 .union(RenderEffects::ANTIALIASING)
22308 .union(RenderEffects::VOLUMETRIC_FOG)
22309 .union(RenderEffects::AUTO_EXPOSURE)
22310 .union(RenderEffects::CMAA2)
22311 .union(RenderEffects::CONTACT_SHADOWS);
22312
22313 /// Every effect this renderer draws is either in the default stack or in
22314 /// [`OUTSIDE_THE_DEFAULT`].
22315 ///
22316 /// The guard on the three sites above: they force [`OUTSIDE_THE_DEFAULT`] on and
22317 /// call the result "every effect", which is only true while nothing else is
22318 /// held out. An effect added outside the default stack and not added
22319 /// here makes this red before it makes a pass-list assertion red — which is
22320 /// the useful order, since a pass list going red says a label moved and this
22321 /// says what actually happened.
22322 #[test]
22323 fn forcing_the_post_effects_on_reaches_every_effect_there_is() {
22324 assert_eq!(
22325 RenderEffects::DEFAULT_STACK.union(OUTSIDE_THE_DEFAULT),
22326 RenderEffects::all(),
22327 "an effect outside the default stack that no test forces on is an effect \
22328 the every-effect frames below have never drawn"
22329 );
22330 }
22331
22332 /// The default sun, turned a little further round for each `lap`.
22333 ///
22334 /// Topic 45's static-caching rung means a second frame over
22335 /// a scene nothing moved in records **no shadow pass at all** — see
22336 /// [`ForwardRenderer::shadow_atlas_cached`]. That is the feature, and it is
22337 /// a difference that every A/B drawing two frames from one renderer would
22338 /// otherwise be measuring on top of the one it is about. Turning the sun is
22339 /// the smallest input the atlas depends on: the cascades are refitted, so
22340 /// the atlas is redrawn, and no pass, pipeline or draw of the frame moves
22341 /// with it.
22342 ///
22343 /// Lap zero is [`DirectionalLight::default`] exactly, so a test whose first
22344 /// frame is the ordinary one keeps the frame every other test draws.
22345 fn moving_sun(lap: u32) -> DirectionalLight {
22346 let sun = DirectionalLight::default();
22347 // A degree a lap, about the axis the default direction is not parallel
22348 // to. Small enough that every cascade still sees the scene, and large
22349 // enough that the snapped cascade origin actually moves.
22350 let turn = Mat4::from_rotation_y(
22351 f32::from(u16::try_from(lap).expect("a handful of laps")) * std::f32::consts::PI
22352 / 180.0,
22353 );
22354 DirectionalLight {
22355 direction: turn.transform_vector3(sun.direction).normalize(),
22356 ..sun
22357 }
22358 }
22359
22360 /// [`frame`] drawn under [`moving_sun`], so this frame's shadow atlas is
22361 /// not the one the lap before it left in the image.
22362 fn frame_moving_the_sun(
22363 device: &dyn Device,
22364 renderer: &mut ForwardRenderer,
22365 queue: QueueHandle,
22366 lap: u32,
22367 ) -> Frame {
22368 frame_lit_by(device, renderer, queue, &moving_sun(lap))
22369 }
22370
22371 fn frame(device: &dyn Device, renderer: &mut ForwardRenderer, queue: QueueHandle) -> Frame {
22372 frame_lit_by(device, renderer, queue, &DirectionalLight::default())
22373 }
22374
22375 fn frame_lit_by(
22376 device: &dyn Device,
22377 renderer: &mut ForwardRenderer,
22378 queue: QueueHandle,
22379 sun: &DirectionalLight,
22380 ) -> Frame {
22381 frame_seen_from(device, renderer, queue, &Camera::default(), sun)
22382 }
22383
22384 fn frame_seen_from(
22385 device: &dyn Device,
22386 renderer: &mut ForwardRenderer,
22387 queue: QueueHandle,
22388 camera: &Camera,
22389 sun: &DirectionalLight,
22390 ) -> Frame {
22391 renderer
22392 .begin_frame(device, camera, sun, TEST_EXTENT)
22393 .expect("write");
22394 let imported = swapchain_image(device);
22395 let mut graph = crate::RenderGraph::new(queue);
22396 let target = graph.import_image("target", imported);
22397 let mut pool = crate::TransientPool::new();
22398 renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
22399 let compiled = graph.compile(&pool).expect("a legal frame");
22400 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
22401 label: Some("forward frame"),
22402 queue,
22403 });
22404 compiled
22405 .execute(device, &mut pool, encoder.as_mut(), None)
22406 .expect("the graph executed");
22407 let commands = encoder.finish().expect("recording succeeded");
22408 Frame {
22409 imported,
22410 pool,
22411 commands,
22412 }
22413 }
22414
22415 /// A stand-in for the acquired swapchain image the frame normally ends in,
22416 /// at [`TEST_EXTENT`].
22417 fn swapchain_image(device: &dyn Device) -> ImportedImage {
22418 swapchain_image_at(device, TEST_EXTENT)
22419 }
22420
22421 /// The same, at an extent of the caller's choosing.
22422 ///
22423 /// A frame's attachments must all be one size — the graph refuses a pass
22424 /// whose colour target and depth disagree — so a test drawing at anything
22425 /// but [`TEST_EXTENT`] has to import a target of that size too.
22426 pub(super) fn swapchain_image_at(device: &dyn Device, extent: (u32, u32)) -> ImportedImage {
22427 let format = Format::Rgba8UnormSrgb;
22428 let image = device
22429 .create_image(&crcbl_hal::ImageDesc {
22430 label: Some("fake swapchain image"),
22431 image_type: crcbl_hal::ImageType::D2,
22432 extent: crcbl_hal::Extent3d::d2(extent.0, extent.1),
22433 format,
22434 mip_levels: 1,
22435 samples: 1,
22436 usage: crcbl_hal::ImageUsage::COLOR_ATTACHMENT | crcbl_hal::ImageUsage::PRESENT,
22437 })
22438 .expect("an image");
22439 let view = device
22440 .create_image_view(&crcbl_hal::ImageViewDesc {
22441 label: Some("fake swapchain view"),
22442 image,
22443 view_type: crcbl_hal::ImageViewType::D2,
22444 format,
22445 range: crcbl_hal::ImageSubresourceRange::all(format),
22446 })
22447 .expect("a view");
22448 ForwardRenderer::present_target(image, view, format, extent)
22449 }
22450
22451 /// The spin is a rotation: no scale, no shear, so the cube neither grows
22452 /// nor mirrors as it turns, and every mesh golden blessed at a `spin` is a
22453 /// picture of one cube.
22454 ///
22455 /// That is also what keeps those goldens insensitive to `mesh.slang`'s
22456 /// `normal_basis`. A matrix with orthonormal rows and a positive
22457 /// determinant is its own cofactor matrix, to within a rounding step, so
22458 /// the vertex stage writes the normals it wrote when it multiplied by the
22459 /// bare 3×3 — see [`crcbl_shaders::mesh::GpuInstance::transform`], which no
22460 /// longer requires a caller to be rigid at all.
22461 #[test]
22462 fn the_spin_matrix_stays_rigid() {
22463 for seconds in [0.0f32, 0.5, 3.25, 100.0] {
22464 let model = ForwardRenderer::spin(seconds);
22465 let basis = glam::Mat3::from_mat4(model);
22466 let product = basis * basis.transpose();
22467 for (row, expected) in [
22468 (product.x_axis, Vec3::X),
22469 (product.y_axis, Vec3::Y),
22470 (product.z_axis, Vec3::Z),
22471 ] {
22472 assert!(
22473 (row - expected).length() < 1e-5,
22474 "the spin at {seconds}s is not orthonormal: {product:?}"
22475 );
22476 }
22477 assert!((model.determinant() - 1.0).abs() < 1e-5, "at {seconds}s");
22478 }
22479 // And it actually moves.
22480 assert_ne!(ForwardRenderer::spin(0.0), ForwardRenderer::spin(1.0));
22481 }
22482
22483 /// The swapchain import says what a swapchain image actually needs, which is
22484 /// the knowledge the hand-written barriers used to carry.
22485 #[test]
22486 fn the_present_target_starts_undefined_and_ends_presentable() {
22487 let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
22488 let image = pool.insert(0).cast();
22489 let view = pool.insert(0).cast();
22490 let imported =
22491 ForwardRenderer::present_target(image, view, Format::Bgra8UnormSrgb, (1280, 720));
22492 assert_eq!(imported.initial, ResourceState::Undefined);
22493 assert_eq!(imported.final_state, ResourceState::Present);
22494 assert_eq!(imported.extent, (1280, 720));
22495 }
22496
22497 /// The scene target is `Rgba16Float`, and the depth target is the
22498 /// reversed-Z format. Both are locked decisions and both are cheap to pin.
22499 #[test]
22500 fn the_scene_targets_are_hdr_and_reversed_z() {
22501 let color = crate::targets::scene_color((64, 48));
22502 assert_eq!(color.format, Format::Rgba16Float);
22503 assert!(color.format.is_hdr_capable());
22504 assert!(color.usage.contains(crcbl_hal::ImageUsage::SAMPLED));
22505
22506 let depth = crate::targets::scene_depth((64, 48));
22507 assert_eq!(depth.format, Format::D32Float);
22508 assert_eq!(
22509 DepthStencilState::default().depth_compare,
22510 crcbl_hal::CompareOp::Greater
22511 );
22512 }
22513
22514 /// A sun ten degrees or so above the horizon, and one further round: two
22515 /// atmospheres whose LUTs are nowhere near each other, so a comparison
22516 /// between them cannot pass by the two skies being alike.
22517 ///
22518 /// Spelled as directions rather than as angles for
22519 /// `crcbl_shaders::atmosphere`'s reason — nothing here takes a `sin` of its
22520 /// own — and normalised by `Atmosphere::parameters` on the way in.
22521 const MOVED_SUN: Atmosphere = Atmosphere {
22522 sun_direction: Vec3::new(1.0, 0.2, 0.0),
22523 ..Atmosphere::NOON
22524 };
22525
22526 /// [`MOVED_SUN`] again, further round and lower.
22527 const MOVED_AGAIN: Atmosphere = Atmosphere {
22528 sun_direction: Vec3::new(1.0, 0.05, 0.5),
22529 ..Atmosphere::NOON
22530 };
22531
22532 /// Frames the striped march takes to cross the LUT.
22533 const MARCH_FRAMES: usize = crcbl_shaders::atmosphere::SKY_VIEW_HEIGHT / SKY_VIEW_BUILD_ROWS;
22534
22535 /// The bytes the most recent sky-view LUT upload put on the device.
22536 ///
22537 /// `crate::sky_pass` writes the whole buffer at offset zero on every frame
22538 /// that has an atmosphere, into the slot that frame is using — so the last
22539 /// write to any of the ring's buffers is the LUT the frame just recorded
22540 /// would draw. That is the only place the presented LUT is observable: the
22541 /// renderer's own copy is what a test could assert about instead, and it
22542 /// would then be asserting about the thing rather than about what reached
22543 /// the device.
22544 fn presented_lut(recorder: &Recorder, luts: &[BufferHandle]) -> Vec<u8> {
22545 recorder
22546 .events()
22547 .into_iter()
22548 .rev()
22549 .find_map(|event| match event {
22550 crcbl_hal::null::Event::BufferWritten { buffer, .. } if luts.contains(&buffer) => {
22551 recorder.buffer_bytes(buffer)
22552 }
22553 _ => None,
22554 })
22555 .expect("a frame with an atmosphere uploads a sky-view LUT")
22556 }
22557
22558 /// A renderer with an atmosphere set and its first LUT marched, and the
22559 /// buffers that LUT reaches the device through.
22560 ///
22561 /// The three tests below all start here: the first march is synchronous, so
22562 /// one frame is what it takes to have a sky to be stale about.
22563 fn with_marched_atmosphere(
22564 device: &dyn Device,
22565 queue: QueueHandle,
22566 atmosphere: Atmosphere,
22567 ) -> (ForwardRenderer, Vec<BufferHandle>) {
22568 let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
22569 .expect("the null backend builds a renderer");
22570 let luts = renderer.primary.sky_pass.luts().to_vec();
22571 renderer.set_atmosphere(Some(atmosphere));
22572 atmosphere_frame(&mut renderer, device);
22573 (renderer, luts)
22574 }
22575
22576 /// One frame of the atmosphere tests: nothing is drawn, and `begin_frame`
22577 /// is what writes the blocks and steps the march.
22578 fn atmosphere_frame(renderer: &mut ForwardRenderer, device: &dyn Device) {
22579 renderer
22580 .begin_frame(
22581 device,
22582 &Camera::default(),
22583 &DirectionalLight::default(),
22584 (64, 48),
22585 )
22586 .expect("the frame's blocks are written");
22587 }
22588
22589 /// A sun that moved is marched a stripe per frame, and every frame until it
22590 /// is finished still uploads the LUT of the sun before it.
22591 ///
22592 /// **The amortisation, from the device's side.** Before this, one
22593 /// `begin_frame` marched the whole LUT, so a scene that swept its sun paid
22594 /// tens of milliseconds of CPU in every frame. The claim now is three
22595 /// things at once, and only the middle one is about performance: the march
22596 /// advances by `SKY_VIEW_BUILD_ROWS` per frame, the bytes reaching the
22597 /// device meanwhile are the *previous* sun's rather than a half-marched
22598 /// sky, and the new sun's LUT arrives whole on the frame the march ends.
22599 ///
22600 /// **And the aerial-perspective LUT keeps the same pace**: it rides the
22601 /// same stripes, so it too uploads the previous sun's air on every frame
22602 /// of the march and the new sun's on the frame that ends it — the lag
22603 /// behind a moving sun is [`MARCH_FRAMES`] for both, and the two never
22604 /// reach the device a sun apart.
22605 #[test]
22606 fn a_moving_sun_is_marched_a_stripe_per_frame() {
22607 let (recorder, device, queue) = open();
22608 let (mut renderer, luts) =
22609 with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22610 let aerials = renderer.primary.sky_pass.aerials().to_vec();
22611
22612 let before_view = SkyView::build(&Atmosphere::NOON.parameters());
22613 let after_view = SkyView::build(&MOVED_SUN.parameters());
22614 let before = before_view.rows();
22615 let after = after_view.rows();
22616 let (air_before, air_after) = (before_view.aerial().rows(), after_view.aerial().rows());
22617 assert_ne!(
22618 before, after,
22619 "the two suns march to the same LUT, so nothing below distinguishes them"
22620 );
22621 assert_ne!(
22622 air_before, air_after,
22623 "the two suns march to the same air, so nothing below distinguishes them"
22624 );
22625 assert!(
22626 renderer.sky_view_build.is_none(),
22627 "the first march is synchronous, so no build is left in flight"
22628 );
22629 assert_eq!(
22630 presented_lut(&recorder, &luts),
22631 before,
22632 "the frame after `set_atmosphere` did not upload that sun's LUT"
22633 );
22634 assert_eq!(
22635 presented_lut(&recorder, &aerials),
22636 air_before,
22637 "the frame after `set_atmosphere` did not upload that sun's air"
22638 );
22639
22640 renderer.set_atmosphere(Some(MOVED_SUN));
22641 for step in 1..MARCH_FRAMES {
22642 atmosphere_frame(&mut renderer, device.as_ref());
22643 assert_eq!(
22644 renderer
22645 .sky_view_build
22646 .as_ref()
22647 .map(SkyViewBuild::rows_done),
22648 Some(step * SKY_VIEW_BUILD_ROWS),
22649 "frame {step} of the march is not a stripe further along than frame {} was",
22650 step - 1
22651 );
22652 assert_eq!(
22653 presented_lut(&recorder, &luts),
22654 before,
22655 "frame {step} of the march uploaded something other than the sky it is still \
22656 drawing"
22657 );
22658 assert_eq!(
22659 presented_lut(&recorder, &aerials),
22660 air_before,
22661 "frame {step} of the march uploaded air other than the sky it is still drawing's"
22662 );
22663 }
22664
22665 atmosphere_frame(&mut renderer, device.as_ref());
22666 assert!(
22667 renderer.sky_view_build.is_none(),
22668 "the march did not finish in the frames its own stripe says it takes"
22669 );
22670 assert_eq!(
22671 presented_lut(&recorder, &luts),
22672 after,
22673 "the frame that finished the march did not upload the new sun's LUT"
22674 );
22675 assert_eq!(
22676 presented_lut(&recorder, &aerials),
22677 air_after,
22678 "the frame that finished the march did not upload the new sun's air"
22679 );
22680 }
22681
22682 /// An atmosphere adds the composite for its air whether or not the fog
22683 /// effect is on, and the block tells the composite which halves to read.
22684 ///
22685 /// **The seam between the two volumes, on the renderer's side.** Three
22686 /// frames of one renderer: no atmosphere and the default stack, which has
22687 /// no fog effect in it — no composite at all, the frame drawn before the
22688 /// air existed; an atmosphere and the same stack — the composite and
22689 /// nothing of the column, and a block saying so; and an atmosphere with
22690 /// the fog effect forced on — all three passes, and a block saying both.
22691 /// The counters are held to the frame on the second: the composite is a
22692 /// full-screen triangle, and a frame that drew it and did not count it
22693 /// makes the debug panel's row disagree with the frame by one.
22694 #[test]
22695 fn an_atmosphere_composites_its_air_with_or_without_the_fog_effect() {
22696 let _blurs = ssao_blur_switch();
22697 let (recorder, device, queue) = open();
22698 let device = device.as_ref();
22699 let mut renderer =
22700 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
22701 let blocks: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
22702 .map(|frame| renderer.primary.volumetric.buffers(frame).params)
22703 .collect();
22704 let imported = swapchain_image(device);
22705 let mut pool = crate::TransientPool::new();
22706 let block = |recorder: &Recorder| {
22707 let bytes: [u8; crcbl_shaders::volumetric::PARAMS_SIZE] =
22708 presented_lut(recorder, &blocks)
22709 .try_into()
22710 .expect("the block is its own size");
22711 crcbl_shaders::volumetric::VolumetricParams::from_bytes(&bytes)
22712 };
22713 let column = ["volumetric-scatter", "volumetric-integrate"];
22714
22715 let bare = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22716 let before = renderer.counters();
22717 assert!(
22718 !bare.iter().any(|pass| pass.starts_with("volumetric")),
22719 "a frame with neither fog nor an atmosphere records {bare:?}"
22720 );
22721 let off = block(&recorder);
22722 assert_eq!(
22723 off.aerial_params,
22724 [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
22725 "a frame with no atmosphere writes something into the aerial row"
22726 );
22727
22728 renderer.set_atmosphere(Some(Atmosphere::NOON));
22729 let air = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22730 assert!(
22731 air.iter().any(|pass| pass == "volumetric-composite")
22732 && !air.iter().any(|pass| column.contains(&pass.as_str())),
22733 "an atmosphere with the fog effect off records {air:?}, where it should composite its \
22734 air and run nothing of the column"
22735 );
22736 let after = renderer.counters();
22737 assert_eq!(
22738 after.draws - before.draws,
22739 (SkyPass::PASSES + u64::from(Volumetric::COMPOSITE_PASSES)) * FULLSCREEN_DRAWS,
22740 "the atmosphere's two full-screen passes — the sky and the air — are not both counted"
22741 );
22742 let aerial_only = block(&recorder);
22743 let sun = Atmosphere::NOON.parameters().sun_direction;
22744 assert_eq!(
22745 aerial_only.aerial_params,
22746 [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON],
22747 "the aerial row does not carry the atmosphere's sun and its switch"
22748 );
22749 assert_eq!(
22750 aerial_only.fog_params[3],
22751 crcbl_shaders::volumetric::LOCAL_COLUMN_OFF,
22752 "the block tells the composite to read a column no pass filled"
22753 );
22754
22755 renderer.set_effect_request(EffectRequest {
22756 programmatic: EffectOverride::none().force(RenderEffects::VOLUMETRIC_FOG, Some(true)),
22757 ..EffectRequest::default()
22758 });
22759 let both = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22760 assert!(
22761 column
22762 .iter()
22763 .chain(&["volumetric-composite"])
22764 .all(|name| both.iter().any(|pass| pass == name)),
22765 "an atmosphere with the fog effect on records {both:?}"
22766 );
22767 assert_eq!(
22768 block(&recorder).fog_params[3],
22769 crcbl_shaders::volumetric::LOCAL_COLUMN_ON,
22770 "the block tells the composite to skip a column the frame filled"
22771 );
22772
22773 renderer.destroy(device);
22774 pool.destroy(device);
22775 device.destroy_image_view(imported.view);
22776 device.destroy_image(imported.image);
22777 recorder.assert_valid();
22778 }
22779
22780 /// A sun that moves while a march is in flight restarts it from row zero.
22781 ///
22782 /// **The decision `refresh_sky_view` writes down**, and the reason a sun
22783 /// that moves every frame shows a frozen sky rather than a stuttering one:
22784 /// finishing a march for a sun that has already moved would swap in a LUT
22785 /// that is wrong on arrival. What is observable is the progress counter —
22786 /// a build that kept its rows would be two stripes along here rather than
22787 /// one — and the sun the build in flight names.
22788 #[test]
22789 fn a_sun_that_moves_mid_march_restarts_it() {
22790 let (recorder, device, queue) = open();
22791 let (mut renderer, luts) =
22792 with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22793 let before = SkyView::build(&Atmosphere::NOON.parameters()).rows();
22794
22795 renderer.set_atmosphere(Some(MOVED_SUN));
22796 atmosphere_frame(&mut renderer, device.as_ref());
22797 atmosphere_frame(&mut renderer, device.as_ref());
22798 assert_eq!(
22799 renderer
22800 .sky_view_build
22801 .as_ref()
22802 .map(SkyViewBuild::rows_done),
22803 Some(2 * SKY_VIEW_BUILD_ROWS),
22804 "two frames of marching did not leave two stripes marched"
22805 );
22806
22807 renderer.set_atmosphere(Some(MOVED_AGAIN));
22808 atmosphere_frame(&mut renderer, device.as_ref());
22809 assert_eq!(
22810 renderer
22811 .sky_view_build
22812 .as_ref()
22813 .map(SkyViewBuild::rows_done),
22814 Some(SKY_VIEW_BUILD_ROWS),
22815 "the march kept the rows it had marched for a sun that has since moved"
22816 );
22817 assert_eq!(
22818 renderer
22819 .sky_view_build
22820 .as_ref()
22821 .map(SkyViewBuild::atmosphere),
22822 Some(MOVED_AGAIN.parameters()),
22823 "the build in flight is marching a sun the caller has moved away from"
22824 );
22825 assert_eq!(
22826 presented_lut(&recorder, &luts),
22827 before,
22828 "a restart uploaded something other than the last LUT that finished"
22829 );
22830 }
22831
22832 /// A frame whose sun has not moved marches nothing and re-takes neither
22833 /// projection.
22834 ///
22835 /// **What `PresentedSky` is for.** `gradient_fit` and `irradiance` used to
22836 /// be taken from the LUT in every `begin_frame`, which is host work a still
22837 /// sun has no reason to pay. Both are now taken once, where the march
22838 /// finishes — so a sentinel written over the cached gradient survives a
22839 /// frame if and only if that frame took neither the march nor the
22840 /// projection again, and the same sentinel's bytes turn up in what the
22841 /// frame wrote, which is what says the cache is the thing being read.
22842 #[test]
22843 fn a_still_sun_marches_nothing_and_reprojects_nothing() {
22844 let (recorder, device, queue) = open();
22845 let (mut renderer, _luts) =
22846 with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22847
22848 let sentinel = crcbl_shaders::sky::SkyGradient {
22849 zenith: [0.125, 0.25, 0.375],
22850 horizon: [0.5, 0.625, 0.75],
22851 ground: [0.875, 1.125, 1.375],
22852 };
22853 let presented = renderer
22854 .sky_view
22855 .as_mut()
22856 .expect("the first frame marched a LUT");
22857 assert_ne!(
22858 presented.gradient, sentinel,
22859 "the sentinel is what the real projection already returns, so it proves nothing"
22860 );
22861 presented.gradient = sentinel;
22862
22863 let before = recorder.events().len();
22864 atmosphere_frame(&mut renderer, device.as_ref());
22865 assert_eq!(
22866 renderer
22867 .sky_view
22868 .as_ref()
22869 .map(|presented| presented.gradient),
22870 Some(sentinel),
22871 "a frame under a sun that has not moved re-took the projections"
22872 );
22873 assert!(
22874 renderer.sky_view_build.is_none(),
22875 "a frame under a sun that has not moved started a march"
22876 );
22877
22878 let wanted: Vec<u8> = sentinel
22879 .rows()
22880 .iter()
22881 .flatten()
22882 .flat_map(|value| value.to_le_bytes())
22883 .collect();
22884 let used = recorder
22885 .events()
22886 .into_iter()
22887 .skip(before)
22888 .filter_map(|event| match event {
22889 crcbl_hal::null::Event::BufferWritten { buffer, .. } => {
22890 recorder.buffer_bytes(buffer)
22891 }
22892 _ => None,
22893 })
22894 .any(|bytes| {
22895 bytes
22896 .windows(wanted.len())
22897 .any(|window| window == wanted.as_slice())
22898 });
22899 assert!(
22900 used,
22901 "the cached gradient reached no block this frame wrote, so the frame is not reading \
22902 the cache at all"
22903 );
22904 }
22905
22906 /// **The frame block's ambient rows carry the marched LUT's own L1
22907 /// projection**, and not the three-band fit's.
22908 ///
22909 /// `begin_frame` writes [`PresentedSky::irradiance`] into
22910 /// [`FrameUniforms::sky_sh_r`] and the two rows beside it, and until this
22911 /// test nothing read them back. The only reader of those rows is arithmetic
22912 /// in `mesh.slang`'s fragment stage, and no frame in the tree draws a
22913 /// surface under an atmosphere — `crcbl`'s
22914 /// `an_atmosphere_frame_is_the_host_lut` puts no geometry in its scene at
22915 /// all — so `PresentedSky::new` handed `view.gradient_fit().irradiance()`
22916 /// instead, the three-band fit's projection rather than the LUT's, was a
22917 /// swap `docs/backlog.md` recorded passing every suite in the tree on
22918 /// 2026-09-06.
22919 ///
22920 /// **Both halves are needed and the second is the sabotage's.** The rows
22921 /// equalling the LUT's projection is the wiring; the rows *differing* from
22922 /// the fit's is what makes the equality a claim about which projection
22923 /// arrived rather than about two numbers that happen to agree. The
22924 /// `assert_ne` above them is the anti-vacuity: a sun for which the two
22925 /// projections coincide would make this test pass under the swap.
22926 ///
22927 /// [`FrameUniforms::sky_sh_r`]: crcbl_shaders::mesh::FrameUniforms::sky_sh_r
22928 #[test]
22929 fn an_atmosphere_writes_the_luts_own_ambient_term() {
22930 /// The three rows, as the little-endian bytes `FrameUniforms::to_bytes`
22931 /// puts in the block.
22932 fn rows(probe: &crcbl_shaders::probe::GpuProbe) -> Vec<u8> {
22933 [probe.sh_r, probe.sh_g, probe.sh_b]
22934 .iter()
22935 .flatten()
22936 .flat_map(|value| value.to_le_bytes())
22937 .collect()
22938 }
22939
22940 let (recorder, device, queue) = open();
22941 let (renderer, _luts) = with_marched_atmosphere(device.as_ref(), queue, MOVED_SUN);
22942
22943 let view = SkyView::build(&MOVED_SUN.parameters());
22944 let marched = rows(&view.irradiance());
22945 let fitted = rows(&view.gradient_fit().irradiance());
22946 assert_ne!(
22947 marched, fitted,
22948 "this sun's LUT and its three-band fit project to the same rows, so a block \
22949 carrying either would satisfy the check below and the swap it exists for would \
22950 pass"
22951 );
22952
22953 let block = recorder
22954 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
22955 .expect("a frame with an atmosphere writes its uniform block");
22956 let at = mesh::SKY_SH_R_OFFSET;
22957 assert_eq!(
22958 &block[at..at + marched.len()],
22959 marched.as_slice(),
22960 "the frame block's sky rows are not `SkyView::irradiance` of the LUT this frame \
22961 marched, so the ambient term the fragment stage evaluates comes from somewhere \
22962 else"
22963 );
22964 assert_ne!(
22965 &block[at..at + fitted.len()],
22966 fitted.as_slice(),
22967 "the frame block's sky rows are the gradient fit's projection — the LUT was \
22968 marched and then thrown away for the three-band approximation of it"
22969 );
22970
22971 renderer.destroy(device.as_ref());
22972 }
22973}