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
//! SGL3D's lighting model (D-32) against independent oracles: a white metal
//! conserves a white furnace's energy under direct light; direct light and
//! the environment reflect the same energy on every channel; one material
//! reflects the same irradiance alike whatever holds it; and a sized light's
//! highlight against the light its sphere or disc gives. Each observes the
//! production shading on the GPU and integrates or compares in f64.
use crate::renderer::Renderer;
use crate::settings::{self, Settings};
use crate::static_lighting::{IrradianceAtlas, Lightmap};
use crate::{
    Backdrop, Camera, DirectionalLight, FrameInput, HemisphereLight, IrradianceCell,
    IrradianceVolume, Light, LightShape, Scene, asset, test_support,
};
use glam::{DVec3, Mat4, Vec3};
use std::f64::consts::{FRAC_PI_2, PI};

/// The hemisphere of directions each integral sums over: steps in polar
/// angle from the normal and in azimuth, and the invocations that share them.
/// A grid this fine integrates GGX's directional albedo to within 0.015% at
/// perceptual roughness 0.25 and above (checked against a 2^18-sample
/// Hammersley integral).
pub(super) const THETA_STEPS: usize = 512;
pub(super) const PHI_STEPS: usize = 1024;
pub(super) const THREADS: usize = 256;

/// The solid angle of one grid cell at polar angle `theta`.
pub(super) fn cell(theta: f64) -> f64 {
    theta.sin() * (FRAC_PI_2 / THETA_STEPS as f64) * (2. * PI / PHI_STEPS as f64)
}

/// The grid's polar angle and azimuth at row `row` and column `column`.
pub(super) fn grid(row: usize, column: usize) -> (f64, f64) {
    (
        (row as f64 + 0.5) / THETA_STEPS as f64 * FRAC_PI_2,
        (column as f64 + 0.5) / PHI_STEPS as f64 * 2. * PI,
    )
}

pub(super) fn polar(theta: f64, phi: f64) -> DVec3 {
    DVec3::new(
        theta.sin() * phi.cos(),
        theta.sin() * phi.sin(),
        theta.cos(),
    )
}

/// WGSL constants and helpers the integrals share: the grid, and a surface
/// facing +Z at the origin seen along `view` with perceptual roughness
/// `rough`, base colour `base` and metallic `metallic`, a dielectric of F0
/// 0.04 and F90 1 where it is not metal.
pub(super) fn grid_wgsl() -> String {
    format!(
        r#"
const THETA_STEPS:u32={THETA_STEPS}u;
const PHI_STEPS:u32={PHI_STEPS}u;
const THREADS:u32={THREADS}u;
fn grid_direction(row:u32,column:u32)->vec3<f32> {{
 let theta=(f32(row)+.5)/f32(THETA_STEPS)*1.5707963267948966;
 let phi=(f32(column)+.5)/f32(PHI_STEPS)*6.283185307179586;
 return vec3(sin(theta)*cos(phi),sin(theta)*sin(phi),cos(theta));
}}
fn case_surface(view:vec3<f32>,rough:f32,base:vec3<f32>,metallic:f32)->Surface {{
 var s:Surface;
 s.normal=vec3(0.,0.,1.);
 s.geometry_normal=s.normal;
 s.coat_normal=s.normal;
 s.view=view;
 s.roughness=rough;
 s.base=vec4(base,1.);
 s.metallic=metallic;
 s.dielectric_f0=vec3(.04);
 s.specular=1.;
 s.environment_scale=1.;
 s.occlusion=1.;
 s.front=true;
 return s;
}}
fn case_reflectance(s:Surface)->SurfaceReflectance {{
 return surface_reflectance(s,surface_dfg(specular_nv(s.normal,s.view),s.roughness));
}}
"#
    )
}

/// One furnace: a surface facing +Z seen along `view`, under unit lights from
/// every direction of the hemisphere whose specular lobes `specular` scales,
/// under an iridescent film of strength, IOR and thickness in nanometres
/// `film`.
#[derive(Clone, Copy, Debug)]
struct Furnace {
    view: DVec3,
    rough: f64,
    base: [f64; 3],
    metallic: f64,
    specular: f64,
    film: [f64; 3],
}

const NO_FILM: [f64; 3] = [0., 1.3, 0.];

/// What each furnace's surface reflects: under its lights, integrated over
/// the hemisphere (the production surface_direct_light, summed by the GPU
/// over each grid row and in f64 here), and under a uniform white
/// environment (the environment path's response: the base lobe's split sum,
/// its multiple scattering and the diffuse weight, at radiance 1).
fn furnaces(cases: &[Furnace]) -> Option<Vec<(DVec3, DVec3)>> {
    let (device, queue) = test_support::device()?;
    let scene = Scene::new(&device, &queue);
    let packed: Vec<[[f32; 4]; 3]> = cases
        .iter()
        .map(|c| {
            [
                c.view.as_vec3().extend(c.rough as f32).to_array(),
                [c.base[0], c.base[1], c.base[2], c.metallic].map(|v| v as f32),
                [c.specular, c.film[0], c.film[1], c.film[2]].map(|v| v as f32),
            ]
        })
        .collect();
    let observation = format!(
        r#"{}
struct Case {{ view:vec4<f32>,base:vec4<f32>,light:vec4<f32> }}
@group(0) @binding(3) var<storage,read> cases:array<Case>;
@group(0) @binding(4) var<storage,read_write> result:array<vec4<f32>>;
@compute @workgroup_size({THREADS}) fn observe(@builtin(workgroup_id) group:vec3<u32>,@builtin(local_invocation_index) thread:u32) {{
 let c=cases[group.x];
 var s=case_surface(c.view.xyz,c.view.w,c.base.rgb,c.base.w);
 s.film=surface_film(s,c.light.y,c.light.z,c.light.w);
 let reflectance=case_reflectance(s);
 for (var row=thread;row<THETA_STEPS;row+=THREADS) {{
  var ring=vec3(0.);
  for (var column=0u;column<PHI_STEPS;column++) {{
   let light=LightSample(grid_direction(row,column),vec3(1.),1.,1.,c.light.x,NO_RECT_LIGHT,0.);
   ring+=surface_direct_light(s,reflectance,light);
  }}
  result[group.x*THETA_STEPS+row]=vec4(ring,0.);
 }}
 if thread==0u {{
  let dfg=reflectance.view_dfg;
  let lobes=specular_lobes(s.normal,s.normal,s.view,reflectance.f0,reflectance.f90,s.roughness,dfg,0.,0.,vec4(0.),lookup_tables,environment_sampler);
  let ibl=surface_ibl_weights(s,reflectance);
  result[arrayLength(&cases)*THETA_STEPS+group.x]=vec4(lobes[0].response+ibl.multi+ibl.diffuse,0.);
 }}
}}
"#,
        grid_wgsl()
    );
    let rows = test_support::observe_surface(
        &device,
        &queue,
        &scene,
        bytemuck::cast_slice(&packed),
        &observation,
        cases.len() as u32,
        cases.len() * (THETA_STEPS + 1),
    );
    let vector = |a: [f32; 4]| DVec3::new(a[0] as f64, a[1] as f64, a[2] as f64);
    Some(
        (0..cases.len())
            .map(|case| {
                let direct = (0..THETA_STEPS)
                    .map(|row| vector(rows[case * THETA_STEPS + row]) * cell(grid(row, 0).0))
                    .sum();
                (direct, vector(rows[cases.len() * THETA_STEPS + case]))
            })
            .collect(),
    )
}

