sgl-post-fx 0.9.2

SGL wgpu post-processing effects: screen-space reflections and temporal anti-aliasing derived from DiligentFX
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
//! #344, #537: intersection reads and writes its own outputs, which the
//! denoiser's clamps can hide.
use super::temporal_neighborhood_tests::{
    SIZE, depth, depth_values, device, half, read_rgba16f, texels, texture,
};
use super::*;
use crate::{CameraAttribs, post_fx_context::FrameDesc};

const NEAR: f32 = 0.1;

/// The projection's horizontal and vertical scales, for a vertical field of
/// view of one radian.
fn projection_scales() -> (f32, f32) {
    let aspect = SIZE[0] as f32 / SIZE[1] as f32;
    (1.0 / 0.5f32.tan() / aspect, 1.0 / 0.5f32.tan())
}

/// A camera at the origin looking along +z with an infinite reversed-Z,
/// left-handed projection: depth = NEAR / z.
fn infinite_reversed_camera() -> CameraAttribs {
    let (a, b) = projection_scales();
    // Columns listed.
    let proj = [
        a, 0., 0., 0., 0., b, 0., 0., 0., 0., 0., 1., 0., 0., NEAR, 0.,
    ];
    let proj_inv = [
        1. / a,
        0.,
        0.,
        0.,
        0.,
        1. / b,
        0.,
        0.,
        0.,
        0.,
        0.,
        1. / NEAR,
        0.,
        0.,
        1.,
        0.,
    ];
    let identity = [
        1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.,
    ];
    let mut camera = CameraAttribs {
        f4_viewport_size: [
            SIZE[0] as f32,
            SIZE[1] as f32,
            1.0 / SIZE[0] as f32,
            1.0 / SIZE[1] as f32,
        ],
        m_view: identity,
        m_proj: proj,
        m_view_proj: proj,
        m_view_inv: identity,
        m_proj_inv: proj_inv,
        m_view_proj_inv: proj_inv,
        ..Default::default()
    };
    camera.set_clip_planes(f32::INFINITY, NEAR);
    camera
}

/// The view-space ray through the centre of pixel (`x`, `y`), at view z 1.
fn pixel_ray(x: u32, y: u32) -> [f64; 3] {
    let (a, b) = projection_scales();
    let [width, height] = SIZE.map(f64::from);
    [
        ((f64::from(x) + 0.5) / width * 2.0 - 1.0) / f64::from(a),
        (1.0 - (f64::from(y) + 0.5) / height * 2.0) / f64::from(b),
        1.0,
    ]
}

/// The depths of a plane 1 below `infinite_reversed_camera` with normal
/// `floor_normal`, and of the sky (depth 0) above its horizon.
fn floor_depths(floor_normal: [f64; 3]) -> Vec<f32> {
    (0..SIZE[1])
        .flat_map(|y| (0..SIZE[0]).map(move |x| (x, y)))
        .map(|(x, y)| {
            let ray = pixel_ray(x, y);
            let towards_floor: f64 = (0..3).map(|i| ray[i] * floor_normal[i]).sum();
            // The ray meets dot(p, n) = -1 at view z = -1 / dot(ray, n).
            if towards_floor < 0.0 {
                (f64::from(NEAR) * -towards_floor) as f32
            } else {
                0.0
            }
        })
        .collect()
}

