threers 0.0.4

Drop-in three.js replacement for Rust and WebAssembly (wgpu) — THREE.* API, scene graph, PBR, post-fx, mesh BVH, CSG, an OpenSCAD front end with a watertight exact-CSG kernel, headless render, and native media codecs
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
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
//! The wgpu compute backend: the same path tracer, as a kernel.
//!
//! # What makes it fast
//!
//! **One bind group, four storage buffers.** WebGPU's baseline guarantees only
//! four storage buffers per stage, and a scene needs a dozen arrays. They are
//! packed into `nodes` / `data` / `idx` / `accum` and addressed through offsets
//! in the uniform block. That keeps the pipeline valid on any device wgpu will
//! create — including one handed over from
//! [`HeadlessRenderer`](crate::HeadlessRenderer), which asks for downlevel
//! limits — and it means the bind group is built once per scene rather than per
//! draw.
//!
//! **One texture.** Every decoded map is shelf-packed into a single
//! `rgba16float` atlas, along with the six environment faces, and each material
//! carries the sub-rectangle it owns. Per-material texture bindings would need
//! binding arrays, which wgpu exposes only as a native-only feature and WebGPU
//! does not guarantee at all; an atlas gets the same result with one binding, no
//! rebinding between materials, and one code path on both targets.
//!
//! **Batched dispatches.** Samples are traced `samples_per_dispatch` at a time
//! rather than all at once. A single dispatch that runs for seconds trips the
//! GPU watchdog on Windows and macOS alike and takes the whole process with it;
//! batches of a few tens of milliseconds keep the device responsive, let a
//! progressive render show intermediate results, and cost one command
//! submission each.
//!
//! **Accumulate on the device.** The film lives in a storage buffer and is only
//! read back when the caller asks to resolve. A thousand-sample render is one
//! transfer, not a thousand.
//!
//! **One pixel per invocation, 8×8 workgroups.** No atomics: the only thread
//! that writes a pixel's accumulator is the one that owns it. 8×8 keeps
//! neighbouring pixels — whose rays go the same way and touch the same BVH
//! nodes — in the same workgroup.
//!
//! # Differences from the CPU backend
//!
//! The estimator is identical, but the random number generator is not, so the
//! two produce different *noise* from the same seed. They converge to the same
//! image; a per-pixel comparison at low sample counts will not match, and the
//! tests compare converged means instead.
//!
//! A texture's `rotation` is not applied (offset and repeat are), and any
//! texture too large for the atlas falls back to its material's constant. Both
//! are reported by [`crate::raytrace::gpu::GpuBackend::report`].

use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;

use crate::math::Vector3;
use crate::textures::TextureWrap;

use super::backend::{RaytraceBackend, RaytraceError};
use super::bsdf::ggx_albedo_table;
use super::camera::RtCamera;
use super::film::Film;
use super::scene::{RaytraceScene, RtLight, RtMaterial};
use super::settings::{BackgroundMode, RaytraceSettings};
use super::texture::CpuTexture;

/// Floats per material record in the `data` buffer.
const MAT_STRIDE: usize = 72;
/// Floats per analytic light.
const LIGHT_STRIDE: usize = 20;
/// Floats per triangle: 3 positions, 3 normals, 3 UVs.
const TRI_STRIDE: usize = 24;
/// Floats per emissive entry: area and cumulative weight.
const EMIT_STRIDE: usize = 2;
/// Floats per pixel in the accumulation buffer.
const ACCUM_STRIDE: usize = 14;
/// Side of the texture atlas, in texels. 4096² of rgba16float is 134 MB, which
/// every discrete GPU has and most integrated ones do; anything that will not
/// fit falls back to material constants rather than failing the render.
const ATLAS_SIZE: u32 = 4096;
/// Gutter between packed textures, so bilinear taps at a rectangle's edge
/// cannot reach its neighbour.
const ATLAS_PAD: u32 = 2;

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Uniforms {
    cam_pos: [f32; 4],
    cam_right: [f32; 4],
    cam_up: [f32; 4],
    cam_forward: [f32; 4],
    inv_view: [f32; 16],
    inv_proj: [f32; 16],
    background: [f32; 4],
    ambient: [f32; 4],
    dims: [u32; 4],
    counts: [u32; 4],
    data_offsets: [u32; 4],
    idx_offsets: [u32; 4],
    params: [f32; 4],
    adaptive: [f32; 4],
    limits: [u32; 4],
    flags: [u32; 4],
    env_offsets: [u32; 4],
    env_dims: [u32; 4],
    env_rect: [[f32; 4]; 6],
    hemi: [[f32; 4]; 12],
    albedo_lut: [[f32; 4]; 256],
}

/// The packed scene, ready to upload.
struct Packed {
    nodes: Vec<f32>,
    data: Vec<f32>,
    idx: Vec<u32>,
    tri_base: u32,
    emissive_base: u32,
    material_base: u32,
    light_base: u32,
    order_base: u32,
    tri_material_base: u32,
    emissive_slot_base: u32,
    emissive_tri_base: u32,
    atlas: Atlas,
    env_func_base: u32,
    env_cond_base: u32,
    env_marg_base: u32,
    env_dist_width: u32,
    env_dist_height: u32,
    env_dist_total: f32,
    env_rect: [[f32; 4]; 6],
    env_packed: bool,
    hemi: [[f32; 4]; 12],
    hemi_count: u32,
    notes: Vec<String>,
}

/// Device resources for one scene. Dropped and rebuilt when the scene changes.
struct SceneResources {
    bind_group: wgpu::BindGroup,
    accum: wgpu::Buffer,
    uniform: wgpu::Buffer,
    /// Identity of the scene these were built for, so a repeat `render` with
    /// the same scene reuses them.
    signature: (usize, usize, usize),
    accum_len: usize,
    /// Sample count the device accumulator holds, when it is known to match the
    /// host film. `None` forces a re-upload.
    accum_samples: Option<u32>,
}

/// A path tracer that runs on the GPU.
pub struct GpuBackend {
    device: Arc<wgpu::Device>,
    queue: Arc<wgpu::Queue>,
    layout: wgpu::BindGroupLayout,
    pipeline: wgpu::ComputePipeline,
    resources: Option<SceneResources>,
    /// Where each packed array starts, recomputed with the resources.
    offsets: Option<Offsets>,
    /// Samples traced per dispatch.
    samples_per_dispatch: u32,
    notes: Vec<String>,
}

impl std::fmt::Debug for GpuBackend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GpuBackend")
            .field("samples_per_dispatch", &self.samples_per_dispatch)
            .field("prepared", &self.resources.is_some())
            .finish()
    }
}

