sgl-3d 0.4.2

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
//! The volumetric fog in real frames: a medium without density leaves the
//! frame as no fog does; a point light's scattering along a froxel column
//! matches a numerical single-scattering integral along its view ray; a
//! shadowed light, local or directional, scatters nothing in the medium its
//! occluder hides from it; the filter blurs each slice by Godot's Gaussian
//! while the history stays unfiltered; a light's fog energy scales its
//! light in the medium and nowhere else; fog volumes add their medium to
//! every froxel they reach; the sky takes its sky affect of the fog; and a
//! light's shadow opacity blends its shadow toward unshadowed on surfaces
//! and in the medium alike.
use super::froxels;
use crate::renderer::Renderer;
use crate::settings::{self, FogQuality, Settings};
use crate::shading::gbuffer;
use crate::{
    Backdrop, Camera, DirectionalLight, DirectionalShadow, Fog, FrameInput, HemisphereLight,
    InstanceState, Light, LightShape, Mobility, Scene, test_support,
};
use glam::{Mat4, Quat, Vec2, Vec3};

const SIZE: [u32; 2] = [160, 90];
const QUALITY: FogQuality = FogQuality::High;

fn projection() -> Mat4 {
    crate::perspective(1., SIZE[0] as f32 / SIZE[1] as f32, 0.1)
}

fn settings(atmosphere: bool) -> Settings {
    Settings {
        antialiasing: settings::Antialiasing::Off,
        bloom: settings::Bloom::Off,
        atmosphere,
        fog_quality: QUALITY,
        ..Settings::default()
    }
}

/// A camera at the origin looking down -Z over a black backdrop, its
/// atmosphere on so that the settings decide whether the fog runs.
fn input(fog: Fog) -> FrameInput {
    let mut input = FrameInput::new(Camera {
        view: Mat4::IDENTITY,
        projection: projection(),
        eye: Vec3::ZERO,
    });
    input.backdrop = Backdrop::Color([0.; 3]);
    input.atmosphere = true;
    input.fog = fog;
    input
}

/// `frames` frames of `scene` seen as `input`, the first a camera cut.
fn render(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    scene: &mut Scene,
    input: &FrameInput,
    settings: &Settings,
    frames: usize,
) -> Renderer {
    let mut renderer = Renderer::for_test(device, queue, SIZE, settings);
    let output = crate::view::targets::target(device, "fog frames", SIZE, gbuffer::COLOR);
    for frame in 0..frames {
        let mut input = *input;
        input.camera_cut = frame == 0;
        let mut encoder = device.create_command_encoder(&Default::default());
        renderer.render(
            device,
            queue,
            &mut encoder,
            scene,
            &input,
            settings,
            &output,
            None,
        );
        queue.submit([encoder.finish()]);
        renderer.finish_frame(scene);
    }
    renderer
}

fn texels(bytes: &[u8]) -> Vec<[f32; 4]> {
    bytes
        .chunks_exact(8)
        .map(|texel| std::array::from_fn(|channel| test_support::half(&texel[channel * 2..])))
        .collect()
}

fn read(device: &wgpu::Device, queue: &wgpu::Queue, view: &wgpu::TextureView) -> Vec<u8> {
    test_support::read(device, queue, view.texture(), 8)
}

/// A static occluder: `test_support::cube` scaled by `scale` about `center`.
fn add_box(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    scene: &mut Scene,
    center: Vec3,
    scale: Vec3,
) {
    let ids = scene
        .add_asset(device, queue, test_support::cube())
        .unwrap();
    scene
        .add_instance(
            device,
            queue,
            InstanceState {
                model: ids.model,
                pose: Mat4::from_translation(center) * Mat4::from_scale(scale),
                visible: true,
                capture_visible: true,
            },
            Mobility::Static,
        )
        .unwrap();
}

/// The world position of froxel `index` of a volume of `size` seen by
/// `input`'s camera at the origin, without jitter: the centre of its
/// column at the centre of its slice.
fn froxel_center(input: &FrameInput, size: [u32; 3], index: [u32; 3]) -> Vec3 {
    let (ndc, depth) = froxel_ray(input, size, [index[0], index[1]], index[2]);
    view_ray(input, ndc) * depth
}

/// Column `column`'s frame position and slice `slice`'s view depth, from
/// the frame's geometry: columns split the frame evenly, and slices split
/// the fog's length as the volume's detail spread spaces them.
fn froxel_ray(input: &FrameInput, size: [u32; 3], column: [u32; 2], slice: u32) -> (Vec2, f32) {
    let u = (column[0] as f32 + 0.5) / size[0] as f32;
    let v = (column[1] as f32 + 0.5) / size[1] as f32;
    let unit = (slice as f32 + 0.5) / size[2] as f32;
    let depth = input.fog.length * unit.powf(crate::shading::fog::DETAIL_SPREAD);
    (Vec2::new(u * 2. - 1., 1. - v * 2.), depth)
}

/// The view-space point a metre deep under frame position `ndc`, which the
/// camera's projection maps there.
fn view_ray(input: &FrameInput, ndc: Vec2) -> Vec3 {
    let p = input.camera.projection;
    Vec3::new(
        (ndc.x + p.z_axis.x) / p.x_axis.x,
        (ndc.y + p.z_axis.y) / p.y_axis.y,
        -1.,
    )
}

// Defect: the volume's split leaves its froxels far from square, or a side
// past the device's 3D texture limit as the frame narrows (at 60×1900 High
// asked for 2090 froxels tall, past WebGPU's default 2048), so creating the
// volume fails. The oracle is the documented sizing: a frame and its
// transpose take transposed volumes, each froxel covers as many pixels
// across as down up to truncating its counts, and no side leaves
// 1..=limit.
#[test]
fn froxels_stay_square_and_within_the_texture_limit_however_thin_the_frame() {
    const LIMIT: u32 = 2048;
    for quality in [FogQuality::Low, FogQuality::High] {
        for render in [[60, 1900], [1900, 60], [40, 1300], [1920, 1080], [7, 7]] {
            let [x, y, _] = froxels(quality, render, LIMIT);
            let [across, down, _] = froxels(quality, [render[1], render[0]], LIMIT);
            assert_eq!([x, y], [down, across], "{quality:?} {render:?} transposed");
            let aspect = (render[0] as f32 / x as f32) / (render[1] as f32 / y as f32);
            let truncation = (x + 1) as f32 / x as f32 * (y + 1) as f32 / y as f32;
            assert!(
                aspect.max(aspect.recip()) <= truncation,
                "{quality:?} {render:?}: {x}×{y} froxels, aspect {aspect}"
            );
        }
        for render in [[1, 1 << 20], [1 << 20, 1]] {
            let [x, y, _] = froxels(quality, render, LIMIT);
            assert!(
                (1..=LIMIT).contains(&x) && (1..=LIMIT).contains(&y),
                "{quality:?} {render:?}: {x}×{y} froxels"
            );
        }
    }
}