/// One SSR frame of `infinite_reversed_camera` over a mirror floor with
/// normal `floor_normal`, reflecting a white scene.
fn trace_mirror_floor(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    floor_normal: [f64; 3],
    feature_flags: FeatureFlags,
    roughness: u8,
    zero_normal: fn(u32, u32) -> bool,
) -> ScreenSpaceReflection {
    let camera = infinite_reversed_camera();
    let mut encoder = device.create_command_encoder(&Default::default());
    let scene_depth = depth_values(device, queue, &mut encoder, &floor_depths(floor_normal));
    let previous_depth = depth(device, &mut encoder, 0.0);
    let floor_normal = floor_normal.map(|v| v as f32);
    let normals: Vec<u8> = (0..SIZE[1])
        .flat_map(|y| (0..SIZE[0]).map(move |x| (x, y)))
        .flat_map(|(x, y)| {
            let [nx, ny, nz] = if zero_normal(x, y) {
                [0.0; 3]
            } else {
                floor_normal
            };
            half(&[nx, ny, nz, 0.0])
        })
        .collect();
    let normal = texels(device, queue, wgpu::TextureFormat::Rgba16Float, &normals);
    // The same material everywhere, the sky included.
    let material = texture(device, queue, wgpu::TextureFormat::R8Unorm, &[roughness]);
    let color = texture(
        device,
        queue,
        wgpu::TextureFormat::Rgba16Float,
        &half(&[1.0, 1.0, 1.0, 1.0]),
    );
    let motion = texels(
        device,
        queue,
        wgpu::TextureFormat::Rgba16Float,
        &half(&[0.0, 0.0, 0.0, 1.0].repeat((SIZE[0] * SIZE[1]) as usize)),
    );
    let mut context = PostFXContext::new(
        device,
        queue,
        post_fx_context::CreateInfo {
            transition_duration: 0.0,
        },
    );
    let mut ssr = ScreenSpaceReflection::new(device);
    context.prepare_resources(
        device,
        &FrameDesc {
            index: 0,
            width: SIZE[0],
            height: SIZE[1],
            output_width: SIZE[0],
            output_height: SIZE[1],
        },
        post_fx_context::FeatureFlags::REVERSED_DEPTH,
    );
    ssr.prepare_resources(device, &mut encoder, &mut context, feature_flags);
    context.execute(&mut post_fx_context::RenderAttributes {
        device,
        queue,
        device_context: &mut encoder,
        curr_depth_buffer_srv: &scene_depth,
        prev_depth_buffer_srv: &previous_depth,
        curr_camera: Some(&camera),
        prev_camera: Some(&camera),
        camera_attribs_cb: None,
        pass_timestamps: None,
    });
    ssr.execute(&mut RenderAttributes {
        device,
        queue,
        device_context: &mut encoder,
        post_fx_context: &mut context,
        color_buffer_srv: &color,
        depth_buffer_srv: &scene_depth,
        normal_buffer_srv: &normal,
        material_buffer_srv: &material,
        motion_vectors_srv: &motion,
        ssr_attribs: &ScreenSpaceReflectionAttribs::default(),
        pass_timestamps: None,
        reset_accumulation: true,
        frame_time: 1.0 / 60.0,
    });
    queue.submit([encoder.finish()]);
    ssr
}

/// The number of texels of `texels` with a non-finite channel.
fn nonfinite(texels: &[[f32; 4]]) -> usize {
    texels
        .iter()
        .filter(|t| !t.iter().all(|v| v.is_finite()))
        .count()
}

// PROVENANCE.md DFX-41: at half resolution a 2×2 block on a glossy floor's
// horizon passes the mask on its floor pixels' depth, while the pixel it
// traces may be the sky, whose depth 0 has no finite position under an
// infinite reversed-Z projection. Every ray's radiance, direction and PDF
// stay finite.
#[test]
fn half_resolution_rays_at_an_infinite_horizon_are_finite() {
    let Some((device, queue)) = device() else {
        return;
    };
    let (_, b) = projection_scales();
    // A floor 1 below a camera pitched down so the horizon lies at NDC y
    // 0.13, between the centres of rows 20 (sky) and 21 (floor), which share
    // 2×2 blocks.
    let (s, c) = (0.13 / f64::from(b)).atan().sin_cos();
    let ssr = trace_mirror_floor(
        &device,
        &queue,
        [0.0, c, -s],
        FeatureFlags::HALF_RESOLUTION,
        0,
        |_, _| false,
    );
    for (name, view) in [
        ("radiance", &ssr.resources().radiance),
        ("direction and PDF", &ssr.resources().ray_direction_pdf),
    ] {
        let rays = read_rgba16f(&device, &queue, view);
        let nonfinite = nonfinite(&rays);
        assert_eq!(nonfinite, 0, "{nonfinite} of {} rays' {name}", rays.len());
    }
}