impl GpuBackend {
    /// Acquire an adapter and build a device of our own. Blocking; native only.
    ///
    /// Prefer [`Self::with_device`] when the process already has a device — two
    /// devices means two copies of every resource and no way to share them.
    pub fn headless() -> Result<Self, RaytraceError> {
        // No `Default` for `InstanceDescriptor` in wgpu 30: a display handle is
        // either present or deliberately absent, and this path is headless.
        let mut instance_desc = wgpu::InstanceDescriptor::new_without_display_handle();
        instance_desc.backends = wgpu::Backends::PRIMARY;
        let instance = wgpu::Instance::new(instance_desc);
        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
            power_preference: wgpu::PowerPreference::HighPerformance,
            compatible_surface: None,
            force_fallback_adapter: false,
            apply_limit_buckets: false,
        }))
        .map_err(|e| RaytraceError::NoDevice(format!("no wgpu adapter: {e}")))?;

        // Ask for exactly what this adapter has. The kernel's own needs are
        // modest — four storage buffers and a 4K texture — but a large scene
        // needs the adapter's real buffer-size limit, not the conservative
        // default, and there is no portability to protect here: this device is
        // used on this adapter and nowhere else.
        let limits = adapter.limits();
        let (device, queue) = pollster::block_on(adapter.request_device(
            &wgpu::DeviceDescriptor {
                label: Some("threers path tracer"),
                required_features: wgpu::Features::empty(),
                required_limits: limits,
                ..Default::default()
            },
        ))
        .map_err(|e| RaytraceError::NoDevice(format!("request_device failed: {e:?}")))?;

        Ok(Self::with_device(Arc::new(device), Arc::new(queue)))
    }

    /// The device and queue this backend runs on.
    ///
    /// For building further backends on the same device — batch work that
    /// renders many scenes wants one adapter for the run, not one per scene,
    /// and [`Self::headless`] acquires a new device every time it is called.
    pub fn device_and_queue(&self) -> (Arc<wgpu::Device>, Arc<wgpu::Queue>) {
        (Arc::clone(&self.device), Arc::clone(&self.queue))
    }

    /// Build on an existing device — the one from
    /// [`HeadlessRenderer::device`](crate::HeadlessRenderer::device), or a
    /// window's.
    pub fn with_device(device: Arc<wgpu::Device>, queue: Arc<wgpu::Queue>) -> Self {
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("threers pathtrace"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("pathtrace.wgsl"))),
        });

        let storage = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {
            binding,
            visibility: wgpu::ShaderStages::COMPUTE,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Storage { read_only },
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        };
        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("threers pathtrace layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                storage(1, true),
                storage(2, true),
                storage(3, true),
                storage(4, false),
                wgpu::BindGroupLayoutEntry {
                    binding: 5,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("threers pathtrace pipeline layout"),
            bind_group_layouts: &[Some(&layout)],
            immediate_size: 0,
        });
        let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("threers pathtrace"),
            layout: Some(&pipeline_layout),
            module: &shader,
            entry_point: Some("trace"),
            compilation_options: Default::default(),
            cache: None,
        });

        Self {
            device,
            queue,
            layout,
            pipeline,
            resources: None,
            offsets: None,
            samples_per_dispatch: 4,
            notes: Vec::new(),
        }
    }

    /// Samples traced per dispatch. Larger amortises submission overhead;
    /// smaller keeps each dispatch short enough not to trip the GPU watchdog on
    /// a heavy scene. The default of 4 is safe for anything.
    pub fn with_samples_per_dispatch(mut self, n: u32) -> Self {
        self.samples_per_dispatch = n.max(1);
        self
    }

    /// What the packing could not carry over — a texture that did not fit the
    /// atlas, a UV rotation the kernel does not apply.
    pub fn report(&self) -> &[String] {
        &self.notes
    }

    pub fn device(&self) -> &Arc<wgpu::Device> {
        &self.device
    }

    pub fn queue(&self) -> &Arc<wgpu::Queue> {
        &self.queue
    }

    /// Build (or reuse) the device-side scene.
    fn ensure_resources(
        &mut self,
        scene: &RaytraceScene,
        film: &Film,
    ) -> Result<(), RaytraceError> {
        // Cheap identity for "is this the same scene as last time". It is not a
        // hash of the contents: the contract is that a changed scene arrives
        // through `invalidate`, which `RaytraceRenderer::prepare` always calls.
        // This only has to catch the case of a caller driving the backend
        // directly and forgetting.
        let signature = (
            scene.tris.len(),
            scene.materials.len() << 20 | scene.lights.len() << 8 | scene.emissive.len().min(255),
            (film.width() as usize) << 16 | film.height() as usize,
        );
        if let Some(r) = &self.resources {
            if r.signature == signature {
                return Ok(());
            }
        }

        let packed = pack_scene(scene);
        self.notes = packed.notes.clone();

        let limits = self.device.limits();
        let data_bytes = (packed.data.len() * 4) as u64;
        if data_bytes > limits.max_storage_buffer_binding_size {
            return Err(RaytraceError::TooLarge(format!(
                "scene geometry is {} MB, past this device's {} MB storage-buffer limit",
                data_bytes / (1 << 20),
                limits.max_storage_buffer_binding_size / (1 << 20)
            )));
        }

        let mk = |label: &str, contents: &[u8], usage: wgpu::BufferUsages| {
            use wgpu::util::DeviceExt;
            self.device
                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some(label),
                    contents,
                    usage,
                })
        };
        // An empty storage buffer is invalid, so every array gets at least one
        // element; the kernel guards on the counts in the uniform anyway.
        let nodes = if packed.nodes.is_empty() {
            vec![0.0f32; 8]
        } else {
            packed.nodes
        };
        let data = if packed.data.is_empty() {
            vec![0.0f32; 4]
        } else {
            packed.data
        };
        let idx = if packed.idx.is_empty() {
            vec![0u32; 4]
        } else {
            packed.idx
        };

        let node_buf = mk(
            "pathtrace nodes",
            bytemuck::cast_slice(&nodes),
            wgpu::BufferUsages::STORAGE,
        );
        let data_buf = mk(
            "pathtrace data",
            bytemuck::cast_slice(&data),
            wgpu::BufferUsages::STORAGE,
        );
        let idx_buf = mk(
            "pathtrace idx",
            bytemuck::cast_slice(&idx),
            wgpu::BufferUsages::STORAGE,
        );

        let accum_len = film.width() as usize * film.height() as usize * ACCUM_STRIDE;
        let accum = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("pathtrace accum"),
            size: (accum_len * 4) as u64,
            // COPY_DST as well as COPY_SRC: the film may already hold samples
            // from an earlier batch, and those are written in before tracing.
            usage: wgpu::BufferUsages::STORAGE
                | wgpu::BufferUsages::COPY_SRC
                | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let uniform = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("pathtrace uniforms"),
            size: std::mem::size_of::<Uniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let atlas_view = packed.atlas.upload(&self.device, &self.queue);

        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("pathtrace bind group"),
            layout: &self.layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: uniform.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: node_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: data_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: idx_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: accum.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 5,
                    resource: wgpu::BindingResource::TextureView(&atlas_view),
                },
            ],
        });

        self.resources = Some(SceneResources {
            bind_group,
            accum,
            uniform,
            signature,
            accum_len,
            accum_samples: None,
        });
        // The offsets and rects computed during packing are needed at dispatch
        // time; stash them alongside the buffers.
        self.offsets = Some(Offsets {
            tri_base: packed.tri_base,
            emissive_base: packed.emissive_base,
            material_base: packed.material_base,
            light_base: packed.light_base,
            order_base: packed.order_base,
            tri_material_base: packed.tri_material_base,
            emissive_slot_base: packed.emissive_slot_base,
            emissive_tri_base: packed.emissive_tri_base,
            env_func_base: packed.env_func_base,
            env_cond_base: packed.env_cond_base,
            env_marg_base: packed.env_marg_base,
            env_dist_width: packed.env_dist_width,
            env_dist_height: packed.env_dist_height,
            env_dist_total: packed.env_dist_total,
            env_rect: packed.env_rect,
            env_packed: packed.env_packed,
            hemi: packed.hemi,
            hemi_count: packed.hemi_count,
        });
        Ok(())
    }
}

/// Where each array starts inside the packed buffers.
#[derive(Clone, Copy)]
struct Offsets {
    tri_base: u32,
    emissive_base: u32,
    material_base: u32,
    light_base: u32,
    order_base: u32,
    tri_material_base: u32,
    emissive_slot_base: u32,
    emissive_tri_base: u32,
    env_func_base: u32,
    env_cond_base: u32,
    env_marg_base: u32,
    env_dist_width: u32,
    env_dist_height: u32,
    env_dist_total: f32,
    env_rect: [[f32; 4]; 6],
    env_packed: bool,
    hemi: [[f32; 4]; 12],
    hemi_count: u32,
}

impl RaytraceBackend for GpuBackend {
    fn name(&self) -> &'static str {
        "gpu"
    }

    fn invalidate(&mut self) {
        self.resources = None;
        self.offsets = None;
    }

    fn render(
        &mut self,
        scene: &RaytraceScene,
        camera: &RtCamera,
        settings: &RaytraceSettings,
        film: &mut Film,
        first_sample: u32,
        samples: u32,
    ) -> Result<(), RaytraceError> {
        if samples == 0 {
            return Ok(());
        }
        self.ensure_resources(scene, film)?;
        let (Some(res), Some(off)) = (self.resources.as_ref(), self.offsets) else {
            return Err(RaytraceError::NoDevice("scene was not prepared".into()));
        };

        // The film may already hold samples — from an earlier batch, or from
        // another backend entirely — so the device accumulator has to start
        // from what it holds. When the previous call is what put those samples
        // there, the device copy is already correct and the upload is skipped:
        // a progressive render at 1080p would otherwise push 99 MB per batch to
        // restore a buffer that never changed.
        if res.accum_samples != Some(film.samples()) {
            let mut seed_accum = vec![0.0f32; res.accum_len];
            for (i, p) in film.pixels().iter().enumerate() {
                let b = i * ACCUM_STRIDE;
                seed_accum[b] = p.color[0];
                seed_accum[b + 1] = p.color[1];
                seed_accum[b + 2] = p.color[2];
                seed_accum[b + 3] = p.alpha;
                seed_accum[b + 4] = p.albedo[0];
                seed_accum[b + 5] = p.albedo[1];
                seed_accum[b + 6] = p.albedo[2];
                seed_accum[b + 7] = p.normal[0];
                seed_accum[b + 8] = p.normal[1];
                seed_accum[b + 9] = p.normal[2];
                seed_accum[b + 10] = p.depth;
                seed_accum[b + 11] = p.depth_samples as f32;
            }
            self.queue
                .write_buffer(&res.accum, 0, bytemuck::cast_slice(&seed_accum));
        }

        // The same value the CPU integrator computes — the two backends have to
        // agree on where a secondary ray starts, or they disagree about
        // self-intersection.
        let epsilon = super::integrator::ray_epsilon(scene, settings);
        let mut uniforms = build_uniforms(scene, camera, settings, film, &off, epsilon);

        let groups_x = film.width().div_ceil(8);
        let groups_y = film.height().div_ceil(8);

        let mut done = 0u32;
        while done < samples {
            let batch = self.samples_per_dispatch.min(samples - done);
            uniforms.dims[2] = first_sample + done;
            uniforms.dims[3] = batch;
            self.queue
                .write_buffer(&res.uniform, 0, bytemuck::bytes_of(&uniforms));

            let mut encoder = self
                .device
                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("pathtrace batch"),
                });
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("pathtrace"),
                    timestamp_writes: None,
                });
                pass.set_pipeline(&self.pipeline);
                pass.set_bind_group(0, &res.bind_group, &[]);
                pass.dispatch_workgroups(groups_x, groups_y, 1);
            }
            self.queue.submit(Some(encoder.finish()));
            done += batch;
        }

        // One readback for the whole call, not one per batch.
        let bytes = (res.accum_len * 4) as u64;
        let staging = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("pathtrace readback"),
            size: bytes,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("pathtrace readback"),
            });
        encoder.copy_buffer_to_buffer(&res.accum, 0, &staging, 0, bytes);
        self.queue.submit(Some(encoder.finish()));

        let slice = staging.slice(..);
        let (tx, rx) = std::sync::mpsc::channel();
        slice.map_async(wgpu::MapMode::Read, move |r| {
            let _ = tx.send(r);
        });
        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
        match rx.recv() {
            Ok(Ok(())) => {}
            other => {
                return Err(RaytraceError::DeviceLost(format!(
                    "readback failed: {other:?}"
                )))
            }
        }
        let mapped = slice.get_mapped_range().expect("buffer range is mapped");
        let values: &[f32] = bytemuck::cast_slice(&mapped);
        for (i, p) in film.pixels_mut().iter_mut().enumerate() {
            let b = i * ACCUM_STRIDE;
            p.color = [values[b], values[b + 1], values[b + 2]];
            p.alpha = values[b + 3];
            p.albedo = [values[b + 4], values[b + 5], values[b + 6]];
            p.normal = [values[b + 7], values[b + 8], values[b + 9]];
            p.depth = values[b + 10];
            p.depth_samples = values[b + 11] as u32;
            p.samples = values[b + 12] as u32;
            p.lum_sq = values[b + 13];
        }
        drop(mapped);
        staging.unmap();

        film.advance(samples);
        if let Some(res) = self.resources.as_mut() {
            res.accum_samples = Some(film.samples());
        }
        Ok(())
    }
}

