crcbl-render 0.17.0

Crucible renderer: the 3D frame on crcbl-frame — meshes, materials, lights, effects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
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
1666
1667
1668
1669
1670
//! Topic 46's screen-space ambient occlusion (`docs/notes/rendering.md`): the
//! full-screen passes between the depth prepass and the forward pass.
//!
//! ```text
//!   pass    ssao ────────▶ ssao-blur ────────▶ ssao-upsample ────────▶ forward
//!   writes  ssao           ssao-blurred        ssao-upsampled          (× frame.ambient)
//!           └─ half extent, Rgba8Unorm ┘      └ scene extent, Rgba8Unorm ┘
//! ```
//!
//! The prepass's `scene-depth` is read by all three of the occlusion passes and
//! is the only input any of them has besides the one before it: the march
//! gathers its horizons from it, the blur weights its kernel by it, and the
//! reconstruction reconciles the two extents against it.
//!
//! A module of its own rather than more of [`crate::forward`], which is a file
//! this crate is trying to stop growing: what lives here is three pipelines,
//! their caches and the pass chain, and none of it is reachable from the
//! geometry passes except through [`Ssao::add_passes`].
//!
//! # The gather runs small and the reconstruction runs full
//!
//! `shaders/ssao.slang`'s `RESOLUTION_DIVISOR` is the factor and that file's
//! header is the argument: occlusion is a low-frequency field, so the march and
//! the blur run over an image [`half_extent`] of the scene's — a quarter of the
//! invocations — and `shaders/ssao_upsample.slang` reconstructs the channel the
//! forward pass binds. The reconstruction is depth-aware rather than bilinear,
//! because the field is low-frequency **within a surface** and discontinuous
//! across a silhouette; a distance weight alone draws the wall's occlusion as a
//! rim around whatever stands in front of it.
//!
//! **Only [`Ssao::add_passes`]' last image is the scene's size**, and only
//! [`half_extent`] decides the others'. A caller that sized them itself would be
//! a second opinion about a division the shaders also hold.
//!
//! **The blur is not optional.** `shaders/ssao.slang` says why in full: its
//! rotation table makes the raw result carry a 4×4 tile as banding, and each of
//! its samples is a binary depth comparison that one driver may resolve
//! differently from another. The blur's footprint is exactly that tile, so it
//! removes the banding — and it divides an isolated flipped sample by sixteen
//! wherever its taps all count, which `shaders/ssao_blur.slang` is precise
//! about: the kernel is weighted on view-space depth, so the divisor is the full
//! sixteen on a flat surface and falls towards one at a silhouette, where the
//! taps it drops are the ones a box blur used to draw a halo with.
//!
//! The off-switch is data rather than a branch: a frame that does not add these
//! passes leaves `ForwardRenderer`'s white placeholder bound, and `mesh.slang`
//! multiplies its ambient by 1.0. There is no device fact to gate on — every
//! backend has a full-screen draw, a sampled `D32Float` and an `Rgba8Unorm`
//! target.
//!
//! # The higher rung, and why it is two switches
//!
//! `docs/backlog.md` records banding along the **tangential** axis, which is a
//! shortage of distinct slice planes rather than of steps along one: the raw
//! channel's neighbourhood carries eight plane orientations at the shipping
//! count, whatever the blur then does with it. [`r_ssao_slices`] is what buys
//! more of them — `shaders/ssao.slang`'s `SLICE_COUNT_MAX` has the arithmetic —
//! and [`r_ssao_blur_passes`] is what widens the footprint they are averaged
//! over.
//!
//! **Two switches and not one**, because they are two different purchases: the
//! slices are arithmetic and texture fetches inside one pass, and a second blur
//! is a whole extra full-screen read and write of an `R8Unorm` image. A
//! bandwidth-bound tier may want the first and refuse the second, and a knob
//! that bundled them could not say so. Both default to what ships, so a frame
//! nobody has touched the console on is the frame every golden was blessed at.
//!
//! # The bent direction is the switch that is on
//!
//! [`r_ssao_bent_normals`] is the second half of the GTAO rung: the same
//! horizon sweep that measures how much
//! of the room is hidden also reports which way what is left of it lies, and
//! `mesh.slang` samples its ambient irradiance along that direction instead of
//! along the shading normal. `shaders/ssao.slang`'s header is where the
//! encoding and the sweep's by-product are argued.
//!
//! **It defaults on, which is the one switch here that does not default to what
//! shipped before it.** The others exist to buy quality a tier may not want to
//! pay for, or to move a picture that is already right; this one is the rung.
//! What it costs is the three channels the target widened by — `R8Unorm` to
//! `Rgba8Unorm` — and the arithmetic in the pass that already runs, and what
//! turning it off restores is the zero sentinel every consumer answers with the
//! shading normal.
//!
//! # The intensity is a switch that buys nothing
//!
//! [`r_ssao_intensity`] is not on that ladder: it costs one comparison in the
//! pass that already runs, and what it changes is how much of the occlusion the
//! horizons measured a frame actually shows.
//! `shaders/ssao_upsample.slang`'s `ao_intensity` is the whole of it — the
//! reconstructed visibility raised to the exponent this writes, at the end of
//! the chain and before `mesh.slang` tints it.
//!
//! **A power and not a blend towards one**, which is what lets it ask for
//! *more* occlusion than the integral found: `docs/backlog.md` records the
//! multi-bounce tint narrowing the contrast of every occluded surface, and a
//! blend could only weaken it further. The default is the exponent that changes
//! nothing, so this switch too leaves the frame every golden was blessed at.
//!
//! # The technique is the switch that changes the shader
//!
//! [`r_ssao_technique`] is the one knob here that reaches a **pipeline** rather
//! than a lane of the uniform block: `shaders/ssao.slang` integrates a horizon
//! and `shaders/ssao_hemisphere.slang` sums eight depth comparisons, and they
//! are two modules because a stage with two entry points is one
//! [`crcbl_shaders::Shader::entry_point`] refuses to choose between. So
//! [`Ssao`] carries a second gather pipeline on the same layout, and
//! [`Ssao::add_passes`] picks which of them each side of the seam records.
//!
//! **`gtao` is the default and is what every golden was blessed at.**
//! The hemisphere was kept as the cheap tier on
//! the antialiasing ladder's FXAA-under-CMAA2 pattern — eight taps and a
//! comparison is a real budget on a software rasteriser — and
//! alcove's second milestone is the two of them either
//! side of [`r_ssao_split`]. What the cheap tier does not produce is a bent
//! direction: it writes the zero sentinel on every pixel, and `mesh.slang`
//! answers that with the shading normal, so [`r_ssao_bent_normals`] has nothing
//! to switch while it is selected.
//!
//! # The radius is the other control, and it is the one with a picture
//!
//! [`r_ssao_radius`] is the world-space disc the horizons are swept over, and
//! it is the second of the two live controls
//! alcove's first milestone asks for beside the AO
//! view — [`r_ssao_intensity`] above is the first. `shaders/ssao.slang`'s
//! `sampling_radius` is the whole of it: read once per gathered pixel and
//! projected to a reach in pixels the march steps out along.
//!
//! **It moves the picture without moving the budget.** The march takes the same
//! `slice_count() * 2 * SLICE_STEPS` samples whatever the disc's size, so
//! nothing here is a purchase either; what widening it spends is fidelity,
//! because the steps are spaced evenly in *pixels* out to the projected radius
//! and a wider disc walks them apart until one lands on the far side of the
//! room. That is what [`ssao::RADIUS_MAX`] bounds, and [`ssao::RADIUS_MIN`] is
//! the other end: under it the projected disc falls below the march's own
//! `MIN_RADIUS_PIXELS` across most of a room, and the knob draws nothing. The
//! default is what every golden was blessed at, so this switch too leaves that
//! frame alone.
//!
//! Three of these are set by a quality preset, and only through keys.
//! `crcbl::settings::presets` writes the `[engine.video]` keys of a tier, and
//! since 2026-09-09 topic 39's tier table has an occlusion row whose
//! `ssao_slices`, `ssao_blur_passes` and `ssao_bent_normals` keys drive
//! [`r_ssao_slices`], [`r_ssao_blur_passes`] and [`r_ssao_bent_normals`]. The
//! rest — the technique, the split, the intensity and the radius — have no key,
//! so they stay what they are: variables declared beside the pass that reads
//! them, the way `crate::debug_draw`'s switch is. What a tier should spend on
//! them is `docs/backlog.md`'s, and so is the open question a `VIDEO_KEYS` row
//! would answer: a preset clears an effect by writing that effect's key, so a
//! knob a preset selects needs a row of its own.