/// The unit view at cosine `nv` to +Z, in the XZ plane.
pub(super) fn view(nv: f64) -> DVec3 {
    DVec3::new((1. - nv * nv).sqrt(), 0., nv)
}

/// The share of light a white dielectric of F0 0.04 and F90 1 seen along
/// `view` diffuses under unit lights from the whole hemisphere: glTF 2.0's
/// dielectric BRDF (Appendix B, fresnel_mix of a Lambertian base under the
/// specular layer, its Fresnel at v.h), integrated in f64.
pub(super) fn coupled_diffuse(view: DVec3) -> f64 {
    let mut sum = 0.;
    for row in 0..THETA_STEPS {
        for column in 0..PHI_STEPS {
            let (theta, phi) = grid(row, column);
            let l = polar(theta, phi);
            let vh = view.dot((view + l).normalize()).clamp(0., 1.);
            let fresnel = 0.04 + 0.96 * (1. - vh).powi(5);
            sum += (1. - fresnel) / PI * l.z * cell(theta);
        }
    }
    sum
}

// Plausible defects: direct light's multiple scattering loses energy (three.js
// r185's heuristic reflected 0.90, 0.84 and 0.72 at roughness 0.5, 0.75 and
// 1 seen at N.V 0.5, and 0.90 at roughness 0.25 near grazing), takes no
// gain, or reads a DFG table that cannot reach roughness 1 (three.js's 16 ×
// 16 gave 0.89); a dielectric's diffuse takes no Fresnel coupling, or takes
// it at N.V or N.L in place of V.H. The oracles are energy conservation: a
// white metal with multiple scattering reflects all a white furnace gives it
// (Heitz et al. 2016), and glTF's dielectric BRDF integrated in f64. The
// metal's bound is the DFG table's accuracy: within 0.5% up to roughness
// 0.95 at N.V from 0.05 (Bevy's 64 × 64 table against f64 integrals), 3% at
// roughness 1, whose last texel holds roughness 0.992. The dielectric's is
// f32 accumulation.
#[test]
fn a_white_furnace_conserves_energy_under_direct_light() {
    let views = [0.1, 0.3, 0.5, 0.7, 0.9, 1.];
    let mut cases = Vec::new();
    for rough in [0.25, 0.5, 0.75, 1.] {
        for &nv in &views {
            cases.push(Furnace {
                view: view(nv),
                rough,
                base: [1.; 3],
                metallic: 1.,
                specular: 1.,
                film: NO_FILM,
            });
        }
    }
    let first_dielectric = cases.len();
    for &nv in &views {
        cases.push(Furnace {
            view: view(nv),
            rough: 0.5,
            base: [1.; 3],
            metallic: 0.,
            specular: 0.,
            film: NO_FILM,
        });
    }
    let Some(observed) = furnaces(&cases) else {
        return;
    };
    let mut worst = [0f64; 3];
    for (case, (direct, _)) in cases[..first_dielectric].iter().zip(&observed) {
        let bound = if case.rough < 1. { 0.01 } else { 0.035 };
        let deviation = (*direct - DVec3::ONE).abs().max_element();
        let at = usize::from(case.rough == 1.);
        worst[at] = worst[at].max(deviation);
        assert!(
            (*direct - DVec3::ONE).abs().max_element() <= bound,
            "white metal {case:?}: reflects {direct:?} of a white furnace"
        );
    }
    for (case, (direct, _)) in cases[first_dielectric..]
        .iter()
        .zip(&observed[first_dielectric..])
    {
        let expected = coupled_diffuse(case.view);
        worst[2] = worst[2].max((*direct - DVec3::splat(expected)).abs().max_element() / expected);
        assert!(
            (*direct - DVec3::splat(expected)).abs().max_element() <= 0.001 * expected,
            "white dielectric under diffuse-only lights {case:?}: {direct:?}, glTF {expected}"
        );
    }
    eprintln!(
        "white furnace: metal within {:.5} below roughness 1 and {:.5} at 1; dielectric within {:.6} of glTF",
        worst[0], worst[1], worst[2]
    );
}

