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