// Defect: the fog adds light or dims where the medium has no density, or
// the composition is not color * transmittance + scattering, so the frame
// with an empty medium, skipped or run, differs from the frame with no fog.
// The run's integrated volume must be exactly clear, and a denser medium
// must change the frame.
#[test]
fn an_empty_medium_leaves_the_frame_as_no_fog_does() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    add_box(
        &device,
        &queue,
        &mut scene,
        Vec3::new(0., -0.5, -6.),
        Vec3::new(3., 1., 3.),
    );
    // All of the hemisphere fill's ambient light, so the ambient's
    // scattering is among what an empty medium must not add.
    let mut frame = input(Fog {
        density: 0.,
        length: 30.,
        anisotropy: 0.5,
        ambient: 1.,
        ..Fog::default()
    });
    frame.directional_lights[0] = Some(DirectionalLight {
        direction: Vec3::new(0.3, -1., -0.4),
        color: [1., 0.9, 0.8],
        illuminance: 4.,
        shadow: Some(DirectionalShadow {
            distance: 30.,
            cascades: 2,
        }),
        ..Default::default()
    });
    frame.hemisphere_light = HemisphereLight {
        sky_color: [0.4, 0.5, 0.7],
        ground_color: [0.1, 0.1, 0.1],
        intensity: 1.,
    };
    frame.backdrop = Backdrop::Color([0.2, 0.3, 0.45]);
    let composite = |renderer: &Renderer| read(&device, &queue, &renderer.targets().composite);
    let unfogged = composite(&render(
        &device,
        &queue,
        &mut scene,
        &frame,
        &settings(false),
        1,
    ));
    // Without a medium the fog has nothing to do.
    let skipped = composite(&render(
        &device,
        &queue,
        &mut scene,
        &frame,
        &settings(true),
        1,
    ));
    assert!(skipped == unfogged, "no medium changed the frame");
    // An empty fog volume runs the fog over a medium without density; the
    // second frame reprojects the first's volume.
    scene
        .update_fog_volumes(
            &device,
            &queue,
            &[crate::FogVolume {
                center: Vec3::new(0., 0., -6.),
                rotation: glam::Quat::IDENTITY,
                size: Vec3::splat(4.),
                density: 0.,
                albedo: [1.; 3],
                edge_fade: 0.,
            }],
        )
        .unwrap();
    let empty = render(&device, &queue, &mut scene, &frame, &settings(true), 2);
    let integrated = texels(&read(&device, &queue, empty.fog_volumes()[2]));
    assert!(
        integrated.iter().all(|texel| *texel == [0., 0., 0., 1.]),
        "an empty medium scattered or dimmed"
    );
    assert!(
        composite(&empty) == unfogged,
        "an empty medium changed the frame"
    );
    frame.fog.density = 0.05;
    let dense = composite(&render(
        &device,
        &queue,
        &mut scene,
        &frame,
        &settings(true),
        1,
    ));
    assert!(dense != unfogged, "a dense medium left the frame unfogged");
}

/// Henyey-Greenstein's phase function.
fn henyey_greenstein(cos_theta: f32, g: f32) -> f32 {
    (1. - g * g) / (4. * std::f32::consts::PI * (1. + g * g - 2. * g * cos_theta).powf(1.5))
}

// Defect: the injection's units, phase, light attenuation or albedo, or the
// integration's step or extinction, are wrong. The
// reference integrates single scattering along each column's view ray from
// the camera to a slice's centre by brute force: a homogeneous medium's
// transmittance exp(-sigma t) (Beer-Lambert) times what it scatters from a
// point light of known intensity, inverse-square falloff and range window
// (the light's documented attenuation), weighted by the phase function.
#[test]
fn point_light_scattering_matches_a_single_scattering_integral() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    let light_position = Vec3::new(1.2, 1.2, -4.5);
    let intensity = 40.;
    let range = 25.;
    scene
        .add_light(
            &device,
            &queue,
            Light {
                position: light_position,
                shape: LightShape::Point {
                    radius: LightShape::DEFAULT_RADIUS,
                },
                color: [1.; 3],
                intensity,
                range,
                baked: false,
                specular: 1.,
                casts_shadow: false,
                ..Default::default()
            },
        )
        .unwrap();
    let fog = Fog {
        density: 0.06,
        albedo: [1., 0.5, 0.25],
        anisotropy: 0.4,
        length: 10.,
        ..Fog::default()
    };
    let frame = input(fog);
    let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    let integrated = texels(&read(&device, &queue, renderer.fog_volumes()[2]));
    let mut checked = 0;
    for column in [
        [size[0] / 2, size[1] / 2],
        [size[0] * 3 / 4, size[1] / 2],
        [size[0] / 3, size[1] / 3],
        [size[0] * 2 / 3, size[1] * 2 / 3],
    ] {
        let along = view_ray(&frame, froxel_ray(&frame, size, column, 0).0);
        let direction = along.normalize();
        // Close passes concentrate the light into a few slices, where the
        // froxels' resolution, not the method, limits agreement.
        let closest = (light_position - direction * light_position.dot(direction)).length();
        assert!(
            closest > 1.,
            "column {column:?} passes {closest} m from the light"
        );
        for slice in [size[2] / 4, size[2] / 2, size[2] * 3 / 4, size[2] - 1] {
            let distance = froxel_ray(&frame, size, column, slice).1 * along.length();
            let steps = 20_000;
            let step = distance / steps as f32;
            let mut reference = [0f32; 3];
            for index in 0..steps {
                let t = (index as f32 + 0.5) * step;
                let point = direction * t;
                let to_light = light_position - point;
                let square = to_light.length_squared();
                let window = (1. - (square / (range * range)).powi(2))
                    .clamp(0., 1.)
                    .powi(2);
                let irradiance = intensity * window / square.max(1e-4);
                let phase = henyey_greenstein(direction.dot(to_light.normalize()), fog.anisotropy);
                let attenuated = irradiance * phase * (-fog.density * t).exp() * step;
                for (sum, albedo) in reference.iter_mut().zip(fog.albedo) {
                    *sum += fog.density * albedo * attenuated;
                }
            }
            let texel = integrated[((slice * size[1] + column[1]) * size[0] + column[0]) as usize];
            for channel in 0..3 {
                let error = (texel[channel] - reference[channel]).abs();
                assert!(
                    error <= 0.03 * reference[channel] + 1e-4,
                    "column {column:?} slice {slice} channel {channel}: {} against the integral's {}",
                    texel[channel],
                    reference[channel]
                );
            }
            let transmittance = (-fog.density * distance).exp();
            assert!(
                (texel[3] - transmittance).abs() <= 2e-3,
                "column {column:?} slice {slice}: transmittance {} against Beer-Lambert's {transmittance}",
                texel[3]
            );
            checked += usize::from(reference[0] > 1e-3);
        }
    }
    assert!(
        checked >= 8,
        "too few samples carry measurable light: {checked}"
    );
}

