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