Skip to main content

crcbl_render/
volumetric.rs

1//! The froxel volume the medium is integrated in, and the pass that composites
2//! it over the frame — rungs 1 and 2 of the ladder whose rules are in
3//! `docs/notes/rendering.md`.
4//!
5//! ```text
6//!  begin_frame ──▶ camera + medium + cascades ──▶ params[frame]
7//!
8//!  add_passes ── compute "volumetric-scatter"   ──▶ froxels[frame]     (per slice)
9//!                          shadow-atlas + light grid ──▶ lighting[frame]
10//!             ── compute "volumetric-integrate" ──▶ froxels[frame]     (per tile)
11//!             ── render  "volumetric-composite" scene-color ──▶ fogged
12//!                          sky_pass's aerial[frame] ──┘
13//! ```
14//!
15//! # The composite also puts the atmosphere's air in front of the scene
16//!
17//! On a frame with an atmosphere the composite reads
18//! [`crcbl_shaders::atmosphere::AerialView`] — `crate::sky_pass` owns its ring
19//! — and composes it **before** the column, so the scene is
20//! `((scene · T_air + S_air) · T_fog) + S_fog`: the local fog is the near
21//! medium and its glow must not be attenuated by the kilometres of air behind
22//! it. Sky pixels are spared, because the sky-view LUT has already integrated
23//! the whole of their ray.
24//!
25//! **The two halves switch independently.** The column's scatter and scan run
26//! with the fog effect and nowhere else, and the composite runs on every frame
27//! with the effect *or* an atmosphere — so a frame with an atmosphere and no
28//! fog effect adds the composite alone, and the block's `fog_params.w` —
29//! [`crcbl_shaders::volumetric::LOCAL_COLUMN_OFF`] — is what stops it reading a
30//! column nothing filled. A frame with the fog effect and no atmosphere writes
31//! the block it always wrote and composes the bytes it always composed.
32//!
33//! A module of its own on [`crate::ssr`]'s terms exactly: two pipelines, a
34//! buffer ring and the pass group, none of it reachable from the geometry
35//! passes except through [`Volumetric::add_passes`].
36//!
37//! # Why a buffer and not a 3D texture
38//!
39//! Every published froxel implementation writes a volume texture, and this one
40//! writes [`crate::light_grid`]'s subdivision into a storage buffer instead.
41//! The reason is a seam fact rather than a preference: [`crate::transient`] is
42//! 2D-only — its descriptor carries no depth and its pool hard-codes
43//! `ImageType::D2` — so a volume here would be the engine's **first** 3D image
44//! on four backends at once. That is the shape of gap that had a read-only
45//! depth attachment compile everywhere and refuse on D3D12. The froxel grid is
46//! already a storage buffer the clustering pass writes and the fragment stage
47//! reads, so the scattering rides a subdivision that four backends already run.
48//!
49//! # The buffer holds two different things, one after the other
50//!
51//! `volumetric.slang` writes each froxel's **own** scattered radiance and
52//! transmittance, and then overwrites every froxel with the **exclusive prefix**
53//! of the column in front of it. The composite therefore reads "everything
54//! between the eye and this slice's start", and integrates the last partial
55//! slice itself along the pixel's own ray — which is what keeps a frame off the
56//! slice boundaries. An exponential split makes the far slices hundreds of
57//! units deep, and snapping a pixel to one of those is the banding this design
58//! exists to avoid.
59//!
60//! # The medium is charged exactly once
61//!
62//! `mesh.slang` composites the same exponential height fog analytically. Both
63//! running is the medium charged twice, so [`ForwardRenderer::add_passes`] zeroes
64//! the frame block's density on a frame that adds these passes — the froxel path
65//! owns the medium when it exists. That is also the rung's observable: the
66//! environment term's single-scattering albedo is one, so a column with no sun
67//! in it is algebraically the closed form the fragment stage was computing and
68//! the two frames have to agree. The sun is added on top of that and is zero
69//! until a caller sets [`Fog::sun_scattering`], which keeps the equality as this
70//! feature's off-switch rather than as a stage it has left behind.
71//!
72//! # The sun is occluded per froxel, in a buffer of its own
73//!
74//! The scatter pass looks each froxel's midpoint up in the cascades
75//! [`crate::shadow`] filled, and scales the *sun* term of its scattering source
76//! by what comes back — the environment term is what reaches the medium from
77//! every direction, and an occluder in front of the sun does not remove it. The
78//! answer is written to a second buffer the scan does not touch, because
79//! `volumetric_composite.slang` integrates the last partial slice for itself and
80//! needs the same source this pass used; [`LIGHTING_STRIDE`] carries the
81//! argument for why that is a buffer rather than a second cascade walk. Rung 2
82//! put the froxel's punctual lights beside it: the scatter pass walks the
83//! froxel's own cluster list — the one `crate::light_grid` built for the mesh
84//! pass — at the slice's midpoint, and the glow rides the same row, occluded
85//! by the lamp's own shadow tiles where its row names them.
86//!
87//! [`ForwardRenderer::add_passes`]: crate::forward::ForwardRenderer::add_passes
88
89use crcbl_hal::{
90    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
91    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
92    BufferUsage, ClearValue, ColorTargetState, ComputePipelineHandle, Device, Format,
93    GraphicsPipelineHandle, HalError, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
94    PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, SampleType, SamplerHandle,
95    ShaderStages, StoreOp, check_portable_storage_buffers,
96};
97use crcbl_shaders::sky::{ATMOSPHERE_OFF, ATMOSPHERE_ON};
98use crcbl_shaders::volumetric::{
99    FROXEL_STRIDE, LIGHTING_STRIDE, LOCAL_COLUMN_OFF, LOCAL_COLUMN_ON, PARAMS_SIZE,
100    VolumetricParams, WORKGROUP_SIZE,
101};
102use crcbl_shaders::{VOLUMETRIC, VOLUMETRIC_COMPOSITE};
103
104use crate::camera::{DirectionalLight, Fog};
105use crate::draw_gen::{UINT_STRIDE, bound, compute_pipeline_entry, storage, uniform};
106use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
107use crate::light_grid::{FrameView, Grid, LightGrid};
108use crate::shadow::{self, Cascades};
109use crate::ssao::cached_group;
110
111/// Vertices in the over-sized full-screen triangle `volumetric_composite.slang`
112/// generates from `SV_VertexID`. No geometry is bound anywhere.
113const FULLSCREEN_VERTICES: u32 = 3;
114
115/// The graph transients [`Volumetric::add_passes`] reads and writes.
116///
117/// One struct rather than three positional arguments, on
118/// [`SsrImages`](crate::ssr::SsrImages)' terms: three values of one type are
119/// three values that can be swapped silently at the call site.
120#[derive(Clone, Copy, Debug)]
121pub(crate) struct VolumetricImages {
122    /// The depth prepass's stored depth: how far along its ray each pixel's
123    /// column is cut off.
124    pub(crate) depth: ImageId,
125    /// The frame as it stands — the forward pass's scene colour with the sky
126    /// drawn into it.
127    pub(crate) color: ImageId,
128    /// Where the composite writes, and the image the caller must go on to use
129    /// in [`VolumetricImages::color`]'s place.
130    pub(crate) composited: ImageId,
131    /// The sun's cascades, as [`crate::shadow`] left them.
132    ///
133    /// Read by the **scatter** pass, which is what puts a shaft in the column:
134    /// declaring it is what moves the atlas from the depth attachment the
135    /// shadow pass wrote into a layout a compute stage can sample.
136    pub(crate) shadow_atlas: ImageId,
137}
138
139/// What [`Volumetric::add_passes`] reads besides the images, and which of its
140/// passes it adds.
141///
142/// One struct rather than three more arguments, on [`VolumetricImages`]'
143/// terms.
144#[derive(Clone, Copy, Debug)]
145pub(crate) struct VolumetricReads {
146    /// The froxel list the clustering pass filled this frame, as the graph
147    /// knows it: the scatter pass declares the read, which is what orders it
148    /// after that dispatch.
149    pub(crate) light_grid: BufferId,
150    /// Whether the fog effect is on, and so whether the scatter and scan run.
151    ///
152    /// It must be what [`Volumetric::begin_frame`] was handed as
153    /// [`Medium::local`]: the block's switch is what stops the composite
154    /// reading a column no pass filled.
155    pub(crate) local: bool,
156    /// [`crate::sky_pass::SkyPass::aerial`]'s slot for this frame, bound
157    /// whether or not the frame has an atmosphere — the block's other switch
158    /// decides whether it is read.
159    pub(crate) aerial: BufferHandle,
160}
161
162/// The buffers one frame's froxel column lives in.
163///
164/// **A window for a test, and the froxel path's only public surface.** The
165/// column is checked against `crcbl_shaders::volumetric` on the host, per
166/// froxel, which is the one thing that can tell a wrong scatter from a wrong
167/// scan: the frame-level checks compare a picture against the closed form, and
168/// at a single-scattering albedo of one those two mistakes compose to the same
169/// answer. Handing out the handles is what lets that comparison exist without
170/// this module's internals leaving it.
171///
172/// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count) is the
173/// same shape and the precedent for it.
174#[derive(Clone, Copy, Debug)]
175pub struct FroxelBuffers {
176    /// The parameter block both compute passes and the composite read —
177    /// [`crcbl_shaders::volumetric::PARAMS_SIZE`] bytes, in the layout
178    /// [`VolumetricParams::from_bytes`] decodes.
179    pub params: BufferHandle,
180    /// The column: [`FROXEL_STRIDE`] bytes per froxel, holding the **exclusive
181    /// prefix** in front of each slice once the frame's passes have run.
182    pub froxels: BufferHandle,
183    /// What each froxel's lights put into it — [`LIGHTING_STRIDE`] bytes per
184    /// froxel: the punctual glow in `rgb`, the sun's visibility in `w`, as the
185    /// scatter pass left them and the scan did not touch them.
186    pub lighting: BufferHandle,
187}
188
189/// What lights the medium on this frame.
190///
191/// One struct rather than three more arguments, on [`VolumetricImages`]' terms:
192/// the three are read together and mean nothing apart. The medium's own
193/// properties are [`Fog`]; the sun and its cascades are what a shaft is cast
194/// by, and they have to be the frame's own — `Cascades::new` builds the
195/// matrices from the camera and the light, so a block carrying one frame's
196/// light with another's cascades would shadow a shaft against boxes that are no
197/// longer where it is.
198#[derive(Clone, Copy, Debug)]
199pub(crate) struct Medium<'a> {
200    /// The medium: its density, its falloff, its colour and how it scatters the
201    /// sun.
202    pub(crate) fog: Fog,
203    /// The sun, whose radiance the medium scatters and whose direction the
204    /// phase function is evaluated against.
205    pub(crate) sun: &'a DirectionalLight,
206    /// The cascades that sun was shadowed through, which is what occludes the
207    /// shaft.
208    pub(crate) cascades: &'a Cascades,
209    /// One matrix per light tile of the atlas, as the frame block carries them
210    /// — the maps the frame's shadowed lamps were drawn into, which is what
211    /// stops a lamp's glow at a wall. The frame's own, on `cascades`' terms:
212    /// `shadow::Selection` handed out the tiles the light rows name, and a
213    /// block with another frame's matrices would read the right tile of the
214    /// wrong map.
215    pub(crate) light_view_proj: &'a [[f32; 16]; shadow::LIGHT_TILES],
216    /// Where each of those maps is in the atlas, as the frame block carries
217    /// them — a scale and an offset per slot, out of the same
218    /// `shadow::Selection` the matrices came from. A froxel that read a
219    /// rectangle from one frame and a matrix from another would sample the
220    /// right map's place for the wrong map.
221    pub(crate) atlas_rects: &'a [[f32; 4]; shadow::TILES],
222    /// Whether this frame's scatter and scan run — the fog effect — and so
223    /// whether the composite reads the column they fill.
224    pub(crate) local: bool,
225    /// The sun the frame's [`crcbl_shaders::atmosphere::AerialView`] was
226    /// marched around, or `None` on a frame with no atmosphere — whose
227    /// composite then puts no air in front of anything.
228    pub(crate) aerial: Option<[f32; 3]>,
229}
230
231/// Everything the froxel volume owns.
232#[derive(Debug)]
233pub(crate) struct Volumetric {
234    /// `[frame]`: the parameter block both shaders read. A ring for the frame
235    /// uniforms' reason — the previous frame may still be reading its own.
236    params: Vec<BufferHandle>,
237    /// `[frame]`: the froxel volume. **Device-local**, because a shader writes
238    /// it: D3D12 has no unordered-access view of an upload-heap resource at
239    /// all — [`crate::draw_gen`]'s module docs carry the full account.
240    /// `TRANSFER_SRC` so a test can read back what the GPU decided.
241    froxels: Vec<BufferHandle>,
242    /// `[frame]`: one `float4` per froxel — what its punctual lights scatter,
243    /// and how much of the sun it sees.
244    ///
245    /// Written by the scatter pass and read by the composite, and untouched by
246    /// the scan between them — which is the whole reason it is a second buffer
247    /// rather than a component of the first, argued at
248    /// [`LIGHTING_STRIDE`].
249    lighting: Vec<BufferHandle>,
250    compute_layout: BindGroupLayoutHandle,
251    compute_pipeline_layout: PipelineLayoutHandle,
252    scatter: ComputePipelineHandle,
253    integrate: ComputePipelineHandle,
254    /// `[frame]`: the compute group. Names only buffers this owns, so it is
255    /// built once rather than cached against a graph-realised view.
256    compute_groups: Vec<BindGroupHandle>,
257    composite_layout: BindGroupLayoutHandle,
258    composite_pipeline_layout: PipelineLayoutHandle,
259    composite_pipeline: GraphicsPipelineHandle,
260    /// `[frame]`: the composite group, cached against both its views together.
261    ///
262    /// **One per frame in flight** on [`crate::ssr`]'s terms: this group names
263    /// [`Volumetric::params`] and [`Volumetric::froxels`] as well as two graph
264    /// transients, and both of those are rings — a single cache keyed on the
265    /// views alone would hand the even frames' buffers to the odd frames.
266    composite_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
267}
268
269impl Volumetric {
270    /// Passes [`Volumetric::add_passes`] adds to a frame at most: the column's
271    /// and the composite's.
272    ///
273    /// A ceiling since the air arrived: a frame whose fog effect is off and
274    /// whose atmosphere is not adds the composite alone.
275    pub(crate) const PASSES: u32 = Self::COLUMN_PASSES + Self::COMPOSITE_PASSES;
276
277    /// The column's compute passes — the scatter and the scan — which run
278    /// exactly when the fog effect does.
279    ///
280    /// Exact rather than a ceiling: a frame always has froxels — [`Grid`] floors
281    /// every extent at one tile and one slice — so neither ever drops out.
282    pub(crate) const COLUMN_PASSES: u32 = 2;
283
284    /// The composite, which runs on every frame with the fog effect or an
285    /// atmosphere, and the only full-screen draw among them.
286    pub(crate) const COMPOSITE_PASSES: u32 = 1;
287
288    /// Builds both pipelines, the buffer rings and the compute groups.
289    ///
290    /// `froxels` is the volume's capacity, which is
291    /// [`FROXEL_CAPACITY`](crate::light_grid::FROXEL_CAPACITY) outside a test
292    /// that wants a smaller one, and it is what [`Grid::for_frame`] is asked to
293    /// fit a frame under.
294    ///
295    /// `lights` is the frame ring the scatter pass reads its light rows and
296    /// its froxel lists from — the same buffers the mesh pass binds — and the
297    /// compute groups name them at construction, which is sound for the reason
298    /// the shadow atlas is: [`LightGrid`] creates its ring once and hands out
299    /// the same handles for its whole life.
300    ///
301    /// `build_fullscreen` is handed in rather than duplicated, on
302    /// [`Ssr::new`](crate::ssr::Ssr::new)'s terms: it is [`crate::forward`]'s,
303    /// because the shape it carries is documented there.
304    ///
305    /// # Errors
306    ///
307    /// [`HalError`] from any seam call. **Nothing is released on the failing
308    /// path**, for the reason every other builder in this crate gives: the
309    /// caller holds a rollback, and this is stored in it whole.
310    pub(crate) fn new(
311        device: &dyn Device,
312        frames: usize,
313        froxels: u32,
314        shadow_atlas: ImageViewHandle,
315        shadow_sampler: SamplerHandle,
316        lights: &LightGrid,
317        build_fullscreen: impl Fn(
318            &dyn Device,
319            &str,
320            &crcbl_shaders::Shader,
321            PipelineLayoutHandle,
322            &[ColorTargetState],
323        ) -> Result<GraphicsPipelineHandle, HalError>,
324    ) -> Result<Self, HalError> {
325        if frames == 0 || froxels == 0 {
326            return Err(HalError::InvalidDescriptor(
327                "a froxel volume needs at least one frame in flight and one froxel".to_string(),
328            ));
329        }
330        // `volumetric.slang`'s declaration order, which is the only order Metal
331        // and D3D12 agree about — see `crcbl_shaders::declaration_order`.
332        let compute_entries = [
333            uniform(0),
334            storage(1, false, crcbl_shaders::volumetric::FROXEL_STRIDE as u32),
335            BindGroupLayoutEntry {
336                binding: 2,
337                visibility: ShaderStages::COMPUTE,
338                kind: BindingKind::SampledImage {
339                    view_type: ImageViewType::D2,
340                    // `Depth`, for the reason the composite's own depth binding
341                    // gives: WebGPU binds a `D32Float` view only through a depth
342                    // sample type, and the WGSL declares `texture_depth_2d`.
343                    sample_type: SampleType::Depth,
344                },
345                count: 1,
346                flags: BindingFlags::empty(),
347            },
348            BindGroupLayoutEntry {
349                binding: 3,
350                visibility: ShaderStages::COMPUTE,
351                // **A comparison sampler in a compute stage**, which is what is
352                // new at this rung. The shader asks with `SampleCmpLevelZero`,
353                // which needs no derivatives and is legal outside a fragment
354                // shader on all four targets — unlike the implicit-LOD form the
355                // forward pass uses.
356                kind: BindingKind::Sampler { comparison: true },
357                count: 1,
358                flags: BindingFlags::empty(),
359            },
360            storage(4, false, crcbl_shaders::volumetric::LIGHTING_STRIDE as u32),
361            // The light rows and the froxel lists, read and never written —
362            // `StructuredBuffer` in the shader, and the clustering pass is what
363            // wrote the second before this pass runs.
364            storage(5, true, crcbl_shaders::light::LIGHT_STRIDE as u32),
365            storage(6, true, UINT_STRIDE),
366        ];
367        let compute_desc = BindGroupLayoutDesc {
368            label: Some("volumetric"),
369            entries: &compute_entries,
370        };
371        check_portable_storage_buffers(Some("volumetric"), &[&compute_desc])?;
372        let compute_layout = device.create_bind_group_layout(&compute_desc)?;
373        let compute_set_layouts = [compute_layout];
374        let compute_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
375            label: Some("volumetric"),
376            bind_group_layouts: &compute_set_layouts,
377            push_constants: None,
378        })?;
379        // Two entry points of one module, which is why this is
380        // `compute_pipeline_entry` rather than `compute_pipeline`: the pair
381        // shares the froxel arithmetic and shaders here have no `#include`.
382        let scatter = compute_pipeline_entry(
383            device,
384            "volumetric scatter",
385            &VOLUMETRIC,
386            "scatterMain",
387            compute_pipeline_layout,
388            WORKGROUP_SIZE,
389        )?;
390        let integrate = compute_pipeline_entry(
391            device,
392            "volumetric integrate",
393            &VOLUMETRIC,
394            "integrateMain",
395            compute_pipeline_layout,
396            WORKGROUP_SIZE,
397        )?;
398
399        let composite_entries = [
400            BindGroupLayoutEntry {
401                binding: 0,
402                visibility: ShaderStages::FRAGMENT,
403                kind: BindingKind::UniformBuffer { dynamic: false },
404                count: 1,
405                flags: BindingFlags::empty(),
406            },
407            BindGroupLayoutEntry {
408                binding: 1,
409                visibility: ShaderStages::FRAGMENT,
410                kind: BindingKind::SampledImage {
411                    view_type: ImageViewType::D2,
412                    // `Depth`, and the paragraph on `crate::ssr`'s own depth
413                    // binding is this one's too: it is the same image, read
414                    // through the same `texture_depth_2d`.
415                    sample_type: SampleType::Depth,
416                },
417                count: 1,
418                flags: BindingFlags::empty(),
419            },
420            BindGroupLayoutEntry {
421                binding: 2,
422                visibility: ShaderStages::FRAGMENT,
423                kind: BindingKind::SampledImage {
424                    view_type: ImageViewType::D2,
425                    // The `Rgba16Float` scene target: an ordinary colour image,
426                    // and the WGSL artifact declares `texture_2d<f32>` for it.
427                    sample_type: SampleType::Float,
428                },
429                count: 1,
430                flags: BindingFlags::empty(),
431            },
432            BindGroupLayoutEntry {
433                binding: 3,
434                visibility: ShaderStages::FRAGMENT,
435                kind: BindingKind::StorageBuffer {
436                    // The prefix scan, read and not written — `StructuredBuffer`
437                    // in the shader, which is the truth rather than a hint.
438                    read_only: true,
439                    dynamic: false,
440                    stride: crcbl_shaders::volumetric::FROXEL_STRIDE as u32,
441                },
442                count: 1,
443                flags: BindingFlags::empty(),
444            },
445            BindGroupLayoutEntry {
446                binding: 4,
447                visibility: ShaderStages::FRAGMENT,
448                kind: BindingKind::StorageBuffer {
449                    // Each froxel's share of its lights, as the scatter pass
450                    // measured it. Read and never written here.
451                    read_only: true,
452                    dynamic: false,
453                    stride: crcbl_shaders::volumetric::LIGHTING_STRIDE as u32,
454                },
455                count: 1,
456                flags: BindingFlags::empty(),
457            },
458            BindGroupLayoutEntry {
459                binding: 5,
460                visibility: ShaderStages::FRAGMENT,
461                kind: BindingKind::StorageBuffer {
462                    // The air in front of the scene — `crate::sky_pass`'s
463                    // aerial ring, written on the host and only read here.
464                    read_only: true,
465                    dynamic: false,
466                    stride: crcbl_shaders::atmosphere::AERIAL_VIEW_ROW_BYTES as u32,
467                },
468                count: 1,
469                flags: BindingFlags::empty(),
470            },
471        ];
472        let composite_desc = BindGroupLayoutDesc {
473            label: Some("volumetric composite"),
474            entries: &composite_entries,
475        };
476        check_portable_storage_buffers(Some("volumetric composite"), &[&composite_desc])?;
477        let composite_layout = device.create_bind_group_layout(&composite_desc)?;
478        let composite_set_layouts = [composite_layout];
479        let composite_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
480            label: Some("volumetric composite"),
481            bind_group_layouts: &composite_set_layouts,
482            push_constants: None,
483        })?;
484        // The same format the forward pass wrote: this image stands in for the
485        // scene colour from here on, so a narrower one would tonemap a truncated
486        // frame — and fog adds a radiance rather than only removing one.
487        let targets = [ColorTargetState::opaque(Format::Rgba16Float)];
488        let composite_pipeline = build_fullscreen(
489            device,
490            "volumetric composite",
491            &VOLUMETRIC_COMPOSITE,
492            composite_pipeline_layout,
493            &targets,
494        )?;
495
496        let mut params = Vec::with_capacity(frames);
497        let mut volumes = Vec::with_capacity(frames);
498        let mut lighting = Vec::with_capacity(frames);
499        let mut compute_groups = Vec::with_capacity(frames);
500        for frame in 0..frames {
501            let block = device.create_buffer(&BufferDesc {
502                label: Some(&format!("volumetric params {frame}")),
503                size: PARAMS_SIZE as u64,
504                // `TRANSFER_SRC` for the reason the froxel volume carries it: a
505                // test reads the block back rather than deriving a second copy
506                // of it, so what it models the column from is what the shaders
507                // were handed. Host-visible memory is not a substitute — an
508                // upload heap is write-combined, and reading it back on the
509                // host is a different question from what the device saw.
510                usage: BufferUsage::UNIFORM | BufferUsage::TRANSFER_SRC,
511                memory: MemoryLocation::HostUpload,
512            })?;
513            let volume = device.create_buffer(&BufferDesc {
514                label: Some(&format!("volumetric froxels {frame}")),
515                size: u64::from(froxels) * FROXEL_STRIDE as u64,
516                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
517                memory: MemoryLocation::DeviceLocal,
518            })?;
519            let seen = device.create_buffer(&BufferDesc {
520                label: Some(&format!("volumetric lighting {frame}")),
521                size: u64::from(froxels) * LIGHTING_STRIDE as u64,
522                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
523                memory: MemoryLocation::DeviceLocal,
524            })?;
525            // **Built once rather than cached against the graph**, which the
526            // shadow atlas and the light ring are what make possible: the
527            // renderer owns that image and those buffers for its whole life and
528            // hands the graph the same handles every frame, so this group names
529            // nothing a frame can change.
530            let group = device.create_bind_group(&BindGroupDesc {
531                label: Some(&format!("volumetric {frame}")),
532                layout: compute_layout,
533                entries: &[
534                    bound(0, block),
535                    bound(1, volume),
536                    BindGroupEntry {
537                        binding: 2,
538                        array_index: 0,
539                        resource: BindingResource::ImageView(shadow_atlas),
540                    },
541                    BindGroupEntry {
542                        binding: 3,
543                        array_index: 0,
544                        resource: BindingResource::Sampler(shadow_sampler),
545                    },
546                    bound(4, seen),
547                    bound(5, lights.lights(frame)),
548                    bound(6, lights.grid(frame)),
549                ],
550                // No binding here is an array, so nothing has a runtime length
551                // to declare — the same `None` every other pass in this crate
552                // passes.
553                variable_count: None,
554            })?;
555            params.push(block);
556            volumes.push(volume);
557            lighting.push(seen);
558            compute_groups.push(group);
559        }
560
561        Ok(Self {
562            params,
563            froxels: volumes,
564            lighting,
565            compute_layout,
566            compute_pipeline_layout,
567            scatter,
568            integrate,
569            compute_groups,
570            composite_layout,
571            composite_pipeline_layout,
572            composite_pipeline,
573            composite_groups: vec![None; frames],
574        })
575    }
576
577    /// Writes `frame`'s parameter block: the camera, the grid and the medium.
578    ///
579    /// `grid` must be the same [`Grid`] handed to [`Volumetric::add_passes`] and
580    /// the same one the frame's clustering pass used — the composite converts a
581    /// pixel to a froxel index with these numbers, and a block from one grid
582    /// with a dispatch from another reads a column built for somewhere else.
583    ///
584    /// # Errors
585    ///
586    /// [`HalError`] from the mapped write.
587    ///
588    /// # Panics
589    ///
590    /// If `frame` is not a slot this was built with.
591    pub(crate) fn begin_frame(
592        &self,
593        device: &dyn Device,
594        frame: usize,
595        grid: Grid,
596        view: FrameView,
597        medium: Medium<'_>,
598    ) -> Result<(), HalError> {
599        let Medium {
600            fog,
601            sun,
602            cascades,
603            light_view_proj,
604            atlas_rects,
605            local,
606            aerial,
607        } = medium;
608        // Row 3 of the view-projection, so a shader can take a point's view
609        // depth with one dot product — [`crate::light_grid`]'s block carries the
610        // same row for the same reason, and both come from this one matrix so
611        // the two passes cut the frustum at the same depths.
612        let columns = view.view_projection.to_cols_array();
613        let depth_row = [columns[3], columns[7], columns[11], columns[15]];
614        let mut shadow_view_proj = [[0.0f32; 16]; shadow::CASCADES];
615        for (matrix, cascade) in shadow_view_proj.iter_mut().zip(&cascades.view_proj) {
616            *matrix = cascade.to_cols_array();
617        }
618        device.write_buffer(
619            self.params[frame],
620            0,
621            &VolumetricParams {
622                inverse_view_proj: view.view_projection.inverse().to_cols_array(),
623                eye: view.eye.extend(1.0).to_array(),
624                depth_row,
625                // The column's switch in `w`: on — the zero this lane held as
626                // padding — wherever the scatter and scan run.
627                fog_params: [
628                    fog.density,
629                    fog.falloff,
630                    fog.reference_height,
631                    if local {
632                        LOCAL_COLUMN_ON
633                    } else {
634                        LOCAL_COLUMN_OFF
635                    },
636                ],
637                fog_color: fog.color.extend(0.0).to_array(),
638                // Towards the sun, which is `mesh.slang`'s `to_light` and the
639                // opposite of the direction its light travels — the phase
640                // function's own convention, spelled out on
641                // `volumetric_phase`. Normalised here rather than trusted: a
642                // caller may hand the renderer any vector, and a longer one
643                // would scale a cosine past the clamp and flatten the lobe.
644                sun_direction: sun
645                    .direction
646                    .normalize_or_zero()
647                    .extend(fog.anisotropy)
648                    .to_array(),
649                // Zero unless a caller asked for it, which is what keeps the
650                // column algebraically the closed form until they do.
651                // And the punctual coefficient beside it, the same zero until
652                // asked for — the rows it scales are the frame's own light list.
653                sun_radiance: (sun.color * fog.sun_scattering)
654                    .extend(fog.light_scattering)
655                    .to_array(),
656                // **The cascades the frame block already carries**, handed to
657                // the scatter pass so a froxel and the surface behind it are
658                // shadowed by one set of matrices. `Cascades::new` builds them
659                // from the camera and the light alone, so there is no version
660                // of this where the two could be a frame apart.
661                shadow_view_proj,
662                cascade_far: cascades.far,
663                shadow_params: Cascades::params(),
664                grid_x: grid.x,
665                grid_y: grid.y,
666                slices: grid.slices,
667                tile_pixels: grid.tile_pixels,
668                viewport_x: view.extent.0.max(1),
669                viewport_y: view.extent.1.max(1),
670                froxel_count: grid.froxels(),
671                light_view_proj: *light_view_proj,
672                shadow_atlas_rect: *atlas_rects,
673                // The atmosphere's own sun, which the LUT's azimuth is measured
674                // from, and the switch. All zeroes on a frame with no
675                // atmosphere, which is the row every frame before the air
676                // existed wrote nothing into.
677                aerial_params: match aerial {
678                    Some(sun) => [sun[0], sun[1], sun[2], ATMOSPHERE_ON],
679                    None => [0.0, 0.0, 0.0, ATMOSPHERE_OFF],
680                },
681            }
682            .to_bytes(),
683        )
684    }
685
686    /// `frame`'s froxel column and the numbers it was built from.
687    ///
688    /// # Panics
689    ///
690    /// If `frame` is not a slot this was built with.
691    pub(crate) fn buffers(&self, frame: usize) -> FroxelBuffers {
692        FroxelBuffers {
693            params: self.params[frame],
694            froxels: self.froxels[frame],
695            lighting: self.lighting[frame],
696        }
697    }
698
699    /// Adds the scatter, integrate and composite passes, in that order — or
700    /// the composite alone where [`VolumetricReads::local`] is false.
701    ///
702    /// [`VolumetricImages::composited`] is what the caller must go on to use:
703    /// the medium is *in* it, and the scene colour it was composited over is not
704    /// the finished picture any more.
705    ///
706    /// Returns the column and its lighting as the graph knows them, so a later
707    /// pass that reads them — [`crate::water`] — declares the read against the
708    /// same ids rather than importing the buffers a second time.
709    ///
710    /// # Panics
711    ///
712    /// If `frame` is not a slot this was built with.
713    pub(crate) fn add_passes<'a>(
714        &'a mut self,
715        graph: &mut RenderGraph<'a>,
716        frame: usize,
717        grid: Grid,
718        images: VolumetricImages,
719        reads: VolumetricReads,
720    ) -> (BufferId, BufferId) {
721        let VolumetricReads {
722            light_grid,
723            local,
724            aerial,
725        } = reads;
726        let VolumetricImages {
727            depth,
728            color,
729            composited,
730            shadow_atlas,
731        } = images;
732        // The volume arrives in the state the previous frame that used this slot
733        // left it in, which is the state declared as final: the composite reads
734        // it. Vacuous on the first frame, and the real prior use on every later
735        // one.
736        let volume = graph.import_buffer(
737            "volumetric-froxels",
738            ImportedBuffer {
739                buffer: self.froxels[frame],
740                initial: ResourceState::ShaderRead,
741                final_state: ResourceState::ShaderRead,
742            },
743        );
744        // The same import the column gets, and for its reason: the composite is
745        // the last pass to read it, which is the state the next frame in this
746        // slot will find it in.
747        let seen = graph.import_buffer(
748            "volumetric-lighting",
749            ImportedBuffer {
750                buffer: self.lighting[frame],
751                initial: ResourceState::ShaderRead,
752                final_state: ResourceState::ShaderRead,
753            },
754        );
755        let compute_layout = self.compute_pipeline_layout;
756        let compute_group = self.compute_groups[frame];
757        let scatter = self.scatter;
758        let integrate = self.integrate;
759
760        // **The column only where the fog effect runs.** An atmosphere frame
761        // with the effect off adds the composite alone, for the air — and the
762        // block's `fog_params.w` is what tells it the column is not there, so
763        // this branch and that switch are one decision made in two places,
764        // both off the caller's `local`.
765        if local {
766            // One invocation per froxel, and never zero: `Grid::for_frame`
767            // floors every extent at one tile and one slice, and Metal rejects
768            // an empty dispatch outright rather than treating it as a no-op.
769            let froxel_groups = grid.froxels().div_ceil(WORKGROUP_SIZE);
770            graph
771                .add_compute_pass("volumetric-scatter")
772                // `ShaderReadWrite` rather than a write-only state, on the
773                // light grid's terms: a storage-buffer descriptor permits reads
774                // whatever the shader does with it.
775                .use_buffer(volume, ResourceState::ShaderReadWrite)
776                .use_buffer(seen, ResourceState::ShaderReadWrite)
777                // The cascades this pass looks a froxel up in. A read rather
778                // than a write, and it is what orders this dispatch after the
779                // shadow pass that filled them.
780                .read_image(shadow_atlas)
781                // And the froxel lists it walks, on the mesh pass's terms: the
782                // clustering pass left them in `ShaderReadWrite`, and declaring
783                // the read is what orders this dispatch after it.
784                .read_buffer(light_grid)
785                .execute(move |ctx| {
786                    let encoder = ctx.encoder();
787                    encoder.bind_compute_pipeline(scatter);
788                    encoder.bind_group(0, compute_group, &[], compute_layout);
789                    encoder.dispatch(froxel_groups, 1, 1);
790                });
791
792            // One invocation per **tile**, not per froxel: this pass walks a
793            // column front to back and turns each froxel into the exclusive
794            // prefix of the ones in front of it, which is a serial scan over
795            // the slice axis.
796            let tile_groups = grid
797                .x
798                .max(1)
799                .saturating_mul(grid.y.max(1))
800                .div_ceil(WORKGROUP_SIZE);
801            graph
802                .add_compute_pass("volumetric-integrate")
803                // The scatter's own output, read and overwritten in place — the
804                // graph's barrier between the two comes from both declaring
805                // this one id.
806                .use_buffer(volume, ResourceState::ShaderReadWrite)
807                .execute(move |ctx| {
808                    let encoder = ctx.encoder();
809                    encoder.bind_compute_pipeline(integrate);
810                    encoder.bind_group(0, compute_group, &[], compute_layout);
811                    encoder.dispatch(tile_groups, 1, 1);
812                });
813        }
814
815        let pipeline = self.composite_pipeline;
816        let pipeline_layout = self.composite_pipeline_layout;
817        let layout = self.composite_layout;
818        let params = self.params[frame];
819        let froxels = self.froxels[frame];
820        let lighting = self.lighting[frame];
821        let cached = &mut self.composite_groups[frame];
822        graph
823            .add_render_pass("volumetric-composite")
824            // `DontCare`, not `Clear`: the full-screen triangle writes every
825            // pixel of the target, so loading or clearing it is pure bandwidth.
826            .color(
827                composited,
828                LoadOp::DontCare,
829                StoreOp::Store,
830                ClearValue::default(),
831            )
832            // The forward pass left the colour in `ColorAttachment` and the
833            // prepass left the depth in `DepthStencilWrite`. Declaring the reads
834            // is what moves each into a shader-readable layout, and without them
835            // every backend reads whatever the last writer left behind.
836            //
837            // The column's two are declared on a frame that did not fill them
838            // too: the buffers are bound either way, and a read of a buffer
839            // already in `ShaderRead` is no barrier at all.
840            .read_image(color)
841            .read_image(depth)
842            .read_buffer(volume)
843            .read_buffer(seen)
844            .execute(move |ctx| {
845                let color_view = ctx.image_view(color);
846                let depth_view = ctx.image_view(depth);
847                let device = ctx.device();
848                let entries = [
849                    BindGroupEntry {
850                        binding: 0,
851                        array_index: 0,
852                        resource: BindingResource::whole_buffer(params),
853                    },
854                    // The two below are overwritten by `cached_group` with the
855                    // realised views; written here so the list is a complete
856                    // description of the layout rather than one with holes in it.
857                    BindGroupEntry {
858                        binding: 1,
859                        array_index: 0,
860                        resource: BindingResource::ImageView(depth_view),
861                    },
862                    BindGroupEntry {
863                        binding: 2,
864                        array_index: 0,
865                        resource: BindingResource::ImageView(color_view),
866                    },
867                    BindGroupEntry {
868                        binding: 3,
869                        array_index: 0,
870                        resource: BindingResource::whole_buffer(froxels),
871                    },
872                    BindGroupEntry {
873                        binding: 4,
874                        array_index: 0,
875                        resource: BindingResource::whole_buffer(lighting),
876                    },
877                    // The aerial ring's slot for this frame, which is the same
878                    // handle every time this slot comes round — so the cache
879                    // below, keyed on the two views alone, stays right.
880                    BindGroupEntry {
881                        binding: 5,
882                        array_index: 0,
883                        resource: BindingResource::whole_buffer(aerial),
884                    },
885                ];
886                let Some(group) = cached_group(
887                    cached,
888                    device,
889                    &[(1, depth_view), (2, color_view)],
890                    "volumetric composite",
891                    layout,
892                    &entries,
893                ) else {
894                    return;
895                };
896                let encoder = ctx.encoder();
897                encoder.bind_graphics_pipeline(pipeline);
898                encoder.bind_group(0, group, &[], pipeline_layout);
899                encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
900            });
901        (volume, seen)
902    }
903
904    /// Releases everything, in dependency order. The device must be idle.
905    pub(crate) fn destroy(self, device: &dyn Device) {
906        for cached in self.composite_groups.into_iter().flatten() {
907            device.destroy_bind_group(cached.1);
908        }
909        device.destroy_graphics_pipeline(self.composite_pipeline);
910        device.destroy_pipeline_layout(self.composite_pipeline_layout);
911        device.destroy_bind_group_layout(self.composite_layout);
912        device.destroy_compute_pipeline(self.integrate);
913        device.destroy_compute_pipeline(self.scatter);
914        device.destroy_pipeline_layout(self.compute_pipeline_layout);
915        for group in self.compute_groups {
916            device.destroy_bind_group(group);
917        }
918        device.destroy_bind_group_layout(self.compute_layout);
919        for buffer in self
920            .params
921            .into_iter()
922            .chain(self.froxels)
923            .chain(self.lighting)
924        {
925            device.destroy_buffer(buffer);
926        }
927    }
928}