// Defect: one jittered sample per froxel of a point light's inverse square
// spikes to thousands of times the froxel's light whenever it lands
// centimetres from the light, and the reprojected history holds each spike
// for frames, so the fog about a still light pulses with the 16-frame jitter
// cycle (and a moving light leaves puffs behind it). A still scene's fog
// must hold still: once the history has settled, the froxel holding the
// light changes by at most a quarter over a whole jitter cycle, on the
// view's axis and at the frame's corners, where the frustum shears a froxel
// half a metre across. The bound follows from the froxel's geometry, not from a
// measurement: with the light at the centre of the froxel's bounding box in
// view space, every jittered sample lies within half the box's diagonal b of
// it, so with b² added to the inverse square's denominator, as the medium
// takes it, each sample's 1/(d² + b²) lies between 1/(1.25 b²) and 1/b², a
// quarter apart at most, and so does any history mix of them. Unbiased, 1/d²
// ranges a thousandfold between the samples.
#[test]
fn a_still_point_light_holds_its_froxel_steady_over_the_jitter_cycle() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.,
        // Slices metres deep a few metres out, as a long fog's are.
        length: 100.,
        ..Fog::default()
    };
    let frame = input(fog);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    // A froxel's corner at unit coordinates `unit` of the volume, in view
    // space (the camera's view is the identity), from the frame's geometry.
    let corner = |unit: Vec3| {
        let ndc = Vec2::new(unit.x * 2. - 1., 1. - unit.y * 2.);
        view_ray(&frame, ndc) * fog.length * unit.z.powf(crate::shading::fog::DETAIL_SPREAD)
    };
    // Froxels about 4 m out, their slices 0.6 m deep and their columns about
    // 5 cm across: on the view's axis, and at the frame's top-left and
    // bottom-right corners.
    for column in [
        [size[0] / 2, size[1] / 2],
        [1, 1],
        [size[0] - 2, size[1] - 2],
    ] {
        let index = [column[0], column[1], 12];
        let (mut low, mut high) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
        for offset in 0..8u32 {
            let unit = Vec3::new(
                (index[0] + (offset & 1)) as f32 / size[0] as f32,
                (index[1] + (offset >> 1 & 1)) as f32 / size[1] as f32,
                (index[2] + (offset >> 2)) as f32 / size[2] as f32,
            );
            let p = corner(unit);
            low = low.min(p);
            high = high.max(p);
        }
        let mut scene = Scene::new(&device, &queue);
        scene
            .add_light(
                &device,
                &queue,
                Light {
                    position: (low + high) * 0.5,
                    shape: LightShape::Point {
                        radius: LightShape::DEFAULT_RADIUS,
                    },
                    color: [1.; 3],
                    intensity: 10.,
                    range: 25.,
                    baked: false,
                    specular: 1.,
                    casts_shadow: false,
                    ..Default::default()
                },
            )
            .unwrap();
        let settings = settings(true);
        let mut renderer = Renderer::for_test(&device, &queue, SIZE, &settings);
        let output = crate::view::targets::target(&device, "fog frames", SIZE, gbuffer::COLOR);
        let at = ((index[2] * size[1] + index[1]) * size[0] + index[0]) as usize;
        let mut light = Vec::new();
        // Three jitter cycles: two for the history to settle, the third read.
        for frame_index in 0..48 {
            let mut input = frame;
            input.camera_cut = frame_index == 0;
            let mut encoder = device.create_command_encoder(&Default::default());
            renderer.render(
                &device,
                &queue,
                &mut encoder,
                &mut scene,
                &input,
                &settings,
                &output,
                None,
            );
            queue.submit([encoder.finish()]);
            renderer.finish_frame(&mut scene);
            if frame_index >= 32 {
                light.push(texels(&read(&device, &queue, renderer.fog_volumes()[0]))[at][0]);
            }
        }
        let (least, most) = light
            .iter()
            .fold((f32::MAX, 0f32), |(least, most), &value| {
                (least.min(value), most.max(value))
            });
        assert!(
            least > 1e-3,
            "froxel {index:?}, holding the light, is unlit: {light:?}"
        );
        assert!(
            most <= 1.25 * least,
            "froxel {index:?}, holding a still light, ranged {least} to {most} over a jitter cycle: {light:?}"
        );
    }
}

// Defect: the medium's bias of a light's inverse square depends on where
// the froxel lies on screen, as one oblique corner-to-corner vector of a
// froxel the frustum shears does: such a measure differs between a froxel
// and its mirror image across the view's axis, so a light near the camera
// would hold different fog on either side of the screen. The camera's
// projection is symmetric, so a light and its mirror image each lit in the
// froxel holding it must hold the same light there, at every corner of the
// frame, within the half-float volume's rounding.
#[test]
fn a_light_holds_the_same_fog_on_either_side_of_the_screen() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.,
        length: 100.,
        ..Fog::default()
    };
    let frame = input(fog);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    // The light a centimetre toward the camera from the centre of froxel
    // `index`, alone (a light exactly at a sample has no direction and
    // lights nothing there); the froxel's light on the first frame, which
    // samples froxel centres.
    let held = |index: [u32; 3]| {
        let mut scene = Scene::new(&device, &queue);
        scene
            .add_light(
                &device,
                &queue,
                Light {
                    position: {
                        let center = froxel_center(&frame, size, index);
                        center - center.normalize() * 0.01
                    },
                    shape: LightShape::Point {
                        radius: LightShape::DEFAULT_RADIUS,
                    },
                    color: [1.; 3],
                    intensity: 10.,
                    range: 25.,
                    baked: false,
                    specular: 1.,
                    casts_shadow: false,
                    ..Default::default()
                },
            )
            .unwrap();
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        let at = ((index[2] * size[1] + index[1]) * size[0] + index[0]) as usize;
        texels(&read(&device, &queue, renderer.fog_volumes()[0]))[at][0]
    };
    for (column, slice) in [([1, 1], 12), ([size[0] - 2, 1], 12), ([3, 5], 20)] {
        let index = [column[0], column[1], slice];
        let mirror = [size[0] - 1 - column[0], size[1] - 1 - column[1], slice];
        let (light, mirrored) = (held(index), held(mirror));
        assert!(
            light > 1e-3,
            "froxel {index:?}, holding the light, is unlit"
        );
        assert!(
            (light - mirrored).abs() <= 4e-3 * light,
            "froxel {index:?} holds {light} of a light at its centre, its mirror image {mirror:?} {mirrored}"
        );
    }
}

// Defect: the medium's bias of a light's inverse square reaches froxels far
// smaller than their distance to the light, dimming a distant light's fog.
// There the bias is the froxel's squared diagonal over thousands of square
// metres, under a thousandth, so each froxel's first-frame light (its centre,
// unjittered) must equal the light's physical falloff at that centre
// (the light's documented attenuation and the phase function), within the
// half-float volume's rounding.
#[test]
fn froxels_far_smaller_than_their_distance_to_a_light_keep_its_falloff() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.,
        // Slices a few centimetres deep near the camera.
        length: 10.,
        ..Fog::default()
    };
    let frame = input(fog);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    // Far ahead of and beside the near froxels below: 4 m and more away from
    // froxels at most about 3 cm across.
    let light_position = Vec3::new(1.5, 0.5, -5.5);
    let intensity = 40.;
    let range = 25.;
    let mut scene = Scene::new(&device, &queue);
    scene
        .add_light(
            &device,
            &queue,
            Light {
                position: light_position,
                shape: LightShape::Point {
                    radius: LightShape::DEFAULT_RADIUS,
                },
                color: [1.; 3],
                intensity,
                range,
                baked: false,
                specular: 1.,
                casts_shadow: false,
                ..Default::default()
            },
        )
        .unwrap();
    let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
    let written = texels(&read(&device, &queue, renderer.fog_volumes()[0]));
    let mut checked = 0;
    for slice in [8, 12, 16] {
        for column in [
            [size[0] / 2, size[1] / 2],
            [size[0] / 4, size[1] / 3],
            [size[0] * 3 / 4, size[1] * 2 / 3],
        ] {
            let index = [column[0], column[1], slice];
            let center = froxel_center(&frame, size, index);
            let square = (light_position - center).length_squared();
            let window = (1. - (square / (range * range)).powi(2))
                .clamp(0., 1.)
                .powi(2);
            let expected =
                fog.density * intensity * window / square * henyey_greenstein(0., fog.anisotropy);
            let texel = written[((slice * size[1] + column[1]) * size[0] + column[0]) as usize][0];
            assert!(
                (texel - expected).abs() <= 2e-3 * expected,
                "froxel {index:?}, {} m from the light: {texel} against its falloff's {expected}",
                square.sqrt()
            );
            checked += 1;
        }
    }
    assert_eq!(checked, 9);
}