fn build_uniforms(
    scene: &RaytraceScene,
    camera: &RtCamera,
    settings: &RaytraceSettings,
    film: &Film,
    off: &Offsets,
    epsilon: f32,
) -> Uniforms {
    let inv_view = camera.inv_view_matrix();
    let inv_proj = camera.inv_proj_matrix();
    let pos = camera.position();
    let right = camera.right();
    let up = camera.up();
    let fwd = camera.forward();

    let mut lut = [[0.0f32; 4]; 256];
    for (i, v) in ggx_albedo_table().iter().enumerate() {
        lut[i / 4][i % 4] = *v;
    }

    let mut flags = 0u32;
    // The scene having an environment is not enough — it also has to have made
    // it into the atlas.
    if scene.world.has_environment() && off.env_packed {
        flags |= 1;
    }
    if scene.shadows_all_opaque {
        flags |= 2;
    }

    Uniforms {
        cam_pos: [
            pos.x,
            pos.y,
            pos.z,
            if camera.is_perspective() { 1.0 } else { 0.0 },
        ],
        cam_right: [right.x, right.y, right.z, settings.aperture],
        cam_up: [up.x, up.y, up.z, camera.focus_distance()],
        cam_forward: [fwd.x, fwd.y, fwd.z, epsilon],
        inv_view: inv_view.elements,
        inv_proj: inv_proj.elements,
        background: [
            scene.world.background.x,
            scene.world.background.y,
            scene.world.background.z,
            scene.world.background_alpha,
        ],
        ambient: [
            scene.world.ambient.x,
            scene.world.ambient.y,
            scene.world.ambient.z,
            scene.world.environment_intensity,
        ],
        dims: [film.width(), film.height(), 0, 0],
        counts: [
            scene.tris.len() as u32,
            scene.materials.len() as u32,
            scene.lights.len() as u32,
            scene.emissive.len() as u32,
        ],
        data_offsets: [
            off.tri_base,
            off.emissive_base,
            off.material_base,
            off.light_base,
        ],
        idx_offsets: [
            off.order_base,
            off.tri_material_base,
            off.emissive_slot_base,
            off.emissive_tri_base,
        ],
        params: [
            settings.clamp_direct,
            settings.clamp_indirect,
            off.env_dist_total,
            0.0,
        ],
        adaptive: [
            settings.adaptive_threshold,
            settings.adaptive_min_samples as f32,
            0.0,
            0.0,
        ],
        limits: [
            settings.max_bounces,
            settings.min_bounces,
            settings.transparent_max_bounces,
            match settings.background {
                BackgroundMode::Color => 0,
                BackgroundMode::Environment => 1,
                BackgroundMode::Transparent => 2,
            },
        ],
        flags: [
            settings.seed as u32,
            (settings.seed >> 32) as u32,
            off.hemi_count,
            flags,
        ],
        env_offsets: [off.env_func_base, off.env_cond_base, off.env_marg_base, 0],
        env_dims: [
            off.env_dist_width,
            off.env_dist_height,
            // Only usable when the environment itself made it into the atlas —
            // importance-sampling a sky the kernel cannot read would aim every
            // sample at radiance of zero.
            u32::from(off.env_dist_width > 0 && (flags & 1) != 0),
            0,
        ],
        env_rect: off.env_rect,
        hemi: off.hemi,
        albedo_lut: lut,
    }
}

// ------------------------------------------------------------------- packing

/// Shelf packer for the texture atlas. Textures arrive in no useful order, so
/// they are packed as they come into rows whose height is set by the first
/// texture in each — simple, and within a few percent of optimal for the
/// power-of-two sizes textures actually are.
struct Atlas {
    pixels: Vec<u16>,
    shelf_x: u32,
    shelf_y: u32,
    shelf_height: u32,
    /// Rightmost column any shelf reached, so the upload can be cropped.
    used_width: u32,
    /// Rectangles already packed, by `Arc` identity — a map shared by twenty
    /// materials is copied in once, as it is decoded once.
    placed: HashMap<usize, [f32; 4]>,
}

impl Atlas {
    fn new() -> Self {
        Self {
            pixels: Vec::new(),
            shelf_x: 0,
            shelf_y: 0,
            shelf_height: 0,
            used_width: 0,
            placed: HashMap::new(),
        }
    }

    /// As [`Self::insert`], but returns the existing rectangle when this exact
    /// texture has already been packed.
    fn insert_shared(&mut self, tex: &Arc<CpuTexture>) -> Option<[f32; 4]> {
        let key = Arc::as_ptr(tex) as usize;
        if let Some(rect) = self.placed.get(&key) {
            return Some(*rect);
        }
        let rect = self.insert(tex)?;
        self.placed.insert(key, rect);
        Some(rect)
    }

    fn ensure_allocated(&mut self) {
        if self.pixels.is_empty() {
            self.pixels = vec![0u16; (ATLAS_SIZE * ATLAS_SIZE * 4) as usize];
        }
    }

    /// Copy a decoded texture in and return its rectangle, or `None` if it does
    /// not fit.
    fn insert(&mut self, tex: &CpuTexture) -> Option<[f32; 4]> {
        let (w, h) = (tex.width(), tex.height());
        if w == 0 || h == 0 || w > ATLAS_SIZE || h > ATLAS_SIZE {
            return None;
        }
        if self.shelf_x + w + ATLAS_PAD > ATLAS_SIZE {
            self.shelf_y += self.shelf_height + ATLAS_PAD;
            self.shelf_x = 0;
            self.shelf_height = 0;
        }
        if self.shelf_y + h > ATLAS_SIZE {
            return None;
        }
        self.ensure_allocated();
        let (x0, y0) = (self.shelf_x, self.shelf_y);
        let flip = tex.flips_y();
        for y in 0..h {
            // `flip_y` is baked in here, so the kernel never has to know about
            // it — one branch removed from the innermost sampling path.
            let src_y = if flip { h - 1 - y } else { y };
            for x in 0..w {
                let c = tex.texel_at(x, src_y);
                let d = (((y0 + y) * ATLAS_SIZE + x0 + x) * 4) as usize;
                for (dst, v) in self.pixels[d..d + 4].iter_mut().zip(c) {
                    // Clamped to the largest finite half. An HDR environment
                    // can legitimately hold values past this, and letting one
                    // become an infinity would put a NaN into the film on the
                    // first ray that found it — permanently, since the film is
                    // a running sum.
                    *dst =
                        crate::renderer::gpu_texture::f32_to_f16_bits(v.clamp(-65504.0, 65504.0));
                }
            }
        }
        self.shelf_x += w + ATLAS_PAD;
        self.used_width = self.used_width.max(x0 + w);
        self.shelf_height = self.shelf_height.max(h);
        Some([x0 as f32, y0 as f32, w as f32, h as f32])
    }

    /// Crop to what was packed and upload.
    ///
    /// The binding has to exist even for a scene with no textures at all, but
    /// it does not have to be 4096² — that is 134 MB of `rgba16float` allocated,
    /// zeroed and pushed across the bus to be sampled zero times. Packing runs
    /// at full width so the shelf arithmetic stays simple; only the upload is
    /// cropped, and since rectangles are measured from the origin they stay
    /// valid.
    fn upload(self, device: &wgpu::Device, queue: &wgpu::Queue) -> wgpu::TextureView {
        let used_w = self.used_width.max(1);
        let used_h = (self.shelf_y + self.shelf_height).max(1);
        let mut pixels = vec![0u16; (used_w * used_h * 4) as usize];
        if !self.pixels.is_empty() {
            for y in 0..used_h {
                let src = (y * ATLAS_SIZE * 4) as usize;
                let dst = (y * used_w * 4) as usize;
                let n = (used_w * 4) as usize;
                pixels[dst..dst + n].copy_from_slice(&self.pixels[src..src + n]);
            }
        }
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("pathtrace atlas"),
            size: wgpu::Extent3d {
                width: used_w,
                height: used_h,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            bytemuck::cast_slice(&pixels),
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(used_w * 8),
                rows_per_image: Some(used_h),
            },
            wgpu::Extent3d {
                width: used_w,
                height: used_h,
                depth_or_array_layers: 1,
            },
        );
        texture.create_view(&wgpu::TextureViewDescriptor::default())
    }
}

fn wrap_code(w: TextureWrap) -> u32 {
    match w {
        TextureWrap::ClampToEdge => 0,
        TextureWrap::Repeat => 1,
        TextureWrap::MirroredRepeat => 2,
    }
}