// PROVENANCE.md DFX-48: a mirror floor reflects every ray into the sky, so
// under an infinite reversed-Z projection each ray leaves through the far
// plane, depth 0, where its camera-space distance is infinite. Rays stepping
// one cell at a time end at or just past depth 0, where the distance is
// infinite or past RGBA16F's range. The camera is pitched up so the horizon
// lies 0.1 pixel above the centre of row 24, the floor's first row. That
// row's rays reach depth 0 0.2 pixel from their origin, so the initial
// advance to the cell boundary half a pixel away overshoots to a clearly
// negative depth, where the distance is finite but meaningless. Each floor
// pixel's stored ray must still point along the mirror direction of its view
// ray about the floor and be as long as RGBA16F holds, and the reconstructed
// output must stay finite.
#[test]
fn rays_past_the_far_plane_keep_their_direction() {
    let Some((device, queue)) = device() else {
        return;
    };
    let (a, b) = projection_scales();
    // Row 24's centre, NDC y -1/48, and 0.1 pixel (0.2/48 in NDC) above it.
    let horizon = -1.0 / 48.0 + 0.2 / 48.0;
    let (s, c) = (horizon / f64::from(b)).atan().sin_cos();
    let floor_normal = [0.0, c, -s];
    let depths = floor_depths(floor_normal);
    let ssr = trace_mirror_floor(
        &device,
        &queue,
        floor_normal,
        FeatureFlags::NONE,
        0,
        |_, _| false,
    );
    let rays = read_rgba16f(&device, &queue, &ssr.resources().ray_direction_pdf);
    let mut wrong = Vec::new();
    let mut row_24_past_far_plane = 0;
    for y in 0..SIZE[1] {
        for x in 0..SIZE[0] {
            let at = (y * SIZE[0] + x) as usize;
            if depths[at] == 0.0 {
                continue;
            }
            assert!(y >= 24, "({x}, {y}) is floor above row 24");
            let ray = rays[at];
            let length = ray[..3].iter().map(|v| v * v).sum::<f32>().sqrt();
            let view = pixel_ray(x, y);
            let view_length = view.iter().map(|v| v * v).sum::<f64>().sqrt();
            let view = view.map(|v| v / view_length);
            let v_dot_n: f64 = (0..3).map(|i| view[i] * floor_normal[i]).sum();
            let mirror: [f32; 3] =
                std::array::from_fn(|i| (view[i] - 2.0 * v_dot_n * floor_normal[i]) as f32);
            // A ray whose vanishing point, where its depth reaches 0, lies on
            // the screen a pixel or more inside its edges leaves through the
            // far plane before the screen's edge. Its length is binary16's
            // largest finite value, 65504, within the rounding of each stored
            // component near it (a spacing of at most 32).
            let vanishing = [
                f64::from(mirror[0] / mirror[2] * a),
                f64::from(mirror[1] / mirror[2] * b),
            ];
            let past_far_plane = mirror[2] > 0.0
                && vanishing[0].abs() < 1.0 - 2.0 / f64::from(SIZE[0])
                && vanishing[1].abs() < 1.0 - 2.0 / f64::from(SIZE[1]);
            if past_far_plane && y == 24 {
                row_24_past_far_plane += 1;
            }
            // Each component holds about 11 significant bits (a relative
            // 4.9e-4), and the GPU rebuilds the ray's origin from its depth
            // in f32, so the unit direction may differ by a few 1e-4.
            if !((!past_far_plane || (65504.0 - 64.0..=65504.0 + 64.0).contains(&length))
                && (0..3).all(|i| (ray[i] / length - mirror[i]).abs() < 4e-3))
            {
                wrong.push(format!("({x}, {y}): {ray:?}, mirror {mirror:?}"));
            }
        }
    }
    assert!(
        row_24_past_far_plane > 0,
        "no ray of row 24 overshoots the far plane"
    );
    assert!(
        wrong.is_empty(),
        "{} of the floor's rays are not along their mirror direction, as long as RGBA16F holds past the far plane:\n{}",
        wrong.len(),
        wrong.join("\n")
    );
    let output = read_rgba16f(&device, &queue, ssr.get_ssr_radiance_srv());
    let nonfinite = nonfinite(&output);
    assert_eq!(nonfinite, 0, "{nonfinite} non-finite output pixels");
}