/// Godot's filter weights (b130438 `volumetric_fog_process.glsl`
/// MODE_FILTER `gauss`), from three froxels before to three after.
const GODOT_GAUSS: [f32; 7] = [
    0.071303, 0.131514, 0.189879, 0.214607, 0.189879, 0.131514, 0.071303,
];

/// `volume` of `size` blurred along `axis` (0 x, 1 y) by Godot's weights,
/// its coordinates clamped to the volume as Godot clamps them.
fn godot_gaussian(volume: &[[f32; 4]], size: [u32; 3], axis: usize) -> Vec<[f32; 4]> {
    let index = |at: [u32; 3]| ((at[2] * size[1] + at[1]) * size[0] + at[0]) as usize;
    let mut blurred = vec![[0.; 4]; volume.len()];
    for z in 0..size[2] {
        for y in 0..size[1] {
            for x in 0..size[0] {
                let at = [x, y, z];
                let sum = &mut blurred[index(at)];
                for (tap, weight) in GODOT_GAUSS.iter().enumerate() {
                    let mut from = at;
                    from[axis] =
                        (at[axis] as i32 + tap as i32 - 3).clamp(0, size[axis] as i32 - 1) as u32;
                    for (channel, value) in volume[index(from)].iter().enumerate() {
                        sum[channel] += weight * value;
                    }
                }
            }
        }
    }
    blurred
}

// Defect: the filter takes other weights, axes or edges than Godot's, the
// integration reads the unfiltered froxels, or the filter reaches the history
// the next frame reprojects, which Godot copies before it filters, or it
// leaves a channel out. Over two frames of a point light in a medium whose
// density falls with height, so its light and its extinction both vary
// across the frame, the froxels the frame wrote are the same with the filter
// as without, the froxels it integrates are Godot's Gaussian of them along x
// and then y within half-float rounding, and the integrated volume differs
// from the unfiltered one.
#[test]
fn the_filter_blurs_each_slice_by_godots_gaussian_and_leaves_the_history_unfiltered() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    scene
        .add_light(
            &device,
            &queue,
            Light {
                position: Vec3::new(0.5, 0.3, -3.),
                shape: LightShape::Point {
                    radius: LightShape::DEFAULT_RADIUS,
                },
                color: [1.; 3],
                intensity: 40.,
                range: 25.,
                baked: false,
                specular: 1.,
                casts_shadow: false,
                ..Default::default()
            },
        )
        .unwrap();
    let frame = input(Fog {
        density: 0.06,
        height: -1.,
        height_falloff: 3.,
        length: 10.,
        ..Fog::default()
    });
    let mut volumes = |fog_filter: bool| {
        let settings = Settings {
            fog_filter,
            ..settings(true)
        };
        let renderer = render(&device, &queue, &mut scene, &frame, &settings, 2);
        renderer
            .fog_volumes()
            .map(|view| texels(&read(&device, &queue, view)))
    };
    let [written, filtered, integrated] = volumes(true);
    let [unfiltered_written, _, unfiltered_integrated] = volumes(false);
    assert!(
        written == unfiltered_written,
        "the filter changed the froxels the next frame reprojects"
    );
    assert!(
        integrated != unfiltered_integrated,
        "the integration ignored the filter"
    );
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    let expected = godot_gaussian(&godot_gaussian(&written, size, 0), size, 1);
    // Two half-float roundings of non-negative sums, one per pass.
    let tolerance = |expected: f32| 2e-3 * expected + 1e-6;
    // Froxels the filter moved by far more than that, in the light (red) and
    // the extinction, where a wrong kernel would show.
    let mut spread = [0; 2];
    for (index, ((filtered, expected), written)) in
        filtered.iter().zip(&expected).zip(&written).enumerate()
    {
        for channel in 0..4 {
            assert!(
                (filtered[channel] - expected[channel]).abs() <= tolerance(expected[channel]),
                "froxel {index} channel {channel}: {} against Godot's Gaussian {}",
                filtered[channel],
                expected[channel]
            );
        }
        for (moved, channel) in spread.iter_mut().zip([0, 3]) {
            *moved += usize::from(
                (expected[channel] - written[channel]).abs() > 10. * tolerance(expected[channel]),
            );
        }
    }
    assert!(
        spread.iter().all(|moved| *moved > 10_000),
        "the filter moved only {spread:?} froxels' light and extinction"
    );
}

// Defect: the injection ignores a light's shadow, or samples it where the
// medium is not, so light leaks into the medium beneath an opaque slab.
// The occluder's geometry decides: froxels well below the slab, within the
// light's reach, see none of a local light and, through Godot's fog tap,
// at most exp(-10 x the metres they lie behind the slab's top) of the
// directional light; froxels above it see it.
#[test]
fn shadowed_lights_scatter_almost_nothing_behind_their_occluder() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.1,
        anisotropy: 0.,
        length: 20.,
        ..Fog::default()
    };
    // The slab spans y 1.4..1.6 and x and z ±20 about (0, -10).
    let slab = |device: &wgpu::Device, queue: &wgpu::Queue| {
        let mut scene = Scene::new(device, queue);
        add_box(
            device,
            queue,
            &mut scene,
            Vec3::new(0., 1.5, -10.),
            Vec3::new(40., 0.2, 40.),
        );
        scene
    };
    let spot = Vec3::new(0., 4., -10.);
    // Where each light reaches the medium.
    let reached = |local: bool, point: Vec3| {
        if local {
            // Within the spot's inner cone and range.
            let below = spot.y - point.y;
            let across = Vec3::new(point.x - spot.x, 0., point.z - spot.z).length();
            below > 0.5 && across < below * 0.6f32.tan() && (spot - point).length() < 12.
        } else {
            // Beneath the slab, away from its edges along the light.
            point.x.abs() < 15. && point.z < -2. && point.z > -25.
        }
    };
    for (label, local) in [("local atlas", true), ("directional cascades", false)] {
        let mut scene = slab(&device, &queue);
        let mut frame = input(fog);
        if local {
            scene
                .add_light(
                    &device,
                    &queue,
                    Light {
                        position: spot,
                        shape: LightShape::Spot {
                            direction: Vec3::NEG_Y,
                            inner_angle: 0.6,
                            outer_angle: 0.9,
                            radius: LightShape::DEFAULT_RADIUS,
                        },
                        color: [1.; 3],
                        intensity: 100.,
                        range: 15.,
                        baked: false,
                        specular: 1.,
                        casts_shadow: true,
                        ..Default::default()
                    },
                )
                .unwrap();
        } else {
            frame.directional_lights[0] = Some(DirectionalLight {
                direction: Vec3::new(0.2, -1., 0.1),
                color: [1.; 3],
                illuminance: 5.,
                shadow: Some(DirectionalShadow {
                    distance: 40.,
                    cascades: 2,
                }),
                ..Default::default()
            });
        }
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
        let froxels = texels(&read(&device, &queue, renderer.fog_volumes()[0]));
        let (mut below, mut above) = (Vec::new(), Vec::new());
        for z in 0..size[2] {
            for y in 0..size[1] {
                for x in 0..size[0] {
                    let point = froxel_center(&frame, size, [x, y, z]);
                    if !reached(local, point) || point.z > -1. {
                        continue;
                    }
                    let light = froxels[((z * size[1] + y) * size[0] + x) as usize][0];
                    if point.y < 0.4 {
                        below.push(light);
                    } else if point.y > 2.6 {
                        above.push(light);
                    }
                }
            }
        }
        assert!(
            below.len() > 100 && above.len() > 10,
            "{label}: {} froxels below and {} above",
            below.len(),
            above.len()
        );
        let darkest_above = above.iter().copied().fold(f32::MAX, f32::min);
        let brightest_below = below.iter().copied().fold(0., f32::max);
        assert!(darkest_above > 0., "{label}: lit medium scattered nothing");
        // Froxels below y 0.4 lie at least 1.2 m behind the slab's top.
        let most_below = if local {
            0.
        } else {
            darkest_above * (-10f32 * 1.2).exp()
        };
        assert!(
            brightest_below <= most_below,
            "{label}: {brightest_below} scattered beneath the occluder, against {darkest_above} above it"
        );
    }
}