/// Flatten the scene into the four device buffers.
fn pack_scene(scene: &RaytraceScene) -> Packed {
    let n_tris = scene.tris.len();
    let mut atlas = Atlas::new();
    let mut notes: Vec<String> = Vec::new();

    // --- nodes: two vec4 each, with the child links bitcast into `w`.
    let mut nodes = Vec::with_capacity(scene.bvh.node_count() * 8);
    for i in 0..scene.bvh.node_count() {
        let n = scene.bvh.node(i);
        nodes.extend_from_slice(&[
            n.min[0],
            n.min[1],
            n.min[2],
            f32::from_bits(n.left_or_first),
            n.max[0],
            n.max[1],
            n.max[2],
            f32::from_bits(n.count),
        ]);
    }

    // --- data: triangles, then emissive, then materials, then lights.
    let mut data: Vec<f32> = Vec::with_capacity(n_tris * TRI_STRIDE + 4096);
    let tri_base = 0u32;
    for (i, t) in scene.tris.iter().enumerate() {
        let sh = &scene.shading[i];
        for v in t {
            data.extend_from_slice(&[v.x, v.y, v.z]);
        }
        for n in &sh.normals {
            data.extend_from_slice(&[n.x, n.y, n.z]);
        }
        for uv in &sh.uvs {
            data.extend_from_slice(&[uv.x, uv.y]);
        }
    }

    let emissive_base = data.len() as u32;
    for e in &scene.emissive.tris {
        let start = data.len();
        data.resize(start + EMIT_STRIDE, 0.0);
        data[start] = e.area;
        data[start + 1] = e.cdf;
    }

    let material_base = data.len() as u32;
    for (mi, m) in scene.materials.iter().enumerate() {
        let start = data.len();
        data.resize(start + MAT_STRIDE, 0.0);
        let s = &mut data[start..start + MAT_STRIDE];
        s[0] = m.base_color.x;
        s[1] = m.base_color.y;
        s[2] = m.base_color.z;
        s[3] = m.opacity;
        s[4] = m.emission.x;
        s[5] = m.emission.y;
        s[6] = m.emission.z;
        s[7] = m.alpha_test;
        s[8] = m.roughness;
        s[9] = m.metallic;
        s[10] = m.transmission;
        s[11] = m.ior;
        s[12] = m.attenuation_color.x;
        s[13] = m.attenuation_color.y;
        s[14] = m.attenuation_color.z;
        s[15] = m.attenuation_distance;
        s[16] = m.clearcoat;
        s[17] = m.clearcoat_roughness;
        s[18] = m.specular_tint.x;
        s[19] = m.specular_tint.y;
        s[20] = m.specular_tint.z;
        s[21] = m.anisotropy;
        s[22] = m.anisotropy_rotation;
        s[23] = if m.unlit { 1.0 } else { 0.0 };
        s[64] = m.normal_scale.x;
        s[65] = m.normal_scale.y;

        let mut wrap_bits = 0u32;
        for (slot, tex) in material_maps(m).iter().enumerate() {
            let Some(tex) = tex else { continue };
            let o = 24 + slot * 8;
            match atlas.insert_shared(tex) {
                Some(rect) => {
                    s[o..o + 4].copy_from_slice(&rect);
                    let (offset, repeat, rotation) = tex.uv_transform();
                    s[o + 4] = offset.x;
                    s[o + 5] = offset.y;
                    s[o + 6] = repeat.x;
                    s[o + 7] = repeat.y;
                    // Two bits an axis, S in the low half and T in the high —
                    // a texture that repeats across but clamps down is rare and
                    // would otherwise sample differently on the two backends.
                    let (wrap_s, wrap_t) = tex.wrap_modes();
                    wrap_bits |= wrap_code(wrap_s) << (slot * 2);
                    wrap_bits |= wrap_code(wrap_t) << (10 + slot * 2);
                    if rotation != 0.0 {
                        notes.push(format!(
                            "material {mi}, map {slot}: UV rotation is not applied by the GPU kernel"
                        ));
                    }
                }
                None => notes.push(format!(
                    "material {mi}, map {slot}: {}x{} does not fit the atlas; the constant is used instead",
                    tex.width(),
                    tex.height()
                )),
            }
        }
        s[66] = wrap_bits as f32;
    }

    let light_base = data.len() as u32;
    for l in &scene.lights {
        let start = data.len();
        data.resize(start + LIGHT_STRIDE, 0.0);
        let s = &mut data[start..start + LIGHT_STRIDE];
        match *l {
            RtLight::Directional {
                direction,
                radiance,
                angular_radius,
            } => {
                s[0] = 0.0;
                write3(s, 1, direction);
                write3(s, 4, radiance);
                s[7] = angular_radius;
            }
            RtLight::Point {
                position,
                intensity,
                radius,
                distance,
                decay,
            } => {
                s[0] = 1.0;
                write3(s, 1, position);
                write3(s, 4, intensity);
                s[7] = radius;
                s[11] = distance;
                s[15] = decay;
            }
            RtLight::Spot {
                position,
                direction,
                intensity,
                radius,
                distance,
                decay,
                cos_outer,
                cos_inner,
            } => {
                s[0] = 2.0;
                write3(s, 1, position);
                write3(s, 4, intensity);
                s[7] = radius;
                write3(s, 8, direction);
                s[11] = distance;
                s[15] = decay;
                s[16] = cos_outer;
                s[17] = cos_inner;
            }
            RtLight::Rect {
                position,
                right,
                up,
                radiance,
            } => {
                s[0] = 3.0;
                write3(s, 1, position);
                write3(s, 4, radiance);
                write3(s, 8, right);
                write3(s, 12, up);
            }
        }
    }

    // --- the environment's sampling distribution. Only the CDFs and the
    // function are uploaded; the per-row integrals exist to *build* the
    // marginal CDF and are not read again.
    let mut env_func_base = 0u32;
    let mut env_cond_base = 0u32;
    let mut env_marg_base = 0u32;
    let mut env_dist_width = 0u32;
    let mut env_dist_height = 0u32;
    let mut env_dist_total = 0.0f32;
    if let Some(dist) = scene.world.env_distribution() {
        let (func, cond, _row, marg) = dist.arrays();
        env_func_base = data.len() as u32;
        data.extend_from_slice(func);
        env_cond_base = data.len() as u32;
        data.extend_from_slice(cond);
        env_marg_base = data.len() as u32;
        data.extend_from_slice(marg);
        env_dist_width = dist.width() as u32;
        env_dist_height = dist.height() as u32;
        env_dist_total = dist.total();
    }

    // --- idx: order, per-triangle material, emissive slot, emissive triangle.
    let order_base = 0u32;
    let mut idx: Vec<u32> = Vec::with_capacity(n_tris * 3 + scene.emissive.len());
    idx.extend_from_slice(scene.bvh.order());
    let tri_material_base = idx.len() as u32;
    idx.extend(scene.shading.iter().map(|s| s.material));
    let emissive_slot_base = idx.len() as u32;
    // The scene already keeps this mapping; searching the emitter list per
    // triangle would be O(triangles x emitters), which on a scene with a
    // hundred thousand triangles and a thousand emitters is a hundred million
    // comparisons for a table that already exists.
    if scene.emissive.slots().len() == n_tris {
        idx.extend_from_slice(scene.emissive.slots());
    } else {
        idx.resize(idx.len() + n_tris, u32::MAX);
    }
    let emissive_tri_base = idx.len() as u32;
    idx.extend(scene.emissive.tris.iter().map(|e| e.triangle));

    // --- environment, packed into the same atlas.
    let mut env_rect = [[0.0f32; 4]; 6];
    // All six faces or none. A missing rectangle reads as a full-white sample,
    // so a partial pack would light the scene from a white sky rather than
    // dropping the environment — the loud failure of the two.
    let mut env_packed = false;
    if let Some(faces) = scene.world.env_faces() {
        env_packed = true;
        for (i, face) in faces.iter().enumerate() {
            match atlas.insert(face) {
                Some(rect) => env_rect[i] = rect,
                None => env_packed = false,
            }
        }
        if !env_packed {
            env_rect = [[0.0f32; 4]; 6];
            notes.push(
                "environment map does not fit the texture atlas; the GPU backend renders no environment"
                    .into(),
            );
        }
    }

    let mut hemi = [[0.0f32; 4]; 12];
    let hemi_count = scene.world.hemispheres.len().min(4);
    for (i, h) in scene.world.hemispheres.iter().take(4).enumerate() {
        hemi[i * 3] = [h.sky.x, h.sky.y, h.sky.z, 0.0];
        hemi[i * 3 + 1] = [h.ground.x, h.ground.y, h.ground.z, 0.0];
        hemi[i * 3 + 2] = [h.up.x, h.up.y, h.up.z, 0.0];
    }
    if scene.world.hemispheres.len() > 4 {
        notes.push(format!(
            "{} hemisphere lights; the GPU kernel carries 4",
            scene.world.hemispheres.len()
        ));
    }

    Packed {
        nodes,
        data,
        idx,
        tri_base,
        emissive_base,
        material_base,
        light_base,
        order_base,
        tri_material_base,
        emissive_slot_base,
        emissive_tri_base,
        atlas,
        env_func_base,
        env_cond_base,
        env_marg_base,
        env_dist_width,
        env_dist_height,
        env_dist_total,
        env_rect,
        env_packed,
        hemi,
        hemi_count: hemi_count as u32,
        notes,
    }
}