// PROVENANCE.md DFX-52: a zero world normal, outside the input contract, has
// no tangent frame to sample a reflection from, which made its ray's
// direction NaN. Every fifth pixel of a mirror floor has a zero normal. Each
// ray's radiance, direction and PDF stay finite at full and half resolution,
// and at full resolution each zero-normal floor pixel reports a miss, no ray
// and no radiance, while each unit-normal floor pixel still stores its ray.
#[test]
fn zero_normals_report_a_miss() {
    let Some((device, queue)) = device() else {
        return;
    };
    let (_, b) = projection_scales();
    let (s, c) = (0.13 / f64::from(b)).atan().sin_cos();
    let floor_normal = [0.0, c, -s];
    let zero_normal = |x: u32, y: u32| (x + y).is_multiple_of(5);
    let depths = floor_depths(floor_normal);
    for feature_flags in [FeatureFlags::NONE, FeatureFlags::HALF_RESOLUTION] {
        let ssr = trace_mirror_floor(&device, &queue, floor_normal, feature_flags, 0, zero_normal);
        let radiance = read_rgba16f(&device, &queue, &ssr.resources().radiance);
        let rays = read_rgba16f(&device, &queue, &ssr.resources().ray_direction_pdf);
        for (name, texels) in [("radiance", &radiance), ("direction and PDF", &rays)] {
            let nonfinite = nonfinite(texels);
            assert_eq!(
                nonfinite,
                0,
                "{feature_flags:?}: {nonfinite} of {} rays' {name}",
                texels.len()
            );
        }
        if feature_flags != FeatureFlags::NONE {
            continue;
        }
        let mut wrong = Vec::new();
        for y in 0..SIZE[1] {
            for x in 0..SIZE[0] {
                let at = (y * SIZE[0] + x) as usize;
                if depths[at] == 0.0 {
                    continue;
                }
                let traced = rays[at][..3].iter().any(|&v| v != 0.0);
                let missed = rays[at] == [0.0; 4] && radiance[at] == [0.0; 4];
                if zero_normal(x, y) && !missed || !zero_normal(x, y) && !traced {
                    wrong.push(format!(
                        "({x}, {y}): ray {:?}, radiance {:?}",
                        rays[at], radiance[at]
                    ));
                }
            }
        }
        assert!(
            wrong.is_empty(),
            "{} floor pixels traced a zero normal or missed a unit one:\n{}",
            wrong.len(),
            wrong.join("\n")
        );
    }
}