// Defect: a light's fog energy does not scale what it scatters in the
// medium, a light at 0 still scatters there, or the energy reaches its
// surface lighting. The reference is the same light's in-scatter at fog
// energy 1, measured froxel by froxel: at 2 each froxel holds twice it, at
// 0 none, and without fog the frame is the same, and lit, at 0 as at 1.
#[test]
fn fog_energy_scales_a_light_in_the_medium_alone() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.3,
        length: 20.,
        ..Fog::default()
    };
    for (label, local) in [("scene light", true), ("directional light", false)] {
        // Each froxel's in-scatter, and the frame without fog, with the light
        // at `fog_energy` over a floor beneath it.
        let observe = |fog_energy: f32| {
            let mut scene = Scene::new(&device, &queue);
            add_box(
                &device,
                &queue,
                &mut scene,
                Vec3::new(0., -2., -10.),
                Vec3::new(20., 1., 20.),
            );
            let mut frame = input(fog);
            if local {
                scene
                    .add_light(
                        &device,
                        &queue,
                        Light {
                            position: Vec3::new(0., 3., -8.),
                            shape: LightShape::Spot {
                                direction: Vec3::NEG_Y,
                                inner_angle: 0.5,
                                outer_angle: 0.8,
                                radius: LightShape::DEFAULT_RADIUS,
                            },
                            intensity: 60.,
                            range: 12.,
                            casts_shadow: true,
                            fog_energy,
                            ..Light::default()
                        },
                    )
                    .unwrap();
            } else {
                frame.directional_lights[0] = Some(DirectionalLight {
                    direction: Vec3::new(0.2, -1., 0.1),
                    illuminance: 3.,
                    shadow: Some(DirectionalShadow {
                        distance: 30.,
                        cascades: 2,
                    }),
                    fog_energy,
                    ..DirectionalLight::default()
                });
            }
            let fogged = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
            let in_scatter: Vec<[f32; 3]> = texels(&read(&device, &queue, fogged.fog_volumes()[0]))
                .into_iter()
                .map(|froxel| [froxel[0], froxel[1], froxel[2]])
                .collect();
            let unfogged = render(&device, &queue, &mut scene, &frame, &settings(false), 1);
            let surfaces = read(&device, &queue, &unfogged.targets().composite);
            (in_scatter, surfaces)
        };
        let (single, surfaces) = observe(1.);
        let lit = single
            .iter()
            .filter(|froxel| froxel.iter().any(|&channel| channel > 1e-3))
            .count();
        assert!(lit > 100, "{label}: {lit} froxels carry measurable light");
        let (double, _) = observe(2.);
        for (index, (twice, once)) in double.iter().zip(&single).enumerate() {
            for channel in 0..3 {
                let expected = 2. * once[channel];
                assert!(
                    (twice[channel] - expected).abs() <= 1e-3 * expected + 1e-6,
                    "{label}: froxel {index} channel {channel} holds {} at fog energy 2, twice {} is {expected}",
                    twice[channel],
                    once[channel]
                );
            }
        }
        let (none, surfaces_at_zero) = observe(0.);
        assert!(
            none.iter().flatten().all(|&channel| channel == 0.),
            "{label}: the medium scattered light at fog energy 0"
        );
        assert!(
            texels(&surfaces)
                .iter()
                .any(|texel| texel[..3].iter().any(|&channel| channel > 0.)),
            "{label}: the light lit no surface"
        );
        assert!(
            surfaces_at_zero == surfaces,
            "{label}: fog energy 0 changed the surfaces' light"
        );
    }
}