/// The five map slots, in the order the kernel indexes them.
fn material_maps(m: &RtMaterial) -> [Option<Arc<CpuTexture>>; 5] {
    [
        m.base_color_map.clone(),
        m.roughness_map.clone(),
        m.metallic_map.clone(),
        m.emissive_map.clone(),
        m.normal_map.clone(),
    ]
}

fn write3(s: &mut [f32], at: usize, v: Vector3) {
    s[at] = v.x;
    s[at + 1] = v.y;
    s[at + 2] = v.z;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cameras::PerspectiveCamera;
    use crate::core::{Mesh, Object3D};
    use crate::geometries::{BoxGeometry, PlaneGeometry, SphereGeometry};
    use crate::lights::{AmbientLight, DirectionalLight};
    use crate::materials::{Material, StandardMaterial};
    use crate::math::Color;
    use crate::raytrace::backend::CpuBackend;
    use crate::scene::Scene;

    /// Machines without a usable adapter (CI containers, mostly) skip rather
    /// than fail — but a machine that *has* one must not silently skip, so the
    /// reason is printed.
    fn backend() -> Option<GpuBackend> {
        match GpuBackend::headless() {
            Ok(b) => Some(b),
            Err(e) => {
                eprintln!("skipping GPU test: {e}");
                None
            }
        }
    }

    fn camera() -> PerspectiveCamera {
        let mut c = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        c.position = Vector3::new(2.5, 2.0, 4.0);
        c.target = Vector3::ZERO;
        c
    }

    fn lit_box_scene() -> Scene {
        let mut scene = Scene::new();
        scene.background = Color::new(0.05, 0.06, 0.09);
        scene.add(Object3D::mesh(Mesh::new(
            BoxGeometry::new(2.0, 2.0, 2.0),
            Material::Standard(StandardMaterial::new(Color::new(0.75, 0.35, 0.2))),
        )));
        let mut floor = Object3D::mesh(Mesh::new(
            PlaneGeometry::new(20.0, 20.0),
            Material::Standard(StandardMaterial::new(Color::new(0.6, 0.6, 0.6))),
        ));
        floor.position = Vector3::new(0.0, -1.0, 0.0);
        floor.rotate_x(-std::f32::consts::FRAC_PI_2);
        scene.add(floor);
        let mut sun = Object3D::light(DirectionalLight::new(Color::WHITE, 2.5));
        sun.position = Vector3::new(3.0, 6.0, 4.0);
        scene.add(sun);
        scene.add_light(AmbientLight::new(Color::new(0.4, 0.5, 0.7), 0.3));
        scene
    }

    fn mean_channel(hdr: &[f32], c: usize) -> f32 {
        let mut sum = 0.0f64;
        let mut n = 0usize;
        for px in hdr.chunks_exact(4) {
            sum += px[c] as f64;
            n += 1;
        }
        (sum / n.max(1) as f64) as f32
    }

    #[test]
    fn the_kernel_compiles_and_runs() {
        let Some(mut gpu) = backend() else { return };
        let mut scene = Scene::new();
        scene.background = Color::new(0.25, 0.5, 0.75);
        let settings = RaytraceSettings::default()
            .with_samples(2)
            .with_denoise(false);
        let rt = RaytraceScene::build(&mut scene, &settings);
        let cam = RtCamera::new(&camera(), &settings);
        let mut film = Film::new(16, 16);
        gpu.render(&rt, &cam, &settings, &mut film, 0, 2).unwrap();
        let hdr = film.resolve_hdr();
        // An empty scene is the background, exactly.
        assert!((hdr[0] - 0.25).abs() < 2e-3, "{:?}", &hdr[..4]);
        assert!((hdr[1] - 0.5).abs() < 2e-3);
        assert!((hdr[2] - 0.75).abs() < 2e-3);
        assert!((hdr[3] - 1.0).abs() < 1e-4);
    }

    /// The furnace test again, this time on the device: a Lambertian of albedo
    /// `a` under uniform radiance `L` must render at `a·L`.
    #[test]
    fn gpu_furnace_test() {
        let Some(mut gpu) = backend() else { return };
        let mut scene = Scene::new();
        scene.background = Color::BLACK;
        scene.add(Object3D::mesh(Mesh::new(
            PlaneGeometry::new(50.0, 50.0),
            Material::Standard(StandardMaterial::new(Color::new(0.6, 0.6, 0.6))),
        )));
        scene.add_light(AmbientLight::new(Color::WHITE, 1.0));

        let settings = RaytraceSettings {
            samples_per_pixel: 256,
            max_bounces: 1,
            min_bounces: 1,
            clamp_indirect: 0.0,
            denoise: false,
            ..Default::default()
        };
        let rt = RaytraceScene::build(&mut scene, &settings);
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 4.0);
        cam.target = Vector3::ZERO;
        let rtc = RtCamera::new(&cam, &settings);
        let mut film = Film::new(16, 16);
        gpu.render(&rt, &rtc, &settings, &mut film, 0, 256).unwrap();
        let hdr = film.resolve_hdr();
        let i = (8 * 16 + 8) * 4;
        assert!((hdr[i] - 0.6).abs() < 0.03, "expected 0.6, got {}", hdr[i]);
    }

    /// The whole point of a second backend: it has to agree with the first.
    /// Compared as converged means over the frame, because the two use
    /// different random sequences and so produce different noise.
    #[test]
    fn gpu_and_cpu_agree_on_a_lit_scene() {
        let Some(mut gpu) = backend() else { return };
        let mut scene = lit_box_scene();
        let settings = RaytraceSettings {
            samples_per_pixel: 96,
            max_bounces: 4,
            min_bounces: 4,
            clamp_indirect: 0.0,
            denoise: false,
            ..Default::default()
        };
        let rt = RaytraceScene::build(&mut scene, &settings);
        let cam = RtCamera::new(&camera(), &settings);

        let mut gpu_film = Film::new(48, 48);
        gpu.render(&rt, &cam, &settings, &mut gpu_film, 0, 96)
            .unwrap();
        let mut cpu_film = Film::new(48, 48);
        CpuBackend::new()
            .render(&rt, &cam, &settings, &mut cpu_film, 0, 96)
            .unwrap();

        let g = gpu_film.resolve_hdr();
        let c = cpu_film.resolve_hdr();
        for channel in 0..3 {
            let gm = mean_channel(&g, channel);
            let cm = mean_channel(&c, channel);
            assert!(gm > 0.01, "channel {channel} rendered black on the GPU");
            assert!(
                (gm - cm).abs() < 0.06 * cm.max(0.05),
                "channel {channel}: gpu mean {gm}, cpu mean {cm}"
            );
        }

        // And the two must agree on the structure, not just the average: the
        // per-pixel difference has to be small where the image is smooth.
        let mut worst = 0.0f32;
        for (a, b) in g.chunks_exact(4).zip(c.chunks_exact(4)) {
            worst = worst.max((a[0] - b[0]).abs());
        }
        assert!(worst < 0.6, "worst per-pixel red difference {worst}");
    }

    #[test]
    fn gpu_handles_emissive_geometry_and_glass() {
        let Some(mut gpu) = backend() else { return };
        let mut scene = Scene::new();
        scene.background = Color::BLACK;
        let mut emitter = StandardMaterial::new(Color::BLACK);
        emitter.emissive = Color::WHITE;
        emitter.emissive_intensity = 12.0;
        let mut panel = Object3D::mesh(Mesh::new(
            PlaneGeometry::new(2.0, 2.0),
            Material::Standard(emitter),
        ));
        panel.position = Vector3::new(0.0, 0.0, 3.0);
        panel.rotate_y(std::f32::consts::PI);
        scene.add(panel);

        let mut glass = crate::materials::PhysicalMaterial::new(Color::WHITE);
        glass.transmission = 1.0;
        glass.roughness = 0.05;
        glass.ior = 1.5;
        scene.add(Object3D::mesh(Mesh::new(
            SphereGeometry::new(0.8, 24, 16),
            Material::Physical(glass),
        )));
        let mut wall = Object3D::mesh(Mesh::new(
            PlaneGeometry::new(20.0, 20.0),
            Material::Standard(StandardMaterial::new(Color::new(0.7, 0.7, 0.7))),
        ));
        wall.position = Vector3::new(0.0, 0.0, -3.0);
        scene.add(wall);

        let settings = RaytraceSettings {
            samples_per_pixel: 32,
            max_bounces: 6,
            denoise: false,
            ..Default::default()
        };
        let rt = RaytraceScene::build(&mut scene, &settings);
        assert!(!rt.emissive.is_empty());
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 6.0);
        cam.target = Vector3::ZERO;
        let rtc = RtCamera::new(&cam, &settings);
        let mut film = Film::new(32, 32);
        gpu.render(&rt, &rtc, &settings, &mut film, 0, 32).unwrap();
        let hdr = film.resolve_hdr();
        assert!(
            hdr.iter().all(|v| v.is_finite() && *v >= 0.0),
            "non-finite output"
        );
        assert!(mean_channel(&hdr, 0) > 0.005, "the emitter lit nothing");
    }

    /// Batching must not change the result, and the film has to survive being
    /// added to across calls.
    #[test]
    fn gpu_accumulation_is_additive() {
        let Some(mut gpu) = backend() else { return };
        let mut scene = lit_box_scene();
        let settings = RaytraceSettings {
            samples_per_pixel: 32,
            max_bounces: 3,
            denoise: false,
            ..Default::default()
        };
        let rt = RaytraceScene::build(&mut scene, &settings);
        let cam = RtCamera::new(&camera(), &settings);

        let mut one = Film::new(24, 24);
        gpu.render(&rt, &cam, &settings, &mut one, 0, 32).unwrap();

        let mut split = Film::new(24, 24);
        gpu.render(&rt, &cam, &settings, &mut split, 0, 12).unwrap();
        gpu.render(&rt, &cam, &settings, &mut split, 12, 20)
            .unwrap();
        assert_eq!(split.samples(), 32);

        let a = one.resolve_hdr();
        let b = split.resolve_hdr();
        for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
            assert!(
                (x - y).abs() < 1e-4,
                "channel {i}: {x} vs {y} — batching changed the sample sequence"
            );
        }
    }

    /// The kernel must handle the glass interface the same way the CPU does —
    /// the relative index flips on the way out, and getting that wrong costs a
    /// factor of eta^4.
    #[test]
    fn gpu_clear_glass_passes_light_through() {
        let Some(mut gpu) = backend() else { return };
        let build = |with_ball: bool| {
            let mut scene = Scene::new();
            scene.background = Color::BLACK;
            let mut em = StandardMaterial::new(Color::BLACK);
            em.emissive = Color::WHITE;
            em.emissive_intensity = 4.0;
            let mut wall = Object3D::mesh(Mesh::new(
                PlaneGeometry::new(20.0, 20.0),
                Material::Standard(em),
            ));
            wall.position = Vector3::new(0.0, 0.0, -4.0);
            scene.add(wall);
            if with_ball {
                let mut glass = crate::materials::PhysicalMaterial::new(Color::WHITE);
                glass.transmission = 1.0;
                glass.roughness = 0.0;
                glass.ior = 1.52;
                scene.add(Object3D::mesh(Mesh::new(
                    SphereGeometry::new(1.0, 48, 32),
                    Material::Physical(glass),
                )));
            }
            scene
        };
        let settings = RaytraceSettings {
            samples_per_pixel: 64,
            max_bounces: 12,
            min_bounces: 8,
            clamp_indirect: 0.0,
            denoise: false,
            ..Default::default()
        };
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        cam.target = Vector3::ZERO;

        let mut centre = |with_ball: bool| {
            let mut scene = build(with_ball);
            let rt = RaytraceScene::build(&mut scene, &settings);
            let rtc = RtCamera::new(&cam, &settings);
            let mut film = Film::new(32, 32);
            gpu.render(&rt, &rtc, &settings, &mut film, 0, 64).unwrap();
            film.resolve_hdr()[(16 * 32 + 16) * 4]
        };
        let clear = centre(false);
        let through_glass = centre(true);
        assert!(
            (clear - 4.0).abs() < 0.02,
            "backdrop should read 4.0, got {clear}"
        );
        assert!(
            through_glass > 0.85 * clear,
            "glass passed only {through_glass} of {clear}"
        );
    }

    #[test]
    fn a_transparent_background_reaches_the_film() {
        let Some(mut gpu) = backend() else { return };
        let mut scene = Scene::new();
        let settings = RaytraceSettings::default()
            .with_samples(4)
            .with_denoise(false)
            .with_background(BackgroundMode::Transparent);
        let rt = RaytraceScene::build(&mut scene, &settings);
        let cam = RtCamera::new(&camera(), &settings);
        let mut film = Film::new(8, 8);
        gpu.render(&rt, &cam, &settings, &mut film, 0, 4).unwrap();
        assert_eq!(film.resolve_hdr()[3], 0.0);
    }

    /// A checkerboard albedo map, which only reaches the kernel through the
    /// texture atlas — sub-rectangle addressing, per-axis wrapping and manual
    /// bilinear filtering all at once.
    #[test]
    fn gpu_matches_cpu_on_a_textured_surface() {
        let Some(mut gpu) = backend() else { return };
        let build = || {
            let mut scene = Scene::new();
            scene.background = Color::BLACK;
            let n = 8u32;
            let mut px = vec![0u8; (n * n * 4) as usize];
            for y in 0..n {
                for x in 0..n {
                    let on = (x + y) % 2 == 0;
                    let i = ((y * n + x) * 4) as usize;
                    px[i] = if on { 230 } else { 30 };
                    px[i + 1] = if on { 60 } else { 200 };
                    px[i + 2] = 90;
                    px[i + 3] = 255;
                }
            }
            let mut tex = crate::textures::Texture::new(
                n,
                n,
                crate::textures::TextureFormat::Rgba8UnormSrgb,
                px,
            );
            tex.wrap_s = crate::textures::TextureWrap::Repeat;
            tex.wrap_t = crate::textures::TextureWrap::Repeat;
            tex.mag_filter = crate::textures::TextureFilter::Linear;
            tex.repeat = crate::math::Vector2::new(3.0, 3.0);
            tex.flip_y = false;
            let mut m = StandardMaterial::new(Color::WHITE);
            m.map = Some(std::sync::Arc::new(tex));
            m.roughness = 0.8;
            scene.add(Object3D::mesh(Mesh::new(
                PlaneGeometry::new(6.0, 6.0),
                Material::Standard(m),
            )));
            scene.add_light(AmbientLight::new(Color::WHITE, 1.0));
            scene
        };
        let settings = RaytraceSettings {
            samples_per_pixel: 64,
            max_bounces: 2,
            denoise: false,
            ..Default::default()
        };
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        cam.target = Vector3::ZERO;

        let mut scene = build();
        let rt = RaytraceScene::build(&mut scene, &settings);
        assert!(
            rt.shadows_all_opaque,
            "an opaque map must keep the fast path"
        );
        let rtc = RtCamera::new(&cam, &settings);

        let mut g = Film::new(48, 48);
        gpu.render(&rt, &rtc, &settings, &mut g, 0, 64).unwrap();
        let mut c = Film::new(48, 48);
        CpuBackend::new()
            .render(&rt, &rtc, &settings, &mut c, 0, 64)
            .unwrap();

        let (gh, ch) = (g.resolve_hdr(), c.resolve_hdr());
        for channel in 0..3 {
            let (gm, cm) = (mean_channel(&gh, channel), mean_channel(&ch, channel));
            assert!(gm > 0.01, "channel {channel} came out black on the GPU");
            assert!(
                (gm - cm).abs() < 0.03 * cm.max(0.05),
                "channel {channel}: gpu {gm}, cpu {cm} — the atlas is not sampling like the CPU"
            );
        }
        // The checker has to survive: a constant image would mean the atlas
        // returned one texel, or white.
        let reds: Vec<f32> = gh.chunks_exact(4).map(|p| p[0]).collect();
        let spread = reds.iter().cloned().fold(0.0f32, f32::max)
            - reds.iter().cloned().fold(f32::MAX, f32::min);
        assert!(
            spread > 0.15,
            "the texture flattened to a constant ({spread})"
        );
    }

    /// An environment map, which reaches the kernel through the same atlas plus
    /// the cube direction mapping. The failure this guards is loud: an
    /// environment that does not pack used to sample as full white.
    #[test]
    fn gpu_matches_cpu_with_an_environment_map() {
        let Some(mut gpu) = backend() else { return };
        let size = 8u32;
        let mut faces: [Vec<u8>; 6] = Default::default();
        // A distinct constant per face, so a mis-mapped direction shows up as a
        // wrong colour rather than as noise.
        let tints: [[u8; 3]; 6] = [
            [220, 40, 40],
            [40, 220, 40],
            [40, 40, 220],
            [220, 220, 40],
            [220, 40, 220],
            [40, 220, 220],
        ];
        for (f, tint) in faces.iter_mut().zip(tints) {
            let mut px = vec![255u8; (size * size * 4) as usize];
            for p in px.chunks_exact_mut(4) {
                p[0] = tint[0];
                p[1] = tint[1];
                p[2] = tint[2];
            }
            *f = px;
        }
        let cube = std::sync::Arc::new(crate::textures::CubeTexture::new(
            size,
            crate::textures::TextureFormat::Rgba8Unorm,
            faces,
        ));

        let mut scene = Scene::new();
        scene.background = Color::BLACK;
        scene.environment = Some(cube);
        scene.add(Object3D::mesh(Mesh::new(
            SphereGeometry::new(1.2, 32, 24),
            Material::Standard(StandardMaterial::new(Color::new(0.8, 0.8, 0.8))),
        )));

        let settings = RaytraceSettings {
            samples_per_pixel: 96,
            max_bounces: 2,
            denoise: false,
            background: BackgroundMode::Environment,
            ..Default::default()
        };
        let rt = RaytraceScene::build(&mut scene, &settings);
        assert!(rt.world.has_environment(), "the cube should have decoded");
        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 4.0);
        cam.target = Vector3::ZERO;
        let rtc = RtCamera::new(&cam, &settings);

        let mut g = Film::new(40, 40);
        gpu.render(&rt, &rtc, &settings, &mut g, 0, 192).unwrap();
        let mut c = Film::new(40, 40);
        CpuBackend::new()
            .render(&rt, &rtc, &settings, &mut c, 0, 96)
            .unwrap();

        let (gh, ch) = (g.resolve_hdr(), c.resolve_hdr());
        for channel in 0..3 {
            let (gm, cm) = (mean_channel(&gh, channel), mean_channel(&ch, channel));
            assert!(
                (gm - cm).abs() < 0.04 * cm.max(0.05),
                "channel {channel}: gpu {gm}, cpu {cm} — cube mapping disagrees"
            );
            // White would be the symptom of an environment that failed to pack.
            assert!(
                gm < 0.95,
                "channel {channel} reads {gm}: suspiciously white"
            );
        }
    }

    /// The kernel has to importance-sample the environment the same way the CPU
    /// does. A sun this small is found about once in eight hundred cosine-
    /// weighted samples, so a kernel that skipped the distribution would come
    /// back visibly darker at this budget and the means would not match.
    #[test]
    fn gpu_importance_samples_the_environment() {
        let Some(mut gpu) = backend() else { return };
        use crate::raytrace::backend::sun::{sun_scene, sun_settings};

        let mut cam = PerspectiveCamera::new(50.0, 1.0, 0.1, 100.0);
        cam.position = Vector3::new(0.0, 0.0, 5.0);
        cam.target = Vector3::ZERO;

        let settings = sun_settings(64);
        let mut scene = sun_scene();
        let rt = RaytraceScene::build(&mut scene, &settings);
        assert!(rt.world.env_distribution().is_some());
        let rtc = RtCamera::new(&cam, &settings);

        let mut g = Film::new(24, 24);
        gpu.render(&rt, &rtc, &settings, &mut g, 0, 64).unwrap();
        let mut c = Film::new(24, 24);
        CpuBackend::new()
            .render(&rt, &rtc, &settings, &mut c, 0, 64)
            .unwrap();

        let (gm, cm) = (
            mean_channel(&g.resolve_hdr(), 0),
            mean_channel(&c.resolve_hdr(), 0),
        );
        assert!(cm > 0.02, "the reference is not lit ({cm})");
        assert!(
            (gm - cm).abs() < 0.08 * cm,
            "gpu {gm} vs cpu {cm} — the kernel is not sampling the sun"
        );
    }

    /// The kernel's stopping rule has to be the CPU's stopping rule, or the two
    /// backends spend different budgets and diverge as they converge.
    #[test]
    fn gpu_adaptive_sampling_matches_the_cpu() {
        let Some(mut gpu) = backend() else { return };
        let mut scene = lit_box_scene();
        let settings = RaytraceSettings {
            samples_per_pixel: 128,
            max_bounces: 3,
            adaptive_threshold: 0.02,
            adaptive_min_samples: 16,
            denoise: false,
            ..Default::default()
        };
        let rt = RaytraceScene::build(&mut scene, &settings);
        let cam = RtCamera::new(&camera(), &settings);

        let mut g = Film::new(32, 32);
        gpu.render(&rt, &cam, &settings, &mut g, 0, 128).unwrap();
        let mut c = Film::new(32, 32);
        CpuBackend::new()
            .render(&rt, &cam, &settings, &mut c, 0, 128)
            .unwrap();

        let (g_lo, g_hi) = g.sample_range();
        let (c_lo, c_hi) = c.sample_range();
        assert!(g_lo < 128, "the kernel stopped nothing ({g_lo}..{g_hi})");
        assert!(c_lo < 128, "the CPU stopped nothing ({c_lo}..{c_hi})");

        let total = |f: &Film| {
            f.resolve_sample_counts()
                .iter()
                .map(|&n| n as f64)
                .sum::<f64>()
        };
        let (gt, ct) = (total(&g), total(&c));
        assert!(
            (gt - ct).abs() < 0.2 * ct,
            "budgets diverged: gpu {gt}, cpu {ct}"
        );

        let gm = mean_channel(&g.resolve_hdr(), 0);
        let cm = mean_channel(&c.resolve_hdr(), 0);
        assert!(
            (gm - cm).abs() < 0.05 * cm.max(0.02),
            "gpu {gm} vs cpu {cm}"
        );
    }

    /// Both backends have to map a direction to the same cube texel, on every
    /// face.
    ///
    /// Rendered with nothing in the scene and the environment as the
    /// background, so a camera ray goes straight to the sky and back: no
    /// scattering, no light sampling, almost no noise, and the comparison is
    /// per pixel rather than per tile. Six camera directions cover all six
    /// faces — an object in the scene only ever exposes the two or three faces
    /// it happens to face, which is how a mis-mapped face survives an
    /// end-to-end test.
    #[test]
    fn gpu_and_cpu_map_the_cube_the_same_way() {
        let Some(mut gpu) = backend() else { return };
        // A sky that encodes the *direction* at each texel, as `0.5 + 0.5 * d`.
        //
        // Not longitude and latitude: those are discontinuous — longitude at
        // the ±pi seam, which is exactly where a frame pointed at -X sits, and
        // both of them at the poles, which is where the ±Y frames sit. A
        // discontinuity there makes a sub-pixel difference in jitter read as a
        // large difference in value, and the test fails on its own encoding
        // rather than on anything the renderer did. The direction itself is
        // smooth over the whole sphere and still identifies every texel.
        let (w, h) = (256u32, 128u32);
        let mut src = vec![0.0f32; (w * h * 4) as usize];
        for y in 0..h {
            let theta = (y as f32 + 0.5) / h as f32 * std::f32::consts::PI;
            for x in 0..w {
                let phi = ((x as f32 + 0.5) / w as f32 - 0.5) * 2.0 * std::f32::consts::PI;
                let d = Vector3::new(
                    theta.sin() * phi.cos(),
                    theta.cos(),
                    theta.sin() * phi.sin(),
                );
                let i = ((y * w + x) * 4) as usize;
                src[i] = 0.5 + 0.5 * d.x;
                src[i + 1] = 0.5 + 0.5 * d.y;
                src[i + 2] = 0.5 + 0.5 * d.z;
                src[i + 3] = 1.0;
            }
        }
        let cube = crate::extras::PmremGenerator::from_equirect_f32(&src, w, h, 128);
        let mut scene = Scene::new();
        scene.environment = Some(std::sync::Arc::new(cube));

        let settings = RaytraceSettings {
            samples_per_pixel: 4,
            max_bounces: 0,
            background: BackgroundMode::Environment,
            adaptive_threshold: 0.0,
            denoise: false,
            ..Default::default()
        };
        let rt = RaytraceScene::build(&mut scene, &settings);

        for (i, target) in [
            Vector3::new(1.0, 0.0, 0.0),
            Vector3::new(-1.0, 0.0, 0.0),
            Vector3::new(0.0, 1.0, 0.0),
            Vector3::new(0.0, -1.0, 0.0),
            Vector3::new(0.0, 0.0, 1.0),
            Vector3::new(0.0, 0.0, -1.0),
        ]
        .into_iter()
        .enumerate()
        {
            let mut cam = PerspectiveCamera::new(60.0, 1.0, 0.1, 100.0);
            cam.position = Vector3::ZERO;
            cam.target = target;
            // Looking straight up or down, the default up-vector is degenerate.
            cam.up = if target.y.abs() > 0.9 {
                Vector3::new(0.0, 0.0, 1.0)
            } else {
                Vector3::new(0.0, 1.0, 0.0)
            };
            let rtc = RtCamera::new(&cam, &settings);

            let mut g = Film::new(24, 24);
            gpu.render(&rt, &rtc, &settings, &mut g, 0, 4).unwrap();
            let mut c = Film::new(24, 24);
            CpuBackend::new()
                .render(&rt, &rtc, &settings, &mut c, 0, 4)
                .unwrap();

            let (gh, ch) = (g.resolve_hdr(), c.resolve_hdr());
            let mut worst = 0.0f32;
            for (a, b) in gh.chunks_exact(4).zip(ch.chunks_exact(4)) {
                for k in 0..3 {
                    worst = worst.max((a[k] - b[k]).abs());
                }
            }
            assert!(
                worst < 0.03,
                "looking at {target:?} (face {i}): worst channel difference {worst} \
                 — the two backends disagree about where the sky is"
            );
        }
    }

    /// An HDR environment with a *directional* feature in it, so a within-face
    /// rotation cannot hide.
    ///
    /// The per-face-constant test above cannot see an orientation error at all:
    /// rotating a constant face leaves it constant. This one encodes longitude
    /// and latitude into the sky and puts a bright sun in it, so the kernel and
    /// the CPU have to agree on *where* the sky is, not just which face it is
    /// on — and on its dynamic range, which only survives if both read the HDR
    /// faces rather than the tone-mapped display copy.
    #[test]
    fn gpu_matches_cpu_on_an_hdr_environment() {
        let Some(mut gpu) = backend() else { return };
        let (w, h) = (256u32, 128u32);
        let sun = Vector3::new(0.55, 0.62, 0.56).normalize();
        let mut src = vec![0.0f32; (w * h * 4) as usize];
        for y in 0..h {
            let v = (y as f32 + 0.5) / h as f32;
            let theta = v * std::f32::consts::PI;
            for x in 0..w {
                let u = (x as f32 + 0.5) / w as f32;
                let phi = (u - 0.5) * 2.0 * std::f32::consts::PI;
                let d = Vector3::new(
                    theta.sin() * phi.cos(),
                    theta.cos(),
                    theta.sin() * phi.sin(),
                );
                let i = ((y * w + x) * 4) as usize;
                let c = if d.dot(sun) > 0.06f32.cos() {
                    [400.0, 380.0, 350.0]
                } else {
                    // A gradient, so the two backends must agree on direction.
                    [0.2 + 0.6 * u, 0.25 + 0.5 * v, 0.6]
                };
                src[i] = c[0];
                src[i + 1] = c[1];
                src[i + 2] = c[2];
                src[i + 3] = 1.0;
            }
        }
        let cube = crate::extras::PmremGenerator::from_equirect_f32(&src, w, h, 64);

        let mut scene = Scene::new();
        scene.environment = Some(std::sync::Arc::new(cube));
        // A near-mirror, not a diffuse ball. A diffuse surface *integrates* the
        // sky over its whole hemisphere, which washes a rearranged face out of
        // the result — the test would then pass with the cube mapping wrong. A
        // sharp metal images the sky instead, so where it is matters. Roughness
        // is 0.08 rather than 0 so the lobe stays non-delta and next-event
        // estimation still runs.
        let mut m = StandardMaterial::new(Color::new(0.95, 0.95, 0.95));
        m.roughness = 0.08;
        m.metalness = 1.0;
        scene.add(Object3D::mesh(Mesh::new(
            SphereGeometry::new(1.2, 48, 32),
            Material::Standard(m),
        )));

        let settings = RaytraceSettings {
            samples_per_pixel: 192,
            max_bounces: 2,
            clamp_indirect: 0.0,
            background: BackgroundMode::Environment,
            // Adaptive stopping would give the two backends different budgets
            // per pixel, which is a second source of difference on top of the
            // one being measured.
            adaptive_threshold: 0.0,
            denoise: false,
            ..Default::default()
        };
        let rt = RaytraceScene::build(&mut scene, &settings);
        assert!(rt.world.env_distribution().is_some());
        // The HDR faces have to have survived the trip.
        let peak = rt.world.lighting_radiance(sun);
        assert!(
            peak.x > 300.0,
            "the sun read back at {} — clamped somewhere",
            peak.x
        );

        // Two viewpoints, because one only shows part of the cube: the
        // background is whatever face the camera looks at and the reflection is
        // whatever the sphere faces. A single angle leaves two faces untested,
        // and a mapping error on those would go unseen.
        for (i, eye) in [Vector3::new(0.0, 0.0, 4.5), Vector3::new(4.5, 0.6, 0.0)]
            .into_iter()
            .enumerate()
        {
            let mut cam = PerspectiveCamera::new(70.0, 1.0, 0.1, 100.0);
            cam.position = eye;
            cam.target = Vector3::ZERO;
            let rtc = RtCamera::new(&cam, &settings);

            let mut g = Film::new(40, 40);
            gpu.render(&rt, &rtc, &settings, &mut g, 0, 192).unwrap();
            let mut c = Film::new(40, 40);
            CpuBackend::new()
                .render(&rt, &rtc, &settings, &mut c, 0, 192)
                .unwrap();

            let (gh, ch) = (g.resolve_hdr(), c.resolve_hdr());
            for channel in 0..3 {
                let (gm, cm) = (mean_channel(&gh, channel), mean_channel(&ch, channel));
                assert!(cm > 0.05, "view {i} channel {channel} is not lit ({cm})");
                assert!(
                    (gm - cm).abs() < 0.05 * cm,
                    "view {i} channel {channel}: gpu {gm}, cpu {cm} — the two disagree about the sky"
                );
            }

            // Spatially, not just on average: a rotated face moves the sky
            // around without changing its total much. Compared as 4x4 tile
            // means over all three channels — red encodes longitude and green
            // latitude, so one channel alone leaves an axis untested — because
            // a per-pixel comparison at this sample count is dominated by the
            // two backends' different random sequences where the sun reflects.
            let tile_means = |v: &[f32], channel: usize| {
                let mut tiles = [[0.0f64; 4]; 4];
                let mut counts = [[0u32; 4]; 4];
                for (p, px) in v.chunks_exact(4).enumerate() {
                    let (x, y) = (p % 40, p / 40);
                    let (tx, ty) = (x * 4 / 40, y * 4 / 40);
                    tiles[ty][tx] += px[channel] as f64;
                    counts[ty][tx] += 1;
                }
                let mut out = [[0.0f64; 4]; 4];
                for y in 0..4 {
                    for x in 0..4 {
                        out[y][x] = tiles[y][x] / counts[y][x].max(1) as f64;
                    }
                }
                out
            };
            for channel in 0..3 {
                let (gt, ct) = (tile_means(&gh, channel), tile_means(&ch, channel));
                for y in 0..4 {
                    for x in 0..4 {
                        assert!(
                            // Loose enough for the Monte-Carlo difference
                            // between two different random sequences where a
                            // 400:1 sun reflects; a mis-mapped face moves a
                            // tile by a third, which is well clear of it.
                            (gt[y][x] - ct[y][x]).abs() < 0.18 * ct[y][x].max(0.05),
                            "view {i} channel {channel}, tile ({x},{y}): gpu {:.4} vs cpu {:.4} \
                             — the sky is in different places",
                            gt[y][x],
                            ct[y][x]
                        );
                    }
                }
            }
        }
    }

    /// The kernel's sampler has to be stratified too, or the GPU quietly needs
    /// several times the samples the CPU does for the same image.
    #[test]
    fn gpu_converges_as_fast_as_the_cpu_at_low_sample_counts() {
        let Some(mut gpu) = backend() else { return };
        use crate::raytrace::backend::sun::{
            area_light_camera, area_light_scene, area_light_settings,
        };

        let reference = {
            let settings = area_light_settings(1024);
            let mut scene = area_light_scene();
            let rt = RaytraceScene::build(&mut scene, &settings);
            let rtc = RtCamera::new(&area_light_camera(), &settings);
            let mut film = Film::new(24, 24);
            CpuBackend::new()
                .render(&rt, &rtc, &settings, &mut film, 0, 1024)
                .unwrap();
            film.resolve_hdr()
        };

        let settings = area_light_settings(16);
        let mut scene = area_light_scene();
        let rt = RaytraceScene::build(&mut scene, &settings);
        let rtc = RtCamera::new(&area_light_camera(), &settings);
        let mut film = Film::new(24, 24);
        gpu.render(&rt, &rtc, &settings, &mut film, 0, 16).unwrap();
        let quick = film.resolve_hdr();

        let mut sse = 0.0f64;
        let mut mean = 0.0f64;
        let mut n = 0usize;
        for (a, b) in quick.chunks_exact(4).zip(reference.chunks_exact(4)) {
            for k in 0..3 {
                let d = (a[k] - b[k]) as f64;
                sse += d * d;
                mean += b[k] as f64;
                n += 1;
            }
        }
        let rms = (sse / n as f64).sqrt();
        let mean = mean / n as f64;
        assert!(mean > 0.05, "the scene is not lit ({mean})");
        assert!(
            rms < 0.048 * mean,
            "16 GPU samples are {:.1}% off converged — the kernel's sampler is not stratified",
            100.0 * rms / mean
        );
    }

    /// The guide passes are computed in both backends and consumed by the
    /// denoiser, so they have to agree. They are also the channels a caller
    /// would hand to an external denoiser, which makes a silent divergence
    /// between the two especially unhelpful.
    #[test]
    fn gpu_and_cpu_agree_on_the_denoiser_guides() {
        let Some(mut gpu) = backend() else { return };
        let mut scene = lit_box_scene();
        // A mirror, so the guides have to follow a specular bounce rather than
        // stopping at the first hit — the case the two could disagree on.
        let mut mirror = StandardMaterial::new(Color::new(0.9, 0.9, 0.95));
        mirror.roughness = 0.03;
        mirror.metalness = 1.0;
        let mut ball = Object3D::mesh(Mesh::new(
            SphereGeometry::new(0.9, 32, 24),
            Material::Standard(mirror),
        ));
        ball.position = Vector3::new(0.0, 0.9, 1.5);
        scene.add(ball);

        let settings = RaytraceSettings {
            samples_per_pixel: 64,
            max_bounces: 3,
            adaptive_threshold: 0.0,
            denoise: false,
            ..Default::default()
        };
        let rt = RaytraceScene::build(&mut scene, &settings);
        let cam = RtCamera::new(&camera(), &settings);

        let mut g = Film::new(32, 32);
        gpu.render(&rt, &cam, &settings, &mut g, 0, 64).unwrap();
        let mut c = Film::new(32, 32);
        CpuBackend::new()
            .render(&rt, &cam, &settings, &mut c, 0, 64)
            .unwrap();

        let (ga, ca) = (g.resolve_albedo(), c.resolve_albedo());
        let mean =
            |v: &[[f32; 3]]| v.iter().map(|p| p[0] as f64).sum::<f64>() / v.len().max(1) as f64;
        let (gm, cm) = (mean(&ga), mean(&ca));
        assert!(cm > 0.02, "the albedo guide is empty ({cm})");
        assert!(
            (gm - cm).abs() < 0.06 * cm,
            "albedo guide: gpu {gm:.4} vs cpu {cm:.4}"
        );

        // Normals are unit vectors, so their mean length says whether the two
        // backends agree about direction and not merely about magnitude.
        let (gn, cn) = (g.resolve_normal(), c.resolve_normal());
        let mut worst = 0.0f32;
        for (a, b) in gn.iter().zip(cn.iter()) {
            let dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
            // Both zero is agreement; otherwise they must point the same way.
            let len_a = (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt();
            let len_b = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt();
            if len_a > 0.1 && len_b > 0.1 {
                worst = worst.max(1.0 - dot);
            }
        }
        assert!(worst < 0.25, "normal guides diverge by {worst} (1 - cos)");
    }

    #[test]
    fn the_renderer_drives_the_gpu_backend() {
        let Some(gpu) = backend() else { return };
        let mut scene = lit_box_scene();
        let cam = camera();
        let mut r = super::super::RaytraceRenderer::with_backend(32, 32, Box::new(gpu));
        r.set_settings(
            RaytraceSettings::default()
                .with_samples(8)
                .with_denoise(false),
        );
        assert_eq!(r.backend_name(), "gpu");
        let rgba = r.render_to_rgba(&mut scene, &cam);
        assert_eq!(rgba.len(), 32 * 32 * 4);
        assert!(rgba.chunks_exact(4).any(|p| p[0] > 8), "image is black");
    }
}