crcbl-render 0.5.0

Crucible renderer: the 3D frame on crcbl-frame — meshes, materials, lights, effects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! The froxel volume the medium is integrated in, and the pass that composites
//! it over the frame — rungs 1 and 2 of the ladder whose rules are in
//! `docs/notes/rendering.md`.
//!
//! ```text
//!  begin_frame ──▶ camera + medium + cascades ──▶ params[frame]
//!
//!  add_passes ── compute "volumetric-scatter"   ──▶ froxels[frame]     (per slice)
//!                          shadow-atlas + light grid ──▶ lighting[frame]
//!             ── compute "volumetric-integrate" ──▶ froxels[frame]     (per tile)
//!             ── render  "volumetric-composite" scene-color ──▶ fogged
//!                          sky_pass's aerial[frame] ──┘
//! ```
//!
//! # The composite also puts the atmosphere's air in front of the scene
//!
//! On a frame with an atmosphere the composite reads
//! [`crcbl_shaders::atmosphere::AerialView`] — `crate::sky_pass` owns its ring
//! — and composes it **before** the column, so the scene is
//! `((scene · T_air + S_air) · T_fog) + S_fog`: the local fog is the near
//! medium and its glow must not be attenuated by the kilometres of air behind
//! it. Sky pixels are spared, because the sky-view LUT has already integrated
//! the whole of their ray.
//!
//! **The two halves switch independently.** The column's scatter and scan run
//! with the fog effect and nowhere else, and the composite runs on every frame
//! with the effect *or* an atmosphere — so a frame with an atmosphere and no
//! fog effect adds the composite alone, and the block's `fog_params.w` —
//! [`crcbl_shaders::volumetric::LOCAL_COLUMN_OFF`] — is what stops it reading a
//! column nothing filled. A frame with the fog effect and no atmosphere writes
//! the block it always wrote and composes the bytes it always composed.
//!
//! A module of its own on [`crate::ssr`]'s terms exactly: two pipelines, a
//! buffer ring and the pass group, none of it reachable from the geometry
//! passes except through [`Volumetric::add_passes`].
//!
//! # Why a buffer and not a 3D texture
//!
//! Every published froxel implementation writes a volume texture, and this one
//! writes [`crate::light_grid`]'s subdivision into a storage buffer instead.
//! The reason is a seam fact rather than a preference: [`crate::transient`] is
//! 2D-only — its descriptor carries no depth and its pool hard-codes
//! `ImageType::D2` — so a volume here would be the engine's **first** 3D image
//! on four backends at once. That is the shape of gap that had a read-only
//! depth attachment compile everywhere and refuse on D3D12. The froxel grid is
//! already a storage buffer the clustering pass writes and the fragment stage
//! reads, so the scattering rides a subdivision that four backends already run.
//!
//! # The buffer holds two different things, one after the other
//!
//! `volumetric.slang` writes each froxel's **own** scattered radiance and
//! transmittance, and then overwrites every froxel with the **exclusive prefix**
//! of the column in front of it. The composite therefore reads "everything
//! between the eye and this slice's start", and integrates the last partial
//! slice itself along the pixel's own ray — which is what keeps a frame off the
//! slice boundaries. An exponential split makes the far slices hundreds of
//! units deep, and snapping a pixel to one of those is the banding this design
//! exists to avoid.
//!
//! # The medium is charged exactly once
//!
//! `mesh.slang` composites the same exponential height fog analytically. Both
//! running is the medium charged twice, so [`ForwardRenderer::add_passes`] zeroes
//! the frame block's density on a frame that adds these passes — the froxel path
//! owns the medium when it exists. That is also the rung's observable: the
//! environment term's single-scattering albedo is one, so a column with no sun
//! in it is algebraically the closed form the fragment stage was computing and
//! the two frames have to agree. The sun is added on top of that and is zero
//! until a caller sets [`Fog::sun_scattering`], which keeps the equality as this
//! feature's off-switch rather than as a stage it has left behind.
//!
//! # The sun is occluded per froxel, in a buffer of its own
//!
//! The scatter pass looks each froxel's midpoint up in the cascades
//! [`crate::shadow`] filled, and scales the *sun* term of its scattering source
//! by what comes back — the environment term is what reaches the medium from
//! every direction, and an occluder in front of the sun does not remove it. The
//! answer is written to a second buffer the scan does not touch, because
//! `volumetric_composite.slang` integrates the last partial slice for itself and
//! needs the same source this pass used; [`LIGHTING_STRIDE`] carries the
//! argument for why that is a buffer rather than a second cascade walk. Rung 2
//! put the froxel's punctual lights beside it: the scatter pass walks the
//! froxel's own cluster list — the one `crate::light_grid` built for the mesh
//! pass — at the slice's midpoint, and the glow rides the same row, occluded
//! by the lamp's own shadow tiles where its row names them.
//!
//! [`ForwardRenderer::add_passes`]: crate::forward::ForwardRenderer::add_passes