use crcbl_hal::{
    BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
    BufferUsage, ClearValue, ColorTargetState, Device, Format, GraphicsPipelineHandle, HalError,
    ImageViewHandle, ImageViewType, LoadOp, MemoryLocation, PipelineLayoutDesc,
    PipelineLayoutHandle, Rect2d, SampleType, ShaderStages, StoreOp,
    check_portable_storage_buffers,
};
use crcbl_shaders::{
    SSAO, SSAO_BLUR, SSAO_BLUR_BENTLESS, SSAO_HEMISPHERE, SSAO_UPSAMPLE, SSAO_UPSAMPLE_BENTLESS,
    ssao,
};

pub(crate) use crate::bind_group_cache::cached_group;
use crate::graph::{ImageId, RenderGraph};
use crate::partial::Partial;

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

crcbl_console::convar! {
    /// Planes each pixel sweeps for a horizon: 4 ships, 2 drops the eighth turn.
    ///
    /// **Four since 2026-09-03, and only worth having with two blur passes.**
    /// The sixteen `SLICE_DIRECTIONS` entries reduce, modulo a half turn, to
    /// eight orientations that the quarter turn permutes onto themselves; the
    /// eighth turn is the one turn that leaves the set, taking the
    /// neighbourhood to twelve. On its own that is a *regression* — measured on
    /// radv it takes the tangential line from 37 sharp edges to 100, because
    /// four orientations arrive with no wider blur to average the tile phases
    /// against. Paired with [`r_ssao_blur_passes`] at two it reaches none.
    pub static r_ssao_slices: i64 in 2 ..= 4 = 4;
}

crcbl_console::convar! {
    /// Times the occlusion blur runs over the raw channel: 2 ships.
    ///
    /// **Two since 2026-09-03.** The second pass is the cheap half of that
    /// change — one more pass of the same footprint, where the extra slices
    /// double the gather — and on its own it already takes the tangential line
    /// from 37 sharp edges to 8. It widens the footprint over the same tile,
    /// which at this footprint is what averages the phases rather than what
    /// spreads them.
    pub static r_ssao_blur_passes: i64 in 1 ..= 2 = 2;
}

crcbl_console::convar! {
    /// Exponent the measured occlusion is raised to: 1 ships, over it darkens.
    pub static r_ssao_intensity: f32 in 0.25 ..= 4.0 = 1.0;
}

crcbl_console::convar! {
    /// Gather a bent direction beside the scalar and steer the ambient by it.
    pub static r_ssao_bent_normals: bool = true;
}

crcbl_console::convar! {
    /// The disc the horizons are swept over, in world units: 0.5 ships.
    pub static r_ssao_radius: f32 in 0.0625 ..= 4.0 = 0.5;
}

crcbl_console::convar! {
    /// Which gather runs: `gtao` ships, `hemisphere` is the cheap tier.
    pub static r_ssao_technique: &'static str one_of ["gtao", "hemisphere"] = "gtao";
}

crcbl_console::convar! {
    /// Compare the console's occlusion against the shipped one: seam at 0..1.
    pub static r_ssao_split: f32 in 0.0 ..= 1.0 = 0.0;
}

/// [`r_ssao_slices`] as the shader's uniform wants it.
///
/// Clamped on the way through rather than trusted: the variable's own range is
/// the console's guard, and this is the one that holds if the constant the
/// shader declares ever moves below it. `ssao.slang`'s `slice_count` clamps
/// again on its side, which is where a value that never reached this function
/// at all is caught.
pub(crate) fn slice_count() -> u8 {
    let asked = r_ssao_slices.get_i64().clamp(
        i64::from(ssao::SLICE_COUNT_DEFAULT),
        i64::from(ssao::SLICE_COUNT_MAX),
    );
    u8::try_from(asked).unwrap_or(ssao::SLICE_COUNT_DEFAULT)
}

/// [`r_ssao_intensity`] as the shader's uniform wants it.
///
/// Clamped on the way through for [`slice_count`]'s reason exactly: the
/// variable's own range is the console's guard and this is the one that holds
/// if `shaders/ssao_upsample.slang`'s bounds ever move inside it.
/// `ao_intensity` clamps again on its side, which is where a value that never
/// reached this function at all is caught — and where a zero is answered with
/// `crcbl_shaders::ssao::INTENSITY_DEFAULT` rather than with the floor, because
/// every visibility raised to zero is one and that frame has no occlusion in it.
pub(crate) fn intensity() -> f32 {
    r_ssao_intensity
        .get_f32()
        .clamp(ssao::INTENSITY_MIN, ssao::INTENSITY_MAX)
}

/// [`r_ssao_bent_normals`] as the shader's uniform wants it.
///
/// **On by default**, unlike the two switches above, which default to what
/// ships: the direction is the half of the AO rung worth having, so the frame a person gets without
/// touching anything is the one with it. Turning it off leaves the gather
/// writing the zero sentinel, and every consumer answers that with the shading
/// normal it already had — see `shaders/ssao.slang`'s `bent_normals`.
pub(crate) fn bent_normals() -> bool {
    r_ssao_bent_normals.get_bool()
}

/// Whether a gather may write a bent direction on a frame whose near side runs
/// `technique` with the switch at `bent`, where `compared` says the frame
/// splits at [`r_ssao_split`]'s seam.
///
/// Only `ssao.slang` with its switch on measures one: `ssao_hemisphere.slang`
/// writes the sentinel unconditionally, and so does `ssao.slang` with
/// `camera.params.w` at zero. A comparing frame runs [`shipped`]'s side as
/// well, and that side's answer is the shipped technique and switch, whatever
/// the console holds — so the filters may skip the direction only when **both**
/// sides wrote none. See [`Ssao::filters_for`].
pub(crate) fn writes_bent(technique: Technique, bent: bool, compared: bool) -> bool {
    let near = technique == Technique::Gtao && bent;
    let far = compared && shipped_technique() == Technique::Gtao && shipped().3;
    near || far
}

/// [`r_ssao_radius`] as the shader's uniform wants it.
///
/// Clamped on the way through for [`slice_count`]'s reason exactly.
/// `sampling_radius` clamps again on its side, which is where a value that
/// never reached this function at all is caught — and where a zero is answered
/// with [`ssao::RADIUS_DEFAULT`] rather than with the floor, because world
/// units have no zero that means anything and an unwritten block is a producer
/// that chose nothing.
pub(crate) fn radius() -> f32 {
    r_ssao_radius
        .get_f32()
        .clamp(ssao::RADIUS_MIN, ssao::RADIUS_MAX)
}

/// The gather a frame runs: one of the two shaders that write the raw channel.
///
/// **A technique is a pipeline and not a uniform**, which is what separates
/// this from every other switch in this module: the two are separate modules
/// (see this module's header) and therefore separate pipelines, so
/// [`Ssao::add_passes`] selects rather than [`Ssao::begin_frame`] writing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Technique {
    /// `shaders/ssao.slang`'s horizon integral. What ships.
    Gtao,
    /// `shaders/ssao_hemisphere.slang`'s eight depth comparisons. The cheap
    /// tier, and it writes no bent direction.
    Hemisphere,
}

impl Technique {
    /// The name [`r_ssao_technique`] holds for this one.
    ///
    /// The `convar!` needs literals, so the names are written twice; the test
    /// below is what holds this copy to the variable's own set.
    const fn label(self) -> &'static str {
        match self {
            Self::Gtao => "gtao",
            Self::Hemisphere => "hemisphere",
        }
    }

    /// The technique `name` names.
    ///
    /// **[`Technique::Gtao`] for a name outside the set**, which the console
    /// cannot deliver — an enum variable refuses a value it does not declare —
    /// so this is what a caller reaching past the console would get, and it is
    /// what ships rather than an arbitrary arm.
    fn of(name: &str) -> Self {
        TECHNIQUES
            .into_iter()
            .find(|technique| technique.label() == name)
            .unwrap_or(Self::Gtao)
    }
}

/// The order [`r_ssao_technique`] declares its names in.
///
/// `crate::debug_view`'s `VIEWS` has the same shape for the same reason: the
/// macro takes literals, so this is the list [`Technique::of`] searches and
/// `the_variable_names_are_the_techniques_labels` in this module's tests is what
/// holds the two spellings together.
const TECHNIQUES: [Technique; 2] = [Technique::Gtao, Technique::Hemisphere];