// Defect: a fog volume's box is placed, turned or sized wrongly, or its
// density does not add to the medium's; or its froxel bounds leave out
// froxels it reaches, at its faces or where it crosses the frame's edge,
// the camera's plane or the volume's far end, or holds the camera; or a
// froxel reads another volume's record for bounds that skip culled
// volumes; or the bounds misplace the camera (its position, turn or
// off-centre projection). The boxes' definitions decide: a froxel holds the
// frame's medium plus each box's density where its centre lies, and
// scatters an isotropic, unshadowed directional light by the albedos those
// densities weight, Godot's scattering.
#[test]
fn fog_volumes_add_their_medium_to_every_froxel_they_reach() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    // A camera away from the origin, turned, with an off-centre projection;
    // each box is placed relative to it.
    let turn = Quat::from_rotation_y(0.7);
    let world_from_camera = Mat4::from_rotation_translation(turn, Vec3::new(12., 1.5, -40.));
    let volume = |center: Vec3, rotation: Quat, size: Vec3, density: f32, albedo: [f32; 3]| {
        crate::FogVolume {
            center: world_from_camera.transform_point3(center),
            rotation: turn * rotation,
            size,
            density,
            albedo,
            edge_fade: 0.,
        }
    };
    let volumes = [
        // Behind the camera, beside the frame and beyond the volume: none
        // reaches a froxel.
        volume(
            Vec3::new(0., 0., 6.),
            Quat::IDENTITY,
            Vec3::splat(3.),
            0.5,
            [1., 0., 0.],
        ),
        volume(
            Vec3::new(-30., 0., -8.),
            Quat::IDENTITY,
            Vec3::splat(2.),
            0.5,
            [0., 1., 0.],
        ),
        volume(
            Vec3::new(0., 0., -30.),
            Quat::IDENTITY,
            Vec3::splat(4.),
            0.5,
            [0., 0., 1.],
        ),
        // Beside the camera, from behind it to in front of it.
        volume(
            Vec3::new(1.5, -1., 0.),
            Quat::IDENTITY,
            Vec3::new(1., 1., 12.),
            0.3,
            [0.2, 0.9, 0.5],
        ),
        // A tunnel holding the camera.
        volume(
            Vec3::new(0., 0., -4.),
            Quat::from_rotation_y(0.1),
            Vec3::new(6., 4., 20.),
            0.05,
            [0.5, 0.5, 1.],
        ),
        // Across the frame's left edge.
        volume(
            Vec3::new(-7.5, 0.5, -8.),
            Quat::from_rotation_y(0.4),
            Vec3::new(3., 2., 3.),
            0.2,
            [0.9, 0.3, 0.6],
        ),
        // Across the volume's far end.
        volume(
            Vec3::new(1., 1., -19.5),
            Quat::IDENTITY,
            Vec3::new(2., 2., 3.),
            0.15,
            [0.4, 0.8, 0.2],
        ),
        // Two overlapping boxes.
        volume(
            Vec3::new(0.5, 0., -9.),
            Quat::from_rotation_y(0.6) * Quat::from_rotation_x(0.3),
            Vec3::new(4., 3., 5.),
            0.2,
            [1., 0.5, 0.25],
        ),
        volume(
            Vec3::new(1.8, 0.6, -10.5),
            Quat::IDENTITY,
            Vec3::splat(3.),
            0.1,
            [0.2, 0.9, 0.6],
        ),
    ];
    let mut scene = Scene::new(&device, &queue);
    scene.update_fog_volumes(&device, &queue, &volumes).unwrap();
    let fog = Fog {
        density: 0.01,
        albedo: [1., 0.7, 0.4],
        anisotropy: 0.,
        ambient: 0.,
        length: 20.,
        ..Fog::default()
    };
    let mut frame = input(fog);
    let mut projection = projection();
    projection.z_axis.x = 0.1;
    projection.z_axis.y = -0.05;
    frame.camera = Camera {
        view: world_from_camera.inverse(),
        projection,
        eye: world_from_camera.w_axis.truncate(),
    };
    // An isotropic phase scatters 1 / (4 PI) of the illuminance toward the
    // camera, so each froxel scatters its albedo-weighted density.
    frame.directional_lights[0] = Some(DirectionalLight {
        direction: Vec3::new(0.3, -1., -0.4),
        color: [1.; 3],
        illuminance: 4. * std::f32::consts::PI,
        shadow: None,
        ..Default::default()
    });
    let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
    let size = froxels(QUALITY, SIZE, device.limits().max_texture_dimension_3d);
    let froxels = texels(&read(&device, &queue, renderer.fog_volumes()[0]));
    let local_from_world = volumes
        .map(|volume| Mat4::from_rotation_translation(volume.rotation, volume.center).inverse());
    let world_from_view = frame.camera.view.inverse();
    let mut reached = [0; 9];
    for z in 0..size[2] {
        for y in 0..size[1] {
            for x in 0..size[0] {
                let point =
                    world_from_view.transform_point3(froxel_center(&frame, size, [x, y, z]));
                let mut density = fog.density;
                let mut scattering = Vec3::from(fog.albedo) * fog.density;
                for (index, volume) in volumes.iter().enumerate() {
                    let local = local_from_world[index].transform_point3(point);
                    let added = volume.density * box_density(local, volume.size * 0.5);
                    density += added;
                    scattering += Vec3::from(volume.albedo) * added;
                    reached[index] += usize::from(added > 0.);
                }
                let froxel = froxels[((z * size[1] + y) * size[0] + x) as usize];
                assert!(
                    (froxel[3] - density).abs() <= 1e-3 * density + 1e-4,
                    "{point}: extinction {} against the boxes' {density}",
                    froxel[3]
                );
                for channel in 0..3 {
                    assert!(
                        (froxel[channel] - scattering[channel]).abs()
                            <= 2e-3 * scattering[channel] + 1e-4,
                        "{point} channel {channel}: scattering {} against the boxes' {}",
                        froxel[channel],
                        scattering[channel]
                    );
                }
            }
        }
    }
    assert!(
        reached[3..].iter().all(|&count| count > 50),
        "froxels inside each box: {reached:?}"
    );
}

/// The share of a box fog volume's density at `local` in the box of
/// `half_size` without edge fade: Godot's box `FogVolume`
/// (`volumetric_fog.glsl`), whose density fades in over the 0.1 m inside its
/// faces by its signed distance.
fn box_density(local: Vec3, half_size: Vec3) -> f32 {
    let q = local.abs() - half_size;
    let distance = q.max(Vec3::ZERO).length() + q.max_element().min(0.);
    let t = ((distance + 0.1) / 0.1).clamp(0., 1.);
    1. - t * t * (3. - 2. * t)
}

// Defect: a blended surface fogs itself at the wrong distance (a fragment's
// position w is one over its view depth). With no light in the medium, an
// unlit blended quad at a known depth keeps exactly the share of its colour
// that Beer-Lambert's law passes along its view ray.
#[test]
fn a_blended_surface_is_fogged_at_its_depth() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let depth = 30.;
    let mut quad = test_support::cube();
    quad.meshes[0] = crate::asset::CpuMesh {
        vertices: [(-1., -1.), (1., -1.), (1., 1.), (-1., 1.)]
            .map(|(x, y)| crate::asset::Vertex {
                tangent: [0.; 4],
                lightmap_bounds: [0., 0., 1., 1.],
                lightmap_uv: [0.; 2],
                position: [x * 4., y * 4., -depth],
                normal: [0., 0., 1.],
                uv: [(x + 1.) / 2., (1. - y) / 2.],
                color: [1.; 4],
            })
            .to_vec(),
        indices: vec![0, 1, 2, 0, 2, 3],
        material: 0,
        deformation: Default::default(),
    };
    quad.materials[0].unlit = true;
    quad.materials[0].base = [1., 0.6, 0.3, 1.];
    quad.materials[0].alpha = crate::AlphaMode::Blend {
        receives_screen_space_reflections: false,
        keeps_specular: false,
    };
    let mut scene = Scene::new(&device, &queue);
    test_support::add_static(&device, &queue, &mut scene, quad);
    let fog = Fog {
        density: 0.02,
        length: 60.,
        ..Fog::default()
    };
    let frame = input(fog);
    let centre = |atmosphere: bool| {
        let renderer = render(
            &device,
            &queue,
            &mut scene,
            &frame,
            &settings(atmosphere),
            1,
        );
        let composite = texels(&read(&device, &queue, &renderer.targets().composite));
        composite[(SIZE[1] / 2 * SIZE[0] + SIZE[0] / 2) as usize]
    };
    let [clear, fogged] = [false, true].map(centre);
    let (ndc, _) = froxel_ray(&frame, [SIZE[0], SIZE[1], 1], [SIZE[0] / 2, SIZE[1] / 2], 0);
    let transmittance = (-fog.density * depth * view_ray(&frame, ndc).length()).exp();
    for channel in 0..3 {
        let share = fogged[channel] / clear[channel];
        assert!(
            (share - transmittance).abs() < 5e-3,
            "channel {channel}: {} of the quad's colour against Beer-Lambert's {transmittance}",
            share
        );
    }
}