// #712: a sharp GGX lobe viewed at grazing incidence exceeds binary16's
// finite range. Execute the production intersection, then evaluate its stored
// rays with the production reconstruction weight; +infinity discards the
// lobe's strongest rays by dropping their weight to the fallback floor.
#[test]
fn glossy_grazing_rays_keep_finite_pdf_and_reconstruction_weight() {
    let Some((device, queue)) = device() else {
        return;
    };
    let normal = [0.0, 1.0, 0.0];
    let ssr = trace_mirror_floor(&device, &queue, normal, FeatureFlags::NONE, 17, |_, _| {
        false
    });
    let rays = read_rgba16f(&device, &queue, &ssr.resources().ray_direction_pdf);
    assert!(
        rays.iter()
            .all(|ray| ray[3].is_finite() && ray[3] <= 65504.0)
    );
    // Use the actual reconstruction function, without copying its BRDF or PDF
    // calculation into the test. The camera rays come from this fixture's
    // analytic perspective projection and the receiver's plane normal.
    let mut source = crate::shaders::shader_source(
        "SSR_ComputeSpatialReconstruction.fx",
        &[
            ("SUPPORTED_SHADER_SRV", "1"),
            ("SSR_OPTION_INVERTED_DEPTH", "1"),
            ("SSR_OPTION_PREVIOUS_FRAME", "0"),
            ("SSR_OPTION_HALF_RESOLUTION", "0"),
            ("SSR_DENOISER_TILE_SIZE", "8"),
        ],
    );
    let (a, b) = projection_scales();
    source.push_str(&format!(
        r#"
@group(0) @binding(9) var<storage, read_write> measured_weights: array<f32>;
@compute @workgroup_size(8, 8)
fn measure_weight(@builtin(global_invocation_id) id: vec3<u32>) {{
    if (id.x >= {width}u || id.y >= {height}u) {{ return; }}
    let uv = (vec2<f32>(id.xy) + 0.5) / vec2<f32>({width}.0, {height}.0);
    let V = -normalize(vec3<f32>((2.0 * uv.x - 1.0) / {a}, (1.0 - 2.0 * uv.y) / {b}, 1.0));
    let N = vec3<f32>(0.0, 1.0, 0.0);
    measured_weights[id.y * {width}u + id.x] = ComputeWeightRayLength(vec2<i32>(id.xy), V, N, 17.0 / 255.0, max(dot(N, V), 1e-6), 1.0).x;
}}
"#,
        width = SIZE[0], height = SIZE[1],
    ));
    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
        label: Some("glossy-floor reconstruction weights"),
        source: wgpu::ShaderSource::Wgsl(source.into()),
    });
    let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
        label: None,
        layout: None,
        module: &shader,
        entry_point: Some("measure_weight"),
        compilation_options: Default::default(),
        cache: None,
    });
    let size = u64::from(SIZE[0] * SIZE[1]) * 4;
    let weights = device.create_buffer(&wgpu::BufferDescriptor {
        label: None,
        size,
        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
        mapped_at_creation: false,
    });
    let readback = device.create_buffer(&wgpu::BufferDescriptor {
        label: None,
        size,
        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
        mapped_at_creation: false,
    });
    let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: None,
        layout: &pipeline.get_bind_group_layout(0),
        entries: &[
            wgpu::BindGroupEntry {
                binding: 5,
                resource: wgpu::BindingResource::TextureView(&ssr.resources().ray_direction_pdf),
            },
            wgpu::BindGroupEntry {
                binding: 9,
                resource: weights.as_entire_binding(),
            },
        ],
    });
    let mut encoder = device.create_command_encoder(&Default::default());
    {
        let mut pass = encoder.begin_compute_pass(&Default::default());
        pass.set_pipeline(&pipeline);
        pass.set_bind_group(0, &bind, &[]);
        pass.dispatch_workgroups(SIZE[0].div_ceil(8), SIZE[1].div_ceil(8), 1);
    }
    encoder.copy_buffer_to_buffer(&weights, 0, &readback, 0, size);
    queue.submit([encoder.finish()]);
    readback.map_async(wgpu::MapMode::Read, .., |r| r.unwrap());
    device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
    let bytes = readback.get_mapped_range(..).unwrap();
    let weights: &[f32] = bytemuck::cast_slice(&bytes);
    let mut saturated = 0;
    for (ray, weight) in rays.iter().zip(weights) {
        if ray[3] == 65504.0 {
            saturated += 1;
            assert!(
                *weight > 1e-6,
                "saturated grazing ray {ray:?} discarded at weight {weight}"
            );
        }
    }
    assert!(
        saturated > 0,
        "fixture did not reach the half-float PDF limit"
    );
}

// The floor is a horizontal mirror at Y = -1. Reflecting a point across
// that plane leaves X and Z unchanged, so a marking on a front-facing
// wall moves the same horizontal screen distance as its floor reflection.
#[derive(Clone, Copy, PartialEq)]
enum MovingWall {
    Painted,
    Slatted,
    RevealsBackground,
    AppearsOverSky,
    Approaching,
}