use crcbl_hal::{
    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
    BufferUsage, ClearValue, ColorTargetState, ComputePipelineHandle, Device, Format,
    GraphicsPipelineHandle, HalError, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
    PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, SampleType, SamplerHandle,
    ShaderStages, StoreOp, check_portable_storage_buffers,
};
use crcbl_shaders::sky::{ATMOSPHERE_OFF, ATMOSPHERE_ON};
use crcbl_shaders::volumetric::{
    FROXEL_STRIDE, LIGHTING_STRIDE, LOCAL_COLUMN_OFF, LOCAL_COLUMN_ON, PARAMS_SIZE,
    VolumetricParams, WORKGROUP_SIZE,
};
use crcbl_shaders::{VOLUMETRIC, VOLUMETRIC_COMPOSITE};

use crate::camera::{DirectionalLight, Fog};
use crate::draw_gen::{UINT_STRIDE, bound, compute_pipeline_entry, storage, uniform};
use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
use crate::light_grid::{FrameView, Grid, LightGrid};
use crate::shadow::{self, Cascades};
use crate::ssao::cached_group;

/// Vertices in the over-sized full-screen triangle `volumetric_composite.slang`
/// generates from `SV_VertexID`. No geometry is bound anywhere.
const FULLSCREEN_VERTICES: u32 = 3;

/// The graph transients [`Volumetric::add_passes`] reads and writes.
///
/// One struct rather than three positional arguments, on
/// [`SsrImages`](crate::ssr::SsrImages)' terms: three values of one type are
/// three values that can be swapped silently at the call site.
#[derive(Clone, Copy, Debug)]
pub(crate) struct VolumetricImages {
    /// The depth prepass's stored depth: how far along its ray each pixel's
    /// column is cut off.
    pub(crate) depth: ImageId,
    /// The frame as it stands — the forward pass's scene colour with the sky
    /// drawn into it.
    pub(crate) color: ImageId,
    /// Where the composite writes, and the image the caller must go on to use
    /// in [`VolumetricImages::color`]'s place.
    pub(crate) composited: ImageId,
    /// The sun's cascades, as [`crate::shadow`] left them.
    ///
    /// Read by the **scatter** pass, which is what puts a shaft in the column:
    /// declaring it is what moves the atlas from the depth attachment the
    /// shadow pass wrote into a layout a compute stage can sample.
    pub(crate) shadow_atlas: ImageId,
}

/// What [`Volumetric::add_passes`] reads besides the images, and which of its
/// passes it adds.
///
/// One struct rather than three more arguments, on [`VolumetricImages`]'
/// terms.
#[derive(Clone, Copy, Debug)]
pub(crate) struct VolumetricReads {
    /// The froxel list the clustering pass filled this frame, as the graph
    /// knows it: the scatter pass declares the read, which is what orders it
    /// after that dispatch.
    pub(crate) light_grid: BufferId,
    /// Whether the fog effect is on, and so whether the scatter and scan run.
    ///
    /// It must be what [`Volumetric::begin_frame`] was handed as
    /// [`Medium::local`]: the block's switch is what stops the composite
    /// reading a column no pass filled.
    pub(crate) local: bool,
    /// [`crate::sky_pass::SkyPass::aerial`]'s slot for this frame, bound
    /// whether or not the frame has an atmosphere — the block's other switch
    /// decides whether it is read.
    pub(crate) aerial: BufferHandle,
}

/// The buffers one frame's froxel column lives in.
///
/// **A window for a test, and the froxel path's only public surface.** The
/// column is checked against `crcbl_shaders::volumetric` on the host, per
/// froxel, which is the one thing that can tell a wrong scatter from a wrong
/// scan: the frame-level checks compare a picture against the closed form, and
/// at a single-scattering albedo of one those two mistakes compose to the same
/// answer. Handing out the handles is what lets that comparison exist without
/// this module's internals leaving it.
///
/// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count) is the
/// same shape and the precedent for it.
#[derive(Clone, Copy, Debug)]
pub struct FroxelBuffers {
    /// The parameter block both compute passes and the composite read —
    /// [`crcbl_shaders::volumetric::PARAMS_SIZE`] bytes, in the layout
    /// [`VolumetricParams::from_bytes`] decodes.
    pub params: BufferHandle,
    /// The column: [`FROXEL_STRIDE`] bytes per froxel, holding the **exclusive
    /// prefix** in front of each slice once the frame's passes have run.
    pub froxels: BufferHandle,
    /// What each froxel's lights put into it — [`LIGHTING_STRIDE`] bytes per
    /// froxel: the punctual glow in `rgb`, the sun's visibility in `w`, as the
    /// scatter pass left them and the scan did not touch them.
    pub lighting: BufferHandle,
}