/// [`r_ssao_technique`] as the pipeline picker wants it.
pub(crate) fn technique() -> Technique {
    Technique::of(r_ssao_technique.get_enum())
}

/// The technique the chain ships, for the other side of the seam.
///
/// [`shipped`]'s rule on its own scalars, applied to the one switch that is not
/// one of them: read off the variable's declared default rather than written
/// down, so the far side follows a default that moves and the comparison is
/// never a configuration against itself.
///
/// **Beside [`shipped`] rather than inside it**, because the two are read at
/// different points: those four scalars are written into a uniform block by
/// [`Ssao::begin_frame`] and this selects a pipeline in [`Ssao::add_passes`].
/// Returning it from that tuple would be a value one caller always discards.
fn shipped_technique() -> Technique {
    match r_ssao_technique.default() {
        crcbl_console::Value::Enum(name) => Technique::of(name),
        // Unreachable by construction: `convar!` builds an enum cell and its
        // default together. This is what a `match` needs.
        _ => Technique::Gtao,
    }
}

/// [`r_ssao_split`] as [`crate::split::halves`] wants it, or `None` for a frame
/// comparing nothing.
///
/// **Zero is off and is the default**, so a frame nobody has touched the console
/// on records the chain once — a comparison is something a person asks for, and
/// every golden in this workspace was blessed without one. `halves` refuses a
/// seam at either edge anyway, so this is the readable spelling of a rule that
/// holds whatever reaches it.
pub(crate) fn split_at() -> Option<f32> {
    let at = r_ssao_split.get_f32();
    (at > 0.0 && at < 1.0).then_some(at)
}

/// The four scalars the chain ships with, for the other side of the seam.
///
/// **Read off the variables' own declared defaults rather than restated.** A
/// second copy of "what ships" is a copy that goes stale the day a default
/// moves — which is exactly what happened to `r_ssao_slices` and
/// `r_ssao_blur_passes` on 2026-09-03 — and the comparison would then be
/// against a configuration nothing has shipped since.
///
/// A wrong-typed default is unreachable by construction: `convar!` builds the
/// cell and the default together, so each of these matches the getter beside
/// it. The fallbacks are what a `match` needs and nothing reaches them.
fn shipped() -> (f32, u8, f32, bool) {
    use crcbl_console::Value;
    let float = |value: &Value| match value {
        Value::Float(at) => *at,
        _ => 0.0,
    };
    let slices = match r_ssao_slices.default() {
        Value::Int(count) => u8::try_from(*count).unwrap_or(ssao::SLICE_COUNT_DEFAULT),
        _ => ssao::SLICE_COUNT_DEFAULT,
    };
    let bent = matches!(r_ssao_bent_normals.default(), Value::Bool(true));
    (
        float(r_ssao_radius.default()).clamp(ssao::RADIUS_MIN, ssao::RADIUS_MAX),
        slices,
        float(r_ssao_intensity.default()).clamp(ssao::INTENSITY_MIN, ssao::INTENSITY_MAX),
        bent,
    )
}

/// The lock [`r_ssao_technique`] is moved under.
///
/// **In this module rather than beside the test that takes it**, because two
/// files move this one variable: [`tests::the_seams_other_side_is_the_technique_that_ships`]
/// and `crate::forward`'s `ssao_technique_switch`. A `cargo test` run shares one
/// process between them, so a variable one left moved is a frame the other did
/// not ask for — `ssao_blur_switch` is where that paragraph is written out in
/// full, off an experiment rather than a guess.
///
/// **Last in the lock order**, after `crate::forward`'s three. It is the only
/// one of them reached from two modules, and a test here takes this one alone,
/// so there is no cycle to have.
///
/// [`tests::the_seams_other_side_is_the_technique_that_ships`]: fn@tests::the_seams_other_side_is_the_technique_that_ships
#[cfg(test)]
pub(crate) static TECHNIQUE_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// The extent the march and the blur run at: `extent` divided by
/// `shaders/ssao.slang`'s `RESOLUTION_DIVISOR` on each axis, **rounded up**.
///
/// **Rounded up, which is what keeps a small frame drawable.** A floor takes
/// every extent under the divisor to zero, and a zero-sized transient is an
/// image no backend will create — so a one-pixel scene would be a frame that
/// fails to build rather than a frame with one occlusion sample in it. The
/// ceiling is also what keeps the two grids covering: every pixel of the scene
/// has a sample at or before it, which is where
/// `shaders/ssao_upsample.slang` reads its nearest tap. What it costs is at most
/// one sample of overhang on an odd axis, whose taps the upsample clamps back
/// into the image.
///
/// **The one place the division is spelled in this crate.** The shaders hold the
/// same constant — `crcbl_shaders::ssao::RESOLUTION_DIVISOR` is the mirror they
/// are checked against — and a second halving written somewhere else is an image
/// the passes would render a fraction of, with nothing to say so but the
/// picture.
pub(crate) fn half_extent(extent: (u32, u32)) -> (u32, u32) {
    let divisor = ssao::RESOLUTION_DIVISOR;
    (extent.0.div_ceil(divisor), extent.1.div_ceil(divisor))
}

/// [`r_ssao_blur_passes`] as a pass count, clamped into what
/// [`Ssao::add_passes`] can record.
pub(crate) fn blur_passes() -> u32 {
    let asked = r_ssao_blur_passes
        .get_i64()
        .clamp(1, i64::from(Ssao::MAX_BLUR_PASSES));
    u32::try_from(asked).unwrap_or(1)
}

/// The images one frame's occlusion chain works in.
///
/// A shape rather than four positional arguments, and not only for
/// [`Ssao::add_passes`]' argument count: three of these are the same thing — a
/// working image at [`half_extent`] — and the fourth is the one that is not,
/// which is exactly the distinction a positional list buries. `crate::forward`
/// is what creates them, and [`Ssao::add_passes`] is where each one's contents
/// and extent are stated.
#[derive(Clone, Copy, Debug)]
pub(crate) struct OcclusionImages {
    /// Where the march writes, at [`half_extent`].
    pub(crate) raw: ImageId,
    /// Where the first blur writes, at [`half_extent`].
    pub(crate) blurred: ImageId,
    /// Where a second blur writes, at [`half_extent`]. [`Some`] exactly when
    /// [`r_ssao_blur_passes`] asked for one.
    pub(crate) again: Option<ImageId>,
    /// Where the reconstruction writes: the **frame's own extent**, and the
    /// image the forward pass binds.
    pub(crate) upsampled: ImageId,
}