// Defect: a coverage-blended surface adds the fog's in-scatter whole rather
// than over its covered share, as Filament ef1a133's fade mode does
// (shaders/src/surface_main.fs 83-84 scales it in the transparent mode
// alone), or its colour is not scaled by its alpha. Porter and Duff's over
// of the fogged surface is the oracle: at alpha 0.5 the frame is half the
// surface fogged as at alpha 1 and half the frame behind it without the
// surface, alpha (c T + I) + (1 - alpha) behind, in a medium that scatters
// the hemisphere fill, so that I and the fogged sky behind are not zero.
#[test]
fn a_blended_surface_covers_its_fog_by_its_alpha() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let depth = 30.;
    let mut quad = test_support::cube();
    quad.meshes[0] = crate::asset::CpuMesh {
        vertices: [(-1., -1.), (1., -1.), (1., 1.), (-1., 1.)]
            .map(|(x, y)| crate::asset::Vertex {
                tangent: [0.; 4],
                lightmap_bounds: [0., 0., 1., 1.],
                lightmap_uv: [0.; 2],
                position: [x * 4., y * 4., -depth],
                normal: [0., 0., 1.],
                uv: [(x + 1.) / 2., (1. - y) / 2.],
                color: [1.; 4],
            })
            .to_vec(),
        indices: vec![0, 1, 2, 0, 2, 3],
        material: 0,
        deformation: Default::default(),
    };
    quad.materials[0].unlit = true;
    quad.materials[0].base = [1., 0.6, 0.3, 1.];
    quad.materials[0].alpha = crate::AlphaMode::Blend {
        receives_screen_space_reflections: false,
        keeps_specular: false,
    };
    let mut scene = Scene::new(&device, &queue);
    let (ids, instance) = test_support::add_static(&device, &queue, &mut scene, quad);
    let fog = Fog {
        density: 0.02,
        length: 60.,
        ambient: 1.,
        ..Fog::default()
    };
    let mut frame = input(fog);
    frame.hemisphere_light = HemisphereLight {
        sky_color: [0.4, 0.5, 0.7],
        ground_color: [0.4, 0.5, 0.7],
        intensity: 1.,
    };
    let mut centre = |alpha: Option<f32>| {
        let mut values = scene.material(ids.materials[0]).unwrap();
        values.base[3] = alpha.unwrap_or(1.);
        scene
            .set_material(&queue, ids.materials[0], values)
            .unwrap();
        let mut state = *scene.instance(instance).unwrap();
        state.visible = alpha.is_some();
        scene.set_instance(&queue, instance, state).unwrap();
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        let composite = texels(&read(&device, &queue, &renderer.targets().composite));
        composite[(SIZE[1] / 2 * SIZE[0] + SIZE[0] / 2) as usize]
    };
    let [whole, half, behind] = [Some(1.), Some(0.5), None].map(&mut centre);
    let (ndc, _) = froxel_ray(&frame, [SIZE[0], SIZE[1], 1], [SIZE[0] / 2, SIZE[1] / 2], 0);
    let transmittance = (-fog.density * depth * view_ray(&frame, ndc).length()).exp();
    for channel in 0..3 {
        let in_scatter = whole[channel] - [1., 0.6, 0.3][channel] * transmittance;
        assert!(
            in_scatter > 0.02 && behind[channel] > 0.02,
            "channel {channel}: too little in-scatter ({in_scatter}) or fogged sky ({}) to tell \
             a share of it",
            behind[channel]
        );
        let expected = 0.5 * whole[channel] + 0.5 * behind[channel];
        assert!(
            (half[channel] - expected).abs() <= 5e-3 * expected + 1e-3,
            "channel {channel}: {} at alpha 0.5, against Porter and Duff's over {expected} \
             of {} at alpha 1 and {} behind",
            half[channel],
            whole[channel],
            behind[channel]
        );
    }
}

// Defect: additive glow adds the fog's in-scatter on top of a background
// that already holds it (D-44), so a black glow brightens the fog and N
// layers add it N times, or its own light is not dimmed by the medium in
// front of it. An unshadowed light at a known depth reaches the camera
// through Beer-Lambert's transmittance alone: in a medium that scatters the
// hemisphere fill, a glow of colour c at alpha 1 raises the frame by c T,
// and a black one leaves it unchanged.
#[test]
fn glow_adds_its_light_through_the_fog_and_none_of_its_in_scatter() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let depth = 30.;
    let fog = Fog {
        density: 0.02,
        length: 60.,
        ambient: 1.,
        ..Fog::default()
    };
    let mut frame = input(fog);
    frame.hemisphere_light = HemisphereLight {
        sky_color: [0.4, 0.5, 0.7],
        ground_color: [0.4, 0.5, 0.7],
        intensity: 1.,
    };
    let mut scene = Scene::new(&device, &queue);
    let mut centre = |color: Option<[f32; 3]>| {
        let vertices = match color {
            Some([r, g, b]) => [
                [-200., -200., -depth],
                [600., -200., -depth],
                [-200., 600., -depth],
            ]
            .map(|position| crate::effects::Glow {
                position,
                color: [r, g, b, 1.],
                kind: crate::effects::GlowKind::Uniform,
                soft_distance: 0.,
            })
            .to_vec(),
            None => Vec::new(),
        };
        scene.update_effects(&device, &queue, &vertices).unwrap();
        let renderer = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
        let composite = texels(&read(&device, &queue, &renderer.targets().composite));
        composite[(SIZE[1] / 2 * SIZE[0] + SIZE[0] / 2) as usize]
    };
    let behind = centre(None);
    let (ndc, _) = froxel_ray(&frame, [SIZE[0], SIZE[1], 1], [SIZE[0] / 2, SIZE[1] / 2], 0);
    let transmittance = (-fog.density * depth * view_ray(&frame, ndc).length()).exp();
    for color in [[0.; 3], [1., 0.6, 0.3]] {
        let glowing = centre(Some(color));
        for channel in 0..3 {
            assert!(
                behind[channel] > 0.02,
                "channel {channel}: too little fog ({}) to tell its in-scatter",
                behind[channel]
            );
            let added = glowing[channel] - behind[channel];
            let expected = color[channel] * transmittance;
            assert!(
                (added - expected).abs() <= 5e-3 * expected + 1e-3,
                "glow {color:?} channel {channel}: added {added} over {} behind, against its \
                 light through Beer-Lambert's {transmittance}, {expected}",
                behind[channel]
            );
        }
    }
}

// Defect: the sky ignores `Fog::sky_affect`, it reaches the surfaces too, or
// it scales one part of the fog (its scattering or its transmittance) alone.
// Godot's sky affect (b130438 sky.glsl) mixes the sky with the fogged sky:
// at 0 the sky stays as without fog while surfaces fog as at 1, and at 0.5
// each sky texel lies halfway between those two frames.
#[test]
fn the_sky_takes_its_sky_affect_of_the_fog() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let mut scene = Scene::new(&device, &queue);
    add_box(
        &device,
        &queue,
        &mut scene,
        Vec3::new(0., -1., -6.),
        Vec3::new(4., 1., 3.),
    );
    // The medium scatters the hemisphere fill, so the sky's fog both dims it
    // and adds light.
    let mut frame = input(Fog {
        density: 0.05,
        length: 30.,
        ambient: 1.,
        ..Fog::default()
    });
    frame.hemisphere_light = HemisphereLight {
        sky_color: [0.4, 0.5, 0.7],
        ground_color: [0.1, 0.1, 0.1],
        intensity: 1.,
    };
    frame.backdrop = Backdrop::Color([0.2, 0.3, 0.45]);
    let mut composite = |frame: &FrameInput, atmosphere: bool| {
        let renderer = render(&device, &queue, &mut scene, frame, &settings(atmosphere), 1);
        texels(&read(&device, &queue, &renderer.targets().composite))
    };
    let clear = composite(&frame, false);
    let whole = composite(&frame, true);
    frame.fog.sky_affect = 0.;
    let none = composite(&frame, true);
    frame.fog.sky_affect = 0.5;
    let half = composite(&frame, true);
    // The frame's top row looks up into the sky, whose backdrop is one colour.
    let sky_colour = clear[0];
    let sky: Vec<_> = (0..clear.len())
        .filter(|&texel| clear[texel] == sky_colour)
        .collect();
    assert!(
        sky.len() < clear.len(),
        "the frame holds no surface: {sky_colour:?}"
    );
    assert!(whole[0] != clear[0], "the whole fog left the sky clear");
    for texel in 0..clear.len() {
        if sky.contains(&texel) {
            assert_eq!(
                none[texel], clear[texel],
                "texel {texel}: no sky affect fogged the sky"
            );
            for channel in 0..3 {
                let midway = (clear[texel][channel] + whole[texel][channel]) / 2.;
                assert!(
                    (half[texel][channel] - midway).abs() < 2e-3,
                    "texel {texel} channel {channel}: half the sky affect gave {} against {midway}",
                    half[texel][channel]
                );
            }
        } else {
            assert_eq!(
                none[texel], whole[texel],
                "texel {texel}: the sky affect fogged a surface"
            );
        }
    }
}