/// What lights the medium on this frame.
///
/// One struct rather than three more arguments, on [`VolumetricImages`]' terms:
/// the three are read together and mean nothing apart. The medium's own
/// properties are [`Fog`]; the sun and its cascades are what a shaft is cast
/// by, and they have to be the frame's own — `Cascades::new` builds the
/// matrices from the camera and the light, so a block carrying one frame's
/// light with another's cascades would shadow a shaft against boxes that are no
/// longer where it is.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Medium<'a> {
    /// The medium: its density, its falloff, its colour and how it scatters the
    /// sun.
    pub(crate) fog: Fog,
    /// The sun, whose radiance the medium scatters and whose direction the
    /// phase function is evaluated against.
    pub(crate) sun: &'a DirectionalLight,
    /// The cascades that sun was shadowed through, which is what occludes the
    /// shaft.
    pub(crate) cascades: &'a Cascades,
    /// One matrix per light tile of the atlas, as the frame block carries them
    /// — the maps the frame's shadowed lamps were drawn into, which is what
    /// stops a lamp's glow at a wall. The frame's own, on `cascades`' terms:
    /// `shadow::Selection` handed out the tiles the light rows name, and a
    /// block with another frame's matrices would read the right tile of the
    /// wrong map.
    pub(crate) light_view_proj: &'a [[f32; 16]; shadow::LIGHT_TILES],
    /// Where each of those maps is in the atlas, as the frame block carries
    /// them — a scale and an offset per slot, out of the same
    /// `shadow::Selection` the matrices came from. A froxel that read a
    /// rectangle from one frame and a matrix from another would sample the
    /// right map's place for the wrong map.
    pub(crate) atlas_rects: &'a [[f32; 4]; shadow::TILES],
    /// Whether this frame's scatter and scan run — the fog effect — and so
    /// whether the composite reads the column they fill.
    pub(crate) local: bool,
    /// The sun the frame's [`crcbl_shaders::atmosphere::AerialView`] was
    /// marched around, or `None` on a frame with no atmosphere — whose
    /// composite then puts no air in front of anything.
    pub(crate) aerial: Option<[f32; 3]>,
}

/// Everything the froxel volume owns.
#[derive(Debug)]
pub(crate) struct Volumetric {
    /// `[frame]`: the parameter block both shaders read. A ring for the frame
    /// uniforms' reason — the previous frame may still be reading its own.
    params: Vec<BufferHandle>,
    /// `[frame]`: the froxel volume. **Device-local**, because a shader writes
    /// it: D3D12 has no unordered-access view of an upload-heap resource at
    /// all — [`crate::draw_gen`]'s module docs carry the full account.
    /// `TRANSFER_SRC` so a test can read back what the GPU decided.
    froxels: Vec<BufferHandle>,
    /// `[frame]`: one `float4` per froxel — what its punctual lights scatter,
    /// and how much of the sun it sees.
    ///
    /// Written by the scatter pass and read by the composite, and untouched by
    /// the scan between them — which is the whole reason it is a second buffer
    /// rather than a component of the first, argued at
    /// [`LIGHTING_STRIDE`].
    lighting: Vec<BufferHandle>,
    compute_layout: BindGroupLayoutHandle,
    compute_pipeline_layout: PipelineLayoutHandle,
    scatter: ComputePipelineHandle,
    integrate: ComputePipelineHandle,
    /// `[frame]`: the compute group. Names only buffers this owns, so it is
    /// built once rather than cached against a graph-realised view.
    compute_groups: Vec<BindGroupHandle>,
    composite_layout: BindGroupLayoutHandle,
    composite_pipeline_layout: PipelineLayoutHandle,
    composite_pipeline: GraphicsPipelineHandle,
    /// `[frame]`: the composite group, cached against both its views together.
    ///
    /// **One per frame in flight** on [`crate::ssr`]'s terms: this group names
    /// [`Volumetric::params`] and [`Volumetric::froxels`] as well as two graph
    /// transients, and both of those are rings — a single cache keyed on the
    /// views alone would hand the even frames' buffers to the odd frames.
    composite_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
}