/// Everything the occlusion chain owns.
///
/// Built once by [`Ssao::new`] and released by [`Ssao::destroy`], which is the
/// shape every other resource group in this crate has — see
/// [`crate::light_grid::LightGrid`].
#[derive(Debug)]
pub(crate) struct Ssao {
    /// `[frame]`: `ssao.slang`'s uniform block. One per frame in flight for the
    /// frame uniforms' reason exactly — the previous frame may still be reading
    /// last frame's while this one is written.
    uniforms: Vec<BufferHandle>,
    /// `[frame]`: the same block holding [`shipped`]'s scalars, for the far side
    /// of [`r_ssao_split`]'s seam.
    ///
    /// **Its own ring and not a second offset into [`Ssao::uniforms`]**: the
    /// gather binds its block as a whole buffer rather than through a dynamic
    /// offset, so two blocks in one buffer would want a binding change to reach
    /// the second. Written every frame whether or not a seam was asked for, for
    /// the ring's own reason — a buffer written only on the frames that compare
    /// holds an older frame's matrices on the first frame that does.
    split_uniforms: Vec<BufferHandle>,
    layout: BindGroupLayoutHandle,
    pipeline_layout: PipelineLayoutHandle,
    pipeline: GraphicsPipelineHandle,
    /// The cheap tier's gather, on [`Ssao::pipeline_layout`] exactly as the
    /// pipeline above is.
    ///
    /// **A second pipeline and nothing else**, which is what makes a technique
    /// switchable at all: `shaders/ssao_hemisphere.slang` declares the same two
    /// bindings in the same order and reads the same block, so one layout, one
    /// uniform ring and one group cache answer for both — see this module's
    /// header. What differs is the module a draw runs.
    ///
    /// Built by [`Ssao::new`] whether or not anything ever selects it, for
    /// [`Ssao::split_uniforms`]' reason: a pipeline created the first time a
    /// person types `r_ssao_technique` is a compile in the frame that typed it,
    /// and what carrying it costs instead is one pipeline object.
    hemisphere_pipeline: GraphicsPipelineHandle,
    /// `[frame]`: the occlusion group, cached against the depth view.
    ///
    /// **One per frame in flight**, because this group names [`Ssao::uniforms`]
    /// as well as the depth transient — and that is a ring. A single cache keyed
    /// on the view alone would hand the even frames' block to the odd frames.
    groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
    /// `[frame]`: the same group against [`Ssao::split_uniforms`].
    ///
    /// **Its own ring for [`Ssao::blur_again_groups`]' reason**: it names a
    /// different buffer, so one cache shared with [`Ssao::groups`] would be
    /// rebuilt twice on every frame that compares.
    split_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
    blur_layout: BindGroupLayoutHandle,
    blur_pipeline_layout: PipelineLayoutHandle,
    blur_pipeline: GraphicsPipelineHandle,
    /// `[frame]`: the blur group, cached against the raw occlusion view and the
    /// depth view together.
    ///
    /// **A ring for [`Ssao::groups`]' reason exactly**: `ssao_blur.slang` weights
    /// its kernel on view-space depth, so it binds the same [`Ssao::uniforms`]
    /// block the occlusion pass does — and a single cache keyed on the views
    /// alone would hand the even frames' block to the odd frames.
    blur_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
    /// `[frame]`: the second blur's group, when [`r_ssao_blur_passes`] asks for
    /// one.
    ///
    /// **Its own ring rather than [`Ssao::blur_groups`] reused**, and not for
    /// tidiness: the two passes bind different occlusion images, so one cache
    /// shared between them would be rebuilt twice a frame — a descriptor write
    /// per pass per frame, which is the cost `cached_group` exists to avoid.
    /// The pipeline and the layout *are* shared, because the second blur is the
    /// same shader reading the first one's output.
    ///
    /// Empty of groups on every frame the switch is at its default, and the
    /// slots themselves cost a pointer each.
    blur_again_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
    /// The reconstruction's pipeline.
    ///
    /// **Its own pipeline on the blur's layout**, and that pairing is the whole
    /// of what the two passes share: `shaders/ssao_upsample.slang` declares the
    /// same three bindings in the same order — the block, an `R8Unorm` occlusion
    /// image, the scene's depth — so one layout describes both, while the shader
    /// behind it answers a different question. Two layouts here would be two
    /// descriptions of one shape to keep in step, and the seam would allocate a
    /// second identical descriptor layout to hold them.
    upsample_pipeline: GraphicsPipelineHandle,
    /// `[frame]`: the reconstruction's group, cached against the blurred
    /// occlusion view and the depth view together.
    ///
    /// **Its own ring rather than [`Ssao::blur_groups`] reused**, for
    /// [`Ssao::blur_again_groups`]' reason exactly: this pass binds a different
    /// occlusion image from the blur that precedes it, so one cache shared
    /// between them would be rebuilt twice a frame.
    upsample_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
    /// The blur and the reconstruction without the bent direction, for the
    /// frames whose gathers wrote none — see [`writes_bent`].
    ///
    /// **Built by [`Ssao::prepare`] on the first frame that can use them**, not
    /// by [`Ssao::new`]: the default stack measures a direction, so a renderer
    /// that never switches it off never pays for the pair. The shaders
    /// are `shaders/ssao_blur_bentless.slang` and
    /// `shaders/ssao_upsample_bentless.slang`; each writes the parent's
    /// visibility bit for bit and the sentinel the parent writes for a channel
    /// of sentinels, so selecting them changes the cost of a frame and nothing
    /// it draws.
    bentless: Option<Filters>,
    /// The bent-direction switch the block [`Ssao::begin_frame`] last wrote
    /// carries, which is what the near side's gather reads.
    ///
    /// **Frozen there rather than read again by [`Ssao::add_passes`]**: a
    /// console moved between the two calls would otherwise select the bent-free
    /// filters over a gather told to measure a direction, and they would
    /// overwrite it with the sentinel. `true` until a block is written, which
    /// selects the filters that carry a direction — correct for any gather.
    frame_bent: bool,
}

/// The filter pipelines one frame runs: the blur, at every pass it records,
/// and the reconstruction, each on [`Ssao::blur_pipeline_layout`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Filters {
    pub(crate) blur: GraphicsPipelineHandle,
    pub(crate) upsample: GraphicsPipelineHandle,
}

impl Ssao {
    /// Blur passes [`r_ssao_blur_passes`] may ask for.
    ///
    /// Two: the shipping one and the second the tangential rung wants. There is
    /// no third because the kernel's footprint doubles with each — see
    /// `shaders/ssao_blur.slang`, whose whole argument is that its footprint is
    /// `ssao.slang`'s tile — and a third would be blurring past every contact
    /// in the frame.
    pub(crate) const MAX_BLUR_PASSES: u32 = 2;

    /// The most passes [`Ssao::add_passes`] can add to a frame: both marches,
    /// every blur behind them, and the reconstruction that ends the chain.
    ///
    /// A **ceiling**, which is what `crate::forward`'s `RENDER_PASSES` needs
    /// from every term it adds up — see [`Ssao::passes`] for what a given frame
    /// actually records. It counts the comparison seam's second march, because
    /// a person may type `r_ssao_split` at any point in a run and the frame
    /// after that types one more pass than the frame before it.
    pub(crate) const MAX_PASSES: u32 = Self::passes(Self::MAX_BLUR_PASSES) + 1;

    /// Passes [`Ssao::add_passes`] adds to a frame that asked for `blurs` of
    /// them: the occlusion march, one per blur, and the reconstruction.
    ///
    /// **The reconstruction is not conditional on anything.** It is what makes
    /// the half-resolution chain a full-resolution channel — see this module's
    /// header — so a frame that records the march records this as well.
    ///
    /// **The comparison seam's second march is not counted here.** This is what
    /// a frame's own counters are checked against, and a frame comparing
    /// nothing — which is every frame nobody has typed `r_ssao_split` in —
    /// records exactly this many. [`Ssao::MAX_PASSES`] is the term that carries
    /// the other one.
    pub(crate) const fn passes(blurs: u32) -> u32 {
        1 + blurs + 1
    }