// Plausible defects: a film's reflectance taken by the specular lobes but
// not from the diffuse beneath them, under the environment (its diffuse
// weight at the bare dielectric's F0) or under lights (coupled at the bare
// dielectric's Fresnel); or the diffuse kept by the film's weakest channel,
// or each channel's, in place of its strongest. The oracles: a film that
// absorbs nothing over a white base reflects all a white environment gives
// it; and under diffuse-only lights from the whole hemisphere a dielectric
// under a film keeps 1 less the strongest channel of the film's Fresnel at
// N.V (KHR_materials_iridescence's rgb_mix), the film the exact thin-film
// sum (iridescence_tests::thin_film). The environment's bound is f32
// rounding; the lights' is the thin film's (0.01) and the grid's.
#[test]
fn a_white_furnace_conserves_energy_under_a_film() {
    let film = [1., 1.8, 400.];
    let cases: Vec<Furnace> = [1., 0.7]
        .into_iter()
        .map(|nv| Furnace {
            view: view(nv),
            rough: 0.5,
            base: [1.; 3],
            metallic: 0.,
            specular: 0.,
            film,
        })
        .collect();
    let Some(observed) = furnaces(&cases) else {
        return;
    };
    for (case, (direct, environment)) in cases.iter().zip(&observed) {
        assert!(
            (*environment - DVec3::ONE).abs().max_element() <= 1e-4,
            "white dielectric under a film {case:?}: reflects {environment:?} of a white environment"
        );
        let thin = super::iridescence_tests::thin_film(film[1], 1.5, film[2], case.view.z);
        let kept = 1. - thin.into_iter().fold(0., f64::max);
        assert!(
            (*direct - DVec3::splat(kept)).abs().max_element() <= 0.011,
            "white dielectric under a film and diffuse-only lights {case:?}: {direct:?}, rgb_mix {kept}"
        );
    }
}

// Plausible defects: a diffuse-only light (`Light::specular` 0) dims a
// coated or sheened base by a layer whose lobe it does not light, on the
// base's front lobe or its passed-through one. The oracle is the bare base:
// under diffuse-only lights from every direction of both hemispheres, a
// base beneath a coat, a sheen or both diffuses exactly what the same base
// without them does, on either side. The bound is f32 accumulation.
#[test]
fn diffuse_only_lights_light_the_base_whole_beneath_its_layers() {
    let layers = [(0., [0.; 3]), (1., [0.; 3]), (0., [1.; 3]), (1., [1.; 3])];
    let mut cases = Vec::new();
    for nv in [0.3, 0.8] {
        for transmission in [0., 0.5] {
            for (coat, sheen) in layers {
                cases.push(Layered {
                    view: view(nv),
                    coat,
                    sheen,
                    transmission,
                    light_specular: 0.,
                    ..Layered::default()
                });
            }
        }
    }
    let Some(observed) = observe_lit(&cases) else {
        return;
    };
    for (cases, observed) in cases
        .chunks(layers.len())
        .zip(observed.chunks(layers.len()))
    {
        let [bare_above, bare_below, _] = observed[0];
        for (case, [above, below, _]) in cases.iter().zip(observed).skip(1) {
            for (side, layered, bare) in [("front", above, bare_above), ("back", below, bare_below)]
            {
                assert!(
                    (*layered - bare).abs().max_element() <= 1e-5 * bare.max_element().max(1e-3),
                    "{case:?}, {side}: {layered:?}, {bare:?} without its layers"
                );
            }
        }
    }
}

// Plausible defects: a dynamic GI probe ray's hit, which takes diffuse light
// alone, dims its base by a coat it does not evaluate: its indirect light,
// its emission or the one light it draws. The oracle is the bare hit: a
// coated hit, through shade_lit as a probe hit and probe_hit_light, takes
// exactly what the same hit without its coat does, under a hemisphere fill
// and a directional light. The bound is f32 rounding.
#[test]
fn a_probe_ray_s_hit_takes_no_coat() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let settings = quiet_settings();
    let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
    let mut scene = Scene::new(&device, &queue);
    let mut input = dark_input();
    input.hemisphere_light = HemisphereLight {
        sky_color: [1.; 3],
        ground_color: [0.5; 3],
        intensity: 1.,
    };
    input.directional_lights[0] = Some(DirectionalLight {
        direction: Vec3::new(0.3, 0., -1.),
        color: [1.; 3],
        illuminance: 1.,
        ..Default::default()
    });
    let observation = format!(
        r#"{}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
@compute @workgroup_size(1) fn observe() {{
 let context=ShadeContext(vec2(0.),SHADOW_RECEIVER_PROBE_HIT,false,true,cluster_range(vec3(0.),vec2(0.)),untraced_reflection());
 for (var coat=0u;coat<2u;coat++) {{
  var s=case_surface(normalize(vec3(-.6,0.,.8)),.5,vec3(.8),0.);
  s.lightmap_uv=vec2(-1.);
  s.coat=f32(coat);
  s.coat_roughness=.3;
  s.emission=vec3(.25);
  output[coat*2u]=vec4(shade_lit(s,context).color,0.);
  output[coat*2u+1u]=vec4(probe_hit_light(s,cluster_range(s.position,vec2(0.)),vec3(0.)),0.);
 }}
}}
"#,
        grid_wgsl()
    );
    let rows = test_support::observe_ray_hits(
        &device,
        &queue,
        &mut renderer,
        &mut scene,
        &input,
        &settings,
        &observation,
        4,
    );
    let vector = |a: [f32; 4]| DVec3::new(a[0] as f64, a[1] as f64, a[2] as f64);
    for (label, bare, coated) in [
        ("indirect light and emission", rows[0], rows[2]),
        ("its light", rows[1], rows[3]),
    ] {
        let (bare, coated) = (vector(bare), vector(coated));
        assert!(bare.min_element() > 0.01, "{label}: {bare:?}");
        assert!(
            (coated - bare).abs().max_element() <= 1e-5 * bare.max_element(),
            "{label}: coated {coated:?}, {bare:?} without its coat"
        );
    }
}