fn trace_moving_wall(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    flags: FeatureFlags,
    scene: MovingWall,
) -> ScreenSpaceReflection {
    let mut camera = infinite_reversed_camera();
    if scene == MovingWall::Approaching {
        // Place the optical axis at a pixel centre. This point of a rigid
        // sign translating along its normal has exactly zero XY motion.
        camera = super::temporal_neighborhood_tests::jittered(
            camera,
            [1. / SIZE[0] as f32, -1. / SIZE[1] as f32],
        );
    }
    let mut ssr = ScreenSpaceReflection::new(device);
    let mut ctx = PostFXContext::new(
        device,
        queue,
        post_fx_context::CreateInfo {
            transition_duration: 0.,
        },
    );
    let mut previous_depth = None;
    for index in 0..2 {
        let shift = 4 * index;
        let mut depths = Vec::new();
        let mut normals = Vec::new();
        let mut materials = Vec::new();
        let mut velocities = Vec::new();
        let mut colors = Vec::new();
        for y in 0..SIZE[1] {
            let slope = pixel_ray(0, y)[1] as f32 - camera.f2_jitter[1] / camera.m_proj[5];
            for x in 0..SIZE[0] {
                let panel = (22 + shift..32 + shift).contains(&x);
                let wall_z = match scene {
                    MovingWall::Approaching => {
                        if index == 0 {
                            8.
                        } else {
                            6.
                        }
                    }
                    MovingWall::AppearsOverSky if index == 0 => f32::INFINITY,
                    MovingWall::RevealsBackground if panel => 6.,
                    MovingWall::Slatted if (x + 16 - shift) % 16 < 2 => f32::INFINITY,
                    _ => 8.,
                };
                let floor = slope < -1. / wall_z;
                let moving = !floor
                    && wall_z.is_finite()
                    && index == 1
                    && scene != MovingWall::AppearsOverSky
                    && (scene != MovingWall::RevealsBackground || panel);
                depths.push(if floor { -NEAR * slope } else { NEAR / wall_z });
                normals.extend(half(&if floor {
                    [0., 1., 0., 0.]
                } else {
                    [0., 0., -1., 0.]
                }));
                let mirror = floor
                    && (scene != MovingWall::Painted
                        || x < SIZE[0] / 2
                        || (x % 2 == 1 && y % 2 == 1));
                materials.push(if !mirror {
                    255
                } else if scene == MovingWall::Slatted {
                    50
                } else {
                    0
                });
                let motion = if scene == MovingWall::Approaching && moving {
                    // Previous Z was 8 m, current Z is 6 m. X and Y on a
                    // rigid sign are fixed in world space, so its old NDC
                    // coordinates are 6/8 of the current unjittered NDC.
                    let dx = 2. * (x as f32 - SIZE[0] as f32 * 0.5) / SIZE[0] as f32;
                    [dx * 0.25, slope * camera.m_proj[5] * 0.25, 2., 1.]
                } else {
                    [
                        if moving { 8. / SIZE[0] as f32 } else { 0. },
                        0.,
                        0.,
                        if !floor
                            && (scene == MovingWall::AppearsOverSky
                                || (scene == MovingWall::Painted && x < SIZE[0] / 2))
                        {
                            0.
                        } else {
                            1.
                        },
                    ]
                };
                velocities.extend(half(&motion));
                let illuminated = match scene {
                    MovingWall::Approaching => (slope * wall_z).abs() < 0.09,
                    MovingWall::RevealsBackground => panel,
                    _ => ((x + 8 - shift) / 4).is_multiple_of(2),
                };
                let light = if !floor && illuminated { 4. } else { 0. };
                colors.extend(half(&[light, light, light, 1.]));
            }
        }
        let format = wgpu::TextureFormat::Rgba16Float;
        let normal = texels(device, queue, format, &normals);
        let material = texels(device, queue, wgpu::TextureFormat::R8Unorm, &materials);
        let motion = texels(device, queue, format, &velocities);
        let color = texels(device, queue, format, &colors);
        let current = CameraAttribs {
            ui_frame_index: index,
            ..camera
        };
        let mut encoder = device.create_command_encoder(&Default::default());
        let depth = depth_values(device, queue, &mut encoder, &depths);
        ctx.prepare_resources(
            device,
            &FrameDesc {
                index,
                width: SIZE[0],
                height: SIZE[1],
                output_width: SIZE[0],
                output_height: SIZE[1],
            },
            post_fx_context::FeatureFlags::REVERSED_DEPTH,
        );
        ssr.prepare_resources(device, &mut encoder, &mut ctx, flags);
        ctx.execute(&mut post_fx_context::RenderAttributes {
            device,
            queue,
            device_context: &mut encoder,
            curr_depth_buffer_srv: &depth,
            prev_depth_buffer_srv: previous_depth.as_ref().unwrap_or(&depth),
            curr_camera: Some(&current),
            prev_camera: Some(&camera),
            camera_attribs_cb: None,
            pass_timestamps: None,
        });
        ssr.execute(&mut RenderAttributes {
            device,
            queue,
            device_context: &mut encoder,
            post_fx_context: &mut ctx,
            color_buffer_srv: &color,
            depth_buffer_srv: &depth,
            normal_buffer_srv: &normal,
            material_buffer_srv: &material,
            motion_vectors_srv: &motion,
            ssr_attribs: &ScreenSpaceReflectionAttribs {
                ggx_importance_sample_bias: 1.,
                ..Default::default()
            },
            pass_timestamps: None,
            reset_accumulation: false,
            frame_time: 1. / 60.,
        });
        queue.submit([encoder.finish()]);
        previous_depth = Some(depth);
    }
    ssr
}