    /// Builds every pipeline and the uniform ring.
    ///
    /// `build_fullscreen` is handed in rather than duplicated: it is
    /// [`crate::forward`]'s, because the tonemap pass is the third caller and the
    /// shape it carries — a triangle out of `SV_VertexID`, no depth state, one
    /// colour target — is documented there.
    ///
    /// # Errors
    ///
    /// [`HalError`] from any seam call. A failure part-way through releases
    /// everything already created — see [`crate::partial`].
    pub(crate) fn new(
        device: &dyn Device,
        frames: usize,
        build_fullscreen: impl Fn(
            &dyn Device,
            &str,
            &crcbl_shaders::Shader,
            PipelineLayoutHandle,
            &[ColorTargetState],
        ) -> Result<GraphicsPipelineHandle, HalError>,
    ) -> Result<Self, HalError> {
        // **No sampler in either layout**, which is the whole of what reading by
        // `Load` buys — see the binding comments in `shaders/ssao.slang`.
        let entries = [
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::UniformBuffer { dynamic: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // **`Depth`, and it is the seam's half of `DepthTexture2D`.**
                    // WebGPU will only bind a `D32Float` view through a depth
                    // sample type, and the WGSL artifact agrees — it declares
                    // `texture_depth_2d`, which `textureLoad` takes. There is no
                    // comparison sampler beside it because nothing here compares:
                    // this binding is fetched, not sampled.
                    sample_type: SampleType::Depth,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
        ];
        let desc = BindGroupLayoutDesc {
            label: Some("ssao depth"),
            entries: &entries,
        };
        check_portable_storage_buffers(Some("ssao"), &[&desc])?;
        let mut made = Partial::new(device);
        let layout = made.add(device.create_bind_group_layout(&desc)?);
        let set_layouts = [layout];
        let pipeline_layout = made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("ssao"),
            bind_group_layouts: &set_layouts,
            push_constants: None,
        })?);

        // **The same shape, one binding longer.** The blur unprojects the depth
        // it weights its kernel by, so it names the uniform block at 0 exactly
        // as the pass above does and its two images follow — see
        // `shaders/ssao_blur.slang`.
        let blur_entries = [
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::UniformBuffer { dynamic: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // `Float`, unlike the depth beside it: the raw occlusion is
                    // an ordinary `R8Unorm` colour image and the WGSL artifact
                    // declares `texture_2d<f32>` for it.
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 2,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    // `Depth`, and the paragraph on the occlusion pass's own
                    // depth binding is this one's too: it is the same image,
                    // read through the same `texture_depth_2d`.
                    sample_type: SampleType::Depth,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
        ];
        let blur_desc = BindGroupLayoutDesc {
            label: Some("ssao blur"),
            entries: &blur_entries,
        };
        check_portable_storage_buffers(Some("ssao blur"), &[&blur_desc])?;
        let blur_layout = made.add(device.create_bind_group_layout(&blur_desc)?);
        let blur_set_layouts = [blur_layout];
        let blur_pipeline_layout =
            made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
                label: Some("ssao blur"),
                bind_group_layouts: &blur_set_layouts,
                push_constants: None,
            })?);

        let targets = [ColorTargetState::opaque(Format::Rgba8Unorm)];
        let pipeline = made.add(build_fullscreen(
            device,
            "ssao",
            &SSAO,
            pipeline_layout,
            &targets,
        )?);
        // The other technique, on the same layout and the same target — see
        // [`Ssao::hemisphere_pipeline`].
        let hemisphere_pipeline = made.add(build_fullscreen(
            device,
            "ssao hemisphere",
            &SSAO_HEMISPHERE,
            pipeline_layout,
            &targets,
        )?);
        let blur_pipeline = made.add(build_fullscreen(
            device,
            "ssao blur",
            &SSAO_BLUR,
            blur_pipeline_layout,
            &targets,
        )?);
        // **The blur's layout, and the same colour target.** The reconstruction
        // writes the same `R8Unorm` channel at a different extent, and an extent
        // is not part of a pipeline — the graph takes the render area from the
        // attachment it was given. See [`Ssao::upsample_pipeline`] for why the
        // layout is shared and the pipeline is not.
        let upsample_pipeline = made.add(build_fullscreen(
            device,
            "ssao upsample",
            &SSAO_UPSAMPLE,
            blur_pipeline_layout,
            &targets,
        )?);

        let mut uniforms = Vec::with_capacity(frames);
        let mut split_uniforms = Vec::with_capacity(frames);
        for (ring, label) in [
            (&mut uniforms, "ssao params"),
            (&mut split_uniforms, "ssao params (shipped)"),
        ] {
            for _ in 0..frames {
                ring.push(made.add(device.create_buffer(&BufferDesc {
                    label: Some(label),
                    size: ssao::PARAMS_SIZE as u64,
                    usage: BufferUsage::UNIFORM,
                    memory: MemoryLocation::HostUpload,
                })?));
            }
        }

        made.keep();
        Ok(Self {
            uniforms,
            split_uniforms,
            layout,
            pipeline_layout,
            pipeline,
            hemisphere_pipeline,
            groups: vec![None; frames],
            split_groups: vec![None; frames],
            blur_layout,
            blur_pipeline_layout,
            blur_pipeline,
            blur_groups: vec![None; frames],
            blur_again_groups: vec![None; frames],
            upsample_pipeline,
            upsample_groups: vec![None; frames],
            bentless: None,
            frame_bent: true,
        })
    }

    /// Builds the bent-free filters where `wanted` and this chain does not hold
    /// them yet.
    ///
    /// **Between frames, never inside one**, on `View::build_passes`' terms —
    /// `View::begin_frame` calls this, and never the build, so what a renderer
    /// makes at construction does not depend on the console. A frame that
    /// finds the pair missing runs the filters that carry the direction, which
    /// draw the same picture.
    ///
    /// # Errors
    ///
    /// [`HalError`] from a pipeline. Neither is kept unless both are built —
    /// see [`crate::partial`].
    pub(crate) fn prepare(
        &mut self,
        device: &dyn Device,
        build_fullscreen: impl Fn(
            &dyn Device,
            &str,
            &crcbl_shaders::Shader,
            PipelineLayoutHandle,
            &[ColorTargetState],
        ) -> Result<GraphicsPipelineHandle, HalError>,
        wanted: bool,
    ) -> Result<(), HalError> {
        if self.bentless.is_some() || !wanted {
            return Ok(());
        }
        let targets = [ColorTargetState::opaque(Format::Rgba8Unorm)];
        let mut made = Partial::new(device);
        let blur = made.add(build_fullscreen(
            device,
            "ssao blur bentless",
            &SSAO_BLUR_BENTLESS,
            self.blur_pipeline_layout,
            &targets,
        )?);
        let upsample = made.add(build_fullscreen(
            device,
            "ssao upsample bentless",
            &SSAO_UPSAMPLE_BENTLESS,
            self.blur_pipeline_layout,
            &targets,
        )?);
        made.keep();
        self.bentless = Some(Filters { blur, upsample });
        Ok(())
    }

    /// Writes `frame`'s uniform block.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the mapped write.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn begin_frame(
        &mut self,
        device: &dyn Device,
        frame: usize,
        params: ssao::SsaoParams,
    ) -> Result<(), HalError> {
        device.write_buffer(self.uniforms[frame], 0, &params.to_bytes())?;
        self.frame_bent = params.bent_normals;
        // The comparison's other side: this frame's own matrices with
        // [`shipped`]'s scalars, so the seam separates the four knobs and
        // nothing else. Building it from `params` rather than beside it is what
        // makes that true — a second block assembled from a second camera would
        // compare two frames.
        let (radius, slices, intensity, bent_normals) = shipped();
        let baseline = ssao::SsaoParams {
            radius,
            slices,
            intensity,
            bent_normals,
            ..params
        };
        device.write_buffer(self.split_uniforms[frame], 0, &baseline.to_bytes())
    }

    /// The two blocks [`Ssao::begin_frame`] wrote for `frame`: the console's and
    /// the comparison seam's.
    ///
    /// Test-only, and it exists because the reference backend can be asked what
    /// bytes a buffer holds but not which buffer a bind group names — so this is
    /// how far a check can follow the seam's far side. See
    /// `crate::forward`'s `the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`
    /// for what that leaves uncovered.
    #[cfg(all(test, not(target_arch = "wasm32")))]
    pub(crate) fn blocks(&self, frame: usize) -> (BufferHandle, BufferHandle) {
        (self.uniforms[frame], self.split_uniforms[frame])
    }

    /// The two gather pipelines [`Ssao::new`] built: the technique that ships,
    /// and the cheap tier.
    ///
    /// Test-only, and [`Ssao::blocks`]' counterpart for the switch that reaches
    /// a pipeline rather than a block — a **stronger** one, because the
    /// reference backend does record which pipeline a pass bound where it does
    /// not record which buffer a group named. See `crate::forward`'s
    /// `the_occlusion_technique_picks_the_gathers_pipeline`.
    #[cfg(all(test, not(target_arch = "wasm32")))]
    pub(crate) const fn gathers(&self) -> (GraphicsPipelineHandle, GraphicsPipelineHandle) {
        (self.pipeline, self.hemisphere_pipeline)
    }

    /// The filters that carry the bent direction, and the bent-free pair if
    /// [`Ssao::prepare`] has built it.
    ///
    /// Test-only, and [`Ssao::gathers`]' counterpart for the filters. See
    /// `crate::forward`'s `lazy_passes::the_filters_skip_the_bent_direction_only_when_no_gather_wrote_one`.
    #[cfg(all(test, not(target_arch = "wasm32")))]
    pub(crate) const fn filters(&self) -> (Filters, Option<Filters>) {
        (
            Filters {
                blur: self.blur_pipeline,
                upsample: self.upsample_pipeline,
            },
            self.bentless,
        )
    }

    /// The filters a frame runs: the bent-free pair where it is held and no
    /// gather of the frame wrote a direction, and the pair that carries one
    /// otherwise — see [`writes_bent`]. `technique` is the near side's gather
    /// and the switch is [`Ssao::frame_bent`], the one its block carries.
    fn filters_for(&self, technique: Technique, compared: bool) -> Filters {
        match self.bentless {
            Some(bentless) if !writes_bent(technique, self.frame_bent, compared) => bentless,
            _ => Filters {
                blur: self.blur_pipeline,
                upsample: self.upsample_pipeline,
            },
        }
    }

    /// The gather pipeline `technique` runs.
    ///
    /// The whole of what the selector reaches — see this module's header on why
    /// a technique is a pipeline and every other switch here is a lane of the
    /// uniform block.
    fn pipeline_for(&self, technique: Technique) -> GraphicsPipelineHandle {
        match technique {
            Technique::Gtao => self.pipeline,
            Technique::Hemisphere => self.hemisphere_pipeline,
        }
    }

    /// Adds the `ssao` pass, its blurs and the reconstruction, in that order,
    /// and returns the image the forward pass should read.
    ///
    /// `depth` must be the prepass's stored depth, at the scene's own extent.
    /// [`OcclusionImages`] is where the chain works: its three working images
    /// must all be [`half_extent`] of that depth, and its `upsampled` is the
    /// full-extent channel the last pass writes. Every occlusion image is the
    /// caller's so it can declare the read on the pass that consumes the last of
    /// them: a pass declares its own accesses and this one cannot declare the
    /// forward pass's.
    ///
    /// **The two extents are the caller's to get right and the graph is what
    /// checks them.** A render pass takes its area from its colour attachment —
    /// see `RenderGraph::compile` — so a working image handed in at the scene's
    /// size is not an error anywhere, it is a march that runs four times and a
    /// reconstruction that reads the corner of its input.
    ///
    /// **The returned id is the one to bind**, rather than the caller assuming
    /// any particular image, because which one holds the finished channel is
    /// this function's business and gets it wrong silently — a forward pass
    /// bound to the half-resolution image draws a frame nobody would question.
    ///
    /// # Panics
    ///
    /// If `frame` is not a slot this was built with.
    pub(crate) fn add_passes<'a>(
        &'a mut self,
        graph: &mut RenderGraph<'a>,
        frame: usize,
        extent: (u32, u32),
        depth: ImageId,
        images: OcclusionImages,
    ) -> ImageId {
        // The gather's own extent, derived here rather than taken: `half_extent`
        // is what sized `images` and a second spelling of the halving is a
        // scissor over an image of another size — see this module's header.
        let half = half_extent(extent);
        let OcclusionImages {
            raw,
            blurred,
            again,
            upsampled,
        } = images;
        // The near side's technique and the far side's, both read before the
        // borrows below split `self`. The console's on the near side and the
        // shipped one on the far, which is [`shipped`]'s rule for the four
        // scalars applied to the switch that is not one of them.
        let near = technique();
        let pipeline = self.pipeline_for(near);
        let shipped_pipeline = self.pipeline_for(shipped_technique());
        // The seam is decided here rather than beside the gathers below, because
        // whether it is drawn decides the filters too — see [`writes_bent`].
        let seam = split_at().and_then(|at| crate::split::halves(half, at));
        let filters = self.filters_for(near, seam.is_some());
        let pipeline_layout = self.pipeline_layout;
        let layout = self.layout;
        let uniforms = self.uniforms[frame];
        // Split so the closures below borrow different halves of `self`; one
        // `&mut self` shared between them is what the borrow checker refuses, and
        // it would be refusing something genuinely wrong — a pass body may run at
        // any point after it is declared.
        let (groups, blur_groups, again_groups, upsample_groups) = (
            &mut self.groups,
            &mut self.blur_groups,
            &mut self.blur_again_groups,
            &mut self.upsample_groups,
        );
        let cached = &mut groups[frame];
        let blur_cached = &mut blur_groups[frame];
        let again_cached = &mut again_groups[frame];
        let upsample_cached = &mut upsample_groups[frame];

        // The gather, once for a frame drawing one picture and twice for one
        // comparing two — see [`crate::split`]. The second reads the same depth
        // and writes the same image, so what separates the two sides is the
        // block each binds, the pipeline each runs and the columns each may
        // write.
        let (split_uniforms, split_groups) = (self.split_uniforms[frame], &mut self.split_groups);
        let split_cached = &mut split_groups[frame];
        match seam {
            None => add_gather(
                graph,
                "ssao",
                cached,
                uniforms,
                layout,
                pipeline_layout,
                pipeline,
                raw,
                depth,
                LoadOp::DontCare,
                None,
            ),
            Some((left, right)) => {
                add_gather(
                    graph,
                    "ssao",
                    cached,
                    uniforms,
                    layout,
                    pipeline_layout,
                    pipeline,
                    raw,
                    depth,
                    LoadOp::DontCare,
                    Some(left),
                );
                // `Load`, where the first is `DontCare`: this pass writes the
                // columns the first one's scissor kept it out of, and a second
                // `DontCare` would licence a backend to discard them.
                add_gather(
                    graph,
                    "ssao-shipped",
                    split_cached,
                    split_uniforms,
                    layout,
                    pipeline_layout,
                    shipped_pipeline,
                    raw,
                    depth,
                    LoadOp::Load,
                    Some(right),
                );
            }
        }

        let blur = Filter {
            uniforms,
            layout: self.blur_layout,
            pipeline_layout: self.blur_pipeline_layout,
            pipeline: filters.blur,
        };
        blur.add_pass(graph, "ssao-blur", blur_cached, raw, depth, blurred);
        let filtered = match again {
            // The second blur reads the first one's output and writes its own
            // image. **Not back into `raw`**, which would be a write-after-read
            // on an image this same frame's march wrote and this same frame's
            // first blur read: the graph would have to order it, the pool could
            // not alias it, and the saving is one `R8Unorm` image on the frames
            // that asked for this at all.
            Some(again) => {
                blur.add_pass(graph, "ssao-blur-2", again_cached, blurred, depth, again);
                again
            }
            None => blurred,
        };
        // The reconstruction, reading whichever blur ran last and the scene's
        // depth, and writing the full-extent channel. **The same pass body as a
        // blur**, because it is the same three bindings and one triangle — what
        // differs is the pipeline and the extent of the image it was handed, and
        // neither of those is something this function does differently.
        let upsample = Filter {
            pipeline: filters.upsample,
            ..blur
        };
        upsample.add_pass(
            graph,
            "ssao-upsample",
            upsample_cached,
            filtered,
            depth,
            upsampled,
        );
        upsampled
    }

    /// Releases everything, in dependency order. The device must be idle.
    pub(crate) fn destroy(self, device: &dyn Device) {
        for cached in self
            .groups
            .into_iter()
            .chain(self.split_groups)
            .chain(self.blur_groups)
            .chain(self.blur_again_groups)
            .chain(self.upsample_groups)
            .flatten()
        {
            device.destroy_bind_group(cached.1);
        }
        // Before the layout they were built against, which is the blur's — see
        // [`Ssao::upsample_pipeline`].
        if let Some(bentless) = self.bentless {
            device.destroy_graphics_pipeline(bentless.upsample);
            device.destroy_graphics_pipeline(bentless.blur);
        }
        device.destroy_graphics_pipeline(self.upsample_pipeline);
        device.destroy_graphics_pipeline(self.blur_pipeline);
        device.destroy_pipeline_layout(self.blur_pipeline_layout);
        device.destroy_bind_group_layout(self.blur_layout);
        device.destroy_graphics_pipeline(self.hemisphere_pipeline);
        device.destroy_graphics_pipeline(self.pipeline);
        device.destroy_pipeline_layout(self.pipeline_layout);
        device.destroy_bind_group_layout(self.layout);
        for buffer in self.uniforms.into_iter().chain(self.split_uniforms) {
            device.destroy_buffer(buffer);
        }
    }
}