// Plausible defect: a light's specular weight above 1 dims a coated or
// sheened base further than the physical layering does, darkening it, where
// the weight is meant only to brighten the layers' lobes (Godot's
// light_specular scales specular alone). The oracle is the weight-1 base:
// a surface's passed-through lobe, which no specular lobe adds to, under
// lights from every direction behind it, is the same under weights 2 and 4
// as under 1, beneath a coat, a sheen or both. The bound is f32
// accumulation.
#[test]
fn specular_weights_above_1_leave_the_base_beneath_its_layers_as_at_1() {
    let layers = [(1., [0.; 3]), (0., [1.; 3]), (1., [1.; 3])];
    let weights = [1., 2., 4.];
    let mut cases = Vec::new();
    for nv in [0.3, 0.8] {
        for (coat, sheen) in layers {
            for light_specular in weights {
                cases.push(Layered {
                    view: view(nv),
                    coat,
                    sheen,
                    transmission: 1.,
                    light_specular,
                    ..Layered::default()
                });
            }
        }
    }
    let Some(observed) = observe_lit(&cases) else {
        return;
    };
    for (cases, observed) in cases
        .chunks(weights.len())
        .zip(observed.chunks(weights.len()))
    {
        let [_, at_1, _] = observed[0];
        assert!(at_1.max_element() > 0., "{:?}: lit from behind", cases[0]);
        for (case, [_, below, _]) in cases.iter().zip(observed).skip(1) {
            assert!(
                (*below - at_1).abs().max_element() <= 1e-5 * at_1.max_element(),
                "{case:?}: {below:?} behind, {at_1:?} at weight 1"
            );
        }
    }
}

// Plausible defects: direct light and the environment scatter a metal's
// light by different models, so a rough metal is darker or brighter and
// shifts hue under the sun against the sky (three.js r185's direct heuristic
// against its environment's Fdez-Agüera: 10–35% darker; Filament's
// 1 + F0 (1/E - 1) against it: up to 19% brighter on iron at roughness 1);
// the lobe's Fresnel or visibility differs from what the DFG table
// integrates. The oracle is S3D-5's one model: the same uniform light, as
// lights from every direction or as the environment, reflects the same
// energy on every channel. The bound is the DFG table's accuracy, as above.
#[test]
fn direct_light_and_the_environment_reflect_alike() {
    let metals = [
        ("gold", [1., 0.766, 0.336]),
        ("copper", [0.955, 0.638, 0.538]),
        ("iron", [0.56, 0.57, 0.58]),
    ];
    let mut cases = Vec::new();
    for (_, base) in metals {
        for rough in [0.25, 0.5, 0.75, 1.] {
            for nv in [0.3, 0.7] {
                cases.push(Furnace {
                    view: view(nv),
                    rough,
                    base,
                    metallic: 1.,
                    specular: 1.,
                    film: NO_FILM,
                });
            }
        }
    }
    let Some(observed) = furnaces(&cases) else {
        return;
    };
    let mut worst = [0f64; 2];
    for (case, (direct, environment)) in cases.iter().zip(observed) {
        let bound = if case.rough < 1. { 0.01 } else { 0.035 };
        let ratio = direct / environment;
        let at = usize::from(case.rough == 1.);
        worst[at] = worst[at].max((ratio - DVec3::ONE).abs().max_element());
        assert!(
            (ratio - DVec3::ONE).abs().max_element() <= bound,
            "{case:?}: direct {direct:?} against the environment's {environment:?}"
        );
    }
    eprintln!(
        "direct against environment: within {:.5} below roughness 1 and {:.5} at 1",
        worst[0], worst[1]
    );
}

/// A camera at the origin looking down -Z, with no light, fill or
/// environment, and baked lighting on.
pub(super) fn dark_input() -> FrameInput {
    let mut input = FrameInput::new(Camera {
        view: Mat4::IDENTITY,
        projection: crate::perspective(1., 1., 0.1),
        eye: Vec3::ZERO,
    });
    input.backdrop = Backdrop::Color([0.; 3]);
    input.hemisphere_light = HemisphereLight {
        sky_color: [0.; 3],
        ground_color: [0.; 3],
        intensity: 0.,
    };
    input.baked_lighting = true;
    input
}

pub(super) fn quiet_settings() -> Settings {
    Settings {
        antialiasing: settings::Antialiasing::Off,
        bloom: settings::Bloom::Off,
        ambient_occlusion: settings::AmbientOcclusionQuality::Off,
        screen_space_reflections: settings::ScreenSpaceReflections::Off,
        world_space_reflections: settings::WorldSpaceReflections::Off,
        dynamic_gi: settings::DynamicGiQuality::Off,
        ..Settings::default()
    }
}

/// The irradiance / PI every source holds in `one_rule_for_every_indirect_source`.
const IRRADIANCE: f32 = 0.5;