impl Volumetric {
    /// Passes [`Volumetric::add_passes`] adds to a frame at most: the column's
    /// and the composite's.
    ///
    /// A ceiling since the air arrived: a frame whose fog effect is off and
    /// whose atmosphere is not adds the composite alone.
    pub(crate) const PASSES: u32 = Self::COLUMN_PASSES + Self::COMPOSITE_PASSES;

    /// The column's compute passes — the scatter and the scan — which run
    /// exactly when the fog effect does.
    ///
    /// Exact rather than a ceiling: a frame always has froxels — [`Grid`] floors
    /// every extent at one tile and one slice — so neither ever drops out.
    pub(crate) const COLUMN_PASSES: u32 = 2;

    /// The composite, which runs on every frame with the fog effect or an
    /// atmosphere, and the only full-screen draw among them.
    pub(crate) const COMPOSITE_PASSES: u32 = 1;

    /// Builds both pipelines, the buffer rings and the compute groups.
    ///
    /// `froxels` is the volume's capacity, which is
    /// [`FROXEL_CAPACITY`](crate::light_grid::FROXEL_CAPACITY) outside a test
    /// that wants a smaller one, and it is what [`Grid::for_frame`] is asked to
    /// fit a frame under.
    ///
    /// `lights` is the frame ring the scatter pass reads its light rows and
    /// its froxel lists from — the same buffers the mesh pass binds — and the
    /// compute groups name them at construction, which is sound for the reason
    /// the shadow atlas is: [`LightGrid`] creates its ring once and hands out
    /// the same handles for its whole life.
    ///
    /// `build_fullscreen` is handed in rather than duplicated, on
    /// [`Ssr::new`](crate::ssr::Ssr::new)'s terms: it is [`crate::forward`]'s,
    /// because the shape it carries is documented there.
    ///
    /// # Errors
    ///
    /// [`HalError`] from any seam call. **Nothing is released on the failing
    /// path**, for the reason every other builder in this crate gives: the
    /// caller holds a rollback, and this is stored in it whole.
    pub(crate) fn new(
        device: &dyn Device,
        frames: usize,
        froxels: u32,
        shadow_atlas: ImageViewHandle,
        shadow_sampler: SamplerHandle,
        lights: &LightGrid,
        build_fullscreen: impl Fn(
            &dyn Device,
            &str,
            &crcbl_shaders::Shader,
            PipelineLayoutHandle,
            &[ColorTargetState],
        ) -> Result<GraphicsPipelineHandle, HalError>,
    ) -> Result<Self, HalError> {
        if frames == 0 || froxels == 0 {
            return Err(HalError::InvalidDescriptor(
                "a froxel volume needs at least one frame in flight and one froxel".to_string(),
            ));
        }
        // `volumetric.slang`'s declaration order, which is the only order Metal
        // and D3D12 agree about — see `crcbl_shaders::declaration_order`.
        let compute_entries = [
            uniform(0),
            storage(1, false, crcbl_shaders::volumetric::FROXEL_STRIDE as u32),
            BindGroupLayoutEntry {
                binding: 2,
                visibility: ShaderStages::COMPUTE,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // `Depth`, for the reason the composite's own depth binding
                    // gives: WebGPU binds a `D32Float` view only through a depth
                    // sample type, and the WGSL declares `texture_depth_2d`.
                    sample_type: SampleType::Depth,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 3,
                visibility: ShaderStages::COMPUTE,
                // **A comparison sampler in a compute stage**, which is what is
                // new at this rung. The shader asks with `SampleCmpLevelZero`,
                // which needs no derivatives and is legal outside a fragment
                // shader on all four targets — unlike the implicit-LOD form the
                // forward pass uses.
                kind: BindingKind::Sampler { comparison: true },
                count: 1,
                flags: BindingFlags::empty(),
            },
            storage(4, false, crcbl_shaders::volumetric::LIGHTING_STRIDE as u32),
            // The light rows and the froxel lists, read and never written —
            // `StructuredBuffer` in the shader, and the clustering pass is what
            // wrote the second before this pass runs.
            storage(5, true, crcbl_shaders::light::LIGHT_STRIDE as u32),
            storage(6, true, UINT_STRIDE),
        ];
        let compute_desc = BindGroupLayoutDesc {
            label: Some("volumetric"),
            entries: &compute_entries,
        };
        check_portable_storage_buffers(Some("volumetric"), &[&compute_desc])?;
        let compute_layout = device.create_bind_group_layout(&compute_desc)?;
        let compute_set_layouts = [compute_layout];
        let compute_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("volumetric"),
            bind_group_layouts: &compute_set_layouts,
            push_constants: None,
        })?;
        // Two entry points of one module, which is why this is
        // `compute_pipeline_entry` rather than `compute_pipeline`: the pair
        // shares the froxel arithmetic and shaders here have no `#include`.
        let scatter = compute_pipeline_entry(
            device,
            "volumetric scatter",
            &VOLUMETRIC,
            "scatterMain",
            compute_pipeline_layout,
            WORKGROUP_SIZE,
        )?;
        let integrate = compute_pipeline_entry(
            device,
            "volumetric integrate",
            &VOLUMETRIC,
            "integrateMain",
            compute_pipeline_layout,
            WORKGROUP_SIZE,
        )?;

        let composite_entries = [
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::UniformBuffer { dynamic: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // `Depth`, and the paragraph on `crate::ssr`'s own depth
                    // binding is this one's too: it is the same image, read
                    // through the same `texture_depth_2d`.
                    sample_type: SampleType::Depth,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 2,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // The `Rgba16Float` scene target: an ordinary colour image,
                    // and the WGSL artifact declares `texture_2d<f32>` for it.
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 3,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::StorageBuffer {
                    // The prefix scan, read and not written — `StructuredBuffer`
                    // in the shader, which is the truth rather than a hint.
                    read_only: true,
                    dynamic: false,
                    stride: crcbl_shaders::volumetric::FROXEL_STRIDE as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 4,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::StorageBuffer {
                    // Each froxel's share of its lights, as the scatter pass
                    // measured it. Read and never written here.
                    read_only: true,
                    dynamic: false,
                    stride: crcbl_shaders::volumetric::LIGHTING_STRIDE as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 5,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::StorageBuffer {
                    // The air in front of the scene — `crate::sky_pass`'s
                    // aerial ring, written on the host and only read here.
                    read_only: true,
                    dynamic: false,
                    stride: crcbl_shaders::atmosphere::AERIAL_VIEW_ROW_BYTES as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
        ];
        let composite_desc = BindGroupLayoutDesc {
            label: Some("volumetric composite"),
            entries: &composite_entries,
        };
        check_portable_storage_buffers(Some("volumetric composite"), &[&composite_desc])?;
        let composite_layout = device.create_bind_group_layout(&composite_desc)?;
        let composite_set_layouts = [composite_layout];
        let composite_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("volumetric composite"),
            bind_group_layouts: &composite_set_layouts,
            push_constants: None,
        })?;
        // The same format the forward pass wrote: this image stands in for the
        // scene colour from here on, so a narrower one would tonemap a truncated
        // frame — and fog adds a radiance rather than only removing one.
        let targets = [ColorTargetState::opaque(Format::Rgba16Float)];
        let composite_pipeline = build_fullscreen(
            device,
            "volumetric composite",
            &VOLUMETRIC_COMPOSITE,
            composite_pipeline_layout,
            &targets,
        )?;

        let mut params = Vec::with_capacity(frames);
        let mut volumes = Vec::with_capacity(frames);
        let mut lighting = Vec::with_capacity(frames);
        let mut compute_groups = Vec::with_capacity(frames);
        for frame in 0..frames {
            let block = device.create_buffer(&BufferDesc {
                label: Some(&format!("volumetric params {frame}")),
                size: PARAMS_SIZE as u64,
                // `TRANSFER_SRC` for the reason the froxel volume carries it: a
                // test reads the block back rather than deriving a second copy
                // of it, so what it models the column from is what the shaders
                // were handed. Host-visible memory is not a substitute — an
                // upload heap is write-combined, and reading it back on the
                // host is a different question from what the device saw.
                usage: BufferUsage::UNIFORM | BufferUsage::TRANSFER_SRC,
                memory: MemoryLocation::HostUpload,
            })?;
            let volume = device.create_buffer(&BufferDesc {
                label: Some(&format!("volumetric froxels {frame}")),
                size: u64::from(froxels) * FROXEL_STRIDE as u64,
                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
                memory: MemoryLocation::DeviceLocal,
            })?;
            let seen = device.create_buffer(&BufferDesc {
                label: Some(&format!("volumetric lighting {frame}")),
                size: u64::from(froxels) * LIGHTING_STRIDE as u64,
                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
                memory: MemoryLocation::DeviceLocal,
            })?;
            // **Built once rather than cached against the graph**, which the
            // shadow atlas and the light ring are what make possible: the
            // renderer owns that image and those buffers for its whole life and
            // hands the graph the same handles every frame, so this group names
            // nothing a frame can change.
            let group = device.create_bind_group(&BindGroupDesc {
                label: Some(&format!("volumetric {frame}")),
                layout: compute_layout,
                entries: &[
                    bound(0, block),
                    bound(1, volume),
                    BindGroupEntry {
                        binding: 2,
                        array_index: 0,
                        resource: BindingResource::ImageView(shadow_atlas),
                    },
                    BindGroupEntry {
                        binding: 3,
                        array_index: 0,
                        resource: BindingResource::Sampler(shadow_sampler),
                    },
                    bound(4, seen),
                    bound(5, lights.lights(frame)),
                    bound(6, lights.grid(frame)),
                ],
                // No binding here is an array, so nothing has a runtime length
                // to declare — the same `None` every other pass in this crate
                // passes.
                variable_count: None,
            })?;
            params.push(block);
            volumes.push(volume);
            lighting.push(seen);
            compute_groups.push(group);
        }

        Ok(Self {
            params,
            froxels: volumes,
            lighting,
            compute_layout,
            compute_pipeline_layout,
            scatter,
            integrate,
            compute_groups,
            composite_layout,
            composite_pipeline_layout,
            composite_pipeline,
            composite_groups: vec![None; frames],
        })
    }

    /// Writes `frame`'s parameter block: the camera, the grid and the medium.
    ///
    /// `grid` must be the same [`Grid`] handed to [`Volumetric::add_passes`] and
    /// the same one the frame's clustering pass used — the composite converts a
    /// pixel to a froxel index with these numbers, and a block from one grid
    /// with a dispatch from another reads a column built for somewhere else.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the mapped write.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn begin_frame(
        &self,
        device: &dyn Device,
        frame: usize,
        grid: Grid,
        view: FrameView,
        medium: Medium<'_>,
    ) -> Result<(), HalError> {
        let Medium {
            fog,
            sun,
            cascades,
            light_view_proj,
            atlas_rects,
            local,
            aerial,
        } = medium;
        // Row 3 of the view-projection, so a shader can take a point's view
        // depth with one dot product — [`crate::light_grid`]'s block carries the
        // same row for the same reason, and both come from this one matrix so
        // the two passes cut the frustum at the same depths.
        let columns = view.view_projection.to_cols_array();
        let depth_row = [columns[3], columns[7], columns[11], columns[15]];
        let mut shadow_view_proj = [[0.0f32; 16]; shadow::CASCADES];
        for (matrix, cascade) in shadow_view_proj.iter_mut().zip(&cascades.view_proj) {
            *matrix = cascade.to_cols_array();
        }
        device.write_buffer(
            self.params[frame],
            0,
            &VolumetricParams {
                inverse_view_proj: view.view_projection.inverse().to_cols_array(),
                eye: view.eye.extend(1.0).to_array(),
                depth_row,
                // The column's switch in `w`: on — the zero this lane held as
                // padding — wherever the scatter and scan run.
                fog_params: [
                    fog.density,
                    fog.falloff,
                    fog.reference_height,
                    if local {
                        LOCAL_COLUMN_ON
                    } else {
                        LOCAL_COLUMN_OFF
                    },
                ],
                fog_color: fog.color.extend(0.0).to_array(),
                // Towards the sun, which is `mesh.slang`'s `to_light` and the
                // opposite of the direction its light travels — the phase
                // function's own convention, spelled out on
                // `volumetric_phase`. Normalised here rather than trusted: a
                // caller may hand the renderer any vector, and a longer one
                // would scale a cosine past the clamp and flatten the lobe.
                sun_direction: sun
                    .direction
                    .normalize_or_zero()
                    .extend(fog.anisotropy)
                    .to_array(),
                // Zero unless a caller asked for it, which is what keeps the
                // column algebraically the closed form until they do.
                // And the punctual coefficient beside it, the same zero until
                // asked for — the rows it scales are the frame's own light list.
                sun_radiance: (sun.color * fog.sun_scattering)
                    .extend(fog.light_scattering)
                    .to_array(),
                // **The cascades the frame block already carries**, handed to
                // the scatter pass so a froxel and the surface behind it are
                // shadowed by one set of matrices. `Cascades::new` builds them
                // from the camera and the light alone, so there is no version
                // of this where the two could be a frame apart.
                shadow_view_proj,
                cascade_far: cascades.far,
                shadow_params: Cascades::params(),
                grid_x: grid.x,
                grid_y: grid.y,
                slices: grid.slices,
                tile_pixels: grid.tile_pixels,
                viewport_x: view.extent.0.max(1),
                viewport_y: view.extent.1.max(1),
                froxel_count: grid.froxels(),
                light_view_proj: *light_view_proj,
                shadow_atlas_rect: *atlas_rects,
                // The atmosphere's own sun, which the LUT's azimuth is measured
                // from, and the switch. All zeroes on a frame with no
                // atmosphere, which is the row every frame before the air
                // existed wrote nothing into.
                aerial_params: match aerial {
                    Some(sun) => [sun[0], sun[1], sun[2], ATMOSPHERE_ON],
                    None => [0.0, 0.0, 0.0, ATMOSPHERE_OFF],
                },
            }
            .to_bytes(),
        )
    }

    /// `frame`'s froxel column and the numbers it was built from.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn buffers(&self, frame: usize) -> FroxelBuffers {
        FroxelBuffers {
            params: self.params[frame],
            froxels: self.froxels[frame],
            lighting: self.lighting[frame],
        }
    }

    /// Adds the scatter, integrate and composite passes, in that order — or
    /// the composite alone where [`VolumetricReads::local`] is false.
    ///
    /// [`VolumetricImages::composited`] is what the caller must go on to use:
    /// the medium is *in* it, and the scene colour it was composited over is not
    /// the finished picture any more.
    ///
    /// Returns the column and its lighting as the graph knows them, so a later
    /// pass that reads them — [`crate::water`] — declares the read against the
    /// same ids rather than importing the buffers a second time.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn add_passes<'a>(
        &'a mut self,
        graph: &mut RenderGraph<'a>,
        frame: usize,
        grid: Grid,
        images: VolumetricImages,
        reads: VolumetricReads,
    ) -> (BufferId, BufferId) {
        let VolumetricReads {
            light_grid,
            local,
            aerial,
        } = reads;
        let VolumetricImages {
            depth,
            color,
            composited,
            shadow_atlas,
        } = images;
        // The volume arrives in the state the previous frame that used this slot
        // left it in, which is the state declared as final: the composite reads
        // it. Vacuous on the first frame, and the real prior use on every later
        // one.
        let volume = graph.import_buffer(
            "volumetric-froxels",
            ImportedBuffer {
                buffer: self.froxels[frame],
                initial: ResourceState::ShaderRead,
                final_state: ResourceState::ShaderRead,
            },
        );
        // The same import the column gets, and for its reason: the composite is
        // the last pass to read it, which is the state the next frame in this
        // slot will find it in.
        let seen = graph.import_buffer(
            "volumetric-lighting",
            ImportedBuffer {
                buffer: self.lighting[frame],
                initial: ResourceState::ShaderRead,
                final_state: ResourceState::ShaderRead,
            },
        );
        let compute_layout = self.compute_pipeline_layout;
        let compute_group = self.compute_groups[frame];
        let scatter = self.scatter;
        let integrate = self.integrate;

        // **The column only where the fog effect runs.** An atmosphere frame
        // with the effect off adds the composite alone, for the air — and the
        // block's `fog_params.w` is what tells it the column is not there, so
        // this branch and that switch are one decision made in two places,
        // both off the caller's `local`.
        if local {
            // One invocation per froxel, and never zero: `Grid::for_frame`
            // floors every extent at one tile and one slice, and Metal rejects
            // an empty dispatch outright rather than treating it as a no-op.
            let froxel_groups = grid.froxels().div_ceil(WORKGROUP_SIZE);
            graph
                .add_compute_pass("volumetric-scatter")
                // `ShaderReadWrite` rather than a write-only state, on the
                // light grid's terms: a storage-buffer descriptor permits reads
                // whatever the shader does with it.
                .use_buffer(volume, ResourceState::ShaderReadWrite)
                .use_buffer(seen, ResourceState::ShaderReadWrite)
                // The cascades this pass looks a froxel up in. A read rather
                // than a write, and it is what orders this dispatch after the
                // shadow pass that filled them.
                .read_image(shadow_atlas)
                // And the froxel lists it walks, on the mesh pass's terms: the
                // clustering pass left them in `ShaderReadWrite`, and declaring
                // the read is what orders this dispatch after it.
                .read_buffer(light_grid)
                .execute(move |ctx| {
                    let encoder = ctx.encoder();
                    encoder.bind_compute_pipeline(scatter);
                    encoder.bind_group(0, compute_group, &[], compute_layout);
                    encoder.dispatch(froxel_groups, 1, 1);
                });

            // One invocation per **tile**, not per froxel: this pass walks a
            // column front to back and turns each froxel into the exclusive
            // prefix of the ones in front of it, which is a serial scan over
            // the slice axis.
            let tile_groups = grid
                .x
                .max(1)
                .saturating_mul(grid.y.max(1))
                .div_ceil(WORKGROUP_SIZE);
            graph
                .add_compute_pass("volumetric-integrate")
                // The scatter's own output, read and overwritten in place — the
                // graph's barrier between the two comes from both declaring
                // this one id.
                .use_buffer(volume, ResourceState::ShaderReadWrite)
                .execute(move |ctx| {
                    let encoder = ctx.encoder();
                    encoder.bind_compute_pipeline(integrate);
                    encoder.bind_group(0, compute_group, &[], compute_layout);
                    encoder.dispatch(tile_groups, 1, 1);
                });
        }

        let pipeline = self.composite_pipeline;
        let pipeline_layout = self.composite_pipeline_layout;
        let layout = self.composite_layout;
        let params = self.params[frame];
        let froxels = self.froxels[frame];
        let lighting = self.lighting[frame];
        let cached = &mut self.composite_groups[frame];
        graph
            .add_render_pass("volumetric-composite")
            // `DontCare`, not `Clear`: the full-screen triangle writes every
            // pixel of the target, so loading or clearing it is pure bandwidth.
            .color(
                composited,
                LoadOp::DontCare,
                StoreOp::Store,
                ClearValue::default(),
            )
            // The forward pass left the colour in `ColorAttachment` and the
            // prepass left the depth in `DepthStencilWrite`. Declaring the reads
            // is what moves each into a shader-readable layout, and without them
            // every backend reads whatever the last writer left behind.
            //
            // The column's two are declared on a frame that did not fill them
            // too: the buffers are bound either way, and a read of a buffer
            // already in `ShaderRead` is no barrier at all.
            .read_image(color)
            .read_image(depth)
            .read_buffer(volume)
            .read_buffer(seen)
            .execute(move |ctx| {
                let color_view = ctx.image_view(color);
                let depth_view = ctx.image_view(depth);
                let device = ctx.device();
                let entries = [
                    BindGroupEntry {
                        binding: 0,
                        array_index: 0,
                        resource: BindingResource::whole_buffer(params),
                    },
                    // The two below are overwritten by `cached_group` with the
                    // realised views; written here so the list is a complete
                    // description of the layout rather than one with holes in it.
                    BindGroupEntry {
                        binding: 1,
                        array_index: 0,
                        resource: BindingResource::ImageView(depth_view),
                    },
                    BindGroupEntry {
                        binding: 2,
                        array_index: 0,
                        resource: BindingResource::ImageView(color_view),
                    },
                    BindGroupEntry {
                        binding: 3,
                        array_index: 0,
                        resource: BindingResource::whole_buffer(froxels),
                    },
                    BindGroupEntry {
                        binding: 4,
                        array_index: 0,
                        resource: BindingResource::whole_buffer(lighting),
                    },
                    // The aerial ring's slot for this frame, which is the same
                    // handle every time this slot comes round — so the cache
                    // below, keyed on the two views alone, stays right.
                    BindGroupEntry {
                        binding: 5,
                        array_index: 0,
                        resource: BindingResource::whole_buffer(aerial),
                    },
                ];
                let Some(group) = cached_group(
                    cached,
                    device,
                    &[(1, depth_view), (2, color_view)],
                    "volumetric composite",
                    layout,
                    &entries,
                ) else {
                    return;
                };
                let encoder = ctx.encoder();
                encoder.bind_graphics_pipeline(pipeline);
                encoder.bind_group(0, group, &[], pipeline_layout);
                encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
            });
        (volume, seen)
    }

    /// Releases everything, in dependency order. The device must be idle.
    pub(crate) fn destroy(self, device: &dyn Device) {
        for cached in self.composite_groups.into_iter().flatten() {
            device.destroy_bind_group(cached.1);
        }
        device.destroy_graphics_pipeline(self.composite_pipeline);
        device.destroy_pipeline_layout(self.composite_pipeline_layout);
        device.destroy_bind_group_layout(self.composite_layout);
        device.destroy_compute_pipeline(self.integrate);
        device.destroy_compute_pipeline(self.scatter);
        device.destroy_pipeline_layout(self.compute_pipeline_layout);
        for group in self.compute_groups {
            device.destroy_bind_group(group);
        }
        device.destroy_bind_group_layout(self.compute_layout);
        for buffer in self
            .params
            .into_iter()
            .chain(self.froxels)
            .chain(self.lighting)
        {
            device.destroy_buffer(buffer);
        }
    }
}