/// Records one occlusion gather, over the whole target or over `scissor`.
///
/// The pass body [`Ssao::add_passes`] used to hold inline, lifted out when the
/// comparison seam gave it a second caller — see [`crate::split`]. `load` is
/// `DontCare` for a gather that writes every pixel and `Load` for one that
/// writes the columns another gather left, and `scissor` is `None` for the
/// former: a full-screen triangle covers the target, so a frame drawing one
/// picture sets no rectangle at all and records what it recorded before this
/// function existed.
///
/// `pipeline` is the technique this gather runs — see [`Technique`]. It is an
/// argument rather than a field read here because the two sides of a comparison
/// may run different ones, which is the whole of what
/// alcove's second milestone asks for.
///
/// **The viewport is not touched.** `ssao.slang` reads `SV_Position`, so a
/// viewport narrowed to the half would squash the whole image into it; the
/// scissor is the one of the pair that crops. [`crate::split`]'s header is where
/// that is argued, because it is where a second effect will look.
#[allow(clippy::too_many_arguments)]
fn add_gather<'a>(
    graph: &mut RenderGraph<'a>,
    label: &'static str,
    cached: &'a mut Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
    uniforms: BufferHandle,
    layout: BindGroupLayoutHandle,
    pipeline_layout: PipelineLayoutHandle,
    pipeline: GraphicsPipelineHandle,
    raw: ImageId,
    depth: ImageId,
    load: LoadOp,
    scissor: Option<Rect2d>,
) {
    graph
        .add_render_pass(label)
        // `DontCare` where the triangle writes every pixel of the target, so
        // loading or clearing it is pure bandwidth; `Load` where a scissor keeps
        // this pass off columns another one wrote.
        .color(raw, load, StoreOp::Store, ClearValue::default())
        // The prepass left this in `DepthStencilWrite`. Declaring the read is
        // what moves it to a shader-readable layout, and without it every
        // backend reads whatever the depth writes left behind.
        .read_image(depth)
        .execute(move |ctx| {
            let view = ctx.image_view(depth);
            let device = ctx.device();
            let entries = [
                BindGroupEntry {
                    binding: 0,
                    array_index: 0,
                    resource: BindingResource::whole_buffer(uniforms),
                },
                BindGroupEntry {
                    binding: 1,
                    array_index: 0,
                    // Overwritten by `cached_group` with the realised view;
                    // written here so the list is a complete description of the
                    // layout rather than a list with a hole in it.
                    resource: BindingResource::ImageView(view),
                },
            ];
            let Some(group) =
                cached_group(cached, device, &[(1, view)], "ssao depth", layout, &entries)
            else {
                return;
            };
            let encoder = ctx.encoder();
            if let Some(rect) = scissor {
                encoder.set_scissor(&rect);
            }
            encoder.bind_graphics_pipeline(pipeline);
            encoder.bind_group(0, group, &[], pipeline_layout);
            encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
        });
}