// Plausible defects: a source of indirect irradiance weights a material's
// diffuse by its own rule (lightmaps and atlas charts by 1 - F0 without
// multiple scattering, the hemisphere fill by 1, against the environment's
// and volumes' 1 - E plus multiple scattering), or leaves the metal's
// multiple scattering out. The oracle is the Surface shading contract: a
// surface reflects the same irradiance alike whatever holds it. A grey
// dielectric and a rough gold, seen at N.V 0.3 where 1 - F0 and 1 - E part
// by 6%, take irradiance / PI of 0.5 from the environment, the hemisphere
// fill, the irradiance volume, a lightmap, an irradiance atlas chart and a
// moving instance's ambient cube in turn; all match the environment's
// within binary16 storage and the environment's filtering, 0.5%.
#[test]
fn one_rule_for_every_indirect_source() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let settings = quiet_settings();
    let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
    let mut scene = Scene::new(&device, &queue);
    // A static square whose material takes the lightmap, and the chart the
    // atlas lights.
    let mut model = test_support::cube();
    model.meshes[0].vertices = [(-1., -1.), (1., -1.), (1., 1.), (-1., 1.)]
        .map(|(x, z)| asset::Vertex {
            tangent: [0.; 4],
            position: [x, -50., z],
            normal: [0., 1., 0.],
            uv: [0.5; 2],
            color: [1.; 4],
            lightmap_uv: [0.5; 2],
            lightmap_bounds: [0., 0., 1., 1.],
        })
        .to_vec();
    model.meshes[0].indices = vec![0, 1, 2, 0, 2, 3];
    let (world, _) = test_support::add_static(&device, &queue, &mut scene, model);
    let irradiance = [IRRADIANCE; 3];
    scene
        .set_lightmap(
            &device,
            &queue,
            &Lightmap {
                size: [2, 2],
                uv_scale_offset: [1., 1., 0., 0.],
                irradiance: vec![irradiance; 4],
                directionality: vec![],
            },
            &world.materials,
        )
        .unwrap();
    scene
        .set_static_irradiance_atlas(
            &device,
            &queue,
            &IrradianceAtlas {
                size: [4, 4],
                irradiance: vec![irradiance; 16],
                back_irradiance: vec![irradiance; 16],
                directionality: vec![],
                back_directionality: vec![],
            },
        )
        .unwrap();
    // A volume about the receiver at (0, 0, 10), away from the others at the
    // origin.
    let volume = IrradianceVolume {
        origin: Vec3::new(-2., -2., 8.),
        cell_size: Vec3::splat(1.),
        cells: [4, 4, 4],
    };
    scene
        .set_irradiance_volume(&device, &queue, Some(volume))
        .unwrap();
    let cells = vec![
        IrradianceCell {
            irradiance: crate::static_lighting::AmbientCube {
                irradiance: [irradiance; 6],
            },
            sky_visibility: [0.; 6],
        };
        64
    ];
    let region = crate::PreparedIrradianceRegion::new(volume.origin, volume.cells, &cells).unwrap();
    scene.write_irradiance_cells(&queue, &region).unwrap();
    let texel: Vec<u8> = [IRRADIANCE, IRRADIANCE, IRRADIANCE, 1.]
        .iter()
        .flat_map(|&value| test_support::to_half(value).to_le_bytes())
        .collect();
    let environment = scene
        .add_environment(
            &device,
            &queue,
            &test_support::environment([255; 4], &texel),
        )
        .unwrap();
    // Each source: what the frame lights and how the receiver takes it.
    // (name, environment, hemisphere fill, receiver position, lightmapped,
    // charted, moving)
    let sources = [
        ("environment", true, false, Vec3::ZERO, false, false, false),
        (
            "hemisphere fill",
            false,
            true,
            Vec3::ZERO,
            false,
            false,
            false,
        ),
        (
            "irradiance volume",
            false,
            false,
            Vec3::new(0., 0., 10.),
            false,
            false,
            false,
        ),
        ("lightmap", false, false, Vec3::ZERO, true, false, false),
        (
            "irradiance atlas",
            false,
            false,
            Vec3::ZERO,
            false,
            true,
            false,
        ),
        ("ambient cube", false, false, Vec3::ZERO, false, false, true),
    ];
    let mut observed = Vec::new();
    for (name, lit_by_environment, filled, position, lightmapped, charted, moving) in sources {
        let mut input = dark_input();
        if lit_by_environment {
            input.environment = Some(environment);
        }
        if filled {
            input.hemisphere_light = HemisphereLight {
                sky_color: [1.; 3],
                ground_color: [1.; 3],
                intensity: IRRADIANCE * std::f32::consts::PI,
            };
        }
        let observation = format!(
            r#"{}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
@compute @workgroup_size(1) fn observe() {{
 let view=normalize(vec3(.95394,.3,0.));
 for (var metal=0u;metal<2u;metal++) {{
  let gold=metal==1u;
  var s=case_surface(view,select(.5,.6,gold),select(vec3(.5),vec3(1.,.766,.336),gold),select(0.,1.,gold));
  s.normal=vec3(0.,1.,0.);
  s.geometry_normal=s.normal;
  s.coat_normal=s.normal;
  s.position=vec3({:?},{:?},{:?});
  s.baked={lightmapped};
  s.moving={moving};
  s.lightmap_uv=select(vec2(-1.),vec2(.5),{lightmapped}||{charted});
  s.lightmap_bounds=vec4(0.,0.,1.,1.);
  for (var face=0u;face<6u;face++) {{
   s.baked_irradiance[face]=vec4({IRRADIANCE:?});
  }}
  let context=ShadeContext(vec2(0.),SHADOW_RECEIVER_CAMERA,false,false,cluster_range(s.position,vec2(0.)),untraced_reflection());
  output[metal]=vec4(shade_lit(s,context).color,0.);
 }}
}}
"#,
            grid_wgsl(),
            position.x,
            position.y,
            position.z,
        );
        let rows = test_support::observe_ray_hits(
            &device,
            &queue,
            &mut renderer,
            &mut scene,
            &input,
            &settings,
            &observation,
            2,
        );
        observed.push((name, rows));
    }
    let (_, reference) = &observed[0];
    assert!(reference.iter().all(|c| c[0] > 0.01), "{reference:?}");
    for (name, rows) in &observed[1..] {
        for (material, (row, expected)) in ["grey dielectric", "rough gold"]
            .iter()
            .zip(rows.iter().zip(reference))
        {
            for channel in 0..3 {
                assert!(
                    (row[channel] - expected[channel]).abs() <= 0.005 * expected[channel],
                    "{material} under the {name}: {row:?}, under the environment {expected:?}"
                );
            }
        }
    }
}

/// The light a white metal (F0 1) facing +Z at perceptual roughness `rough`
/// reflects toward `view` from a disc of directions about unit `centre`, of
/// angular radius `radius` and uniform radiance `radiance`: GGX with
/// height-correlated Smith visibility, integrated over the disc in f64.
fn disc_reference(view: DVec3, rough: f64, centre: DVec3, radius: f64, radiance: f64) -> f64 {
    let a2 = rough.powi(4);
    let tangent = centre.cross(DVec3::Y).normalize();
    let bitangent = centre.cross(tangent);
    let steps = 1000;
    let mut sum = 0.;
    for i in 0..steps {
        let theta = (i as f64 + 0.5) / steps as f64 * radius;
        for j in 0..steps {
            let phi = (j as f64 + 0.5) / steps as f64 * 2. * PI;
            let l =
                centre * theta.cos() + (tangent * phi.cos() + bitangent * phi.sin()) * theta.sin();
            let (nl, nv) = (l.z, view.z);
            if nl <= 0. {
                continue;
            }
            let nh = (view + l).normalize().z;
            let d = a2 / (PI * (nh * nh * (a2 - 1.) + 1.).powi(2));
            let visibility = 0.5
                / (nl * (nv * nv * (1. - a2) + a2).sqrt() + nv * (nl * nl * (1. - a2) + a2).sqrt());
            let solid_angle = theta.sin() * (radius / steps as f64) * (2. * PI / steps as f64);
            sum += d * visibility * nl * solid_angle;
        }
    }
    sum * radiance
}

