Skip to main content

crcbl_render/forward/
view.rs

1//! One camera's share of the forward frame.
2//!
3//! [`ForwardRenderer`] owns two kinds of state, and this module is the line
4//! between them. The **scene** is what every camera draws: the geometry and
5//! instance pools, the materials and their pages, the probes, the shadow atlas
6//! and everything that decides what it holds. A **view** is what one camera
7//! needs to turn that scene into a picture: its own cull and the survivor lists
8//! it writes, its frame block, its light clustering, its bind groups and the
9//! ring of per-frame blocks every screen-space pass keeps.
10//!
11//! # Why the line is here
12//!
13//! Everything on this side is either sized by what one camera sees or carries
14//! one camera's history from a frame to the next. Topic 25's
15//! hysteresis lives in [`DrawGen::group_state`], so two cameras sharing one
16//! generator would each undo the other's cut. Auto-exposure reads the previous
17//! slot's measurement, and [`View::previous_view_projection`] is where the
18//! motion vectors come from. Every one of those is wrong the moment a second
19//! camera writes it.
20//!
21//! Nothing on the other side is. An instance is where it is whoever looks at
22//! it, and the shadow atlas is drawn once for the frame.
23
24use super::*;
25use crate::draw_gen::OcclusionFrame;
26
27/// How many views one [`ForwardRenderer`] draws at most, the camera
28/// [`ForwardRenderer::begin_frame`] opens included.
29///
30/// The width of
31/// [`GpuInstance::HIDDEN_VIEWS_MASK`](crcbl_shaders::mesh::GpuInstance::HIDDEN_VIEWS_MASK),
32/// which is where a view's bit lives: an instance record has one bit per view
33/// to say it is hidden there, and a ninth view would have no bit to cull on.
34pub const MAX_VIEWS: usize = 8;
35
36/// Names one camera a [`ForwardRenderer`] draws.
37///
38/// [`ViewId::PRIMARY`] is the camera [`ForwardRenderer::begin_frame`] opens and
39/// always exists. Every other id comes from [`ForwardRenderer::create_view`]
40/// and stays valid until [`ForwardRenderer::destroy_view`] hands it back, after
41/// which the renderer may give the same id to the next view it creates.
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub struct ViewId(u8);
44
45impl ViewId {
46    /// The camera [`ForwardRenderer::begin_frame`] opens, and the one
47    /// [`ForwardRenderer::add_passes`] draws into the caller's target.
48    pub const PRIMARY: Self = Self(0);
49
50    /// This view's index: `0` for [`ViewId::PRIMARY`], and below [`MAX_VIEWS`]
51    /// for every other.
52    #[must_use]
53    pub const fn index(self) -> usize {
54        self.0 as usize
55    }
56
57    /// The bit of [`GpuInstance::flags`](crcbl_shaders::mesh::GpuInstance::flags)
58    /// that hides an instance from this view.
59    pub(super) const fn hidden_bit(self) -> u32 {
60        1 << (mesh::GpuInstance::HIDDEN_VIEWS_SHIFT + self.0 as u32)
61    }
62}
63
64/// The views an instance is drawn in — see
65/// [`ForwardRenderer::set_instance_views`].
66///
67/// A set of [`ViewId`]s, one bit each. [`ViewMask::ALL`] is what every instance
68/// starts with, so a caller that never names a view draws everything in every
69/// view.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
71pub struct ViewMask(u8);
72
73impl ViewMask {
74    /// Every view, including the ones not created yet.
75    pub const ALL: Self = Self(u8::MAX);
76    /// No view at all: the instance stays resident, and every camera's cull
77    /// rejects it before it tests a bound.
78    pub const NONE: Self = Self(0);
79
80    /// `view` alone.
81    #[must_use]
82    pub const fn only(view: ViewId) -> Self {
83        Self(1 << view.0)
84    }
85
86    /// This set with `view` added.
87    #[must_use]
88    pub const fn with(self, view: ViewId) -> Self {
89        Self(self.0 | (1 << view.0))
90    }
91
92    /// This set with `view` taken out.
93    #[must_use]
94    pub const fn without(self, view: ViewId) -> Self {
95        Self(self.0 & !(1 << view.0))
96    }
97
98    /// Whether `view` draws an instance carrying this set.
99    #[must_use]
100    pub const fn contains(self, view: ViewId) -> bool {
101        self.0 & (1 << view.0) != 0
102    }
103
104    /// The hidden-views bits an instance record carries for this set — its
105    /// complement, so [`ViewMask::ALL`] is the all-zero field every record
106    /// starts with.
107    pub(super) const fn hidden_bits(self) -> u32 {
108        ((!self.0) as u32) << mesh::GpuInstance::HIDDEN_VIEWS_SHIFT
109    }
110
111    /// The set an instance record's hidden-views bits describe.
112    pub(super) const fn from_flags(flags: u32) -> Self {
113        let hidden =
114            (flags & mesh::GpuInstance::HIDDEN_VIEWS_MASK) >> mesh::GpuInstance::HIDDEN_VIEWS_SHIFT;
115        Self(!(hidden as u8))
116    }
117}
118
119/// What a [`ViewBackground::Transparent`] view's scene colour is cleared to.
120const TRANSPARENT_CLEAR: [f32; 4] = [0.0; 4];
121
122/// What [`ForwardRenderer::create_view`] builds.
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct ViewDesc {
125    /// The effects this view may draw — intersected, every frame, with what the
126    /// frame resolved (see [`ForwardRenderer::resolved_effects`]), so a view
127    /// can ask for less than the frame draws and never for more.
128    ///
129    /// [`RenderEffects::SHADOWS`] is not a view's to take away and is ignored
130    /// here: the atlas is drawn once for the frame, and every view samples it
131    /// whenever the frame drew it. A [`ViewLighting::Fixed`] view also never
132    /// draws [`ViewLighting::SCENE_EFFECTS`], whatever this asks for.
133    pub effects: RenderEffects,
134    /// What the view's picture holds where no geometry is — see
135    /// [`ViewBackground`].
136    pub background: ViewBackground,
137    /// What lights the view's surfaces — see [`ViewLighting`].
138    pub lighting: ViewLighting,
139}
140
141impl Default for ViewDesc {
142    /// Every effect the frame draws, over the frame's own background, lit by
143    /// the frame's own light.
144    fn default() -> Self {
145        Self {
146            effects: RenderEffects::all(),
147            background: ViewBackground::Scene,
148            lighting: ViewLighting::Scene,
149        }
150    }
151}
152
153impl ViewDesc {
154    /// A [`ViewBackground::Transparent`] view with every effect the frame draws
155    /// except the ones such a view cannot take, and auto-exposure.
156    ///
157    /// The two antialiasing tiers are what
158    /// [`ForwardRenderer::create_view`] refuses on a transparent view.
159    /// [`RenderEffects::AUTO_EXPOSURE`] it would accept, and it is left out
160    /// because the meter reads the whole target: the transparent background is
161    /// metered as black, so a model filling a quarter of the picture would be
162    /// exposed differently from the same model filling half of it. The view
163    /// takes the caller's exposure instead — see
164    /// [`ForwardRenderer::set_exposure`].
165    #[must_use]
166    pub const fn transparent() -> Self {
167        Self {
168            effects: RenderEffects::all().difference(
169                ViewBackground::REFUSED_ON_TRANSPARENT.union(RenderEffects::AUTO_EXPOSURE),
170            ),
171            background: ViewBackground::Transparent,
172            lighting: ViewLighting::Scene,
173        }
174    }
175}
176
177/// What lights a view's surfaces — see [`ViewDesc::lighting`].
178#[derive(Clone, Copy, Debug, Default, PartialEq)]
179pub enum ViewLighting {
180    /// The frame's own light: the sun and every light row
181    /// [`ForwardRenderer::set_lights`] handed over, the sky's irradiance, the
182    /// irradiance probes, the reflections and the fog. What the primary camera
183    /// is lit by, and what every view was lit by before this choice existed.
184    #[default]
185    Scene,
186    /// One constant light, whatever the frame is lit by: the key's direction
187    /// and colour as the only direct light, its
188    /// [`ambient`](DirectionalLight::ambient) as the only diffuse indirect one,
189    /// and `environment` as the only thing a reflection sees.
190    ///
191    /// For a picture that must not change with the world around it, such as a
192    /// model rendered into an inventory icon: the same model under the same
193    /// fixed light draws the same pixels in a sunlit level and a dark one.
194    ///
195    /// # What it ignores
196    ///
197    /// * **The frame's sun and every light row** — a point, spot or rectangle
198    ///   light near the view's camera included. The key light is the view's
199    ///   one row, which is a choice rather than a limit: an icon's model is
200    ///   placed away from the world, so a local light that did reach it would
201    ///   be lighting it by accident.
202    /// * **Every shadow.** The key light is not occluded — not by the frame's
203    ///   cascades, which were fitted to the primary camera and cover whatever
204    ///   happens to be there, and not by contact shadows. The view's frame
205    ///   block names no shadow map: every atlas rectangle in it is empty, which
206    ///   the shaders read as a map never rendered and answer lit. The frame's
207    ///   atlas is still drawn and the view's instances may still cast into it;
208    ///   see [`ForwardRenderer::set_instance_casts_shadow`].
209    /// * **The sky and the irradiance probes**: the view's frame block carries
210    ///   no sky rows and an empty probe header, and the view binds a probe
211    ///   table of one zeroed row in place of the scene's — to the forward pass,
212    ///   the reflection march and the water surface alike — so the diffuse
213    ///   ambient is the fill alone and a reflection that finds no geometry
214    ///   sees `environment` alone.
215    /// * **The air**: [`Self::SCENE_EFFECTS`] are dropped from the view's
216    ///   effects whatever [`ViewDesc::effects`] asked for, and the height fog
217    ///   is [`Fog::NONE`].
218    ///
219    /// What it keeps is everything the view's own geometry decides: its
220    /// materials and emission, its ambient occlusion, its reflections of
221    /// itself, and every effect after the forward pass. The background is
222    /// [`ViewDesc::background`]'s, so a view asking for
223    /// [`ViewBackground::Scene`] still draws the frame's sky behind a model it
224    /// does not light.
225    Fixed {
226        /// The one direct light, and in its
227        /// [`ambient`](DirectionalLight::ambient) the diffuse fill.
228        key: DirectionalLight,
229        /// The radiance a reflection sees in every direction — a uniform
230        /// environment, in linear RGB, that **may exceed 1.0** like the key's
231        /// colour. It is what gives a dark glossy surface its sheen: a
232        /// near-black dielectric scatters almost none of the key and the fill,
233        /// and still reflects this at its `F0`, rising towards grazing angles
234        /// by the split-sum Fresnel term — so what the camera sees edge-on
235        /// reads brighter than what faces it. A metal reflects it tinted by
236        /// its base colour.
237        ///
238        /// **Specular only.** A uniform environment of radiance `L` would also
239        /// reach a diffuse surface, as `π·L` — what [`Self::Scene`] adds for
240        /// a uniform [`crate::Sky`] of that radiance — but here that half
241        /// is the key's `ambient` and nothing else, so the two are never
242        /// summed and the fill means what it meant before this field existed.
243        /// A caller who wants the pair to describe one physical environment
244        /// sets `ambient` to `π` times this.
245        ///
246        /// It reaches a surface through the reflection pass, so it needs
247        /// [`RenderEffects::REFLECTIONS`] in both the frame's effects and
248        /// [`ViewDesc::effects`]; a view drawn without it reflects nothing.
249        /// Zero is a view whose reflections find nothing but its own geometry.
250        environment: Vec3,
251    },
252}
253
254impl ViewLighting {
255    /// The effects a [`ViewLighting::Fixed`] view never draws, because each
256    /// brings the frame's light into it: the froxel volume is lit by the sun
257    /// and the scene's lights, and the contact march shadows along the frame's
258    /// sun.
259    ///
260    /// Reflections are not among them. The march's fallback is the probe table
261    /// and the sky rows, and a fixed view hands it its own — the zeroed row and
262    /// a sky of `environment` in every direction — so what it reflects is the
263    /// view's own geometry and the fixed environment.
264    pub const SCENE_EFFECTS: RenderEffects =
265        RenderEffects::VOLUMETRIC_FOG.union(RenderEffects::CONTACT_SHADOWS);
266
267    /// The effects this lighting takes out of a view's frame.
268    pub(super) const fn dropped_effects(self) -> RenderEffects {
269        match self {
270            Self::Scene => RenderEffects::empty(),
271            Self::Fixed { .. } => Self::SCENE_EFFECTS,
272        }
273    }
274}
275
276/// What a view's picture holds where no geometry covers a pixel — see
277/// [`ViewDesc::background`].
278#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
279pub enum ViewBackground {
280    /// The frame's own background: the sky where one is set, [`SCENE_CLEAR`]
281    /// where none is, and an alpha of one at every pixel. What the primary
282    /// camera draws, and what every view drew before this choice existed.
283    #[default]
284    Scene,
285    /// Nothing: the view clears to transparent black, draws no sky, and its
286    /// target's alpha is the frame's **coverage** — one where geometry was
287    /// drawn and zero where it was not.
288    ///
289    /// For a picture composited over something else, such as a model rendered
290    /// into an icon. The colour is **straight**, not premultiplied, which is
291    /// what [`SpriteRenderer`](crate::SpriteRenderer) blends: a covered pixel
292    /// holds the colour an opaque view would have drawn there, and a
293    /// transparent one holds whatever light the air in front of the far plane
294    /// scattered — zero on a frame without volumetric fog — which a
295    /// straight-alpha blend weighs by zero.
296    ///
297    /// # What keeps the alpha, and what cannot
298    ///
299    /// The forward pass, grass and water write coverage; the volumetric
300    /// composite, the reflection composite and the bloom composite carry the
301    /// alpha they read; the tonemap writes it into the target. **The two
302    /// antialiasing tiers cannot**: each blends a pixel's colour with its
303    /// neighbours' across exactly the edges the coverage has, so an edge
304    /// pixel would come out mixed with the transparent black beside it — a
305    /// premultiplied colour under a straight-alpha consumer, which is a dark
306    /// fringe. [`ForwardRenderer::create_view`] refuses a transparent view
307    /// whose [`ViewDesc::effects`] name either of them, and
308    /// [`ViewDesc::transparent`] is a description it accepts.
309    ///
310    /// [`render_scale`](ForwardRenderer::render_scale)'s upscale filters on
311    /// the same terms and so **does not apply**: a transparent view is drawn at
312    /// its target's own extent whatever the scale is.
313    ///
314    /// Bloom and auto-exposure keep the alpha and change the colour. Bloom's
315    /// glow past a silhouette lands on pixels the coverage says are empty and
316    /// is dropped with them; auto-exposure meters the background as black —
317    /// see [`ViewDesc::transparent`].
318    Transparent,
319}
320
321impl ViewBackground {
322    /// The effects a [`ViewBackground::Transparent`] view is refused with —
323    /// see that variant.
324    pub const REFUSED_ON_TRANSPARENT: RenderEffects =
325        RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2);
326
327    /// Whether this background leaves the target's alpha as coverage.
328    pub(super) const fn is_transparent(self) -> bool {
329        matches!(self, Self::Transparent)
330    }
331}
332
333/// What one call to [`ForwardRenderer::add_passes_with_views`] draws into.
334#[derive(Clone, Copy, Debug)]
335pub struct FrameTargets<'v> {
336    /// The primary camera's target, imported into the graph the call records
337    /// into.
338    pub target: ImageId,
339    /// That target's extent.
340    pub extent: (u32, u32),
341    /// The skinning plan whose dispatch the frame records, or `None` for a
342    /// frame that skins nothing — see
343    /// [`ForwardRenderer::add_skinned_passes`].
344    pub skinning: Option<&'v Skinning>,
345    /// Every secondary view the frame draws, each into its own target.
346    pub views: &'v [ViewTarget],
347}
348
349impl<'v> FrameTargets<'v> {
350    /// The primary camera alone, into `target`.
351    #[must_use]
352    pub const fn primary(
353        target: ImageId,
354        extent: (u32, u32),
355        skinning: Option<&'v Skinning>,
356    ) -> Self {
357        Self {
358            target,
359            extent,
360            skinning,
361            views: &[],
362        }
363    }
364}
365
366/// Where one secondary view's frame goes — see
367/// [`ForwardRenderer::add_passes_with_views`].
368#[derive(Clone, Copy, Debug, PartialEq, Eq)]
369pub struct ViewTarget {
370    /// The view to draw. Never [`ViewId::PRIMARY`], whose target is the one the
371    /// call itself takes.
372    pub view: ViewId,
373    /// The image the view's frame ends in, imported into the same graph.
374    pub target: ImageId,
375    /// That image's extent, which the view's internal frame is sized from
376    /// exactly as the primary's is sized from its own.
377    pub extent: (u32, u32),
378}
379
380/// Everything [`View::build`] reads out of the scene it draws.
381///
382/// Handles and borrowed tables, and nothing a view owns: each is created and
383/// destroyed by [`ForwardRenderer`], which outlives every view built against
384/// it.
385pub(super) struct ViewInputs<'a> {
386    /// Which view this is, whose bit its cull rejects instances on.
387    pub(super) id: ViewId,
388    /// The effects it may draw — see [`ViewDesc::effects`].
389    pub(super) effects: RenderEffects,
390    /// What it draws where no geometry is — see [`ViewDesc::background`].
391    pub(super) background: ViewBackground,
392    /// What lights it — see [`ViewDesc::lighting`].
393    pub(super) lighting: ViewLighting,
394    /// The format the caller's target has, which the resolves and the upscale
395    /// write.
396    pub(super) target_format: Format,
397    /// Which call the forward pass records.
398    pub(super) emit: EmitTail,
399    /// The instance ring, one buffer per frame in flight.
400    pub(super) instances: &'a [BufferHandle],
401    /// The mesh table's buffer.
402    pub(super) mesh_table: BufferHandle,
403    /// The bucket and level tables every generator of the scene is built from
404    /// — see [`DrawGenDesc`].
405    pub(super) bucket_meshes: &'a [u32],
406    pub(super) bucket_modes: &'a [u32],
407    pub(super) bucket_clusters: &'a [u32],
408    pub(super) bucket_cluster_bases: &'a [u32],
409    pub(super) mesh_levels: &'a [level_select::MeshLevels],
410    pub(super) level_groups: &'a [level_select::LevelGroup],
411    pub(super) level_meshes: &'a [u32],
412    /// [`SceneDesc::capacities`]' instance and light counts.
413    pub(super) instance_capacity: u32,
414    pub(super) light_capacity: u32,
415    /// §3.5's clusters, on the mesh path only.
416    pub(super) clusters: Option<&'a ClusterPool>,
417    /// [`DrawGenDesc::task_lanes`] for this view's generator: the task chunk
418    /// where the mesh tail runs behind the amplification stage, zero
419    /// everywhere else.
420    pub(super) task_lanes: u32,
421    /// The mesh layout every group below is built against.
422    pub(super) mesh_layout: BindGroupLayoutHandle,
423    /// The scene's half of every group — see [`SharedBindings`]. The pages
424    /// and their sampler are per slot, because [`ForwardRenderer::adopt_pages`]
425    /// moves each slot to new ones on that slot's own frame.
426    pub(super) vertices: BufferHandle,
427    pub(super) draw_constants: BufferHandle,
428    pub(super) materials: BufferHandle,
429    pub(super) pages: &'a [PageBindings],
430    pub(super) probes: &'a [BufferHandle],
431    pub(super) specular_dfg: ImageViewHandle,
432    pub(super) ltc_table: ImageViewHandle,
433    /// The shadow atlas and the sampler that compares against it.
434    pub(super) shadow_map: ImageViewHandle,
435    pub(super) shadow_sampler: SamplerHandle,
436    /// The stand-ins a group names until the forward pass rebuilds it against
437    /// the frame's own images.
438    pub(super) ambient_occlusion: ImageViewHandle,
439    pub(super) contact_shadow: ImageViewHandle,
440    pub(super) probe_visibility: ImageViewHandle,
441}
442
443/// What the frame [`View::begin_frame`] opens already knows, handed to every
444/// view it begins.
445///
446/// Copies and borrows of the renderer's own fields, assembled once per view by
447/// [`ForwardRenderer`] so a view's blocks are written from exactly the numbers
448/// the primary camera's were.
449pub(super) struct ViewFrame<'a> {
450    /// The frame-in-flight slot every block is written into.
451    pub(super) slot: usize,
452    /// [`ForwardRenderer::frame_serial`] for the frame being opened.
453    pub(super) serial: u64,
454    /// The target's aspect, and the internal extent the frame is drawn at.
455    pub(super) aspect: f32,
456    pub(super) extent: (u32, u32),
457    /// The frame's resolved effects, before this view's own mask.
458    pub(super) effects: RenderEffects,
459    /// Every element the instance pool has handed out — see
460    /// [`InstancePool::slot_count`].
461    pub(super) instance_count: u32,
462    /// The eye detail is selected from.
463    pub(super) selection_eye: Vec3,
464    pub(super) lod_error_budget: f32,
465    pub(super) lod_hold_ratio: f32,
466    /// The sun, the light rows and the shadow matrices the frame fitted.
467    pub(super) scene: &'a FrameScene,
468    /// What the frame's grass field holds, for the generation block this view
469    /// writes — see [`crate::grass`].
470    pub(super) grass: Option<crate::grass::GrassFrame>,
471    /// The wind's block, as the renderer was last handed it.
472    pub(super) wind: crcbl_shaders::wind::WindParams,
473    pub(super) fog: Fog,
474    pub(super) probe_volume: crcbl_shaders::probe::ProbeVolume,
475    pub(super) attribute_base: u32,
476    /// The frame's sky, resolved once — see `ForwardRenderer::refresh_sky_view`.
477    pub(super) gradient: crcbl_shaders::sky::SkyGradient,
478    pub(super) sky_irradiance: crcbl_shaders::probe::GpuProbe,
479    pub(super) debug_view_lane: f32,
480    pub(super) exposure: f32,
481    pub(super) exposure_adaptation: Option<ExposureAdaptation>,
482    pub(super) tonemap_curve: tonemap::TonemapCurve,
483    /// The occlusion and small-feature culls this frame asks for — see
484    /// [`ForwardRenderer::occlusion_culling`], resolved against the frame.
485    pub(super) occlusion: OcclusionCulling,
486}
487
488/// Where [`View::add_passes`] ends a view's frame, and the two extents it is
489/// drawn between.
490#[derive(Clone, Copy, Debug)]
491pub(super) struct ViewOutput {
492    /// The image the frame ends in.
493    pub(super) target: ImageId,
494    /// That image's extent.
495    pub(super) target_extent: (u32, u32),
496    /// The internal extent the frame is drawn at — see
497    /// [`ForwardRenderer::frame_extents`].
498    pub(super) extent: (u32, u32),
499}
500
501/// What [`View::add_cull`] recorded, for [`View::add_passes`] to draw from.
502#[derive(Clone, Debug)]
503pub(super) struct ViewCull {
504    /// The cull and draw-argument pair's outputs.
505    pub(super) generated: GeneratedDraws,
506    /// The view's record of the cut, on the mesh path.
507    pub(super) selection: Option<BufferId>,
508    /// The froxel grid the clustering pass filled.
509    pub(super) light_grid: BufferId,
510    /// The farthest-depth pyramid a two-phase occlusion frame reads and
511    /// rewrites, or `None` for a frame that culls in one phase.
512    pub(super) pyramid: Option<ViewPyramid>,
513    /// Instances the cull tested, which the second phase tests again.
514    pub(super) instance_count: u32,
515}
516
517/// [`ViewCull::pyramid`]: the pyramid's levels as this frame's graph knows them,
518/// and the cull's group naming them.
519#[derive(Clone, Debug)]
520pub(super) struct ViewPyramid {
521    pub(super) levels: Vec<ImageId>,
522    pub(super) group: BindGroupHandle,
523}
524
525/// The tonemap's pipeline and what its group names besides the frame.
526#[derive(Clone, Copy, Debug)]
527pub(super) struct TonemapPipeline {
528    pub(super) sampler: SamplerHandle,
529    pub(super) layout: BindGroupLayoutHandle,
530    pub(super) pipeline_layout: PipelineLayoutHandle,
531    pub(super) pipeline: GraphicsPipelineHandle,
532}
533
534/// What the frame's scene passes left in the graph, and the scene's own
535/// handles, for every view's [`View::add_passes`] to read.
536pub(super) struct FramePasses {
537    /// The frame-in-flight slot.
538    pub(super) slot: usize,
539    pub(super) emit: EmitTail,
540    pub(super) target_format: Format,
541    /// How many occlusion blurs this frame runs — see
542    /// `ForwardRenderer::frame_ssao_blurs`.
543    pub(super) ssao_blurs: u32,
544    /// Whether the background pass draws.
545    pub(super) draws_sky: bool,
546    /// What the frame's water draws, or `None` for a frame with none — see
547    /// [`crate::water`].
548    pub(super) water: Option<WaterFrame>,
549    /// What the frame's grass field holds, or `None` for a frame with none —
550    /// see [`crate::grass`].
551    pub(super) grass: Option<crate::grass::GrassFrame>,
552    /// The skinning dispatch's vertex pool, when the frame skins.
553    pub(super) skinned: Option<BufferId>,
554    /// This frame's slot of the probe ring, as a handle and as the graph's id.
555    pub(super) probe_buffer: BufferHandle,
556    pub(super) probe_table: BufferId,
557    /// The two 1×1 stand-ins a group names when an effect is off.
558    pub(super) occlusion_placeholder: ImageId,
559    pub(super) contact_placeholder: ImageId,
560    /// The material pages, imported once for the frame.
561    pub(super) pages: MaterialPages,
562    /// The atlas the shadow pass drew, or its import where it was cached.
563    pub(super) shadow_atlas: ImageId,
564    /// The probe-visibility maps, or their placeholder.
565    pub(super) probe_visibility: ImageViewHandle,
566    pub(super) mesh_layout: BindGroupLayoutHandle,
567    /// The wireframe twin pair, where a caller switched the view on.
568    pub(super) wireframe: Option<SidedPipelines>,
569    /// The two passes' call lists, split by pipeline — see
570    /// `ForwardRenderer::depth_partitions` and `ForwardRenderer::sided_partitions`.
571    /// The same for every view: a bucket's offsets are a function of the bucket
572    /// alone.
573    pub(super) prepass_partitions: Vec<BucketDraws>,
574    pub(super) color_partitions: Vec<BucketDraws>,
575    pub(super) tonemap: TonemapPipeline,
576}
577
578/// What both depth prepasses declare and do not write, as the graph knows it —
579/// see [`declare_prepass_reads`].
580#[derive(Clone, Copy, Debug)]
581struct PrepassReads {
582    shadow_atlas: ImageId,
583    occlusion_placeholder: ImageId,
584    pages: MaterialPages,
585    probe_table: BufferId,
586    skinned: Option<BufferId>,
587    selection: Option<BufferId>,
588    prepass_stats: BufferId,
589}
590
591/// Declares everything a depth prepass binds — the early one and, with the
592/// occlusion cull on, the late one, which bind the same group and draw from the
593/// same generator.
594/// [`DrawGenDesc::task_lanes`] for a renderer whose mesh pipeline does or does
595/// not carry the amplification stage — see
596/// [`ForwardRenderer::culls_clusters`]. Every generator of one renderer takes
597/// the same answer, because every pass draws through the same pipeline kind.
598pub(super) fn task_lanes(culls_clusters: bool) -> u32 {
599    if culls_clusters {
600        crcbl_shaders::meshlet::TASK_LANES
601    } else {
602        0
603    }
604}
605
606fn declare_prepass_reads<'g, 'a>(
607    pass: PassBuilder<'g, 'a>,
608    reads: &PrepassReads,
609    generated: &GeneratedDraws,
610    emit: EmitTail,
611) -> PassBuilder<'g, 'a> {
612    let pass = pass
613        // Both are in this pass's bind group and neither is sampled by
614        // either depth-only pipeline — but a bound descriptor whose image is
615        // in the wrong layout is what
616        // `VUID-vkCmdDrawIndexedIndirectCount-imageLayout-00344` names, and
617        // the other backends read whatever the last writer left behind.
618        .read_image(reads.shadow_atlas)
619        .read_image(reads.occlusion_placeholder)
620        // And the page, which the **cutout** pipeline does sample: the alpha
621        // it cuts against is a texel of it. Declared on every frame rather
622        // than on the masked ones, because a declaration is also what lets
623        // the graph order a copy into a page layer against this pass — see
624        // `base_color_page_import`.
625        .read_image(reads.pages.base_color)
626        // And §2's other three pages, which are in the same groups for the
627        // same reason and are sampled here just as little.
628        .read_image(reads.pages.normal)
629        .read_image(reads.pages.mro)
630        .read_image(reads.pages.emissive)
631        // And the probe rows, which `mesh_layout` names in this group too
632        // and which the depth-only pipeline reads not at all — declared for
633        // the colour pass's reason exactly: they are device-local and
634        // writable-by-copy so a gather can fill them, and the graph orders a
635        // write against a pass only if that pass declared the read.
636        .read_buffer(reads.probe_table);
637    // `read_draw_sources` declares the *camera's* statistics buffer, because
638    // that is the one the arguments came out of; the prepass writes its own
639    // instead, so both are declared and the graph barriers both.
640    let pass = read_draw_sources(pass, generated, emit)
641        .use_buffer(reads.prepass_stats, ResourceState::ShaderReadWrite);
642    // The skinned vertices, on the shadow pass's terms. This pass writes the
643    // depth the occlusion pair samples and the forward pass tests against,
644    // so a prepass reading the region before the dispatch is visible lays
645    // down the previous pose's silhouette and the frame is rejected against
646    // it.
647    let pass = match reads.skinned {
648        Some(vertices) => pass.read_buffer(vertices),
649        None => pass,
650    };
651    // The camera's own cut, written here and again by the forward pass with
652    // the same camera and the same budget. Shared rather than a buffer of its
653    // own — unlike a cascade's, which a *later* pass would overwrite before
654    // anything could read it — because the second write is the one that stands
655    // and it writes the same words.
656    match reads.selection {
657        Some(selection) if emit.is_mesh() => {
658            pass.use_buffer(selection, ResourceState::ShaderReadWrite)
659        }
660        _ => pass,
661    }
662}
663
664/// The primary camera's overlays — nothing for a secondary view.
665#[derive(Default)]
666pub(super) struct Overlays<'a> {
667    /// The debug draw layer, drawn into the HDR frame before the tonemap.
668    pub(super) debug_draw: Option<&'a DebugDraw>,
669    /// The ground grid, where a caller switched it on.
670    pub(super) ground_grid: Option<&'a GroundGrid>,
671    /// The shadow atlas viewer, on the frame the debug view shows it.
672    pub(super) atlas_viewer: Option<&'a mut AtlasView>,
673}
674
675/// One camera's resources and history — see the [module docs](self).
676#[derive(Debug)]
677pub(super) struct View {
678    /// The effects this view may draw, as [`ViewDesc::effects`] asked for them.
679    pub(super) effects: RenderEffects,
680    /// What this view draws where no geometry is, as
681    /// [`ViewDesc::background`] asked for it.
682    pub(super) background: ViewBackground,
683    /// What lights this view, as [`ViewDesc::lighting`] asked for it.
684    pub(super) lighting: ViewLighting,
685    /// What this frame draws in this view: the frame's resolved effects under
686    /// [`View::effects`], frozen by [`View::begin_frame`] so that the frame's
687    /// two halves agree on it.
688    pub(super) frame_effects: RenderEffects,
689    /// Whether this frame puts the atmosphere's air in front of this view's
690    /// surfaces — an atmosphere under [`ViewLighting::Scene`] — frozen by
691    /// [`View::begin_frame`] beside [`View::frame_effects`] and for its
692    /// reason: the block that switch writes and the composite
693    /// [`View::add_passes`] adds for it have to agree.
694    pub(super) frame_aerial: bool,
695    /// The extent of the image the reflection march writes this frame —
696    /// [`crate::ssr::march_extent`] of the frame's extent at
697    /// `crate::ssr::r_ssr_resolution` — frozen by [`View::begin_frame`] beside
698    /// [`View::frame_effects`] and for its reason: the block that tells
699    /// `ssr.slang` this extent and the image [`View::add_passes`] creates at it
700    /// have to agree, and the console can move the variable between the two.
701    pub(super) frame_ssr_extent: (u32, u32),
702    /// The frame serial [`View::begin_frame`] last ran for — see
703    /// [`ForwardRenderer::frame_serial`]. A secondary view records passes only
704    /// in the frame it was begun for.
705    pub(super) begun: u64,
706    /// The cull and draw-argument passes, and the indirect arguments they
707    /// produce.
708    pub(super) draws: DrawGen,
709    /// One buffer per frame in flight holding the cut the descent chose, or
710    /// empty where there is no amplification stage to choose one. See
711    /// [`ForwardRenderer::cluster_selection`].
712    pub(super) cluster_selection: Vec<BufferHandle>,
713    /// The one zeroed probe row a [`ViewLighting::Fixed`] view's groups, its
714    /// reflection march and its water surface bind in place of the scene's
715    /// table, or `None` for a view lit by the scene — see [`View::build`].
716    pub(super) fixed_probes: Option<BufferHandle>,
717    /// What [`begin_frame`](ForwardRenderer::begin_frame) last handed
718    /// [`DrawGen::begin_frame`], kept so a reader can compute the same cut
719    /// host-side without re-deriving it from the camera.
720    ///
721    /// Pixels per unit, the budget a group starts expanding over, and the budget
722    /// it is held down to — topic 25's hysteresis, and
723    /// [`LOD_HOLD_RATIO`] is what puts the third below the second.
724    pub(super) lod_params: [f32; 3],
725    /// Topic 18's light list and froxel grid, and the compute pass between them.
726    pub(super) lights: LightGrid,
727    /// This frame's froxel grid, as [`begin_frame`](ForwardRenderer::begin_frame)
728    /// decided it from the viewport and the camera.
729    ///
730    /// Held rather than recomputed at [`ForwardRenderer::add_passes`], because
731    /// the number of froxels the dispatch covers and the number the frame block
732    /// tells the fragment stage about have to be the same one.
733    pub(super) grid: Grid,
734    /// `[frame]`: the frame block, one per frame in flight — see the
735    /// [forward module docs](super) on why it is a ring.
736    pub(super) uniforms: Vec<BufferHandle>,
737    /// `[frame]`: the camera's group of the mesh layout, naming this view's
738    /// frame block and survivors.
739    pub(super) mesh_groups: Vec<BindGroupHandle>,
740    /// `[frame]`: `tonemap.slang`'s exposure block, written by
741    /// [`begin_frame`](ForwardRenderer::begin_frame).
742    ///
743    /// One per frame in flight for the frame uniforms' reason exactly — the
744    /// previous frame may still be reading last frame's while this one is
745    /// written.
746    pub(super) tonemap_uniforms: Vec<BufferHandle>,
747    /// `[frame]`: the tonemap group, cached against the scene target's view.
748    ///
749    /// Rebuilt only when that view changes, which is only on a resize. The graph
750    /// hands the view to the pass body; caching against it is what keeps a
751    /// steady-state frame free of descriptor writes.
752    ///
753    /// **One per frame in flight**, for [`crate::ssao`]'s reason: this group
754    /// names [`View::tonemap_uniforms`] as well as the scene transient, and that
755    /// is a ring — a single cache keyed on the view alone would hand the even
756    /// frames' block to the odd frames.
757    pub(super) tonemap_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
758    /// `[frame]`: the entries [`View::mesh_groups`] was built from.
759    ///
760    /// Kept because the occlusion image is a graph transient: its view is known
761    /// only at execute time, so the camera's group has to be rebuilt inside the
762    /// forward pass, and re-deriving twenty bindings there would mean carrying
763    /// half of `build`'s locals into the frame. Exactly two entries —
764    /// [`AMBIENT_OCCLUSION_BINDING`]'s and [`CONTACT_SHADOW_BINDING`]'s — differ
765    /// between the stored list and what the rebuild writes.
766    pub(super) mesh_group_entries: Vec<Vec<BindGroupEntry>>,
767    /// `[frame]`: the entries [`View::prepass_groups`] was built from.
768    ///
769    /// Kept for one rebuild only: the pages' and their sampler's, which
770    /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
771    /// layout a slot holds. Handles, so the cost is a few words a group.
772    pub(super) prepass_group_entries: Vec<Vec<BindGroupEntry>>,
773    /// `[frame]`: the camera's group rebuilt against the two screen-space
774    /// channels the forward pass reads — the blurred occlusion and the contact
775    /// shadow — cached against both views together.
776    ///
777    /// [`View::tonemap_groups`]' shape, one per frame in flight because the
778    /// group it replaces is per frame in flight. Rebuilt only when a view
779    /// changes, which is only on a resize or a toggle.
780    ///
781    /// **One cache for both channels rather than one each**, because they are
782    /// two bindings of *one* group: rebuilding it twice a frame would be a
783    /// descriptor write per pass per frame, which is what
784    /// [`crate::ssao::cached_group`] exists to avoid. Its key is every view, so
785    /// either one moving is a miss.
786    ///
787    /// [`View::mesh_groups`] is the fallback and is *not* dead weight: it is
788    /// what the depth prepass binds, because that pass runs before there is any
789    /// occlusion to name.
790    pub(super) screen_channel_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
791    /// `[frame]`: the depth prepass's group — the camera's, with the occlusion
792    /// placeholder and **a culling-statistics buffer of its own**.
793    ///
794    /// The second half is the whole reason this is a group rather than
795    /// [`View::mesh_groups`] reused. On the mesh-shader path the prepass runs
796    /// the same amplification stage the forward pass does, and that stage counts
797    /// every surviving cluster into the buffer bound at CLUSTER_CULL_STATS_BINDING — so sharing
798    /// the camera's would make
799    /// [`CullStats::clusters`](crate::cull_stats::CullStats::clusters) report
800    /// every cluster of the frame twice, which is a plausible number and a wrong
801    /// one.
802    ///
803    /// **Nothing reads what this counts and nothing clears it.** It is a sink: a
804    /// wrapping `u32` whose value is never looked at, which is the honest price
805    /// of a prepass that shares a pipeline with the pass it precedes.
806    pub(super) prepass_groups: Vec<BindGroupHandle>,
807    /// `[frame]`: the sink [`View::prepass_groups`] counts into.
808    ///
809    /// Held so the prepass can declare it and the graph can barrier it. A ring
810    /// rather than one buffer for every other per-frame resource's reason: the
811    /// previous frame's submission may still be writing last frame's.
812    pub(super) prepass_stats: Vec<BufferHandle>,
813    /// This frame's camera view-projection, as
814    /// [`begin_frame`](ForwardRenderer::begin_frame) computed it.
815    ///
816    /// Kept because the ground grid's pass needs it and `add_passes` has no
817    /// camera: recomputing it there would be a second `aspect` to get wrong, and
818    /// a grid drawn through a camera the frame is not drawn with lands on the
819    /// wrong pixels while still looking like a grid.
820    pub(super) camera_view_proj: Mat4,
821    /// The view-projection the **previous** frame was drawn with, or [`None`]
822    /// before there was one.
823    ///
824    /// The camera-side twin of
825    /// [`GpuInstance::previous_transform`](crcbl_shaders::mesh::GpuInstance::previous_transform):
826    /// the pool says where each object was and this says where the viewer was,
827    /// and `mesh.slang`'s `motion_vector` is what turns the pair into a screen
828    /// offset. It reaches the shader as
829    /// [`FrameUniforms::previous_view_proj`](crcbl_shaders::mesh::FrameUniforms::previous_view_proj).
830    ///
831    /// **Advanced once per frame, in
832    /// [`begin_frame_body`](ForwardRenderer::begin_frame_body)** — which runs
833    /// exactly once per [`InstancePool::rotate`], so the camera's history and
834    /// the instances' settle on the same boundary. Advancing it anywhere a
835    /// frame can reach twice would report a camera that moved half as far as it
836    /// did, and a still scene would never come back to rest.
837    ///
838    /// [`None`] means the first frame, which is drawn with its own matrix in
839    /// both slots: a camera that has not moved yet has not moved, and an
840    /// identity or a zero here would put every pixel of the first frame in
841    /// motion.
842    pub(super) previous_view_projection: Option<Mat4>,
843    /// Topic 46's occlusion pair — see [`crate::ssao`].
844    pub(super) ssao: Ssao,
845    /// Topic 45's contact-shadow march — see
846    /// [`crate::contact_shadows`].
847    pub(super) contact_shadows: ContactShadows,
848    /// Topic 47's depth pyramid, which the reflection
849    /// march climbs — see [`crate::hiz`].
850    pub(super) hiz: Hiz,
851    /// Topic 03 §3.3's farthest-depth pyramid,
852    /// which the occlusion cull reads — see [`crate::occlusion_cull`].
853    pub(super) occlusion_pyramid: OcclusionPyramid,
854    /// Topic 47's reflection march — see
855    /// [`crate::ssr`].
856    pub(super) ssr: Ssr,
857    /// The froxel volume and its composite — see
858    /// [`crate::volumetric`].
859    pub(super) volumetric: Volumetric,
860    /// Topic 43 §6's auto-exposure — see
861    /// [`crate::exposure`]. Named for what it owns rather than for the value:
862    /// [`ForwardRenderer::exposure`] is the number a caller set.
863    pub(super) auto_exposure: Exposure,
864    /// Topic 48's bloom chain — see [`crate::bloom`].
865    pub(super) bloom: Bloom,
866    /// The cheap antialiasing tier — see
867    /// [`crate::fxaa`].
868    pub(super) fxaa: Fxaa,
869    /// The higher antialiasing tier — see
870    /// [`crate::cmaa2`]. It takes the resolve slot from [`View::fxaa`] on the
871    /// frames [`RenderEffects::CMAA2`] is set for, and neither is built per
872    /// frame: both exist, and at most one records.
873    pub(super) cmaa2: Cmaa2,
874    /// [`crate::upscale`], and it draws nothing at a
875    /// [`render_scale`](ForwardRenderer::render_scale) of `1.0`.
876    pub(super) upscale: Upscale,
877    /// Topic 43 §8's background pass — see
878    /// [`crate::sky_pass`]. It draws on no frame whose sky is [`Sky::NONE`],
879    /// which is every frame until a caller calls
880    /// [`set_sky`](ForwardRenderer::set_sky).
881    pub(super) sky_pass: SkyPass,
882    /// `docs/plan/55-water.md`'s surface passes — see [`crate::water`]. They
883    /// draw on no frame with no bodies, which is every frame until a caller
884    /// calls [`set_water`](ForwardRenderer::set_water).
885    pub(super) water: Water,
886    /// `docs/plan/57-grass.md`'s three passes — see [`crate::grass`]. They run
887    /// on no frame with no field, which is every frame until a caller calls
888    /// [`set_grass`](ForwardRenderer::set_grass).
889    pub(super) grass: crate::grass::Grass,
890}
891
892impl View {
893    /// Creates one camera's resources against the scene `inputs` describes.
894    ///
895    /// **All or nothing**: a failure part-way releases what this call had
896    /// created, so the caller has nothing of the view to clean up, and a success
897    /// hands every handle to the returned [`View`] — none of them is left in a
898    /// rollback the caller might run later.
899    ///
900    /// `service` is called after each subsystem is built, and between the
901    /// grass pass's pipelines — see
902    /// [`ForwardRenderer::with_scene_serviced`], which is where the reason and
903    /// the measurement are.
904    ///
905    /// # Errors
906    ///
907    /// [`HalError`] if any buffer, group or pipeline could not be created.
908    pub(super) fn build(
909        device: &dyn Device,
910        queue: QueueHandle,
911        inputs: &ViewInputs<'_>,
912        service: &mut dyn FnMut(),
913    ) -> Result<Self, HalError> {
914        let mut rollback = Rollback::default();
915        let built = Self::build_into(device, queue, inputs, &mut rollback, service);
916        if built.is_err() {
917            rollback.run(device);
918        }
919        built
920    }
921
922    /// [`View::build`]'s body, with every handle it creates placed in
923    /// `rollback` until the view is whole.
924    fn build_into(
925        device: &dyn Device,
926        queue: QueueHandle,
927        inputs: &ViewInputs<'_>,
928        rollback: &mut Rollback,
929        service: &mut dyn FnMut(),
930    ) -> Result<Self, HalError> {
931        let frames = inputs.instances.len();
932        let draws = DrawGen::new(
933            device,
934            queue,
935            &DrawGenDesc {
936                label: Some("forward"),
937                instances: inputs.instances,
938                mesh_table: inputs.mesh_table,
939                bucket_meshes: inputs.bucket_meshes,
940                bucket_modes: inputs.bucket_modes,
941                bucket_clusters: inputs.bucket_clusters,
942                bucket_cluster_bases: inputs.bucket_cluster_bases,
943                mesh_levels: inputs.mesh_levels,
944                level_groups: inputs.level_groups,
945                level_meshes: inputs.level_meshes,
946                instance_capacity: inputs.instance_capacity,
947                hidden_view: inputs.id.hidden_bit(),
948                // Every camera can cull by occlusion: the regions it adds are a
949                // few words a bucket, and the switch is per frame.
950                mode: crcbl_shaders::draw_gen::DrawMode::Occlusion,
951                task_lanes: inputs.task_lanes,
952            },
953        )?;
954        let runs: Vec<BufferHandle> = (0..frames).map(|frame| draws.runs(frame)).collect();
955        let args: Vec<BufferHandle> = (0..frames).map(|frame| draws.args(frame)).collect();
956        // What the amplification stage reads and writes, and nothing else does:
957        // this frame's frustum, and the culling statistics its surviving
958        // clusters are counted into.
959        let cull_params: Vec<BufferHandle> =
960            (0..frames).map(|frame| draws.cull_params(frame)).collect();
961        let cull_stats: Vec<BufferHandle> = (0..frames)
962            .map(|frame| draws.visible_count(frame))
963            .collect();
964        rollback.draws = Some(draws);
965        service();
966
967        // Topic 25's observable: one word per resident cluster,
968        // holding the cut the descent chose. Empty where there is no
969        // amplification stage, which is the same condition CLUSTER_SELECTION_BINDING exists
970        // under — and the two cannot disagree, because this vector is what
971        // decides whether the entry is written.
972        //
973        // **One buffer per frame in flight**, on `cull_stats`' terms exactly: a
974        // frame still in flight is a frame still writing, and one buffer shared
975        // across the ring would have the next frame's dispatch overwriting what
976        // this one recorded. `TRANSFER_SRC` because reading it is the point.
977        //
978        // Allocated on the whole mesh path rather than only where there is an
979        // amplification stage to write them, because the layout declares
980        // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued. On
981        // a device with no task stage nothing writes them and
982        // `ForwardRenderer::cluster_selection` still answers `None`, so the
983        // cost is the allocation and nothing else.
984        let mut cluster_selection: Vec<BufferHandle> = Vec::new();
985        if inputs.emit.is_mesh() {
986            let count = inputs
987                .clusters
988                .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
989                .count();
990            for frame in 0..frames {
991                let buffer = device.create_buffer(&BufferDesc {
992                    label: Some(&format!("cluster selection {frame}")),
993                    size: u64::from(count) * 4,
994                    usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
995                    memory: MemoryLocation::DeviceLocal,
996                })?;
997                rollback.buffers.push(buffer);
998                cluster_selection.push(buffer);
999            }
1000        }
1001
1002        // Topic 18's light list and the froxel grid its compute pass fills.
1003        //
1004        // Built after the cull because it needs the culling-statistics ring:
1005        // its overflow counter is a word of that buffer, which is what keeps
1006        // topic 03 §3.6's readback at one.
1007        rollback.lights = Some(LightGrid::new(
1008            device,
1009            &LightGridDesc {
1010                label: Some("lights"),
1011                frames,
1012                lights: inputs.light_capacity,
1013                froxels: FROXEL_CAPACITY,
1014                stats: &cull_stats,
1015            },
1016        )?);
1017        service();
1018        let lights = rollback.lights.as_ref().expect("just stored");
1019        let draws = rollback.draws.as_ref().expect("stored above");
1020
1021        // **A fixed view's probe table is one zeroed row**, bound in place of
1022        // the scene's. Its frame block carries the empty probe header, and
1023        // `mesh.slang` evaluates that header as row 0 of whatever table is
1024        // bound — which is zero for a scene with no probes only because that
1025        // scene's table is. Host-uploaded and read-only, on the light list's
1026        // terms, and written once: nothing ever changes a zero.
1027        //
1028        // **Zero even when the view has an environment**, which reaches the
1029        // reflection march as its sky rows instead. A probe row is weighed by
1030        // the frame's per-probe visibility map before it is divided back out,
1031        // and `(a * w) / w` is not always `a` in floating point — so a lit row
1032        // here could come back rounded differently from one level to the next.
1033        // A zero comes back zero whatever it is weighed by.
1034        let fixed_probes = match inputs.lighting {
1035            ViewLighting::Scene => None,
1036            ViewLighting::Fixed { .. } => {
1037                let buffer = device.create_buffer(&BufferDesc {
1038                    label: Some("fixed view probes"),
1039                    size: crcbl_shaders::probe::PROBE_STRIDE as u64,
1040                    usage: BufferUsage::STORAGE,
1041                    memory: MemoryLocation::HostUpload,
1042                })?;
1043                rollback.buffers.push(buffer);
1044                device.write_buffer(buffer, 0, &crcbl_shaders::probe::GpuProbe::ZERO.to_bytes())?;
1045                Some(buffer)
1046            }
1047        };
1048
1049        let mut uniforms = Vec::with_capacity(frames);
1050        let mut mesh_groups = Vec::with_capacity(frames);
1051        let mut mesh_group_entries = Vec::with_capacity(frames);
1052        let mut prepass_groups = Vec::with_capacity(frames);
1053        let mut prepass_stats = Vec::with_capacity(frames);
1054        let mut prepass_group_entries = Vec::with_capacity(frames);
1055        for (frame, &slot_instances) in inputs.instances.iter().enumerate() {
1056            // Everything a group of this layout names that is the same in all of
1057            // this frame's. The per-group half is what `MeshGroup` below varies,
1058            // and the two exist so the colour pass's group and the shadow pass's
1059            // are one description rather than two that agree today.
1060            let shared = SharedBindings {
1061                vertices: inputs.vertices,
1062                draw_constants: inputs.draw_constants,
1063                mesh_table: inputs.mesh_table,
1064                materials: inputs.materials,
1065                pages: inputs.pages[frame],
1066                clusters: inputs.clusters,
1067                shadow_sampler: inputs.shadow_sampler,
1068                lights: lights.lights(frame),
1069                light_grid: lights.grid(frame),
1070                probes: fixed_probes.unwrap_or(inputs.probes[frame]),
1071                tables: draws.tables(),
1072                specular_dfg: inputs.specular_dfg,
1073                ltc_table: inputs.ltc_table,
1074            };
1075            let buffer = device.create_buffer(&BufferDesc {
1076                label: Some("mesh frame uniforms"),
1077                size: mesh::FRAME_UNIFORMS_SIZE as u64,
1078                usage: BufferUsage::UNIFORM,
1079                memory: MemoryLocation::HostUpload,
1080            })?;
1081            rollback.buffers.push(buffer);
1082            let entries = MeshGroup {
1083                uniforms: buffer,
1084                instances: slot_instances,
1085                runs: runs[frame],
1086                args: args[frame],
1087                cull_params: cull_params[frame],
1088                cull_stats: cull_stats[frame],
1089                cluster_selection: cluster_selection.get(frame).copied(),
1090                group_state: inputs.emit.is_mesh().then(|| draws.group_state()),
1091                // The colour pass reads the finished atlas. Its own pass writes
1092                // nothing to it, so there is no conflict to avoid here.
1093                shadow_map: inputs.shadow_map,
1094                // The placeholder even for the camera's group: the occlusion
1095                // image is a graph transient and its view does not exist until
1096                // execute time. `add_passes` rebuilds this group against the real
1097                // one and caches it, and *this* group is what the depth prepass
1098                // binds — which runs before there is any occlusion to name.
1099                ambient_occlusion: inputs.ambient_occlusion,
1100                // The same, one binding along, and for the same reason.
1101                contact_shadow: inputs.contact_shadow,
1102                probe_visibility: inputs.probe_visibility,
1103            }
1104            .entries(&shared);
1105            let group = device.create_bind_group(&BindGroupDesc {
1106                label: Some("mesh frame"),
1107                layout: inputs.mesh_layout,
1108                entries: &entries,
1109                variable_count: None,
1110            })?;
1111            rollback.bind_groups.push(group);
1112            uniforms.push(buffer);
1113            mesh_groups.push(group);
1114            // Kept so the forward pass can rebuild this group against the
1115            // occlusion image the graph realised, without re-deriving twenty
1116            // bindings out of fields that no longer exist by then. Only the
1117            // screen-space channels and the probe visibility maps differ — see
1118            // [`View::screen_channel_groups`].
1119            mesh_group_entries.push(entries);
1120
1121            // The depth prepass's group: this one again, counting its clusters
1122            // somewhere the camera's counter cannot see. See
1123            // [`View::prepass_groups`] for why that matters, and note that only
1124            // the amplification stage writes this binding, although both mesh
1125            // layouts retain it to preserve native argument indices.
1126            //
1127            // `DeviceLocal`, because a shader writes it: D3D12 has no unordered
1128            // access view of a host-visible resource, and `create_bind_group`
1129            // enforces it.
1130            let stats = device.create_buffer(&BufferDesc {
1131                label: Some("depth prepass cluster survivors"),
1132                size: u64::from(crcbl_shaders::cull::STATS_WORDS) * 4,
1133                usage: BufferUsage::STORAGE,
1134                memory: MemoryLocation::DeviceLocal,
1135            })?;
1136            rollback.buffers.push(stats);
1137            let entries = MeshGroup {
1138                uniforms: buffer,
1139                instances: slot_instances,
1140                runs: runs[frame],
1141                args: args[frame],
1142                cull_params: cull_params[frame],
1143                cull_stats: stats,
1144                cluster_selection: cluster_selection.get(frame).copied(),
1145                group_state: inputs.emit.is_mesh().then(|| draws.group_state()),
1146                shadow_map: inputs.shadow_map,
1147                ambient_occlusion: inputs.ambient_occlusion,
1148                contact_shadow: inputs.contact_shadow,
1149                probe_visibility: inputs.probe_visibility,
1150            }
1151            .entries(&shared);
1152            let group = device.create_bind_group(&BindGroupDesc {
1153                label: Some("depth prepass"),
1154                layout: inputs.mesh_layout,
1155                entries: &entries,
1156                variable_count: None,
1157            })?;
1158            rollback.bind_groups.push(group);
1159            prepass_groups.push(group);
1160            prepass_stats.push(stats);
1161            // For the page sampler's rebuild — see [`View::prepass_group_entries`].
1162            prepass_group_entries.push(entries);
1163        }
1164
1165        // The exposure block, one per frame in flight for the frame uniforms'
1166        // reason exactly — the previous frame may still be reading last frame's
1167        // while this one is written. See the forward module docs on the ring.
1168        let mut tonemap_uniforms = Vec::with_capacity(frames);
1169        for _ in 0..frames {
1170            let buffer = device.create_buffer(&BufferDesc {
1171                label: Some("tonemap params"),
1172                size: tonemap::PARAMS_SIZE as u64,
1173                usage: BufferUsage::UNIFORM,
1174                memory: MemoryLocation::HostUpload,
1175            })?;
1176            rollback.buffers.push(buffer);
1177            tonemap_uniforms.push(buffer);
1178        }
1179
1180        // --- the screen-space occlusion pair ---
1181        //
1182        // Stored in the rollback whole, like the light grid: it owns two
1183        // pipelines and a ring of buffers, and `Ssao::destroy` is the one place
1184        // their release order lives.
1185        rollback.ssao = Some(Ssao::new(
1186            device,
1187            frames,
1188            ForwardRenderer::build_fullscreen,
1189        )?);
1190        service();
1191
1192        // --- the screen-space contact-shadow march ---
1193        //
1194        // Stored whole for the pair above's reason, and after them because
1195        // `Rollback::run` releases in the reverse order of construction.
1196        rollback.contact_shadows = Some(ContactShadows::new(
1197            device,
1198            frames,
1199            ForwardRenderer::build_fullscreen,
1200        )?);
1201        service();
1202
1203        // --- the screen-space reflection march ---
1204        //
1205        // Stored whole for the pair above's reason, and after them because
1206        // `Rollback::run` releases in the reverse order of construction.
1207        rollback.ssr = Some(Ssr::new(
1208            device,
1209            queue,
1210            frames,
1211            ForwardRenderer::build_fullscreen,
1212        )?);
1213        service();
1214
1215        // --- the Hi-Z pyramid the march climbs ---
1216        //
1217        // After the march it serves and before the chain below, on their reason:
1218        // `Rollback::run` releases in the reverse order of construction. Its
1219        // pipeline is the only one in this file with a depth attachment and no
1220        // colour one — see [`ForwardRenderer::build_depth_fullscreen`].
1221        rollback.hiz = Some(Hiz::new(
1222            device,
1223            frames,
1224            ForwardRenderer::build_depth_fullscreen,
1225        )?);
1226        service();
1227        // The occlusion cull's farthest pyramid beside it, built from the same
1228        // reduction. Its images wait for a frame's extent.
1229        rollback.occlusion_pyramid = Some(OcclusionPyramid::new(
1230            device,
1231            frames,
1232            ForwardRenderer::build_depth_fullscreen,
1233        )?);
1234        service();
1235
1236        // --- the froxel volume ---
1237        //
1238        // Stored whole for the three above's reason, and after them because
1239        // `Rollback::run` releases in the reverse order of construction. It sits
1240        // between the march and the chain in the frame as well: the medium is
1241        // scene content and the chain is a lens. Its volume holds the same
1242        // [`FROXEL_CAPACITY`] the clustering pass's grid does, because it is
1243        // subdivided by the same [`Grid`] — see [`crate::volumetric`].
1244        rollback.volumetric = Some(Volumetric::new(
1245            device,
1246            frames,
1247            FROXEL_CAPACITY,
1248            inputs.shadow_map,
1249            inputs.shadow_sampler,
1250            lights,
1251            ForwardRenderer::build_fullscreen,
1252        )?);
1253        service();
1254
1255        // --- auto-exposure ---
1256        //
1257        // Stored whole for the volume's reason, and after it because
1258        // `Rollback::run` releases in the reverse order of construction. It runs
1259        // between the chain and the tonemap in the frame as well: it bins the
1260        // picture the tonemap is about to read, which is the one with the lens
1261        // already on it — see [`crate::exposure`].
1262        rollback.exposure = Some(Exposure::new(device, queue, frames)?);
1263        service();
1264
1265        // --- the bloom chain ---
1266        //
1267        // Stored whole for the pair above's reason, and after them because
1268        // `Rollback::run` releases in the reverse order of construction. It owns
1269        // a **linear** sampler of its own; the tonemap's sampler is `Nearest` on
1270        // purpose and `crate::bloom` says why the chain cannot share it.
1271        rollback.bloom = Some(Bloom::new(
1272            device,
1273            frames,
1274            ForwardRenderer::build_fullscreen,
1275        )?);
1276        service();
1277
1278        // --- the antialiasing resolve ---
1279        //
1280        // Stored whole for the three above's reason, and after them because
1281        // `Rollback::run` releases in the reverse order of construction. It is
1282        // the one of the four that needs `target_format`: it writes the caller's
1283        // target where the others write `Rgba16Float` transients of their own
1284        // choosing — see [`crate::fxaa`]. Its sampler is **linear** for the
1285        // chain's reason and not the tonemap's.
1286        rollback.fxaa = Some(Fxaa::new(
1287            device,
1288            frames,
1289            inputs.target_format,
1290            ForwardRenderer::build_fullscreen,
1291        )?);
1292        service();
1293
1294        // --- the higher antialiasing tier ---
1295        //
1296        // The same slot, filled by CMAA2's two dispatches and one draw
1297        // instead of FXAA's one draw — see [`crate::cmaa2`], which says why the
1298        // two are built together and at most one recorded. It carries no lookup
1299        // table, so unlike the tier it replaced it takes no `queue`: there is
1300        // nothing to upload.
1301        rollback.cmaa2 = Some(Cmaa2::new(
1302            device,
1303            frames,
1304            inputs.target_format,
1305            ForwardRenderer::build_fullscreen,
1306        )?);
1307        service();
1308
1309        // --- the render-scale upscale ---
1310        //
1311        // The second pass that writes the caller's target rather than a
1312        // transient of its own. It draws on no frame at a render scale of
1313        // `1.0`, which is every frame until a caller moves it — see
1314        // [`crate::upscale`].
1315        rollback.upscale = Some(Upscale::new(
1316            device,
1317            frames,
1318            inputs.target_format,
1319            ForwardRenderer::build_fullscreen,
1320        )?);
1321        service();
1322
1323        // --- the background ---
1324        //
1325        // Built last, so `Rollback::run` releases it first. It writes the scene
1326        // target rather than the caller's — it is scene content, drawn before
1327        // the operator, unlike the ground grid — and takes the depth format as
1328        // well, because it is the one full-screen pass in this frame that tests
1329        // against an attachment. See [`crate::sky_pass`].
1330        rollback.sky_pass = Some(SkyPass::new(
1331            device,
1332            frames,
1333            Format::Rgba16Float,
1334            Format::D32Float,
1335            ForwardRenderer::build_tested_fullscreen,
1336        )?);
1337        service();
1338
1339        // --- the water surface ---
1340        //
1341        // After the background, so `Rollback::run` releases it before that
1342        // pass. It takes the atlas's sampler, which the renderer owns for its
1343        // life, and the full-screen builder with a depth state, because its copy
1344        // pass writes a colour target and a depth one at once. See
1345        // [`crate::water`].
1346        rollback.water = Some(Water::new(
1347            device,
1348            frames,
1349            inputs.shadow_sampler,
1350            ForwardRenderer::build_fullscreen_with,
1351        )?);
1352        service();
1353
1354        // --- the grass field ---
1355        //
1356        // After the water surface, so `Rollback::run` releases it first. It
1357        // takes the atlas's sampler for the same reason that one does: the
1358        // cards are lit through a copy of the forward pass's cascade walk, and
1359        // the walk reads the atlas through a comparison sampler the renderer
1360        // owns for its life. See [`crate::grass`].
1361        rollback.grass = Some(crate::grass::Grass::new(
1362            device,
1363            frames,
1364            inputs.shadow_sampler,
1365            service,
1366        )?);
1367        service();
1368
1369        // Whole, so the rollback lets go of every handle: the view owns them
1370        // from here, and a rollback still naming one would release it twice.
1371        let view =
1372            Self {
1373                effects: inputs.effects,
1374                background: inputs.background,
1375                lighting: inputs.lighting,
1376                // Replaced by every `begin_frame`, on `lod_params`' terms.
1377                frame_effects: inputs.effects,
1378                // Replaced by every `begin_frame`, on `frame_effects`' terms.
1379                frame_aerial: false,
1380                // Replaced by every `begin_frame`, on `frame_effects`' terms.
1381                frame_ssr_extent: (1, 1),
1382                // No frame has begun it.
1383                begun: 0,
1384                draws: rollback.draws.take().unwrap_or_else(|| {
1385                    unreachable!("draw generation was placed in the rollback above")
1386                }),
1387                cluster_selection,
1388                fixed_probes,
1389                // Overwritten by the first `begin_frame`, which is the only thing
1390                // that can know the viewport. A zero scale with a budget of zero
1391                // selects nothing at all, and there is no frame yet to select for.
1392                lod_params: [0.0, 0.0, 0.0],
1393                lights: rollback.lights.take().unwrap_or_else(|| {
1394                    unreachable!("the light grid was placed in the rollback above")
1395                }),
1396                // Overwritten by the first `begin_frame` on `lod_params`' terms: a
1397                // one-froxel grid is the smallest legal one, and there is no
1398                // viewport yet to size a real one against.
1399                grid: Grid {
1400                    x: 1,
1401                    y: 1,
1402                    slices: 1,
1403                    tile_pixels: 1,
1404                },
1405                uniforms,
1406                mesh_groups,
1407                tonemap_uniforms,
1408                tonemap_groups: vec![None; frames],
1409                mesh_group_entries,
1410                prepass_group_entries,
1411                screen_channel_groups: vec![None; frames],
1412                prepass_groups,
1413                prepass_stats,
1414                // Replaced by every `begin_frame`, which `add_passes` documents as
1415                // having to run first.
1416                camera_view_proj: Mat4::IDENTITY,
1417                // No frame has been drawn, so there is no previous camera — see the
1418                // field, which says why that is not the identity.
1419                previous_view_projection: None,
1420                ssao: rollback.ssao.take().unwrap_or_else(|| {
1421                    unreachable!("the occlusion pair was placed in the rollback above")
1422                }),
1423                contact_shadows: rollback.contact_shadows.take().unwrap_or_else(|| {
1424                    unreachable!("the contact march was placed in the rollback above")
1425                }),
1426                hiz: rollback.hiz.take().unwrap_or_else(|| {
1427                    unreachable!("the pyramid was placed in the rollback above")
1428                }),
1429                occlusion_pyramid: rollback.occlusion_pyramid.take().unwrap_or_else(|| {
1430                    unreachable!("the occlusion pyramid was placed in the rollback above")
1431                }),
1432                ssr: rollback.ssr.take().unwrap_or_else(|| {
1433                    unreachable!("the reflection march was placed in the rollback above")
1434                }),
1435                volumetric: rollback.volumetric.take().unwrap_or_else(|| {
1436                    unreachable!("the froxel volume was placed in the rollback above")
1437                }),
1438                auto_exposure: rollback.exposure.take().unwrap_or_else(|| {
1439                    unreachable!("the histogram was placed in the rollback above")
1440                }),
1441                bloom: rollback.bloom.take().unwrap_or_else(|| {
1442                    unreachable!("the bloom chain was placed in the rollback above")
1443                }),
1444                fxaa: rollback.fxaa.take().unwrap_or_else(|| {
1445                    unreachable!("the resolve was placed in the rollback above")
1446                }),
1447                cmaa2: rollback.cmaa2.take().unwrap_or_else(|| {
1448                    unreachable!("the higher tier was placed in the rollback above")
1449                }),
1450                upscale: rollback.upscale.take().unwrap_or_else(|| {
1451                    unreachable!("the upscale was placed in the rollback above")
1452                }),
1453                sky_pass: rollback
1454                    .sky_pass
1455                    .take()
1456                    .unwrap_or_else(|| unreachable!("the sky was placed in the rollback above")),
1457                water: rollback
1458                    .water
1459                    .take()
1460                    .unwrap_or_else(|| unreachable!("the water was placed in the rollback above")),
1461                grass: rollback
1462                    .grass
1463                    .take()
1464                    .unwrap_or_else(|| unreachable!("the grass was placed in the rollback above")),
1465            };
1466        rollback.buffers.clear();
1467        rollback.bind_groups.clear();
1468        Ok(view)
1469    }
1470
1471    /// Writes every per-frame block this view reads, for `camera`, into the
1472    /// slot `frame` names — the camera's half of
1473    /// [`ForwardRenderer::begin_frame`].
1474    ///
1475    /// Returns the frame block it wrote, which the shadow views of the primary
1476    /// camera are spread from.
1477    ///
1478    /// # Errors
1479    ///
1480    /// [`HalError`] if any of the view's blocks could not be written.
1481    pub(super) fn begin_frame(
1482        &mut self,
1483        device: &dyn Device,
1484        camera: &Camera,
1485        frame: &ViewFrame<'_>,
1486        sky_view: Option<&PresentedSky>,
1487    ) -> Result<mesh::FrameUniforms, HalError> {
1488        let scene = frame.scene;
1489        let slot = frame.slot;
1490        let extent = frame.extent;
1491        // Read before this call advances it below: the first occlusion phase
1492        // reprojects through the matrix the pyramid it reads was drawn with.
1493        let previous_view_projection = self.previous_view_projection;
1494        // One matrix, used twice. Recomputing it for the frustum below would be
1495        // two chances to pass a different aspect ratio, and the failure that
1496        // produces — geometry culled against a camera the frame does not draw
1497        // with — is invisible until something at the edge of the screen
1498        // disappears.
1499        let view_projection = camera.view_projection(frame.aspect);
1500        // What this frame draws here, frozen for the reason the frame's own
1501        // effects are: this call and the passes have to agree. The shadow bit is
1502        // the frame's whatever this view asked for — see [`ViewDesc::effects`] —
1503        // and the effects that bring the frame's light in are this view's
1504        // lighting's to take away — see [`ViewLighting::SCENE_EFFECTS`].
1505        self.frame_effects = frame
1506            .effects
1507            .intersection(self.effects.union(RenderEffects::SHADOWS))
1508            .difference(self.lighting.dropped_effects());
1509        // What lights this view: the frame's sun, rows, probes, sky, fog and
1510        // shadow maps, or the one constant light its description fixed and
1511        // nothing of the frame's. Resolved once here so every block below reads
1512        // the same answer — a sun taken from one and a fill from the other
1513        // would be a view lit by half of each.
1514        //
1515        // **A fixed view's atlas rectangles are all empty**, which is how its
1516        // key light goes unshadowed with no shader of its own: every sampler of
1517        // the atlas answers lit for an empty rectangle before it reads a texel
1518        // (`mesh.slang`'s `atlas_rect_is_empty`), and the key is the view's only
1519        // row, so nothing else could name a tile.
1520        //
1521        // **A fixed view's environment is the sky its reflections see**, and
1522        // only its reflections: the gradient the march falls back to, with all
1523        // three bands the one radiance and no atmosphere, while the frame
1524        // block's L1 sky — the diffuse half — stays zero, so the fill is the
1525        // whole diffuse ambient. A uniform gradient is that radiance along
1526        // every direction and, to rounding, under every lobe the march
1527        // prefilters. The background pass keeps the frame's gradient: the
1528        // view's background is [`ViewDesc::background`]'s, not its lighting's.
1529        let key_row;
1530        let (light, rows, probe_volume, sky, fog, atlas_rects, reflected, reflected_air) =
1531            match self.lighting {
1532                ViewLighting::Scene => (
1533                    scene.light,
1534                    &scene.rows[..],
1535                    frame.probe_volume,
1536                    frame.sky_irradiance,
1537                    frame.fog,
1538                    scene.atlas_rects,
1539                    frame.gradient,
1540                    sky_view,
1541                ),
1542                ViewLighting::Fixed { key, environment } => {
1543                    key_row = [sun_row(&key)];
1544                    let band = environment.to_array();
1545                    (
1546                        key,
1547                        &key_row[..],
1548                        crcbl_shaders::probe::ProbeVolume::default(),
1549                        crcbl_shaders::probe::GpuProbe::ZERO,
1550                        Fog::NONE,
1551                        [[0.0; 4]; shadow::TILES],
1552                        crcbl_shaders::sky::SkyGradient {
1553                            zenith: band,
1554                            horizon: band,
1555                            ground: band,
1556                        },
1557                        None,
1558                    )
1559                }
1560            };
1561        self.begun = frame.serial;
1562        // The same matrix again for the ground grid, whose pass `add_passes`
1563        // records and which has no camera to ask.
1564        self.camera_view_proj = view_projection;
1565        // Topic 25's two selection numbers, from this frame's
1566        // viewport and this frame's camera. An orthographic projection has no
1567        // distance falloff for the metric to divide by, so it selects under a
1568        // budget nothing satisfies and draws the base level whole — see
1569        // [`LOD_BUDGET_NONE`].
1570        let lod_scale = camera.projection.pixels_per_unit(extent.1 as f32);
1571        let lod_budget = if camera.projection.is_orthographic() {
1572            LOD_BUDGET_NONE
1573        } else {
1574            frame.lod_error_budget
1575        };
1576        self.lod_params = [lod_scale, lod_budget, lod_budget * frame.lod_hold_ratio];
1577
1578        // The grid this frame's viewport and camera get. An orthographic camera
1579        // has no view depth to slice by — its `clip.w` is 1 everywhere — so it
1580        // runs with one slice, which `light_cluster.slang` builds a different
1581        // way rather than pretending it is a perspective frustum.
1582        let perspective = !camera.projection.is_orthographic();
1583        self.grid = Grid::for_frame(extent, perspective, self.lights.froxel_capacity());
1584        self.lights.begin_frame(
1585            device,
1586            slot,
1587            rows,
1588            self.grid,
1589            FrameView {
1590                extent,
1591                view_projection,
1592                eye: camera.eye,
1593                perspective,
1594            },
1595        )?;
1596        // The froxel volume's block: the same grid, the same camera and the
1597        // medium. **The same `Grid` value the clustering pass was just given**,
1598        // not a second `Grid::for_frame` — the composite converts a pixel to a
1599        // froxel index with these numbers, and two grids would have it read a
1600        // column built for somewhere else.
1601        //
1602        // Written whether or not this frame adds the passes, on every other
1603        // block's terms: one written only on the frames that draw is stale on
1604        // the frame a caller first switches the effect on.
1605        self.volumetric.begin_frame(
1606            device,
1607            slot,
1608            self.grid,
1609            FrameView {
1610                extent,
1611                view_projection,
1612                eye: camera.eye,
1613                perspective,
1614            },
1615            Medium {
1616                fog: frame.fog,
1617                sun: &scene.light,
1618                cascades: &scene.cascades,
1619                light_view_proj: &scene.light_view_proj,
1620                atlas_rects: &scene.atlas_rects,
1621                local: self.frame_effects.contains(RenderEffects::VOLUMETRIC_FOG),
1622                // The air follows the view's lighting, as the reflected sky
1623                // does: a fixed view is lit by nothing of the frame's, and the
1624                // atmosphere is the frame's.
1625                aerial: reflected_air.map(|presented| presented.view.sun_direction()),
1626            },
1627        )?;
1628        self.frame_aerial = reflected_air.is_some();
1629        self.frame_ssr_extent = crate::ssr::march_extent(extent, crate::ssr::resolution_scale());
1630
1631        let gradient = frame.gradient;
1632        let uniforms = mesh::FrameUniforms {
1633            view_proj: view_projection.to_cols_array(),
1634            camera_position: camera.eye.extend(1.0).to_array(),
1635            // The ambient's `w` is the normals view's switch — see
1636            // `set_normals_view` and the constants it names. A renderer nobody
1637            // has called that on writes the `0.0` this line has always written,
1638            // which is what makes every golden image untouched by the feature.
1639            ambient: light.ambient.extend(frame.debug_view_lane).to_array(),
1640            // **The frame's cascades, whichever camera this is.** They were
1641            // fitted to the primary camera and drawn once; a secondary view
1642            // samples the same maps through the same matrices, which is
1643            // `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
1644            shadow_view_proj: scene.shadow_view_proj,
1645            cascade_far: scene.cascades.far,
1646            shadow_params: Cascades::params(),
1647            cluster_grid: self.grid.to_frame_block(),
1648            light_view_proj: scene.light_view_proj,
1649            // The scene's grid, unchanged since `with_scene` read it: the
1650            // probes are static and nothing here varies them per frame. A
1651            // description with no probes leaves the default, which evaluates to
1652            // exactly zero in the shader.
1653            probes: probe_volume,
1654            // The very numbers the draw-argument pass selected under, carried
1655            // into the geometry stage so the screen-error heatmap shades by the
1656            // metric the cut was chosen with rather than by a second derivation
1657            // of it. `w` is padding — the block's rows are sixteen bytes wide
1658            // whatever is in them.
1659            lod_params: [
1660                self.lod_params[0],
1661                self.lod_params[1],
1662                self.lod_params[2],
1663                0.0,
1664            ],
1665            // `w` is padding on both rows — the block's rows are sixteen bytes
1666            // wide whatever is in them. A renderer nobody called `set_fog` on
1667            // writes a zero density here, which the fragment stage composites
1668            // as the identity.
1669            //
1670            // **Zeroed on a frame that runs the froxel volume**, which
1671            // integrates the same medium along the same rays: leaving it would
1672            // charge the air twice, once here and once in
1673            // `volumetric_composite.slang`, and the frame would be plausibly
1674            // over-fogged rather than wrong in a way anything reports. See
1675            // [`RenderEffects::VOLUMETRIC_FOG`].
1676            fog_params: [
1677                if self.frame_effects.contains(RenderEffects::VOLUMETRIC_FOG) {
1678                    0.0
1679                } else {
1680                    fog.density
1681                },
1682                fog.falloff,
1683                fog.reference_height,
1684                0.0,
1685            ],
1686            fog_color: fog.color.extend(0.0).to_array(),
1687            sky_sh_r: sky.sh_r,
1688            sky_sh_g: sky.sh_g,
1689            sky_sh_b: sky.sh_b,
1690            // **Last frame's camera, and this frame's on the first frame** —
1691            // see the field, which says why the fallback is this matrix rather
1692            // than the identity.
1693            previous_view_proj: self
1694                .previous_view_projection
1695                .unwrap_or(view_projection)
1696                .to_cols_array(),
1697            // Where the pool's attribute region begins, which is the one thing
1698            // about topic 43 §2's two streams that a
1699            // shader cannot derive: it is the pool's *capacity*, and a shader
1700            // has never been told that. Fixed for the life of the pool and
1701            // written every frame anyway, because this is the block that
1702            // carries it and there is no cheaper place. `yzw` are padding.
1703            vertex_pool: [frame.attribute_base, 0, 0, 0],
1704            // Where each atlas slot's map went, out of the allocator
1705            // `shadow::Selection::update` just spent — the *whole* of what the
1706            // sampling side knows about the atlas's shape, so a map is read
1707            // from the rectangle it was rendered into whatever size that was.
1708            // None at all on a fixed view — see `atlas_rects` above.
1709            shadow_atlas_rect: atlas_rects,
1710            // Which filter each side of the comparison seam samples through,
1711            // and where the seam falls — see `crate::split`, whose header
1712            // carries why a scene pass selects per pixel where a full-screen
1713            // effect records itself twice.
1714            //
1715            // **The column comes from `split::halves`' left rectangle** rather
1716            // than from a second multiplication here, so the seam module stays
1717            // the one place a fraction becomes a column: a frame comparing
1718            // nothing carries the console's own filter in both lanes and a zero
1719            // column, which is a row of zeroes at the default and therefore the
1720            // frame every golden was blessed as.
1721            shadow_filter: {
1722                let near = shadow::filter().mode();
1723                let seam = shadow::split_at().and_then(|at| crate::split::halves(extent, at));
1724                let (far, column) = seam.map_or((near, 0), |(left, _)| {
1725                    (shadow::shipped_filter().mode(), left.width)
1726                });
1727                [near, far, column, 0]
1728            },
1729        };
1730        // Advanced here, between writing the block that reads it and anything
1731        // else that could look at it: this runs exactly once per
1732        // `InstancePool::rotate` for a view that is drawn every frame, so the
1733        // camera's history moves on the same frame boundary the instances' does.
1734        // See the field.
1735        self.previous_view_projection = Some(view_projection);
1736        device.write_buffer(self.uniforms[slot], 0, &uniforms.to_bytes())?;
1737
1738        // The extent auto-exposure bins, which is the internal one — the
1739        // histogram reads the scene target, not the caller's window.
1740        //
1741        // Written whether or not this frame adds the passes, on every other
1742        // block's terms: one written only on the frames that measure is stale on
1743        // the frame a caller first switches the effect on.
1744        self.auto_exposure
1745            .begin_frame(device, slot, extent, frame.exposure_adaptation)?;
1746
1747        // The tonemap's one number, written here rather than in `add_passes` for
1748        // every other block's reason: a pass body runs at execute time, and the
1749        // buffer it reads has to have been written before the frame was
1750        // submitted.
1751        device.write_buffer(
1752            self.tonemap_uniforms[slot],
1753            0,
1754            &tonemap::TonemapParams {
1755                exposure: frame.exposure,
1756                // **Resolved rather than requested**, on `resolved_effects`'
1757                // terms: a readout view runs the clamp whatever the caller set,
1758                // because its pixels are data — see `resolved_tonemap_curve`.
1759                curve: frame.tonemap_curve,
1760                // **The switch, and it is this view's effects rather than the
1761                // caller's request**: a device that refused the effect draws the
1762                // frame with the number a caller set, and reading a buffer no
1763                // pass wrote would be reading whatever the last frame in this
1764                // slot left there.
1765                auto_exposure: self.frame_effects.contains(RenderEffects::AUTO_EXPOSURE),
1766                // The frame's coverage into the target's alpha on a transparent
1767                // view, and the opaque one every other view writes — see
1768                // [`ViewBackground::Transparent`].
1769                coverage_alpha: self.background.is_transparent(),
1770            }
1771            .to_bytes(),
1772        )?;
1773
1774        // Topic 46's occlusion block. **The projection
1775        // alone, not the view-projection**: the occlusion integral asks what is
1776        // near a surface, and view space is where "near" is isotropic and the eye
1777        // is at the origin — a world-space reconstruction would put the camera
1778        // somewhere else every frame and the hemisphere would have to be rotated
1779        // into it for no gain.
1780        //
1781        // `inverse` here rather than a hand-derived unprojection: an infinite
1782        // reversed-Z perspective and a reversed orthographic box do not share a
1783        // closed form, and the two matrices this pass needs are then provably
1784        // each other's inverse rather than two derivations that agree today.
1785        let projection = camera.projection.matrix(frame.aspect);
1786        let inv_projection = projection.inverse();
1787        self.ssao.begin_frame(
1788            device,
1789            slot,
1790            ssao::SsaoParams {
1791                inv_proj: inv_projection.to_cols_array(),
1792                proj: projection.to_cols_array(),
1793                // View → world, for the bent direction alone: the gather works
1794                // in view space and its one output has to reach `mesh.slang`'s
1795                // world-space ambient term. The same expression the reflection
1796                // pass's block carries, a few lines below.
1797                inv_view: camera.view().inverse().to_cols_array(),
1798                radius: crate::ssao::radius(),
1799                slices: crate::ssao::slice_count(),
1800                intensity: crate::ssao::intensity(),
1801                bent_normals: crate::ssao::bent_normals(),
1802            },
1803        )?;
1804        // The contact march's block: the same two matrices, and the sun in view
1805        // space.
1806        //
1807        // **Rotated here rather than in the shader**, because the shader has no
1808        // view matrix and no world-space anything: it walks a view-space ray in
1809        // screen space, so the one rotation the frame needs happens once on the
1810        // host instead of once per covered pixel. `Mat4::transform_vector3`
1811        // takes the direction through the rotation and drops the translation,
1812        // which is what a direction wants.
1813        //
1814        // `normalize_or_zero` for `sun_row`'s reason: a caller may hand this a
1815        // zero direction, and the march reads a zero as "the sun is along the
1816        // view axis at every pixel" and reports lit — which is the frame a
1817        // scene with no sun should draw.
1818        let to_light = camera
1819            .view()
1820            .transform_vector3(light.direction.normalize_or_zero())
1821            .normalize_or_zero();
1822        self.contact_shadows.begin_frame(
1823            device,
1824            slot,
1825            contact_shadows::ContactShadowParams {
1826                inv_proj: inv_projection.to_cols_array(),
1827                proj: projection.to_cols_array(),
1828                to_light: to_light.to_array(),
1829            },
1830        )?;
1831        // The reflection march's block: the same two matrices and nothing else.
1832        // Its own buffer rather than the pair's — see [`crate::ssr::Ssr`] — and
1833        // the same pair of `glam` values, so a march and an occlusion sample can
1834        // never be looking at two different cameras.
1835        self.ssr.begin_frame(
1836            device,
1837            slot,
1838            ssr::SsrParams {
1839                inv_proj: inv_projection.to_cols_array(),
1840                proj: projection.to_cols_array(),
1841                inv_view: camera.view().inverse().to_cols_array(),
1842                probe_volume,
1843                // How far up the pyramid the march may climb, which is the
1844                // pyramid this extent has — `add_passes` records the reduction
1845                // whenever it records the march, so the two never disagree. A
1846                // frame too small to halve gets zero, and the march walks the
1847                // prepass at full resolution.
1848                hiz_levels: crate::hiz::levels_for(extent),
1849                // The image the march writes, which `add_passes` creates at
1850                // this same frozen extent.
1851                march_extent: [self.frame_ssr_extent.0, self.frame_ssr_extent.1],
1852                // The gradient itself rather than the projection the frame
1853                // block carries: this pass wants the radiance along one
1854                // direction and `Sky::gradient` is what has it exactly. A
1855                // renderer nobody called `set_sky` on writes three zero rows,
1856                // which the march adds to its probe fallback and changes
1857                // nothing. A fixed view's is its environment — see `reflected`
1858                // above.
1859                sky: reflected.rows(),
1860                // And the arm, on the background pass's terms below: an
1861                // atmosphere frame hands the march the sun its LUT was built
1862                // around, and every other frame — a fixed view's included —
1863                // the exactly-zero `w` that leaves `ssr.slang` evaluating the
1864                // gradient it always did.
1865                atmosphere: match reflected_air {
1866                    Some(presented) => {
1867                        let sun = presented.view.sun_direction();
1868                        [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON]
1869                    }
1870                    None => [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
1871                },
1872            },
1873        )?;
1874        // The background pass's block: the same two inverses `SsrParams` above
1875        // carries and the same three gradient rows, so a reflection that missed
1876        // and the sky behind it cannot be looking at two different skies.
1877        // Written whether or not this frame adds the pass, on the blocks below's
1878        // terms — a block written only on the frames that draw one is stale on
1879        // the frame a caller first calls `set_sky`.
1880        self.sky_pass.begin_frame(
1881            device,
1882            slot,
1883            inv_projection.to_cols_array(),
1884            camera.view().inverse().to_cols_array(),
1885            &gradient,
1886            sky_view.map(|presented| &presented.view),
1887        )?;
1888        // The water surface's own block: the sun its scattering is lit by and
1889        // whether this frame's air is the froxel column's. Written whether or
1890        // not the frame has water, on the blocks above's terms. The sun is
1891        // normalised on `sun_row`'s terms — a caller may hand the renderer any
1892        // vector, and the shader reads this as a unit direction.
1893        self.water.begin_frame(
1894            device,
1895            slot,
1896            crcbl_shaders::water::WaterParams {
1897                sun_direction: light.direction.normalize_or_zero().extend(0.0).to_array(),
1898                sun_color: light.color.extend(0.0).to_array(),
1899                froxels: self.frame_effects.contains(RenderEffects::VOLUMETRIC_FOG),
1900            },
1901        )?;
1902        // The grass field's two blocks: the generation pass's, whose camera is
1903        // this view's, and the wind's, which the renderer holds for the whole
1904        // frame. Written whether or not the frame has a field, on the block
1905        // above's terms.
1906        self.grass.begin_frame(
1907            device,
1908            slot,
1909            frame
1910                .grass
1911                .as_ref()
1912                .map_or_else(Default::default, |grass| grass.gen_params(camera.eye)),
1913            frame.wind,
1914            crcbl_shaders::grass::Params {
1915                limits: [
1916                    crate::grass::SLOT_CAPACITY,
1917                    frame
1918                        .grass
1919                        .as_ref()
1920                        .map_or(1, crate::grass::GrassFrame::rows),
1921                    0,
1922                    0,
1923                ],
1924                // **How many pixels a metre spans at one unit of view depth.**
1925                // The projection's own `x` scale is `1 / (aspect · tan(fov/2))`
1926                // for a perspective camera and `1 / half-width` for an
1927                // orthographic one, and half the viewport's width takes a
1928                // normalised-device length to pixels — so a card of `w` metres
1929                // at a view depth of `d` is `w · this / d` pixels across, which
1930                // is exactly what `grassCardLevel` reads. Taken off the very
1931                // matrix this frame draws with rather than from the camera's
1932                // own fields, so a projection this view resolved differently
1933                // cannot disagree with it.
1934                screen: [
1935                    view_projection.x_axis.x * 0.5 * extent.0 as f32,
1936                    0.0,
1937                    0.0,
1938                    0.0,
1939                ],
1940            },
1941        )?;
1942        // The bloom chain's blocks, one row per step: each step needs the texel
1943        // size of the image it reads, and the chain's shape is a function of the
1944        // extent alone. Written whether or not the chain is in this frame, on
1945        // the two blocks above's terms — a row nobody reads costs sixteen bytes.
1946        self.bloom.begin_frame(device, slot, extent)?;
1947        // The resolve's block: the reciprocal of the extent and three constants.
1948        // Written on the chain's terms above — a frame that adds no resolve pays
1949        // for twenty bytes nobody reads, and a block written only on the frames
1950        // that use it is a block that is stale on the frame a caller switches
1951        // the effect on.
1952        self.fxaa.begin_frame(device, slot, extent)?;
1953        // The higher tier's block: the extent and the two list capacities it
1954        // implies, written on the resolve's terms above. Sixteen bytes, and a
1955        // frame that resolves through the other tier pays for them and reads
1956        // none.
1957        self.cmaa2.begin_frame(device, slot, extent)?;
1958        // The upscale's block: the internal extent and its reciprocal. Written
1959        // on the two above's terms — a frame at full scale adds no upscale pass
1960        // and pays for sixteen bytes nobody reads, and a block written only on
1961        // the frames that use it is stale on the frame a caller moves the knob.
1962        self.upscale.begin_frame(device, slot, extent)?;
1963
1964        // The camera and the two selection numbers go to the cull/draw-argument
1965        // pair as well as into the block above, and they are handed over rather
1966        // than re-derived: topic 25's uniform cut runs there, the
1967        // mesh path's per-cluster descent runs off the block, and a frame that
1968        // selected detail against one camera while drawing with another is a
1969        // difference nothing in the frame can see.
1970        //
1971        // **The eye is the selection's**, which is the camera's unless a caller
1972        // pinned the primary camera's — `set_frozen_selection_eye`, and the
1973        // whole of what that feature is. It reaches this parameter block and
1974        // nothing else: the frustum handed over with it is extracted from this
1975        // frame's own view-projection, and the frame block written above carries
1976        // `camera.eye`, so a pinned selection changes which cut is chosen and
1977        // nothing about what is culled, faced or drawn.
1978        //
1979        // **And what the cull does beyond the frustum.** The pyramid is made to
1980        // match this frame's extent first — a resize replaces it and forgets
1981        // its history — and a frame with no pyramid to read culls by the
1982        // frustum alone, which is what a one-texel target gets.
1983        let history = self.occlusion_pyramid.take_history(extent);
1984        let cull = match self.draws.occlusion_layout() {
1985            Some(layout) if frame.occlusion.any() => {
1986                self.occlusion_pyramid.prepare(device, extent, layout)?;
1987                if self.occlusion_pyramid.cull_group().is_some() {
1988                    FrameCull::Occlusion(OcclusionFrame {
1989                        view_projection,
1990                        previous_view_projection: previous_view_projection
1991                            .unwrap_or(view_projection),
1992                        target: extent,
1993                        pyramid_levels: self.occlusion_pyramid.levels(),
1994                        occlusion: frame.occlusion.occlusion,
1995                        // A first frame has no previous camera, and a chain
1996                        // just rebuilt holds nothing.
1997                        history: history && previous_view_projection.is_some(),
1998                        small_feature_pixels: frame.occlusion.small_feature_pixels,
1999                    })
2000                } else {
2001                    FrameCull::Plain
2002                }
2003            }
2004            _ => FrameCull::Plain,
2005        };
2006        self.draws.begin_frame_with(
2007            device,
2008            slot,
2009            &Frustum::from_view_projection(view_projection),
2010            frame.instance_count,
2011            crate::draw_gen::Selection {
2012                camera_position: [
2013                    frame.selection_eye.x,
2014                    frame.selection_eye.y,
2015                    frame.selection_eye.z,
2016                ],
2017                lod_params: self.lod_params,
2018            },
2019            &cull,
2020        )?;
2021        Ok(uniforms)
2022    }
2023
2024    /// Records this view's cull and draw-argument dispatches and the light
2025    /// clustering after them — the passes every other pass of the view reads.
2026    ///
2027    /// Separate from [`View::add_passes`] because the primary camera records
2028    /// these before the shadow atlas, which is where they always ran, and a
2029    /// secondary view records them straight before the rest of its frame.
2030    pub(super) fn add_cull(
2031        &self,
2032        graph: &mut RenderGraph<'_>,
2033        pool: &TransientPool,
2034        slot: usize,
2035        instance_count: u32,
2036    ) -> ViewCull {
2037        // The cull dispatch and the draw-argument dispatch, before anything
2038        // draws. Every barrier between them and the passes that draw — including
2039        // the one into `IndirectArgument` — is the graph's, computed from what
2040        // each pass declares.
2041        //
2042        // **Through the occlusion entry point** on a frame `begin_frame` began
2043        // with occlusion or small-feature culling, reading the pyramid the last
2044        // frame left: `DrawGen::begin_frame_with` recorded which.
2045        let occlusion_group = self
2046            .occlusion_pyramid
2047            .cull_group()
2048            .filter(|_| self.draws.uses_occlusion_entry(slot));
2049        let (generated, pyramid) = match occlusion_group {
2050            Some(group) => {
2051                let levels = self.occlusion_pyramid.import(graph, pool);
2052                let generated = self.draws.add_occlusion_passes(
2053                    graph,
2054                    slot,
2055                    instance_count,
2056                    &crate::draw_gen::PyramidInputs {
2057                        levels: &levels,
2058                        group,
2059                    },
2060                );
2061                let two_phase =
2062                    self.draws.frame_mode(slot) == crcbl_shaders::draw_gen::DrawMode::Occlusion;
2063                (
2064                    generated,
2065                    two_phase.then_some(ViewPyramid { levels, group }),
2066                )
2067            }
2068            None => (self.draws.add_passes(graph, slot, instance_count), None),
2069        };
2070        // Topic 25's record of the view's cut. Written by exactly
2071        // one mesh pass of this view, so what the graph orders here is this
2072        // frame's write against the next frame's use of the same slot.
2073        let selection = self
2074            .cluster_selection
2075            .get(slot)
2076            .map(|&buffer| import_read_write(graph, "cluster-selection", buffer));
2077        // Topic 18's clustering, **after the pair above and before anything
2078        // draws**. After, because the clearing dispatch is what zeroes the
2079        // overflow counter this pass adds to, and the two are ordered by the
2080        // graph out of the one id they both declare — which is why `stats` is
2081        // the id the draw generator handed back rather than a second import of
2082        // the same buffer. It has no other dependency on the cull: lights are
2083        // assigned to froxels, and a froxel is a property of the camera.
2084        let light_grid = self
2085            .lights
2086            .add_pass(graph, slot, generated.visible_count_id, self.grid);
2087        ViewCull {
2088            generated,
2089            selection,
2090            light_grid,
2091            pyramid,
2092            instance_count,
2093        }
2094    }
2095
2096    /// Records this view's frame: its prepass, the screen-space passes, the
2097    /// forward pass and every pass after it, ending in `target`.
2098    ///
2099    /// `output` is where the frame ends and how large it is drawn; `cull` is
2100    /// what [`View::add_cull`] recorded for this frame. The scene's passes — the
2101    /// skinning dispatch, the shadow atlas and the probe gather — are already
2102    /// in `graph`, and `passes` names what they left behind.
2103    ///
2104    /// Returns the image the tonemap read, which is the HDR frame before the
2105    /// operator.
2106    pub(super) fn add_passes<'a, F>(
2107        &'a mut self,
2108        graph: &mut RenderGraph<'a>,
2109        passes: &FramePasses,
2110        cull: ViewCull,
2111        output: ViewOutput,
2112        overlays: Overlays<'a>,
2113        overlay: F,
2114    ) -> ImageId
2115    where
2116        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
2117    {
2118        let ViewOutput {
2119            target,
2120            target_extent,
2121            extent,
2122        } = output;
2123        let frame = passes.slot;
2124        // What this frame draws in this view, frozen by `begin_frame` — see
2125        // [`View::frame_effects`]. Read once here so every conditional below is
2126        // about one value rather than about a read of a field each.
2127        let effects = self.frame_effects;
2128        let upscaling = extent != target_extent;
2129        let ViewCull {
2130            generated,
2131            selection,
2132            light_grid,
2133            pyramid: culled_pyramid,
2134            instance_count,
2135        } = cull;
2136        let emit = passes.emit;
2137        let skinned = passes.skinned;
2138        // The frame's sky, on every view but a transparent one — whose
2139        // background is the empty one it clears to. See
2140        // [`ViewBackground::Transparent`].
2141        let transparent = self.background.is_transparent();
2142        let draws_sky = passes.draws_sky && !transparent;
2143        // The table the reflection march and the water surface fall back to:
2144        // the scene's, or a fixed view's zeroed row — the one its forward
2145        // groups were built naming, see [`View::fixed_probes`]. The graph read
2146        // stays the scene's slot, which the frame wrote either way.
2147        let probe_buffer = self.fixed_probes.unwrap_or(passes.probe_buffer);
2148        let probe_table = passes.probe_table;
2149        let occlusion_placeholder = passes.occlusion_placeholder;
2150        let contact_placeholder = passes.contact_placeholder;
2151        let shadow_atlas = passes.shadow_atlas;
2152        let MaterialPages {
2153            base_color: base_color_page,
2154            normal: normal_page,
2155            mro: mro_page,
2156            emissive: emissive_page,
2157        } = passes.pages;
2158        let wireframe = passes.wireframe;
2159        let prepass_partitions = passes.prepass_partitions.clone();
2160        let color_partitions = passes.color_partitions.clone();
2161        let group = self.mesh_groups[frame];
2162
2163        let scene_color = graph.create_image("scene-color", crate::targets::scene_color(extent));
2164        let scene_depth = graph.create_image("scene-depth", crate::targets::scene_depth(extent));
2165        // The occlusion chain's transients, and **every one of them is
2166        // conditional**: a transient nothing reads or writes is a physical image
2167        // taken out of the pool for a pass that does not exist. What the forward
2168        // pass binds when they are absent is the 1×1 placeholder — see the pair
2169        // below.
2170        //
2171        // **Three of the four are at [`crate::ssao::half_extent`]**, which is
2172        // where the march and the blurs run — see that module's header. Only the
2173        // reconstruction's target is the scene's own size, because it is the
2174        // image `mesh.slang` reads at `SV_Position`.
2175        //
2176        // The blur's target is requested first, which is the order the two were
2177        // requested in when only one of them was conditional. The pool hands out
2178        // physical images in request order, and an AO-on frame has to be the
2179        // frame it was before this became a chain.
2180        let occlusion_chain = effects.contains(RenderEffects::AMBIENT_OCCLUSION).then(|| {
2181            let gathered = crate::ssao::half_extent(extent);
2182            let blurred =
2183                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
2184            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
2185            // The second blur's target, and requested **last of the small ones**
2186            // so the two above keep the physical images they had before this one
2187            // could be asked for — the pool hands them out in request order, and
2188            // a frame at the default switch has to be the frame it was.
2189            let again = (passes.ssao_blurs > 1).then(|| {
2190                graph.create_image(
2191                    "ssao-blurred-2",
2192                    crate::targets::ambient_occlusion(gathered),
2193                )
2194            });
2195            // The reconstruction's target, and the only one of these at the
2196            // scene's extent. Requested after the small ones for their reason
2197            // inverted: it is a different description, so it could not have
2198            // aliased them whatever the order, and asking for it last leaves
2199            // every request before it where it was.
2200            let upsampled =
2201                graph.create_image("ssao-upsampled", crate::targets::ambient_occlusion(extent));
2202            crate::ssao::OcclusionImages {
2203                raw,
2204                blurred,
2205                again,
2206                upsampled,
2207            }
2208        });
2209        // The contact march's one transient, conditional for the occlusion
2210        // pair's reason: an image nothing reads or writes is a physical image
2211        // out of the pool for a pass that does not exist. Requested **after**
2212        // the pair so that a frame with contact shadows off keeps the physical
2213        // images it had before this rung existed — the pool hands them out in
2214        // request order.
2215        let contact_mask = effects.contains(RenderEffects::CONTACT_SHADOWS).then(|| {
2216            graph.create_image("contact-shadows", crate::targets::contact_shadows(extent))
2217        });
2218        // **Created whatever the reflections are doing**, unlike the pair above.
2219        // It is one of the forward pass's colour attachments, which is in that
2220        // pipeline whether or not anything reads what it wrote — see the
2221        // `clear_color` on it below.
2222        let reflectivity = graph.create_image("reflectivity", crate::targets::reflectivity(extent));
2223        // **Created whatever else the frame is doing**, on the reflectivity
2224        // attachment's terms exactly: it is the forward pass's third colour
2225        // attachment, which is in that pipeline whether or not anything reads
2226        // what it wrote. Nothing does yet — TAA (`docs/backlog.md`) is the
2227        // first pass that will, and until then `DebugView::Motion`
2228        // is what observes the subtraction.
2229        let motion = graph.create_image("motion", crate::targets::motion(extent));
2230        // The march's output and the blur's, both in the scene target's format:
2231        // the blur writes the scene colour plus a term, so a narrower image
2232        // there would tonemap a truncated frame, and the march writes a
2233        // reflection *out of* that same colour, so an eight-bit image here would
2234        // clip the frame's bright end before the tonemap saw it. The march runs
2235        // at the extent `begin_frame` froze (`crate::ssr::march_extent`), which
2236        // is the scene's own at full resolution — and then three live requests
2237        // for one description are three physical images, see
2238        // `TransientPool::image`. The composite stays at the scene extent
2239        // because it replaces the scene colour from here on.
2240        let reflected = effects.contains(RenderEffects::REFLECTIONS).then(|| {
2241            (
2242                graph.create_image(
2243                    "reflection",
2244                    crate::targets::scene_color(self.frame_ssr_extent),
2245                ),
2246                graph.create_image("scene-reflected", crate::targets::scene_color(extent)),
2247            )
2248        });
2249        // Where the froxel volume's composite writes, conditional on the effect
2250        // for the reflection pair's reason exactly: an image nobody reads or
2251        // writes is a physical image taken out of the pool for a pass that does
2252        // not exist. It is the scene target's description, because it stands in
2253        // for that image from here on.
2254        //
2255        // **The fog effect or an atmosphere**: the composite is also what puts
2256        // the air in front of the scene — see [`crate::volumetric`] — so a
2257        // frame with an atmosphere composites whether or not its fog does.
2258        let fogged = (effects.contains(RenderEffects::VOLUMETRIC_FOG) || self.frame_aerial)
2259            .then(|| graph.create_image("scene-fogged", crate::targets::scene_color(extent)));
2260        // The Hi-Z pyramid's levels, **conditional on the march** that is the
2261        // only thing that reads them: an image nobody samples is a physical
2262        // image out of the pool for a pass that does not exist. Level 0 is the
2263        // prepass itself and is not in this list.
2264        //
2265        // Empty on a target too small to halve, which is a frame the march walks
2266        // at full resolution — `crate::hiz::levels_for` carries that floor, and
2267        // `SsrParams::hiz_levels` is what tells the shader about it.
2268        let pyramid: Vec<ImageId> = if reflected.is_some() {
2269            (1..=crate::hiz::levels_for(extent))
2270                .map(|level| {
2271                    graph.create_image(
2272                        format!("hiz-{level}"),
2273                        crate::targets::hiz_level(crate::hiz::level_extent(extent, level)),
2274                    )
2275                })
2276                .collect()
2277        } else {
2278            Vec::new()
2279        };
2280        // The bloom chain's levels and the image its composite writes, and
2281        // **all of them are conditional** on the pair above's terms exactly: a
2282        // transient nothing reads or writes is a physical image taken out of the
2283        // pool for a pass that does not exist.
2284        //
2285        // `None` covers two cases that are one case downstream — the toggle is
2286        // off, or the target is too small for even one level of chain (see
2287        // [`crate::bloom`]) — and in both the tonemap reads whatever it would
2288        // have read before, which is what makes this effect's off-switch
2289        // bit-identical.
2290        //
2291        // The levels are requested largest first, which is the order the
2292        // downsample chain writes them in. The composite's target is the scene
2293        // target's description exactly — it stands in for that image from here
2294        // on, so a narrower one would tonemap a truncated frame — which makes it
2295        // a fourth live request for that description on a frame that also
2296        // reflects, and therefore a fourth distinct physical image out of the
2297        // pool. See `TransientPool::image`.
2298        let bloomed = effects
2299            .contains(RenderEffects::BLOOM)
2300            .then(|| crate::bloom::mips_for(extent))
2301            .filter(|levels| *levels > 0)
2302            .map(|levels| {
2303                let mips: Vec<ImageId> = (1..=levels)
2304                    .map(|level| {
2305                        graph.create_image(
2306                            format!("bloom-mip-{level}"),
2307                            crate::targets::bloom_mip(crate::bloom::mip_extent(extent, level)),
2308                        )
2309                    })
2310                    .collect();
2311                (
2312                    mips,
2313                    graph.create_image("bloom-color", crate::targets::scene_color(extent)),
2314                )
2315            });
2316        // Where the tonemap writes, and it is the caller's `target` on every
2317        // frame that adds no resolve.
2318        //
2319        // **This is the one effect that changes the shape of the frame rather
2320        // than adding a pass to it** — see [`crate::fxaa`]. The resolve reads
2321        // what the tonemap wrote, so the tonemap has to write something the
2322        // resolve can sample, and a swapchain image is not that. So with the bit
2323        // on the tonemap writes a transient of the target's own description and
2324        // the resolve writes the target; with it off the tonemap writes the
2325        // target and there is no second image at all, which is what makes this
2326        // effect's off-switch bit-identical on the three above's terms.
2327        // Where the last pass of the internal frame writes, and it is the
2328        // caller's `target` on every frame drawn at full render scale.
2329        //
2330        // **This is the second effect in the frame that changes its shape rather
2331        // than adding a pass to it** — see [`crate::upscale`], and the resolve
2332        // below for the first. The upscale reads what the internal frame ended
2333        // with, so that last write has to go somewhere it can sample, and a
2334        // swapchain image at the caller's own extent is not it. So with the
2335        // scale below one the chain ends in a transient at the *internal*
2336        // extent and the upscale writes the target; at full scale there is no
2337        // second image at all, which is what makes the knob's off position
2338        // bit-identical.
2339        let present = if upscaling {
2340            graph.create_image(
2341                "render-scale-color",
2342                crate::targets::display_color(extent, passes.target_format),
2343            )
2344        } else {
2345            target
2346        };
2347        //
2348        // **Two tiers share that slot and at most one fills it** — see
2349        // [`RenderEffects::CMAA2`], which is where "never both" is written down.
2350        // The shape above is the same either way; what differs is what the
2351        // resolve reads besides the tonemap's image. CMAA2's two working
2352        // buffers are declared inside its own pass group rather than here,
2353        // where the tier it replaced declared two images: they are buffers,
2354        // and [`crate::cmaa2`]'s header says why the graph owns them all the
2355        // same.
2356        let resolving = effects.intersects(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2));
2357        let display = if resolving {
2358            graph.create_image(
2359                "display-color",
2360                crate::targets::display_color(extent, passes.target_format),
2361            )
2362        } else {
2363            present
2364        };
2365        // --- the depth prepass ---
2366        //
2367        // Topic 46's prepass, and it is unusually cheap:
2368        // the depth-only pipeline is already the shadow cascades' own, built from
2369        // the same modules and the same layout as the colour pipeline, so driven
2370        // with the camera's draws and a copy of the camera's bind group it *is* a
2371        // scene depth prepass — no new pipeline and no new shader. On a frame
2372        // whose material table masks nothing it is `depthVertexMain` and no
2373        // fragment stage, which is why the split-stream vertex pool pays for this
2374        // pass as well as for the atlas; a scene that masks something records its
2375        // masked buckets under the cutout twin and its opaque ones under this
2376        // one, and `depth_partitions` is where that split and its price are
2377        // argued.
2378        //
2379        // **Stored, unlike the depth the forward pass writes.** This is what the
2380        // occlusion pass samples, and it is the only reason
2381        // `crate::targets::scene_depth` carries `SAMPLED`.
2382        //
2383        // # The overdraw win, and what it rests on
2384        //
2385        // With this depth in the buffer the colour pass tests `GreaterOrEqual`
2386        // with writes off — `PassBuilder::depth_read` and
2387        // `DepthStencilState::equal_depth_read_only` — so every hidden fragment's
2388        // clustered-forward shading goes away. See
2389        // `MeshModules::color_depth_stencil`.
2390        //
2391        // **It rests on `SV_Position.z` invariance between the two pipelines**,
2392        // which the engine does not decorate for: a fragment the colour pass
2393        // places a hair farther than this pass did is *rejected*, and that
2394        // arrives as holes in the frame rather than as an error. Two things make
2395        // it hold rather than hope. On the mesh path the two passes run the
2396        // **same** geometry stage — `depth_pipeline`'s doc says so — so there is
2397        // nothing to diverge. On the vertex path `depthVertexMain` is the same
2398        // clip position written the same way as `vertexMain`'s, out of the same
2399        // module compiled in one invocation — and the cutout pipeline runs
2400        // `vertexMain` itself, so a masked frame's prepass is not merely the same
2401        // arithmetic as the colour pass's but the same code. The observable is a screenshot:
2402        // holes are not subtle, and the render-e2e goldens are what would catch
2403        // them on a rasteriser this machine does not have.
2404        let depth_group = self.prepass_groups[frame];
2405        // The prepass's own cluster counter — see
2406        // [`View::prepass_stats`]. Imported in the state the last frame
2407        // on this slot left it in, on `cluster-selection`'s terms exactly: a
2408        // barrier naming `Undefined` as its source carries no source scope, so it
2409        // would order this frame's write against nothing.
2410        let prepass_stats = import_read_write(graph, "prepass-stats", self.prepass_stats[frame]);
2411        let prepass_reads = PrepassReads {
2412            shadow_atlas,
2413            occlusion_placeholder,
2414            pages: passes.pages,
2415            probe_table,
2416            skinned,
2417            selection,
2418            prepass_stats,
2419        };
2420        // **Which of the generator's draw regions the prepass draws.** With the
2421        // occlusion cull on it is the survivors the first phase passed — the
2422        // late prepass below draws the ones the second phase rescued, and the
2423        // forward pass region 0, which is both. Off, it is region 0, which is
2424        // every survivor, exactly as before the cull existed.
2425        let two_phase = culled_pyramid.is_some();
2426        let early_region = if two_phase {
2427            crcbl_shaders::draw_gen::EARLY_REGION
2428        } else {
2429            0
2430        };
2431        let prepass = graph.add_render_pass("depth-prepass").depth(
2432            scene_depth,
2433            LoadOp::Clear,
2434            StoreOp::Store,
2435            crcbl_hal::ClearValue {
2436                depth: crcbl_hal::depth::CLEAR,
2437                ..crcbl_hal::ClearValue::default()
2438            },
2439        );
2440        let prepass = declare_prepass_reads(prepass, &prepass_reads, &generated, emit);
2441        let early_partitions = if two_phase {
2442            prepass_partitions.clone()
2443        } else {
2444            Vec::new()
2445        };
2446        prepass.execute(move |ctx| {
2447            let encoder = ctx.encoder();
2448            // One `open` per partition and its own buckets under it: the whole
2449            // pass is still one indirect call per bucket, drawn under the
2450            // pipeline that bucket's mode asked for.
2451            for partition in &prepass_partitions {
2452                partition.open(encoder);
2453                partition.record_region(encoder, depth_group, &generated, early_region);
2454            }
2455        });
2456
2457        // --- the occlusion cull's second phase ---
2458        //
2459        // Topic 03 §3.3: this frame's farthest
2460        // pyramid out of the early depth, every survivor the first phase marked
2461        // tested against it, and the ones it rescues drawn into the same depth
2462        // before anything reads it. See [`crate::occlusion_cull`].
2463        if let Some(culled) = &culled_pyramid {
2464            let levels = culled.levels.clone();
2465            let group = culled.group;
2466            self.occlusion_pyramid
2467                .add_passes(graph, frame, scene_depth, &levels);
2468            self.draws.add_late_passes(
2469                graph,
2470                frame,
2471                instance_count,
2472                &generated,
2473                &crate::draw_gen::PyramidInputs {
2474                    levels: &levels,
2475                    group,
2476                },
2477            );
2478            // **Loaded, not cleared**: the early prepass's depth is what the
2479            // rescued survivors are drawn into, and what everything after reads
2480            // is the two together.
2481            let late = graph.add_render_pass("depth-prepass-late").depth(
2482                scene_depth,
2483                LoadOp::Load,
2484                StoreOp::Store,
2485                crcbl_hal::ClearValue::default(),
2486            );
2487            let late = declare_prepass_reads(late, &prepass_reads, &generated, emit);
2488            late.execute(move |ctx| {
2489                let encoder = ctx.encoder();
2490                for partition in &early_partitions {
2491                    partition.open(encoder);
2492                    partition.record_region(
2493                        encoder,
2494                        depth_group,
2495                        &generated,
2496                        crcbl_shaders::draw_gen::LATE_REGION,
2497                    );
2498                }
2499            });
2500        }
2501
2502        // Topic 46's occlusion pair, or the one texel
2503        // that stands for "no occlusion was computed" where it is switched off.
2504        //
2505        // # The switched-off arm is the 1×1 placeholder, and the shader is what
2506        // makes that work
2507        //
2508        // Topic 18 sanctions the placeholder — "a renderer-owned 1×1 `R8Unorm`
2509        // cleared to 1.0, bound when the AO passes are not added" — and it is
2510        // what this binds. The property it rests on is not free: `mesh.slang`
2511        // reads this channel with a `Load` at `SV_Position.xy`, and a `Load`
2512        // outside a texture's extent yields **zero** rather than the nearest
2513        // texel, so the fetch has to be clamped against the image's own extent
2514        // or a one-texel image occludes everything but the origin. That clamp is
2515        // in `mesh.slang` and `crcbl`'s `forward_e2e::depth_probe` is what asks
2516        // whether it is; a frame drawn without it is black wherever ambient is the whole of
2517        // the light, on real hardware, with nothing reporting an error.
2518        //
2519        // So an AO-off frame records **no occlusion pass at all** and takes no
2520        // frame-sized image out of the transient pool: no shader permutation, no
2521        // uniform branch, one pipeline, and a bound value that occludes nothing.
2522        //
2523        // The placeholder's other job is unchanged — filling the binding for the
2524        // two depth-only passes, neither of which has a fragment stage and so
2525        // neither of which ever samples it.
2526        let occlusion = match occlusion_chain {
2527            Some(images) => self
2528                .ssao
2529                .add_passes(graph, frame, extent, scene_depth, images),
2530            None => occlusion_placeholder,
2531        };
2532        // Topic 45's contact march, or the one texel that
2533        // stands for "the sun reaches this surface" where it is switched off.
2534        //
2535        // The occlusion pair's arms exactly, and the clamp the off-arm rests on
2536        // is `mesh.slang`'s `contact_at`. What differs is what it costs to get
2537        // wrong: an unclamped `Load` past this placeholder's one texel would
2538        // report *total* shadow at every pixel but one, so a frame with the
2539        // effect off would lose its sun rather than its ambient.
2540        //
2541        // Recorded here, after the occlusion pair and before the forward pass,
2542        // because the forward pass is what binds it — and the prepass it reads
2543        // has already run.
2544        let contact = match contact_mask {
2545            Some(mask) => self
2546                .contact_shadows
2547                .add_passes(graph, frame, scene_depth, mask),
2548            None => contact_placeholder,
2549        };
2550
2551        let pass = graph
2552            .add_render_pass("forward")
2553            // Transparent black on a transparent view: zero coverage where no
2554            // geometry lands, and no colour for the air in front of the far
2555            // plane to add to but its own.
2556            .clear_color(
2557                scene_color,
2558                if transparent {
2559                    TRANSPARENT_CLEAR
2560                } else {
2561                    SCENE_CLEAR
2562                },
2563            )
2564            // `mesh.slang`'s second target, and **cleared rather than loaded or
2565            // discarded**. A pixel no geometry covered has no material, and the
2566            // pass that will read this marches a ray from whatever it finds
2567            // there — so the value that has to be in it is the one that says
2568            // "nothing reflects here", not the last frame's or an undefined
2569            // one. `NO_REFLECTION` is that value: no `F0`, and fully rough —
2570            // the alpha is a roughness, so a zero there would read as a
2571            // mirror. No picture tells the two apart, because a zero `F0`
2572            // leaves the reflection nothing to scale but Schlick's grazing
2573            // tail; what the alpha buys is that `ssr.slang` takes its early
2574            // return on every uncovered pixel instead of marching the sky.
2575            .clear_color(reflectivity, ssr::NO_REFLECTION)
2576            // `mesh.slang`'s third target, **cleared to zero** on the
2577            // reflectivity attachment's terms: a pixel no geometry covered has
2578            // no motion of its own, and zero is what a consumer reading its
2579            // history at `uv - motion` needs there — it reads the same pixel
2580            // back. It is not the *right* answer for the sky, whose motion is
2581            // the camera's and is owed to the pass that first wants it; it is
2582            // the answer that reprojects onto itself rather than onto
2583            // somewhere undefined. `docs/backlog.md` carries what is owed.
2584            .clear_color(motion, [0.0; 4]);
2585        // **Loaded and stored rather than cleared, and read-only**, which is the
2586        // half of the depth prepass that pays for the pass itself:
2587        // `MeshModules::color_depth_stencil` tests `GreaterOrEqual` with writes
2588        // off, so a fragment survives only where the prepass already put its
2589        // surface — and the clustered-forward shading of everything a nearer
2590        // surface goes on to cover is never run. It is stored because the
2591        // reflection march is downstream and reads exactly this image; the
2592        // values are the prepass's, which are this pass's own answer written by
2593        // the same transform.
2594        //
2595        // **The wireframe frame keeps the old shape**, because
2596        // `PolygonMode::Line` does not reproduce the prepass's depths — see
2597        // `color_depth_stencil`. It must *clear*: loading the prepass's depth
2598        // under the default `Greater` test rejects every fragment of the same
2599        // geometry, and the frame goes black.
2600        let pass = match wireframe {
2601            Some(_) => pass.depth(
2602                scene_depth,
2603                LoadOp::Clear,
2604                StoreOp::Store,
2605                crcbl_hal::ClearValue {
2606                    depth: crcbl_hal::depth::CLEAR,
2607                    ..crcbl_hal::ClearValue::default()
2608                },
2609            ),
2610            None => pass.depth_read(scene_depth),
2611        };
2612        let pass = pass
2613            // The occlusion channel this frame's ambient term is scaled by. On
2614            // an AO-on frame the blur pass wrote it as a colour attachment a
2615            // moment ago, so this declaration is the barrier into a
2616            // shader-readable layout; on an AO-off frame it is the imported
2617            // placeholder, which is in that layout already and has nothing to
2618            // transition.
2619            .read_image(occlusion)
2620            // The contact-shadow channel this frame's sun is scaled by, declared
2621            // on the occlusion channel's terms exactly: the march wrote it as a
2622            // colour attachment a moment ago and this is the barrier into a
2623            // shader-readable layout, or it is the imported placeholder and there
2624            // is nothing to transition.
2625            .read_image(contact)
2626            // **The page this pass's materials actually sample**, and the one
2627            // pass of the three where that is literally true. Declared so the
2628            // graph can order a caller's copy into a page layer against these
2629            // draws — see `base_color_page_import`.
2630            .read_image(base_color_page)
2631            // **And §2's other three pages, every one of which this pass's
2632            // fragment stage literally samples** — the normal map it perturbs
2633            // through, the packed roughness and metalness its lobe takes, and
2634            // the emissive radiance it adds. See `normal_page_import`.
2635            .read_image(normal_page)
2636            .read_image(mro_page)
2637            .read_image(emissive_page)
2638            // **The barrier out of the shadow pass's depth attachment.** The
2639            // atlas is in this pass's bind group at `SHADOW_ATLAS_BINDING`, and
2640            // without this declaration the graph leaves it in
2641            // `DepthStencilWrite` — which Vulkan reports as
2642            // `VUID-vkCmdDrawIndexedIndirectCount-imageLayout-00344` naming the
2643            // binding, and which every other backend reads as whatever the
2644            // depth writes left behind.
2645            .read_image(shadow_atlas)
2646            // The froxel grid, on the shadow atlas's terms exactly: the
2647            // clustering pass left it in `ShaderReadWrite` and the fragment
2648            // stage has it bound, so declaring the read is what moves it — and
2649            // without the declaration the fragment stage reads a buffer the
2650            // compute pass may still be writing.
2651            .read_buffer(light_grid)
2652            // The probe rows, on the froxel grid's terms and for a hazard that
2653            // does not exist yet: nothing writes a probe on the GPU today, so
2654            // this frame's slot is already in `ShaderRead` and the graph has
2655            // nothing to transition. It is declared anyway, because the rows are
2656            // device-local and `TRANSFER_DST` precisely so
2657            // the irradiance probes' gather can write them — and
2658            // a pass that binds a buffer without declaring it is a pass the
2659            // graph cannot barrier the day something does.
2660            .read_buffer(probe_table);
2661        // And the skinned vertices, which is the declaration this whole entry
2662        // point exists for: without it the vertex stage pulls a region the
2663        // compute dispatch may still be writing, and the graph — which is told
2664        // about every other hazard in the frame — has not been told about this
2665        // one.
2666        let pass = match skinned {
2667            Some(vertices) => pass.read_buffer(vertices),
2668            None => pass,
2669        };
2670        let pass = read_draw_sources(pass, &generated, emit);
2671        let pass = match selection {
2672            // The colour pass's own, which no cascade writes — the cascades
2673            // record into buffers of their own, so what survives a frame here is
2674            // the camera's cut and what survives there is each cascade's. The
2675            // depth prepass above writes this one too, with the same camera and
2676            // the same budget, and is ordered before this pass by the graph.
2677            Some(selection) if emit.is_mesh() => {
2678                pass.use_buffer(selection, ResourceState::ShaderReadWrite)
2679            }
2680            _ => pass,
2681        };
2682
2683        // The camera's group rebuilt against the two screen-space channels the
2684        // graph just realised, cached against both views and the probe
2685        // visibility maps — the shape the tonemap group below has, and for the
2686        // same reason: a graph transient's view is not known until execute time.
2687        // Three entries of the stored list differ; see
2688        // `View::mesh_group_entries`.
2689        //
2690        //
2691        // The rebuild is unconditional, so there is one shape of forward pass
2692        // rather than two: the group is cached against the views it was built
2693        // from, so an AO-off frame naming the placeholder's view and an AO-on
2694        // frame naming the blur's target are the same code and one cache miss
2695        // apiece when a toggle moves. **The key is both views**, because a group
2696        // naming two transients is stale as soon as either one moves.
2697        let entries = self.mesh_group_entries[frame].as_slice();
2698        let mesh_layout = passes.mesh_layout;
2699        // The captured probe-visibility maps, or the one-texel placeholder when
2700        // nothing has been captured or the console switch is off. It rides
2701        // through the same cache as the two channels beside it — it is not a
2702        // graph transient, but it does change between frames when the switch
2703        // moves, and a group cached against a view it no longer names is the
2704        // failure that cache exists to stop.
2705        let probe_visibility_view = passes.probe_visibility;
2706        let cached_mesh = &mut self.screen_channel_groups[frame];
2707        pass.execute(move |ctx| {
2708            let view = ctx.image_view(occlusion);
2709            let contact_view = ctx.image_view(contact);
2710            let device = ctx.device();
2711            let group = cached_group(
2712                cached_mesh,
2713                device,
2714                &[
2715                    (AMBIENT_OCCLUSION_BINDING, view),
2716                    (CONTACT_SHADOW_BINDING, contact_view),
2717                    (PROBE_VISIBILITY_BINDING, probe_visibility_view),
2718                ],
2719                "mesh frame",
2720                mesh_layout,
2721                entries,
2722            )
2723            // Falling back to the group built at `build` rather than dropping
2724            // the frame, and **the fallback costs the occlusion and the contact
2725            // shadow and nothing else**: that group names the two 1×1 white
2726            // placeholders, which `mesh.slang` clamps its `Load`s into and reads
2727            // as "nothing occludes" and "the sun reaches here". A descriptor
2728            // failure therefore draws the frame this scene would have drawn with
2729            // both effects switched off, rather than one with no ambient term
2730            // and no sun in it.
2731            .unwrap_or(group);
2732            let encoder = ctx.encoder();
2733            // One `open` per partition and its own buckets under it, on the
2734            // depth prepass's terms: the pass is still one indirect call per
2735            // bucket, drawn under the pipeline that bucket's side asked for.
2736            for partition in &color_partitions {
2737                partition.open(encoder);
2738                partition.record(encoder, group, &generated);
2739            }
2740        });
2741
2742        // `docs/plan/57-grass.md`'s field, **after the forward pass and before
2743        // the background**. Grass is opaque scene content with a cutout: the
2744        // depth its cards write has to be in the buffer before the sky decides
2745        // which pixels it covers, before the Hi-Z pyramid is built and before
2746        // the reflection march reads the frame. A frame with no field adds
2747        // nothing here and takes no transient — see [`crate::grass`].
2748        if let Some(field) = passes.grass {
2749            let frame_block = self.uniforms[frame];
2750            self.grass.add_passes(
2751                graph,
2752                frame,
2753                crate::grass::GrassImages {
2754                    color: scene_color,
2755                    depth: scene_depth,
2756                    shadow_atlas,
2757                },
2758                crate::grass::GrassInputs {
2759                    frame_block,
2760                    lights: self.lights.lights(frame),
2761                    cluster_lights: self.lights.grid(frame),
2762                    light_grid,
2763                    field,
2764                },
2765            );
2766        }
2767
2768        // --- the background ---
2769        //
2770        // **After the forward pass and before everything that reads the scene
2771        // colour**, which is what makes the sky the background of the frame the
2772        // reflection composite, the bloom chain and the tonemap all work on
2773        // rather than a colour added at the end.
2774        //
2775        // It does not disturb the reflection itself. The march reads the scene
2776        // colour only at a crossing it found in the depth prepass, and the far
2777        // plane has no surface to cross to — `ssr.slang` returns before it
2778        // marches on a pixel whose depth is the clear value — so nothing this
2779        // pass writes is ever tapped as a reflected colour. A ray that leaves
2780        // the frame still falls back to the analytic gradient rather than to
2781        // these texels, which is the same sky evaluated exactly.
2782        //
2783        // Conditional on the sky and not on [`RenderEffects`], on the ground
2784        // grid's terms: see [`crate::sky_pass`] for why the off position has to
2785        // be no pass at all.
2786        if draws_sky {
2787            self.sky_pass
2788                .add_pass(graph, frame, scene_color, scene_depth);
2789        }
2790
2791        // What the water surface reads out of three other passes' state, read
2792        // before those passes take their mutable borrows below — see
2793        // [`crate::water`] for why it binds their handles rather than copies.
2794        let water_reads = (
2795            self.uniforms[frame],
2796            self.ssr.uniforms(frame),
2797            self.ssr.sky_prefilter_view(),
2798            self.volumetric.buffers(frame),
2799            self.sky_pass.lut(frame),
2800        );
2801
2802        // The froxel volume, and it composites over
2803        // the sky as well as over the geometry — a pixel at the far plane is a
2804        // whole column of air, which is exactly what makes a distant horizon
2805        // read as distant.
2806        //
2807        // **Before the reflection march**, where `mesh.slang`'s closed form also
2808        // ran: the march reads the scene colour as reflected radiance, and fog
2809        // it can see is fog the surface it bounced off could see. The reflection
2810        // the blur adds afterwards is still unfogged, which is the same gap the
2811        // analytic path has and `docs/backlog.md` carries.
2812        //
2813        // The atmosphere's air is composed in the same pass, and on the same
2814        // side of the reflection march, for the same reason: the march reads
2815        // what the surface it bounced off could see.
2816        let (scene_color, froxel_ids) = match fogged {
2817            Some(composited) => {
2818                // Read before the split borrow below, on `sky_view_lut`'s
2819                // terms: `self.volumetric` is taken mutably.
2820                let aerial = self.sky_pass.aerial(frame);
2821                let ids = self.volumetric.add_passes(
2822                    graph,
2823                    frame,
2824                    self.grid,
2825                    VolumetricImages {
2826                        depth: scene_depth,
2827                        color: scene_color,
2828                        composited,
2829                        shadow_atlas,
2830                    },
2831                    VolumetricReads {
2832                        light_grid,
2833                        local: effects.contains(RenderEffects::VOLUMETRIC_FOG),
2834                        aerial,
2835                    },
2836                );
2837                (composited, Some(ids))
2838            }
2839            None => (scene_color, None),
2840        };
2841
2842        // Topic 47's reflection march and its blur, and
2843        // **the second of them is the composite**: the march reads the scene
2844        // colour, the depth prepass and the reflectivity attachment and writes
2845        // the reflection alone, and the blur filters that and adds it to the
2846        // scene colour — so everything below this line works on `tonemapped`
2847        // rather than on `scene_color`. A frame that does not add the pair hands
2848        // `scene_color` on and is bit-identical, which is this effect's whole
2849        // off-switch.
2850        let tonemapped = match reflected {
2851            Some((reflection, composited)) => {
2852                // Read before the split borrow below: `self.ssr` is taken
2853                // mutably by `add_passes` and this names a different field.
2854                let sky_view_lut = self.sky_pass.lut(frame);
2855                // The pyramid first: the march climbs it, so every level has to
2856                // be written before the pass that reads it is recorded. Skipped
2857                // outright on a frame whose extent has no levels, which
2858                // `Hiz::add_passes` would record zero passes for anyway.
2859                self.hiz
2860                    .add_passes(graph, frame, extent, scene_depth, &pyramid);
2861                self.ssr.add_passes(
2862                    graph,
2863                    frame,
2864                    SsrImages {
2865                        depth: scene_depth,
2866                        color: scene_color,
2867                        reflectivity,
2868                        reflection,
2869                        composited,
2870                        pyramid: crate::hiz::level_slots(scene_depth, &pyramid),
2871                    },
2872                    SsrEnvironment {
2873                        probes: probe_buffer,
2874                        probe_id: probe_table,
2875                        // The same view the forward pass's own group named, so
2876                        // the reflection's probe fallback is weighed by the
2877                        // maps the diffuse gather was weighed by — or by the
2878                        // placeholder, when there are none and every probe
2879                        // keeps all of its weight.
2880                        probe_visibility: probe_visibility_view,
2881                        // The background pass's own LUT slot, not a copy of it
2882                        // — see [`crate::sky_pass::SkyPass::lut`]. A frame with
2883                        // no atmosphere binds the zeroes that buffer was
2884                        // created holding, and `ssr.slang` returns before
2885                        // reading it.
2886                        sky_view: sky_view_lut,
2887                    },
2888                );
2889                composited
2890            }
2891            None => scene_color,
2892        };
2893
2894        // `docs/plan/55-water.md`'s surface, **after the reflection composite
2895        // and before the bloom chain**. After, because the surface computes its
2896        // own reflection and is not a receiver of the shared march, which has
2897        // already run; before, because water is scene content and the chain is
2898        // a lens. It draws into the image the chain would have read and into the
2899        // scene depth, in place, so every pass below reads the same two images
2900        // it always did. A frame with no bodies adds nothing here and takes no
2901        // transient — see [`crate::water`] — and requests its two after every
2902        // other image this view asks for, so the pool hands each of those the
2903        // physical image it had before water existed.
2904        if let Some(mesh) = passes.water.clone() {
2905            let color_copy = graph.create_image("water-color", crate::targets::scene_color(extent));
2906            let depth_copy = graph.create_image("water-depth", crate::targets::hiz_level(extent));
2907            let (frame_block, reflection_block, sky_prefilter, froxels, sky_view) = water_reads;
2908            let inputs = WaterInputs {
2909                frame_block,
2910                reflection_block,
2911                froxels,
2912                froxel_ids,
2913                probes: probe_buffer,
2914                probe_id: probe_table,
2915                probe_visibility: passes.probe_visibility,
2916                sky_prefilter,
2917                sky_view,
2918                mesh,
2919            };
2920            self.water.add_passes(
2921                graph,
2922                frame,
2923                WaterImages {
2924                    color: tonemapped,
2925                    depth: scene_depth,
2926                    color_copy,
2927                    depth_copy,
2928                    shadow_atlas,
2929                },
2930                inputs,
2931            );
2932        }
2933
2934        // Topic 48's bloom chain, and it slots in
2935        // exactly where the reflection composite left off: it reads whatever the
2936        // tonemap was about to read, writes a new full-resolution image, and the
2937        // tonemap reads that instead. A frame that does not add it hands the
2938        // image on untouched and is bit-identical, which is this effect's whole
2939        // off-switch — and the group the tonemap builds below is cached against
2940        // its source view, so a toggle costs one cache miss and nothing else.
2941        let tonemapped = match &bloomed {
2942            Some((mips, composited)) => {
2943                self.bloom
2944                    .add_passes(graph, frame, extent, tonemapped, mips, *composited);
2945                *composited
2946            }
2947            None => tonemapped,
2948        };
2949
2950        // Topic 43 §6's auto-exposure, and it reads
2951        // the image the tonemap is about to read: the frame with the medium, the
2952        // reflection and the chain already in it, which is the picture a viewer
2953        // sees and therefore the one to expose for. Binning `scene_color`
2954        // instead would expose the frame for a picture nobody looks at.
2955        //
2956        // Read first because the passes borrow the ring for the rest of this
2957        // function, and the tonemap below needs the handle out of it.
2958        let measured = self.auto_exposure.measured(frame);
2959        if effects.contains(RenderEffects::AUTO_EXPOSURE) {
2960            self.auto_exposure
2961                .add_passes(graph, frame, extent, tonemapped);
2962        }
2963
2964        // --- the debug draw layer ---
2965        //
2966        // **Before the tonemap, into the HDR image the tonemap is about to
2967        // read**, which is `docs/plan/18-render-features.md`'s interaction rule:
2968        // "Debug overlays (debug draw, gizmos) render pre-tonemap in HDR
2969        // (they're in the world) except UI-space panels." A segment is therefore
2970        // exposed and tonemapped like the geometry it annotates, which is the
2971        // opposite of the ground grid below — and [`crate::grid`]'s header and
2972        // [`crate::debug_draw`]'s carry the two halves of that argument.
2973        //
2974        // **And after everything that reads the scene colour.** The reflection
2975        // march, the bloom chain and the auto-exposure histogram have all
2976        // already been recorded against this image, so a debug line does not
2977        // reflect in a surface, does not bloom, and does not move the exposure
2978        // the scene is metered at. Each of those would be an overlay changing
2979        // the picture it is drawn over, which is the one thing an overlay must
2980        // not do.
2981        //
2982        // Nothing here is conditional on [`RenderEffects`], on the ground
2983        // grid's terms: a frame that appended no segment is the frame this
2984        // renderer recorded before [`crate::debug_draw`] existed — no pass, no
2985        // pipeline, no block.
2986        if let Some(debug_draw) = overlays.debug_draw {
2987            debug_draw.add_pass(graph, frame, tonemapped, scene_depth);
2988        }
2989
2990        // **None of the display work under the shadow atlas viewer.** It fills
2991        // every display pixel with a `DontCare` load, so a tonemapped frame or a
2992        // grid recorded first would be stored and immediately discarded. The HDR
2993        // scene passes above stay: callers still read their output.
2994        if overlays.atlas_viewer.is_none() {
2995            // The tonemap group names a *graph-owned* view, so it can only be built
2996            // once the graph has realised one. It is cached against the view handle
2997            // and therefore rebuilt only on a resize.
2998            let TonemapPipeline {
2999                sampler,
3000                layout,
3001                pipeline_layout,
3002                pipeline: tonemap_pipeline,
3003            } = passes.tonemap;
3004            let exposure_block = self.tonemap_uniforms[frame];
3005            let cached = &mut self.tonemap_groups[frame];
3006
3007            graph
3008                .add_render_pass("tonemap")
3009                // `DontCare`, not `Clear`: the full-screen triangle writes every
3010                // pixel of the target, so loading or clearing it is pure bandwidth.
3011                .color(
3012                    display,
3013                    LoadOp::DontCare,
3014                    StoreOp::Store,
3015                    crcbl_hal::ClearValue::default(),
3016                )
3017                // **The reflection pass's output where there is one, and the forward
3018                // pass's where there is not.** The two are the same description and
3019                // different images, and tonemapping the first one on a frame that
3020                // reflected would compile, draw a picture, and silently be the frame
3021                // without reflections in it.
3022                .read_image(tonemapped)
3023                .execute(move |ctx| {
3024                    let view = ctx.image_view(tonemapped);
3025                    let device = ctx.device();
3026                    let entries = [
3027                        BindGroupEntry {
3028                            binding: 0,
3029                            array_index: 0,
3030                            resource: BindingResource::ImageView(view),
3031                        },
3032                        BindGroupEntry {
3033                            binding: 1,
3034                            array_index: 0,
3035                            resource: BindingResource::Sampler(sampler),
3036                        },
3037                        BindGroupEntry {
3038                            binding: 2,
3039                            array_index: 0,
3040                            resource: BindingResource::whole_buffer(exposure_block),
3041                        },
3042                        BindGroupEntry {
3043                            binding: 3,
3044                            array_index: 0,
3045                            resource: BindingResource::whole_buffer(measured),
3046                        },
3047                    ];
3048                    let Some(group) = cached_group(
3049                        cached,
3050                        device,
3051                        &[(0, view)],
3052                        "tonemap scene",
3053                        layout,
3054                        &entries,
3055                    ) else {
3056                        return;
3057                    };
3058                    let encoder = ctx.encoder();
3059                    encoder.bind_graphics_pipeline(tonemap_pipeline);
3060                    encoder.bind_group(0, group, &[], pipeline_layout);
3061                    // Three vertices, no geometry bound, no vertex buffer anywhere.
3062                    encoder.draw(0..3, 0..1);
3063                });
3064
3065            // --- the ground grid ---
3066            //
3067            // **After the tonemap, into the target the tonemap just wrote**, and
3068            // that placement is the decision rather than an accident of ordering.
3069            // The grid is reference chrome, not scene content: drawn into
3070            // `scene_color` it would be exposed and tonemapped like geometry, so its
3071            // colour would shift with how bright the scene happens to be — and a
3072            // grid whose lines change with the exposure is no longer a reference.
3073            // Blender draws its overlays the same way, in display space after the
3074            // render.
3075            //
3076            // It still takes `scene_depth`, read-only, so geometry in front of the
3077            // ground occludes it. That the depth survives this far is not luck: the
3078            // forward pass stores it (`StoreOp::Store`) because the reflection march
3079            // reads it, and the graph moves it from whatever state that left it in
3080            // into `DepthStencilRead` for this pass.
3081            //
3082            // Nothing here is conditional on [`RenderEffects`]: the grid is a
3083            // caller's opt-in, and a frame that never asked for one is the frame
3084            // this renderer recorded before [`crate::grid`] existed — no pass, no
3085            // pipeline, no block.
3086            if let Some(grid) = overlays.ground_grid {
3087                let view_proj = self.camera_view_proj;
3088                grid.add_pass(
3089                    graph,
3090                    frame,
3091                    display,
3092                    scene_depth,
3093                    view_proj,
3094                    // The one inversion in the frame, and it is here rather than in
3095                    // the pass: `begin_frame` has no reason to compute it for a grid
3096                    // that is usually off.
3097                    view_proj.inverse(),
3098                );
3099            }
3100        }
3101
3102        // --- the shadow atlas viewer ---
3103        //
3104        // **After the grid and before the resolve, and it replaces what both of
3105        // them were about.** Sundial's atlas viewer:
3106        // the `D32Float` image the shadow pass filled, drawn over the finished
3107        // frame so that which slot holds which map is something a reviewer can
3108        // look at. [`crate::atlas_view`] carries why it draws here — in display
3109        // space, after the operator — rather than into the scene colour.
3110        //
3111        // After the grid because a grid over a readout is noise; before the
3112        // resolve because there is nothing to resolve, and nothing to resolve
3113        // *with*: [`Self::resolved_effects`] takes both antialiasing tiers off
3114        // for every debug view, so `display` and `present` are one image on
3115        // every frame this branch runs on.
3116        //
3117        // Nothing here is conditional on [`RenderEffects`], on the ground
3118        // grid's terms: a frame that resolved any other view is the frame this
3119        // renderer recorded before this module existed — no pass, no pipeline,
3120        // no block read.
3121        if let Some(atlas_viewer) = overlays.atlas_viewer {
3122            atlas_viewer.add_pass(graph, frame, shadow_atlas, display);
3123        }
3124
3125        overlay(
3126            graph,
3127            ForwardOverlayTargets {
3128                display,
3129                depth: scene_depth,
3130                internal_extent: extent,
3131            },
3132        );
3133
3134        // --- the antialiasing resolve ---
3135        //
3136        // **After the grid, and that is the same decision the grid's placement
3137        // was.** The grid is a field of thin high-contrast lines, which is the
3138        // thing an edge filter exists for; drawing it into the target *after*
3139        // the resolve would leave it the one aliased element in an antialiased
3140        // frame. The UI goes the other way and is composited onto `target` by
3141        // the caller after this, so its glyphs are never filtered — topic 18
3142        // refuses to antialias text in as many words.
3143        //
3144        // `display` is `present` when neither antialiasing bit is on, and this
3145        // is the branch that makes that true: no pass, no second image, and the
3146        // frame the tonemap wrote is already where the frame ends.
3147        //
3148        // **Which tier fills the slot is decided here, once.** CMAA2 is the
3149        // higher one and takes it whenever its bit is on, whatever the FXAA bit
3150        // says — the two are never both recorded, which is what
3151        // [`RenderEffects::CMAA2`] means by a tier that is off being a frame with
3152        // fewer passes rather than a shader branch. Everything the paragraph
3153        // above says about the grid, the UI and the ordering holds for either.
3154        if display != present {
3155            if effects.contains(RenderEffects::CMAA2) {
3156                self.cmaa2.add_passes(graph, frame, display, present);
3157            } else {
3158                self.fxaa.add_pass(graph, frame, display, present);
3159            }
3160        }
3161
3162        // --- the render-scale upscale ---
3163        //
3164        // **After the resolve, and that ordering is not interchangeable.**
3165        // Either tier filters the edges the renderer actually drew; run the
3166        // other way round
3167        // it would be filtering an interpolation of them, which is both more
3168        // expensive — the resolve would run at the target's extent rather than
3169        // the internal one — and worse, because the edge it is looking for has
3170        // already been spread across several target texels.
3171        //
3172        // The UI goes the other way and is composited onto `target` by the
3173        // caller after this, at native resolution. That is the whole reason a
3174        // render-scale knob is usable: the 3D frame gets cheap and the text does
3175        // not get soft.
3176        if present != target {
3177            self.upscale.add_pass(graph, frame, present, target);
3178        }
3179
3180        tonemapped
3181    }
3182
3183    /// Releases every resource this view owns.
3184    ///
3185    /// The caller's to call once no frame in flight still names them — the
3186    /// same contract [`ForwardRenderer::destroy`] has, because these are the
3187    /// handles that frame's passes and groups bind.
3188    pub(super) fn destroy(self, device: &dyn Device) {
3189        for (_, group) in self.tonemap_groups.into_iter().flatten() {
3190            device.destroy_bind_group(group);
3191        }
3192        for buffer in self.tonemap_uniforms {
3193            device.destroy_buffer(buffer);
3194        }
3195        self.grass.destroy(device);
3196        self.water.destroy(device);
3197        self.sky_pass.destroy(device);
3198        self.upscale.destroy(device);
3199        self.cmaa2.destroy(device);
3200        self.fxaa.destroy(device);
3201        self.bloom.destroy(device);
3202        self.auto_exposure.destroy(device);
3203        self.volumetric.destroy(device);
3204        self.ssr.destroy(device);
3205        self.hiz.destroy(device);
3206        self.occlusion_pyramid.destroy(device);
3207        self.contact_shadows.destroy(device);
3208        self.ssao.destroy(device);
3209        for group in self
3210            .mesh_groups
3211            .into_iter()
3212            .chain(self.prepass_groups)
3213            .chain(
3214                self.screen_channel_groups
3215                    .into_iter()
3216                    .flatten()
3217                    .map(|(_, group)| group),
3218            )
3219        {
3220            device.destroy_bind_group(group);
3221        }
3222        for buffer in self.prepass_stats {
3223            device.destroy_buffer(buffer);
3224        }
3225        for buffer in self.uniforms {
3226            device.destroy_buffer(buffer);
3227        }
3228        for buffer in self.cluster_selection {
3229            device.destroy_buffer(buffer);
3230        }
3231        if let Some(buffer) = self.fixed_probes {
3232            device.destroy_buffer(buffer);
3233        }
3234        self.lights.destroy(device);
3235        self.draws.destroy(device);
3236    }
3237}
3238
3239/// # Views
3240///
3241/// `docs/plan/29-fp-rendering.md`'s second camera: a view draws the scene this
3242/// renderer already holds, through a camera of its own, into a target of its
3243/// own — and shares every pool, page, probe and shadow map with the primary
3244/// camera rather than building them again.
3245impl ForwardRenderer {
3246    /// Builds a view of this renderer's scene and hands back its id.
3247    ///
3248    /// **What a view costs** is one camera's share of the frame and nothing
3249    /// else: its own cull and draw-argument buffers (sized by the instance
3250    /// capacity, like the primary camera's), its frame blocks, its light
3251    /// clustering and the per-frame blocks of every screen-space pass. Geometry,
3252    /// materials, pages, probes and the shadow atlas are the scene's, and a
3253    /// view reads them where they already are.
3254    ///
3255    /// A view draws nothing until a frame begins it — see
3256    /// [`begin_view`](Self::begin_view) and
3257    /// [`add_passes_with_views`](Self::add_passes_with_views).
3258    ///
3259    /// # Errors
3260    ///
3261    /// [`HalError::InvalidDescriptor`] when [`MAX_VIEWS`] views already exist,
3262    /// or for a [`ViewBackground::Transparent`] view whose effects name one of
3263    /// [`ViewBackground::REFUSED_ON_TRANSPARENT`] — a filter that would blend
3264    /// its coverage edges with the empty background, see that variant. And
3265    /// whatever the device refuses while building one — in which case nothing
3266    /// of the view is left behind.
3267    pub fn create_view(
3268        &mut self,
3269        device: &dyn Device,
3270        queue: QueueHandle,
3271        desc: &ViewDesc,
3272    ) -> Result<ViewId, HalError> {
3273        let refused = desc
3274            .effects
3275            .intersection(ViewBackground::REFUSED_ON_TRANSPARENT);
3276        if desc.background.is_transparent() && !refused.is_empty() {
3277            return Err(HalError::InvalidDescriptor(format!(
3278                "a transparent view cannot run {refused:?}: an antialiasing filter blends each \
3279                 edge pixel with the transparent black beside it, which a straight-alpha consumer \
3280                 draws as a dark fringe. Take them out of `ViewDesc::effects`, as \
3281                 `ViewDesc::transparent()` does"
3282            )));
3283        }
3284        let free = (0..MAX_VIEWS - 1)
3285            .find(|index| self.views.get(*index).is_none_or(Option::is_none))
3286            .ok_or_else(|| {
3287                HalError::InvalidDescriptor(format!(
3288                    "a forward renderer draws at most {MAX_VIEWS} views, the primary camera \
3289                     included, and every one is in use"
3290                ))
3291            })?;
3292        let id = ViewId(u8::try_from(free + 1).unwrap_or_else(|_| unreachable!("below MAX_VIEWS")));
3293        let probes: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
3294            .map(|frame| self.probes.buffer(frame))
3295            .collect();
3296        let probe_visibility = self.probe_visibility_placeholder.view;
3297        let view = View::build(
3298            device,
3299            queue,
3300            &ViewInputs {
3301                id,
3302                effects: desc.effects,
3303                background: desc.background,
3304                lighting: desc.lighting,
3305                target_format: self.target_format,
3306                emit: self.emit,
3307                instances: self.instances.buffers(),
3308                mesh_table: self.pool.table_buffer(),
3309                bucket_meshes: &self.draw_tables.bucket_meshes,
3310                bucket_modes: &self.bucket_modes,
3311                bucket_clusters: &self.draw_tables.bucket_clusters,
3312                bucket_cluster_bases: &self.draw_tables.bucket_cluster_bases,
3313                mesh_levels: &self.draw_tables.mesh_levels,
3314                level_groups: &self.draw_tables.level_groups,
3315                level_meshes: &self.draw_tables.level_meshes,
3316                instance_capacity: self.draw_tables.instance_capacity,
3317                light_capacity: self.draw_tables.light_capacity,
3318                clusters: self.clusters.as_ref(),
3319                task_lanes: task_lanes(self.culls_clusters),
3320                mesh_layout: self.mesh_layout,
3321                vertices: self.pool.vertex_buffer(),
3322                draw_constants: self.draw_constants,
3323                materials: self.materials.buffer(),
3324                // What each slot's groups name today, so a view built while a
3325                // new anisotropy or a replaced page is still moving through the
3326                // ring is adopted on the same frames the primary camera's
3327                // groups are.
3328                pages: &self.slot_pages,
3329                probes: &probes,
3330                specular_dfg: self.specular_dfg.view,
3331                ltc_table: self.ltc_table.view,
3332                shadow_map: self.shadow_atlas_view,
3333                shadow_sampler: self.shadow_sampler,
3334                ambient_occlusion: self.ambient_occlusion_placeholder.view,
3335                contact_shadow: self.contact_shadow_placeholder.view,
3336                probe_visibility,
3337            },
3338            &mut || {},
3339        )?;
3340        if self.views.len() <= free {
3341            self.views.resize_with(free + 1, || None);
3342        }
3343        self.views[free] = Some(view);
3344        Ok(id)
3345    }
3346
3347    /// Releases `view` and hands its id back.
3348    ///
3349    /// **Every instance is drawn in the view the id names next**: the bit this
3350    /// view hid instances with is cleared from every record, so a view created
3351    /// later under the same id starts from [`ViewMask::ALL`] rather than from
3352    /// what a view it never was had hidden.
3353    ///
3354    /// Like [`destroy`](Self::destroy), the caller's to call once no frame in
3355    /// flight still names the view's buffers and groups.
3356    ///
3357    /// # Panics
3358    ///
3359    /// If `view` is [`ViewId::PRIMARY`], which lives as long as the renderer,
3360    /// or names no view this renderer built.
3361    pub fn destroy_view(&mut self, device: &dyn Device, view: ViewId) {
3362        assert!(
3363            view != ViewId::PRIMARY,
3364            "the primary camera is released with the renderer, not on its own"
3365        );
3366        let built = self
3367            .views
3368            .get_mut(view.index() - 1)
3369            .and_then(Option::take)
3370            .unwrap_or_else(|| panic!("{view:?} is not a view this renderer built"));
3371        built.destroy(device);
3372        self.instances.clear_flags(view.hidden_bit());
3373    }
3374
3375    /// Writes `view`'s blocks for this frame, drawn through `camera` into a
3376    /// target of `extent`.
3377    ///
3378    /// **After [`begin_frame`](Self::begin_frame), in the same frame**, which is
3379    /// what rotated the instance ring, skinned what moves and fitted the shadow
3380    /// maps: a view writes into the slot that call chose, lit by the sun it was
3381    /// handed and shadowed through the maps the primary camera's frame draws —
3382    /// unless its [`ViewDesc::lighting`] fixes a light of its own. A view begun and then not named in
3383    /// [`add_passes_with_views`](Self::add_passes_with_views) records nothing.
3384    ///
3385    /// # Errors
3386    ///
3387    /// [`HalError`] if one of the view's blocks could not be written.
3388    ///
3389    /// # Panics
3390    ///
3391    /// If `view` is [`ViewId::PRIMARY`] — its blocks are `begin_frame`'s — or
3392    /// names no view this renderer built, or if no frame has begun.
3393    pub fn begin_view(
3394        &mut self,
3395        device: &dyn Device,
3396        view: ViewId,
3397        camera: &Camera,
3398        extent: (u32, u32),
3399    ) -> Result<(), HalError> {
3400        assert!(
3401            view != ViewId::PRIMARY,
3402            "the primary camera's blocks are written by `begin_frame`"
3403        );
3404        let background = self
3405            .views
3406            .get(view.index() - 1)
3407            .and_then(Option::as_ref)
3408            .unwrap_or_else(|| panic!("{view:?} is not a view this renderer built"))
3409            .background;
3410        let scene = self
3411            .frame_scene
3412            .take()
3413            .expect("`begin_view` follows the `begin_frame` that opened the frame");
3414        let mut frame = self.view_frame(&scene, extent, self.instances.slot_count(), camera.eye);
3415        frame.extent = self.view_extent(background, extent);
3416        let written = self
3417            .views
3418            .get_mut(view.index() - 1)
3419            .and_then(Option::as_mut)
3420            .unwrap_or_else(|| panic!("{view:?} is not a view this renderer built"))
3421            .begin_frame(device, camera, &frame, self.sky_view.as_ref());
3422        self.frame_scene = Some(scene);
3423        written.map(|_| ())
3424    }
3425
3426    /// Sets the views `handle` is drawn in. Every instance starts in
3427    /// [`ViewMask::ALL`].
3428    ///
3429    /// **A camera's cull and nothing else**: a view the instance is hidden from
3430    /// rejects it before testing a bound, and every shadow map still draws it —
3431    /// so a weapon hidden from a scope's view goes on casting the shadow the
3432    /// primary camera sees.
3433    ///
3434    /// Not a move: the record's transform history is left as it is, so a
3435    /// visibility change does not report motion. A stale handle is ignored, on
3436    /// [`set_instance`](Self::set_instance)'s terms.
3437    pub fn set_instance_views(&mut self, handle: InstanceHandle, views: ViewMask) {
3438        if let Some(record) = self.instances.get(handle) {
3439            let flags =
3440                (record.flags & !mesh::GpuInstance::HIDDEN_VIEWS_MASK) | views.hidden_bits();
3441            self.instances.set_flags(handle, flags);
3442        }
3443    }
3444
3445    /// The views `handle` is drawn in, or `None` for a stale handle.
3446    #[must_use]
3447    pub fn instance_views(&self, handle: InstanceHandle) -> Option<ViewMask> {
3448        self.instances
3449            .get(handle)
3450            .map(|record| ViewMask::from_flags(record.flags))
3451    }
3452
3453    /// `view`'s draw generator — [`draws`](Self::draws) for a view other than
3454    /// the primary camera.
3455    ///
3456    /// # Panics
3457    ///
3458    /// If `view` names no view this renderer built.
3459    #[must_use]
3460    pub fn view_draws(&self, view: ViewId) -> &DrawGen {
3461        if view == ViewId::PRIMARY {
3462            return &self.primary.draws;
3463        }
3464        &self
3465            .views
3466            .get(view.index() - 1)
3467            .and_then(Option::as_ref)
3468            .unwrap_or_else(|| panic!("{view:?} is not a view this renderer built"))
3469            .draws
3470    }
3471
3472    /// The target's aspect and the internal extent a frame into `target` is
3473    /// drawn at.
3474    ///
3475    /// **The aspect is the target's and the extent is the internal render
3476    /// extent's.** What a viewer sees is the target: the upscale maps the whole
3477    /// internal image onto the whole of it, so a frame composed for the internal
3478    /// extent's own aspect would be composed for a rectangle nobody looks at.
3479    /// What the rounding of the two extents leaves is a sub-pixel
3480    /// non-squareness in the internal target, which the upscale undoes on the
3481    /// way out.
3482    ///
3483    /// A minimised window reports a zero extent in *either* dimension, and
3484    /// `Projection::matrix` asserts a finite positive aspect. Guarding only the
3485    /// height left `extent.0 == 0` producing `0.0`, which trips that assert and
3486    /// takes the frame loop down with it.
3487    ///
3488    /// The extent is the one a frame is *drawn* at, which is the caller's at a
3489    /// render scale of `1.0` and smaller below it. Every use of it sizes
3490    /// something — the cluster grid, the LOD metric's pixel budget, the Hi-Z
3491    /// pyramid's height, the bloom chain, the resolve's texel size — and every
3492    /// one of those wants the extent the pixels are actually at. See
3493    /// [`Self::set_render_scale`].
3494    pub(super) fn frame_extents(&self, target: (u32, u32)) -> (f32, (u32, u32)) {
3495        let aspect = if target.0 == 0 || target.1 == 0 {
3496            1.0
3497        } else {
3498            target.0 as f32 / target.1 as f32
3499        };
3500        (aspect, self.internal_extent(target))
3501    }
3502
3503    /// The internal extent a secondary view with `background` is drawn at, for
3504    /// a target of `target`: [`frame_extents`](Self::frame_extents)' answer,
3505    /// except that a [`ViewBackground::Transparent`] view is always drawn at
3506    /// its target's own extent — the upscale would filter its coverage edges,
3507    /// see that variant.
3508    pub(super) fn view_extent(&self, background: ViewBackground, target: (u32, u32)) -> (u32, u32) {
3509        if background.is_transparent() {
3510            target
3511        } else {
3512            self.frame_extents(target).1
3513        }
3514    }
3515
3516    /// What every view's [`View::begin_frame`] reads of this frame, for a view
3517    /// drawn into a target of `target_extent`.
3518    pub(super) fn view_frame<'s>(
3519        &self,
3520        scene: &'s FrameScene,
3521        target_extent: (u32, u32),
3522        instance_count: u32,
3523        selection_eye: Vec3,
3524    ) -> ViewFrame<'s> {
3525        let (aspect, extent) = self.frame_extents(target_extent);
3526        // The frame's gradient, resolved once and handed to all three of the
3527        // things that want a sky: the L1 projection below for the ambient term,
3528        // the march's block for a reflection that hit nothing, and the pass that
3529        // draws the background. One `SkyGradient` rather than three readings of
3530        // the field, so the sky a surface is lit by cannot differ from the one
3531        // behind it.
3532        //
3533        // An atmosphere replaces the gradient outright — see `set_atmosphere`.
3534        // `gradient_fit` is what the reflection pass and the background's own
3535        // gradient rows take, `irradiance` is the ambient term, and the LUT
3536        // itself is what the background samples. The first two are taken when
3537        // a march finishes rather than here — see `PresentedSky` — so a frame
3538        // whose sun has not moved reads them.
3539        let sky_view = self.sky_view.as_ref();
3540        let gradient = match sky_view {
3541            Some(presented) => presented.gradient,
3542            None => self.sky.gradient(),
3543        };
3544        // Projected on the host — once per gradient, and for an atmosphere once
3545        // per completed march rather than once per frame — which is also why
3546        // the shading rule that governs `mesh.slang` has nothing to say about
3547        // it: these coefficients reach every backend as uploaded numbers.
3548        let sky_irradiance = match sky_view {
3549            Some(presented) => presented.irradiance,
3550            None => gradient.irradiance(),
3551        };
3552        ViewFrame {
3553            slot: self.frame,
3554            serial: self.frame_serial,
3555            aspect,
3556            extent,
3557            effects: self.frame_effects,
3558            instance_count,
3559            selection_eye,
3560            lod_error_budget: self.lod_error_budget,
3561            lod_hold_ratio: self.lod_hold_ratio,
3562            scene,
3563            // The field as it stands, and the weather over it. Read here rather
3564            // than in `View::begin_frame` because that method takes `&mut self`
3565            // on the view and the field is the *renderer's*.
3566            grass: self.grass.frame(),
3567            wind: self.wind,
3568            fog: self.fog,
3569            probe_volume: self.probe_volume,
3570            attribute_base: self.pool.attribute_base(),
3571            gradient,
3572            sky_irradiance,
3573            debug_view_lane: self.debug_view_lane(),
3574            exposure: self.exposure,
3575            exposure_adaptation: self.exposure_adaptation,
3576            tonemap_curve: self.resolved_tonemap_curve(),
3577            occlusion: self.resolved_occlusion_culling(),
3578        }
3579    }
3580}
3581
3582// Uses `forward::tests`' fixtures, which are native-only with them.
3583#[cfg(all(test, not(target_arch = "wasm32")))]
3584mod tests;