#[test]
fn a_moving_wall_marking_leaves_no_trail_on_a_stationary_mirror() {
    let Some((device, queue)) = device() else {
        return;
    };
    for flags in [FeatureFlags::NONE, FeatureFlags::HALF_RESOLUTION] {
        let ssr = trace_moving_wall(&device, &queue, flags, MovingWall::Painted);
        let image = read_rgba16f(&device, &queue, ssr.get_ssr_radiance_srv());
        for y in [35, 37, 39] {
            for x in (21..44).step_by(2) {
                // On the right half only one receiver per 2×2 block is
                // glossy. Half resolution must still trace its reflection.
                let pixel = image[(y * SIZE[0] + x) as usize];
                let expected = if (x / 4) % 2 == 1 { 4. } else { 0. };
                assert!(
                    pixel[3] > 0.5 && (pixel[0] / pixel[3] - expected).abs() < 0.01,
                    "{flags:?} ({x},{y}) expected {expected} from the wall, got {pixel:?}"
                );
            }
        }
    }
}

#[test]
fn a_moving_panel_reveals_the_reflected_background() {
    let Some((device, queue)) = device() else {
        return;
    };
    for flags in [FeatureFlags::NONE, FeatureFlags::HALF_RESOLUTION] {
        let ssr = trace_moving_wall(&device, &queue, flags, MovingWall::RevealsBackground);
        let image = read_rgba16f(&device, &queue, ssr.get_ssr_radiance_srv());
        for y in [35, 37, 39] {
            for x in [24, 25, 26, 27] {
                let pixel = image[(y * SIZE[0] + x) as usize];
                // The panel moved from [22,32) to [26,36). Light at the
                // vacated pixels now comes from a stationary black wall.
                let expected = if x < 26 { 0. } else { 4. };
                assert!(
                    pixel[3] > 0.5 && (pixel[0] / pixel[3] - expected).abs() < 0.01,
                    "{flags:?} ({x},{y}) expected {expected} from panel/wall, got {pixel:?}"
                );
            }
        }
    }
}