/// A sized light's highlight on a white metal facing +Z: what it reflects
/// along `peak_view`, the mirror of the light's centre, and its energy, the
/// reflected light integrated over the hemisphere of views (each weighted by
/// its cosine). `light` draws the LightSample for a surface `s` in WGSL.
fn highlight(
    (device, queue): (&wgpu::Device, &wgpu::Queue),
    renderer: &mut Renderer,
    scene: &mut Scene,
    input: &FrameInput,
    rough: f64,
    peak_view: DVec3,
    light: &str,
) -> (f64, f64) {
    let observation = format!(
        r#"{}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
fn reflected(view:vec3<f32>)->f32 {{
 let s=case_surface(view,{rough:?},vec3(1.),1.);
 let reflectance=case_reflectance(s);
 return surface_direct_light(s,reflectance,{light}).g;
}}
@compute @workgroup_size({THREADS}) fn observe(@builtin(local_invocation_index) thread:u32) {{
 for (var row=thread;row<THETA_STEPS;row+=THREADS) {{
  var ring=0.;
  for (var column=0u;column<PHI_STEPS;column++) {{
   let view=grid_direction(row,column);
   ring+=reflected(view)*view.z;
  }}
  output[row]=vec4(ring,0.,0.,0.);
 }}
 if thread==0u {{
  output[THETA_STEPS]=vec4(reflected(vec3({:?},{:?},{:?})),0.,0.,0.);
 }}
}}
"#,
        grid_wgsl(),
        peak_view.x as f32,
        peak_view.y as f32,
        peak_view.z as f32,
    );
    let rows = test_support::observe_ray_hits(
        device,
        queue,
        renderer,
        scene,
        input,
        &quiet_settings(),
        &observation,
        THETA_STEPS + 1,
    );
    let energy = (0..THETA_STEPS)
        .map(|row| rows[row][0] as f64 * cell(grid(row, 0).0))
        .sum();
    (rows[THETA_STEPS][0] as f64, energy)
}

// Plausible defects: a light's radius or the directional light's disc leaves
// its highlight a point (a mirror-like surface then shows a sphere 8 to
// 3600 times too bright at its centre), widens it without Karis's
// normalisation (7 to 4700 times the energy), or widens it by its
// normal-incidence angle alone, which reflects about 1/cos of the energy of
// a light at an elevation from the normal (1.2 times it at 0.6 rad, 1.8 at
// 1.0, 3.7 at 1.3). The oracles are the sphere's or disc's own light: along
// the mirror direction of its centre, the f64 integral of GGX over the
// directions it fills at its radiance (a sphere of intensity I and radius r
// has radiance I / (π r²), a disc of illuminance E and angular radius θ,
// E / (π sin² θ)), and in all, its irradiance at the surface (I cos θ / d²,
// exact for a sphere above the horizon, and E cos θ), which a white metal
// reflects whole. The representative point is an approximation: against
// those integrals the shipped widening measured 0.61–0.98 along the mirror
// direction and 0.87–0.98 in energy over these cases at elevations 0.6, 1.0
// and 1.3 rad (f64), so the bounds are 0.55–1.1 and 0.8–1.1, which also
// hold the multiple-scattering gain and f32.
#[test]
fn a_sized_light_spreads_its_highlight_over_its_sphere_or_disc() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    let settings = quiet_settings();
    let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
    let within = |ratio: f64, low: f64, high: f64| (low..=high).contains(&ratio);
    for elevation in [0.6f64, 1.0, 1.3] {
        let centre = DVec3::new(elevation.sin(), 0., elevation.cos());
        let mirror = DVec3::new(-centre.x, 0., centre.z);
        // (perceptual roughness, radius over distance)
        for (rough, size) in [(0.045, 0.05), (0.1, 0.05), (0.1, 0.2), (0.25, 0.2)] {
            let distance = 2.;
            let radius = size * distance;
            let mut scene = Scene::new(&device, &queue);
            scene
                .add_light(
                    &device,
                    &queue,
                    Light {
                        position: (centre * distance).as_vec3(),
                        shape: LightShape::Point {
                            radius: radius as f32,
                        },
                        color: [1.; 3],
                        intensity: 1.,
                        range: 1000.,
                        baked: false,
                        specular: 1.,
                        casts_shadow: false,
                        ..Default::default()
                    },
                )
                .unwrap();
            let (peak, energy) = highlight(
                (&device, &queue),
                &mut renderer,
                &mut scene,
                &dark_input(),
                rough,
                mirror,
                "scene_light_sample(0u,s.position,s.normal,s.coat_normal,s.geometry_normal,vec2(0.),SHADOW_RECEIVER_CAPTURE,false,s.position,0.)",
            );
            let angular = (radius / distance).asin();
            let expected =
                disc_reference(mirror, rough, centre, angular, 1. / (PI * radius * radius));
            let irradiance = centre.z / (distance * distance);
            eprintln!(
                "sphere at elevation {elevation}, roughness {rough}, radius/distance {size}: mirror {:.3} of the sphere's, energy {:.3}",
                peak / expected,
                energy / irradiance
            );
            // Where the sphere is wider than the lobe, a mirror-like surface
            // shows it; on a rougher one the lobe blurs it and the energy
            // alone is the oracle.
            assert!(
                rough > 0.1 || within(peak / expected, 0.55, 1.1),
                "sphere at elevation {elevation}, roughness {rough}, radius/distance {size}: {peak} along the mirror, the sphere gives {expected}"
            );
            assert!(
                within(energy / irradiance, 0.8, 1.1),
                "sphere at elevation {elevation}, roughness {rough}, radius/distance {size}: reflects {energy} of irradiance {irradiance}"
            );
        }
        // The directional light's disc, at an angular radius of 0.05.
        let mut scene = Scene::new(&device, &queue);
        for rough in [0.045, 0.1] {
            let mut input = dark_input();
            input.directional_lights[0] = Some(DirectionalLight {
                direction: -centre.as_vec3(),
                illuminance: 1.,
                angular_diameter: 0.1,
                ..Default::default()
            });
            let (peak, energy) = highlight(
                (&device, &queue),
                &mut renderer,
                &mut scene,
                &input,
                rough,
                mirror,
                "directional_light_sample(0u,s.position,s.normal,s.coat_normal,s.geometry_normal,ShadeContext(vec2(0.),SHADOW_RECEIVER_CAPTURE,false,false,cluster_range(s.position,vec2(0.)),untraced_reflection()),false,s.position)",
            );
            let angular = 0.05f64;
            let expected = disc_reference(
                mirror,
                rough,
                centre,
                angular,
                1. / (PI * angular.sin().powi(2)),
            );
            eprintln!(
                "disc at elevation {elevation}, roughness {rough}: mirror {:.3} of the disc's, energy {:.3}",
                peak / expected,
                energy / centre.z
            );
            assert!(
                within(peak / expected, 0.55, 1.1),
                "disc at elevation {elevation}, roughness {rough}: {peak} along the mirror, the disc gives {expected}"
            );
            assert!(
                within(energy / centre.z, 0.8, 1.1),
                "disc at elevation {elevation}, roughness {rough}: reflects {energy} of irradiance {}",
                centre.z
            );
        }
    }
}

