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