#[test]
fn reflections_across_a_gap_follow_the_moving_wall() {
    let Some((device, queue)) = device() else {
        return;
    };
    for flags in [FeatureFlags::NONE, FeatureFlags::HALF_RESOLUTION] {
        let ssr = trace_moving_wall(&device, &queue, flags, MovingWall::Slatted);
        let raw = read_rgba16f(&device, &queue, &ssr.resources().radiance);
        let current = read_rgba16f(&device, &queue, &ssr.resources().resolved_radiance);
        let history = read_rgba16f(&device, &queue, &ssr.resources().radiance_history[1]);
        let scale = if flags == FeatureFlags::HALF_RESOLUTION {
            2
        } else {
            1
        };
        let mut supported = 0;
        for y in 35..40 {
            for x in 12..50 {
                let i = (y * SIZE[0] + x) as usize;
                let center = ((y / scale) * (SIZE[0] / scale) + x / scale) as usize;
                if raw[center][3] == 0. && current[i][3] > 0.1 {
                    // The centre ray missed. Every nonzero contribution
                    // to the reconstructed RGB was traced to a moving slat.
                    supported += 1;
                    assert!(
                        (current[i][0] - history[i][0]).abs() < 0.01
                            && (current[i][3] - history[i][3]).abs() < 0.01,
                        "{flags:?} ({x},{y}) center missed, reconstructed {:?}, retained {:?}",
                        current[i],
                        history[i]
                    );
                }
            }
        }
        assert!(
            supported > 0,
            "{flags:?}: no reflected slats reached across a miss"
        );
    }
}

// At the luminosity stripe's centre the sign moves towards the camera along
// its sightline. Its screen position stays fixed while its virtual image,
// two metres below the optical axis, moves down the mirror.
#[test]
fn a_sign_moving_along_the_sightline_moves_in_the_floor_mirror() {
    let Some((device, queue)) = device() else {
        return;
    };
    for flags in [FeatureFlags::NONE, FeatureFlags::HALF_RESOLUTION] {
        let ssr = trace_moving_wall(&device, &queue, flags, MovingWall::Approaching);
        let image = read_rgba16f(&device, &queue, ssr.get_ssr_radiance_srv());
        // The stripe lies on Y=0. Its virtual image is at Y=-2, so its
        // displacement from the optical axis is 2 × focal length / Z.
        let focal = projection_scales().1 * SIZE[1] as f32 * 0.5;
        let pixel = |z: f32| {
            let y = (SIZE[1] as f32 * 0.5 + 2. * focal / z).round() as u32;
            image[(y * SIZE[0] + SIZE[0] / 2) as usize]
        };
        let old = pixel(8.);
        let now = pixel(6.);
        assert!(
            old[3] > 0.5 && old[0] < 0.01,
            "{flags:?}: trail at old stripe {old:?}"
        );
        assert!(
            now[3] > 0.5 && (now[0] / now[3] - 4.).abs() < 0.01,
            "{flags:?}: missing axial reflection {now:?}"
        );
    }
}

// The wall first becomes visible against an empty sky. For an infinite
// reversed-Z camera the previous wall texel is exactly depth zero. Its old
// reflected radiance is a miss, while the newly visible stripe is lit.
#[test]
fn a_wall_appearing_over_infinite_sky_lights_its_reflection() {
    let Some((device, queue)) = device() else {
        return;
    };
    for flags in [FeatureFlags::NONE, FeatureFlags::HALF_RESOLUTION] {
        let ssr = trace_moving_wall(&device, &queue, flags, MovingWall::AppearsOverSky);
        let image = read_rgba16f(&device, &queue, ssr.get_ssr_radiance_srv());
        for y in [37, 39] {
            for x in [22, 23, 24, 25] {
                // Below the optical axis the mirror sees the wall above the
                // horizon. Its stripe ends at x=24; both sides have a hit.
                let pixel = image[(y * SIZE[0] + x) as usize];
                let expected = if x < 24 { 4. } else { 0. };
                assert!(
                    pixel[3] > 0.5 && (pixel[0] / pixel[3] - expected).abs() < 0.01,
                    "{flags:?} ({x},{y}) expected {expected} from new wall, got {pixel:?}"
                );
            }
        }
    }
}