// Plausible defects: the directional light's sample skips the front's
// shadow lookup where a lobe still takes the light, so the front goes dark
// there: where the coat's normal faces the light and the base's does not
// (a test on the base normal alone), or within the disc's radius below the
// base's horizon, where the sized light's representative point
// (pbr_sized_light) lights the specular lobes (a test without the disc).
// The oracle is the production lobes under the same light with full
// visibility, the light the front takes before any shadow: skipping a
// lookup must change none of it. Base normals sweep the sphere, each with
// its coat normal tilted toward the light by 0, 0.4 and 0.9 rad, seen
// between the two; under a disc of angular diameter 0.2 each surface
// reflects what the full-visibility light gives it within f32 rounding.
#[test]
fn the_directional_light_s_front_skips_no_light_it_gives() {
    let Some((device, queue)) = test_support::device() else {
        return;
    };
    const ROWS: usize = 128;
    const COLUMNS: usize = 256;
    let settings = quiet_settings();
    let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
    let mut scene = Scene::new(&device, &queue);
    let mut input = dark_input();
    input.directional_lights[0] = Some(DirectionalLight {
        direction: -Vec3::new(0.3, 0.2, 0.93).normalize(),
        illuminance: 1.,
        angular_diameter: 0.2,
        ..Default::default()
    });
    let observation = format!(
        r#"{}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
@compute @workgroup_size({ROWS}) fn observe(@builtin(local_invocation_index) row:u32) {{
 let light=frame.directional_lights[0];
 let l=normalize(light.direction_to_light);
 var mismatched=0.;
 var behind=0.;
 var most=0.;
 for (var column=0u;column<{COLUMNS}u;column++) {{
  let theta=(f32(row)+.5)/f32({ROWS})*3.141592653589793;
  let phi=(f32(column)+.5)/f32({COLUMNS})*6.283185307179586;
  let n=vec3(sin(theta)*cos(phi),sin(theta)*sin(phi),cos(theta));
  let across=l-n*dot(n,l);
  let toward=select(n,normalize(across),dot(across,across)>1e-8);
  for (var tilt=0u;tilt<3u;tilt++) {{
   let angle=array<f32,3>(0.,.4,.9)[tilt];
   let coat_normal=normalize(n*cos(angle)+toward*sin(angle));
   var s=case_surface(normalize(n+coat_normal),.3,vec3(1.),0.);
   s.normal=n;
   s.geometry_normal=n;
   s.coat_normal=coat_normal;
   s.coat=1.;
   s.coat_roughness=.3;
   let reflectance=case_reflectance(s);
   let context=ShadeContext(vec2(0.),SHADOW_RECEIVER_CAPTURE,false,false,cluster_range(s.position,vec2(0.)),untraced_reflection());
   let sampled=surface_direct_light(s,reflectance,directional_light_sample(0u,s.position,s.normal,s.coat_normal,s.geometry_normal,context,false,s.position));
   let full=surface_direct_light(s,reflectance,LightSample(l,light.color*light.illuminance,1.,0.,1.,NO_RECT_LIGHT,light.disc_radius));
   if any(abs(sampled-full)>full*1e-4+1e-12) {{
    mismatched+=1.;
   }}
   if dot(n,l)<=0. && any(full>vec3(0.)) {{
    behind+=1.;
   }}
   most=max(most,max(full.r,max(full.g,full.b)));
  }}
 }}
 output[row]=vec4(mismatched,behind,most,0.);
}}
"#,
        grid_wgsl(),
    );
    let rows = test_support::observe_ray_hits(
        &device,
        &queue,
        &mut renderer,
        &mut scene,
        &input,
        &settings,
        &observation,
        ROWS,
    );
    let total = |channel: usize| rows.iter().map(|row| row[channel] as f64).sum::<f64>();
    let most = rows.iter().map(|row| row[2]).fold(0f32, f32::max);
    eprintln!(
        "{} surfaces take the light with the base normal turned away; brightest {most}",
        total(1)
    );
    assert!(most > 0.1, "the light reflects {most} at most");
    assert_eq!(
        total(0),
        0.,
        "surfaces whose front reflects other than the full-visibility light gives"
    );
}

/// A surface facing +Z at the origin for `observe_lit`: seen along `view` at
/// perceptual roughness `rough`, of base colour `base` and metallic
/// `metallic`, a dielectric of F0 `dielectric_f0` and F90 1 (0 and 0 for a
/// bare Lambertian), under a coat of strength `coat`, a sheen of colour
/// `sheen` and perceptual roughness `sheen_rough`, passing `transmission`
/// of its diffuse light to its other side in `transmission_color` across a
/// volume `volume_thickness` world metres thick of attenuation coefficient
/// `attenuation` per metre, at material occlusion `occlusion`; its lights'
/// specular lobes scaled by `light_specular`.
#[derive(Clone, Copy, Debug)]
pub(super) struct Layered {
    pub view: DVec3,
    pub rough: f64,
    pub base: [f64; 3],
    pub metallic: f64,
    pub dielectric_f0: f64,
    pub coat: f64,
    pub sheen: [f64; 3],
    pub sheen_rough: f64,
    pub transmission: f64,
    pub transmission_color: [f64; 3],
    pub volume_thickness: f64,
    pub attenuation: [f64; 3],
    pub occlusion: f64,
    pub light_specular: f64,
}