/// The pipeline, layout and uniform block every pass behind the march shares.
///
/// All of them take one occlusion image, the scene's depth and the block, and
/// draw one triangle into an `R8Unorm` target: the second blur is the *same
/// shader* reading the first one's output — see this module's header on why
/// there can be a second at all — and the reconstruction is a different shader
/// on the same layout, which is [`Ssao::upsample_pipeline`]'s paragraph. So what
/// differs between them is a pipeline, three image ids and a label, and
/// everything else is this. Gathered into a type rather than passed as seven
/// arguments, and extracted the moment there were two callers rather than left
/// as a copy of the pass body with two ids changed.
#[derive(Clone, Copy)]
struct Filter {
    uniforms: BufferHandle,
    layout: BindGroupLayoutHandle,
    pipeline_layout: PipelineLayoutHandle,
    pipeline: GraphicsPipelineHandle,
}

impl Filter {
    /// Adds one pass: `source` and `depth` in, `target` out.
    ///
    /// `cached` is this pass's own group ring slot — each of these passes binds
    /// a different source image, so sharing one slot between them would rebuild
    /// the group once per pass per frame.
    ///
    /// **`target` is what decides the extent the pass runs at.** The graph takes
    /// a render pass's area from its colour attachment, so the same body records
    /// a half-extent blur and a full-extent reconstruction without either being
    /// told which it is.
    fn add_pass<'a>(
        self,
        graph: &mut RenderGraph<'a>,
        label: &'static str,
        cached: &'a mut Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
        source: ImageId,
        depth: ImageId,
        target: ImageId,
    ) {
        let Self {
            uniforms,
            layout,
            pipeline_layout,
            pipeline,
        } = self;
        graph
            .add_render_pass(label)
            .color(
                target,
                LoadOp::DontCare,
                StoreOp::Store,
                ClearValue::default(),
            )
            .read_image(source)
            // **The depth this pass weights its kernel by**, and the
            // declaration is what gives it a shader-readable layout here as
            // well: the march declared its own read, and a barrier the graph was
            // never told about is one it does not insert.
            .read_image(depth)
            .execute(move |ctx| {
                let view = ctx.image_view(source);
                let depth_view = ctx.image_view(depth);
                let device = ctx.device();
                let entries = [
                    BindGroupEntry {
                        binding: 0,
                        array_index: 0,
                        resource: BindingResource::whole_buffer(uniforms),
                    },
                    BindGroupEntry {
                        binding: 1,
                        array_index: 0,
                        // Overwritten by `cached_group` with the realised view,
                        // as is the depth below; written here so the list is a
                        // complete description of the layout rather than a list
                        // with two holes in it.
                        resource: BindingResource::ImageView(view),
                    },
                    BindGroupEntry {
                        binding: 2,
                        array_index: 0,
                        resource: BindingResource::ImageView(depth_view),
                    },
                ];
                let Some(group) = cached_group(
                    cached,
                    device,
                    &[(1, view), (2, depth_view)],
                    label,
                    layout,
                    &entries,
                ) else {
                    return;
                };
                let encoder = ctx.encoder();
                encoder.bind_graphics_pipeline(pipeline);
                encoder.bind_group(0, group, &[], pipeline_layout);
                encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
            });
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The gather extent **rounds up**, so no axis of a drawable frame reaches
    /// zero.
    ///
    /// A floor is the spelling this would otherwise have, and it is wrong at
    /// both ends: it takes a frame narrower than the divisor to a zero-width
    /// transient, which is an image no backend creates and therefore a frame
    /// that fails rather than a frame with one occlusion sample in it, and it
    /// leaves an odd axis one sample short of its own last pixel — see
    /// [`tests::every_pixel_of_a_frame_has_a_sample_at_or_before_it`].
    ///
    /// [`tests::every_pixel_of_a_frame_has_a_sample_at_or_before_it`]: fn@every_pixel_of_a_frame_has_a_sample_at_or_before_it
    #[test]
    fn the_gather_extent_rounds_up() {
        assert_eq!(
            half_extent((1920, 1080)),
            (960, 540),
            "an even frame halves exactly"
        );
        assert_eq!(
            half_extent((1921, 1081)),
            (961, 541),
            "an odd axis keeps the sample its last pixel needs"
        );
        assert_eq!(
            half_extent((1, 1)),
            (1, 1),
            "and the smallest frame there is still has one sample in it"
        );
    }

    /// Every pixel of the frame has an occlusion sample at or before it.
    ///
    /// `shaders/ssao_upsample.slang` divides its pixel by the same constant to
    /// find the first of the samples it reads, and clamps the result into the
    /// image. That clamp is there for the *second* tap, which genuinely runs off
    /// the edge; a gather extent that floored would put the last row and column
    /// of an odd frame past the last sample as well, and the clamp would answer
    /// silently for the first tap too — reconstructing the frame's far edge from
    /// the sample before the one it wanted.
    ///
    /// Swept rather than spot-checked, because the property is about the odd
    /// extents and a fixture is only ever one of them.
    #[test]
    fn every_pixel_of_a_frame_has_a_sample_at_or_before_it() {
        for width in 1..=64u32 {
            let (samples, _) = half_extent((width, width));
            let nearest = (width - 1) / ssao::RESOLUTION_DIVISOR;
            assert!(
                nearest < samples,
                "the last pixel of a {width}-wide frame reads sample {nearest} of {samples}, so \
                 the upsample's clamp is standing in for a sample that is not there"
            );
        }
    }

    /// The console's range is the shader's range, and its default is the
    /// exponent that changes nothing.
    ///
    /// `convar!` takes its bounds as literals — a macro cannot read a constant
    /// — so the two numbers in the declaration above are a copy of
    /// `crcbl_shaders::ssao`'s, and this is what holds them to it. A console
    /// range wider than the shader's is a value a person can set and the frame
    /// silently ignores; narrower, and part of the shader's range is
    /// unreachable. Neither shows up as anything but a knob that does less than
    /// it says.
    ///
    /// Holds [`TECHNIQUE_SWITCH`] for the reason
    /// [`the_console_radius_range_is_the_range_the_march_honours`] does:
    /// [`the_seams_other_side_is_what_the_chain_ships`] moves this default to
    /// `INTENSITY_MAX` and back under it.
    ///
    /// [`the_seams_other_side_is_what_the_chain_ships`]: fn@the_seams_other_side_is_what_the_chain_ships
    #[test]
    fn the_console_range_is_the_range_the_reconstruction_honours() {
        let _technique = TECHNIQUE_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(
            r_ssao_intensity.kind(),
            crcbl_console::Kind::Float {
                min: ssao::INTENSITY_MIN,
                max: ssao::INTENSITY_MAX,
            },
            "`r_ssao_intensity` accepts a range `shaders/ssao_upsample.slang` does not honour"
        );
        assert_eq!(
            intensity(),
            ssao::INTENSITY_DEFAULT,
            "a frame nobody has touched the console on must reach the shader at the exponent \
             every golden in this workspace was blessed under"
        );
    }

    /// The seam's other side is what the chain ships, whatever the console holds.
    ///
    /// [`shipped`] reads each variable's own declared default, so this moves
    /// every one of them and checks that none of the four followed. A copy of
    /// "what ships" written out beside the variables would pass the first half
    /// of this and fail the second the day a default moved — which is what
    /// happened to `r_ssao_slices` and `r_ssao_blur_passes` on 2026-09-03.
    ///
    /// **The moved values are each on the far side of the default from the
    /// other**, so a `shipped` that returned the *live* value would differ from
    /// the expected one in every field rather than in a lucky one.
    ///
    /// Holds [`TECHNIQUE_SWITCH`] for the whole of it, and alone. The four
    /// variables it moves are rows of the occlusion params block, and
    /// `crate::forward`'s `four_slices_reach_the_frame_the_shader_reads`
    /// compares that block across two rings byte for byte; a move here landing
    /// between its batches is a row that test never asked to change.
    #[test]
    fn the_seams_other_side_is_what_the_chain_ships() {
        use crcbl_console::Value;

        let _technique = TECHNIQUE_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let before = (
            r_ssao_radius.get_f32(),
            r_ssao_slices.get_i64(),
            r_ssao_intensity.get_f32(),
            r_ssao_bent_normals.get_bool(),
        );
        let shipped_before = shipped();
        for (name, value) in [
            ("r_ssao_radius", Value::Float(ssao::RADIUS_MAX)),
            (
                "r_ssao_slices",
                Value::Int(i64::from(ssao::SLICE_COUNT_DEFAULT)),
            ),
            ("r_ssao_intensity", Value::Float(ssao::INTENSITY_MAX)),
            ("r_ssao_bent_normals", Value::Bool(false)),
        ] {
            let var = match name {
                "r_ssao_radius" => &r_ssao_radius,
                "r_ssao_slices" => &r_ssao_slices,
                "r_ssao_intensity" => &r_ssao_intensity,
                _ => &r_ssao_bent_normals,
            };
            var.set(&value).expect("a writable variable in range");
        }

        // Anti-vacuity: every knob has to have actually moved, or the equality
        // below holds of a console nobody changed.
        let moved = (
            r_ssao_radius.get_f32(),
            r_ssao_slices.get_i64(),
            r_ssao_intensity.get_f32(),
            r_ssao_bent_normals.get_bool(),
        );
        let live = (
            radius(),
            i64::from(slice_count()),
            intensity(),
            bent_normals(),
        );
        assert_eq!(live, moved, "the getters did not follow the console");

        let after = shipped();
        assert_eq!(
            after, shipped_before,
            "the shipped block moved when the console did, so the seam compares a configuration \
             against itself"
        );
        assert_ne!(
            (after.0, i64::from(after.1), after.2, after.3),
            live,
            "the shipped block is what the console holds, so both sides of the seam are the same \
             picture"
        );
        assert_eq!(
            after,
            (
                ssao::RADIUS_DEFAULT,
                ssao::SLICE_COUNT_MAX,
                ssao::INTENSITY_DEFAULT,
                true
            ),
            "the shipped block is not the four defaults the variables above declare"
        );

        for (var, value) in [
            (&r_ssao_radius, Value::Float(before.0)),
            (&r_ssao_intensity, Value::Float(before.2)),
        ] {
            var.set(&value).expect("putting a float back");
        }
        r_ssao_slices
            .set(&Value::Int(before.1))
            .expect("putting the count back");
        r_ssao_bent_normals
            .set(&Value::Bool(before.3))
            .expect("putting the switch back");
    }

    /// [`TECHNIQUES`] and [`r_ssao_technique`] must name the same set, in the
    /// same order.
    ///
    /// `crate::debug_view`'s `the_variable_names_are_the_renderers_labels` is
    /// this test on the other enum variable, for its reason: the `convar!` takes
    /// literals, so the names exist twice, and [`Technique::of`] searches the
    /// copy. A name that drifted would be a value a person can set and
    /// [`technique`] answers with [`Technique::Gtao`] — the selector silently
    /// doing nothing.
    ///
    /// **It holds the names and not the enum's completeness**, which is worth
    /// saying because the two look alike: a variant added to [`Technique`] and
    /// left out of [`TECHNIQUES`] passes here. What it costs is nothing a frame
    /// can reach — the console cannot name it, so nothing can select it — and
    /// what would catch it is a derive this workspace does not have.
    #[test]
    fn the_variable_names_are_the_techniques_labels() {
        let crcbl_console::Kind::Enum(names) = r_ssao_technique.kind() else {
            panic!("`r_ssao_technique` is an enum variable");
        };
        let labels: Vec<&str> = TECHNIQUES.into_iter().map(Technique::label).collect();
        assert_eq!(names, labels.as_slice());
    }

    /// A frame nobody has touched the console on runs what ships, and so does
    /// the far side of the seam whatever the console holds.
    ///
    /// [`the_seams_other_side_is_what_the_chain_ships`]'s claim for the switch
    /// that is not one of the four scalars, and it is the same failure: a
    /// [`shipped_technique`] that followed the console would be a comparison of
    /// one technique against itself, which is a seam that draws one picture and
    /// says nothing.
    ///
    /// [`the_seams_other_side_is_what_the_chain_ships`]: fn@the_seams_other_side_is_what_the_chain_ships
    #[test]
    fn the_seams_other_side_is_the_technique_that_ships() {
        use crcbl_console::Value;

        let _guard = TECHNIQUE_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let before = r_ssao_technique.get_enum();
        assert_eq!(
            technique(),
            Technique::Gtao,
            "a frame nobody has touched the console on must gather through the technique every \
             golden in this workspace was blessed under"
        );
        let shipped_before = shipped_technique();

        r_ssao_technique
            .set(&Value::Enum(Technique::Hemisphere.label()))
            .expect("a writable enum in the set");
        // Anti-vacuity: the knob has to have actually moved, or the equality
        // below holds of a console nobody changed.
        assert_eq!(
            technique(),
            Technique::Hemisphere,
            "the getter did not follow the console"
        );
        assert_eq!(
            shipped_technique(),
            shipped_before,
            "the shipped technique moved when the console did, so the seam compares a technique \
             against itself"
        );
        assert_ne!(
            shipped_technique(),
            technique(),
            "the shipped technique is what the console holds, so both sides of the seam run one \
             shader"
        );

        r_ssao_technique
            .set(&Value::Enum(before))
            .expect("putting the technique back");
    }

    /// The same holding, for the disc the march sweeps.
    ///
    /// Separate from the test above because it is a separate copy: the bounds
    /// on `r_ssao_radius` are literals repeating `crcbl_shaders::ssao`'s, and
    /// the two pairs can drift apart one at a time.
    ///
    /// Holds [`TECHNIQUE_SWITCH`] because the default it reads is a row
    /// [`the_seams_other_side_is_what_the_chain_ships`] moves to
    /// `RADIUS_MAX` and back under that switch; a read between its set and
    /// its restore sees the moved value, which is a red that only opens under
    /// the workspace run's parallelism.
    ///
    /// [`the_seams_other_side_is_what_the_chain_ships`]: fn@the_seams_other_side_is_what_the_chain_ships
    #[test]
    fn the_console_radius_range_is_the_range_the_march_honours() {
        let _technique = TECHNIQUE_SWITCH
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(
            r_ssao_radius.kind(),
            crcbl_console::Kind::Float {
                min: ssao::RADIUS_MIN,
                max: ssao::RADIUS_MAX,
            },
            "`r_ssao_radius` accepts a range `shaders/ssao.slang` does not honour"
        );
        assert_eq!(
            radius(),
            ssao::RADIUS_DEFAULT,
            "a frame nobody has touched the console on must reach the shader at the radius \
             every golden in this workspace was blessed under"
        );
    }
}