// Defect: a light's shadow opacity does not lighten its shadow, lightens it
// on surfaces or in the medium alone, or scales the light rather than its
// shadow. Godot's shadow_opacity blends the shadow toward unshadowed,
// mix(1, shadow, opacity), and lighting is linear in it: at 0.5 each
// surface texel and froxel lies halfway between the light without a shadow
// and with its whole shadow, and at 0 it is as without one.
#[test]
fn shadow_opacity_blends_a_lights_shadow_on_surfaces_and_in_the_medium() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let fog = Fog {
        density: 0.05,
        anisotropy: 0.3,
        length: 20.,
        ..Fog::default()
    };
    for (label, local) in [("scene light", true), ("directional light", false)] {
        // Each froxel's in-scatter and the frame without fog, of a floor and
        // a slab above it shadowing part of it and of the medium, lit by the
        // light with a shadow at `opacity`, or without one.
        let observe = |opacity: Option<f32>| {
            let mut scene = Scene::new(&device, &queue);
            add_box(
                &device,
                &queue,
                &mut scene,
                Vec3::new(0., -2., -10.),
                Vec3::new(20., 1., 20.),
            );
            add_box(
                &device,
                &queue,
                &mut scene,
                Vec3::new(0., 1., -8.),
                Vec3::new(3., 0.2, 3.),
            );
            let mut frame = input(fog);
            if local {
                scene
                    .add_light(
                        &device,
                        &queue,
                        Light {
                            position: Vec3::new(0., 3., -8.),
                            shape: LightShape::Spot {
                                direction: Vec3::NEG_Y,
                                inner_angle: 0.6,
                                outer_angle: 0.9,
                                radius: LightShape::DEFAULT_RADIUS,
                            },
                            intensity: 60.,
                            range: 12.,
                            casts_shadow: opacity.is_some(),
                            shadow_opacity: opacity.unwrap_or(1.),
                            ..Light::default()
                        },
                    )
                    .unwrap();
            } else {
                frame.directional_lights[0] = Some(DirectionalLight {
                    direction: Vec3::new(0.2, -1., 0.1),
                    illuminance: 3.,
                    shadow: opacity.map(|_| DirectionalShadow {
                        distance: 30.,
                        cascades: 2,
                    }),
                    shadow_opacity: opacity.unwrap_or(1.),
                    ..DirectionalLight::default()
                });
            }
            let fogged = render(&device, &queue, &mut scene, &frame, &settings(true), 1);
            let medium: Vec<f32> = texels(&read(&device, &queue, fogged.fog_volumes()[0]))
                .into_iter()
                .flat_map(|froxel| [froxel[0], froxel[1], froxel[2]])
                .collect();
            let unfogged = render(&device, &queue, &mut scene, &frame, &settings(false), 1);
            let surfaces: Vec<f32> = texels(&read(&device, &queue, &unfogged.targets().composite))
                .into_iter()
                .flat_map(|texel| [texel[0], texel[1], texel[2]])
                .collect();
            [medium, surfaces]
        };
        let unshadowed = observe(None);
        let shadowed = observe(Some(1.));
        let half = observe(Some(0.5));
        let clear = observe(Some(0.));
        for (part, receiver) in ["medium", "surfaces"].into_iter().enumerate() {
            let (unshadowed, shadowed, half) = (&unshadowed[part], &shadowed[part], &half[part]);
            let darkened = unshadowed
                .iter()
                .zip(shadowed)
                .filter(|(lit, dark)| *lit - *dark > 1e-2 * *lit + 1e-4)
                .count();
            assert!(
                darkened > 100,
                "{label}: the slab shadowed {darkened} values of the {receiver}"
            );
            for (index, ((lit, dark), blended)) in
                unshadowed.iter().zip(shadowed).zip(half).enumerate()
            {
                let expected = (lit + dark) / 2.;
                assert!(
                    (blended - expected).abs() <= 2e-3 * lit.abs() + 1e-4,
                    "{label}: {receiver} value {index} is {blended} at shadow opacity 0.5, halfway from {dark} to {lit} is {expected}"
                );
            }
            assert!(
                clear[part] == *unshadowed,
                "{label}: shadow opacity 0 drew a shadow on the {receiver}"
            );
        }
    }
}

// Defect: the filter overwrites the previous frame's volume but leaves its
// old camera label. A submitted frame retried without finish_frame must
// reject that volume. Black albedo scatters no light: any nonzero RGB in
// the retry's froxels is illumination retained from the overwritten volume.
#[test]
fn a_submitted_filtered_frame_is_not_reprojected_as_previous_on_retry() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let settings = Settings {
        fog_filter: true,
        ..settings(true)
    };
    let mut scene = Scene::new(&device, &queue);
    let mut frame = input(Fog {
        density: 0.05,
        length: 10.,
        albedo: [0.; 3],
        ambient: 1.,
        ..Default::default()
    });
    frame.hemisphere_light = HemisphereLight {
        sky_color: [1.; 3],
        ground_color: [1.; 3],
        intensity: 1.,
    };
    let mut renderer = Renderer::for_test(&device, &queue, SIZE, &settings);
    let output = crate::view::targets::target(&device, "fog retry", SIZE, gbuffer::COLOR);
    for step in 0..3 {
        frame.fog.albedo = if step == 1 { [1.; 3] } else { [0.; 3] };
        let mut encoder = device.create_command_encoder(&Default::default());
        renderer.render(
            &device,
            &queue,
            &mut encoder,
            &mut scene,
            &frame,
            &settings,
            &output,
            None,
        );
        queue.submit([encoder.finish()]);
        if step != 1 {
            renderer.finish_frame(&mut scene);
        }
        let froxels = texels(&read(&device, &queue, renderer.fog_volumes()[1]));
        let light = froxels
            .iter()
            .flat_map(|texel| &texel[..3])
            .copied()
            .fold(0f32, f32::max);
        if step == 1 {
            assert!(
                light > 0.,
                "the submitted volume must hold light to expose stale reprojection"
            );
        } else {
            assert_eq!(
                light, 0.,
                "step {step}: black albedo cannot scatter prior illumination"
            );
        }
    }
}