impl Default for Layered {
    fn default() -> Self {
        Self {
            view: DVec3::Z,
            rough: 0.5,
            base: [1.; 3],
            metallic: 0.,
            dielectric_f0: 0.04,
            coat: 0.,
            sheen: [0.; 3],
            sheen_rough: 0.5,
            transmission: 0.,
            transmission_color: [1.; 3],
            volume_thickness: 0.,
            attenuation: [0.; 3],
            occlusion: 1.,
            light_specular: 1.,
        }
    }
}

/// What each case reflects toward its view: under unit lights from every
/// direction of the hemisphere above it and of the one below it, each
/// integrated (the production surface_direct_light, summed by the GPU over
/// each grid row and in f64 here), and under a uniform environment of
/// radiance 1 all around, as a probe capture's surface takes it (the
/// production shade_lit, its environment specular and material occlusion
/// included), in that order.
pub(super) fn observe_lit(cases: &[Layered]) -> Option<Vec<[DVec3; 3]>> {
    let (device, queue) = test_support::device()?;
    let settings = quiet_settings();
    let mut renderer = Renderer::for_test(&device, &queue, [16, 16], &settings);
    let mut scene = Scene::new(&device, &queue);
    let texel: Vec<u8> = [1f32; 4]
        .iter()
        .flat_map(|&value| test_support::to_half(value).to_le_bytes())
        .collect();
    let environment = scene
        .add_environment(
            &device,
            &queue,
            &test_support::environment([255; 4], &texel),
        )
        .unwrap();
    let mut input = dark_input();
    input.environment = Some(environment);
    let v3 = |v: [f64; 3]| {
        format!(
            "vec3({:?},{:?},{:?})",
            v[0] as f32, v[1] as f32, v[2] as f32
        )
    };
    let surfaces: Vec<String> = cases
        .iter()
        .map(|c| {
            format!(
                "Layered({},{:?},{},{:?},{:?},{:?},{},{:?},{:?},{},{:?},{},{:?},{:?})",
                v3(c.view.to_array()),
                c.rough as f32,
                v3(c.base),
                c.metallic as f32,
                c.dielectric_f0 as f32,
                c.coat as f32,
                v3(c.sheen),
                c.sheen_rough as f32,
                c.transmission as f32,
                v3(c.transmission_color),
                c.volume_thickness as f32,
                v3(c.attenuation),
                c.occlusion as f32,
                c.light_specular as f32,
            )
        })
        .collect();
    let count = cases.len();
    let observation = format!(
        r#"{}
struct Layered {{ view:vec3<f32>,rough:f32,base:vec3<f32>,metallic:f32,dielectric_f0:f32,coat:f32,sheen:vec3<f32>,sheen_rough:f32,transmission:f32,transmission_color:vec3<f32>,volume_thickness:f32,attenuation:vec3<f32>,occlusion:f32,light_specular:f32 }}
@group(3) @binding(0) var<storage,read_write> output:array<vec4<f32>>;
fn layered(c:Layered)->Surface {{
 var s=case_surface(c.view,c.rough,c.base,c.metallic);
 s.dielectric_f0=vec3(c.dielectric_f0);
 s.specular=select(0.,1.,c.dielectric_f0>0.);
 s.coat=c.coat;
 s.coat_roughness=.3;
 s.sheen=c.sheen;
 s.sheen_roughness=c.sheen_rough;
 s.diffuse_transmission=c.transmission;
 s.diffuse_transmission_color=c.transmission_color;
 s.volume_thickness=c.volume_thickness;
 s.volume_attenuation=c.attenuation;
 s.occlusion=c.occlusion;
 s.lightmap_uv=vec2(-1.);
 return s;
}}
@compute @workgroup_size({THREADS}) fn observe(@builtin(local_invocation_index) thread:u32) {{
 var cases=array<Layered,{count}>({});
 for (var index=0u;index<{count}u;index++) {{
  let c=cases[index];
  let s=layered(c);
  let reflectance=case_reflectance(s);
  for (var row=thread;row<THETA_STEPS;row+=THREADS) {{
   var above=vec3(0.);
   var below=vec3(0.);
   for (var column=0u;column<PHI_STEPS;column++) {{
    let l=grid_direction(row,column);
    above+=surface_direct_light(s,reflectance,LightSample(l,vec3(1.),1.,1.,c.light_specular,NO_RECT_LIGHT,0.));
    below+=surface_direct_light(s,reflectance,LightSample(vec3(l.xy,-l.z),vec3(1.),1.,1.,c.light_specular,NO_RECT_LIGHT,0.));
   }}
   output[(index*THETA_STEPS+row)*2u]=vec4(above,0.);
   output[(index*THETA_STEPS+row)*2u+1u]=vec4(below,0.);
  }}
  if thread==0u {{
   let context=ShadeContext(vec2(0.),SHADOW_RECEIVER_CAPTURE,true,true,cluster_range(s.position,vec2(0.)),untraced_reflection());
   output[{count}u*THETA_STEPS*2u+index]=vec4(shade_lit(s,context).color,0.);
  }}
 }}
}}
"#,
        grid_wgsl(),
        surfaces.join(","),
    );
    let rows = test_support::observe_ray_hits(
        &device,
        &queue,
        &mut renderer,
        &mut scene,
        &input,
        &settings,
        &observation,
        count * (THETA_STEPS * 2 + 1),
    );
    let vector = |a: [f32; 4]| DVec3::new(a[0] as f64, a[1] as f64, a[2] as f64);
    Some(
        (0..count)
            .map(|case| {
                let side = |half: usize| {
                    (0..THETA_STEPS)
                        .map(|row| {
                            vector(rows[(case * THETA_STEPS + row) * 2 + half])
                                * cell(grid(row, 0).0)
                        })
                        .sum()
                };
                [
                    side(0),
                    side(1),
                    vector(rows[count * THETA_STEPS * 2 + case]),
                ]
            })
            .collect(),
    )
}