crcbl-frame 0.20.0

Crucible frame core: render graph, transient pool, texture uploads and the UI pass
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
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
//! One texture upload, for every format and every caller.
//!
//! ```text
//! pixels ──pad rows to the device's copy alignment──▶ staging buffer
//!            │
//!            └──barrier ▸ copy_buffer_to_image ▸ barrier──▶ sampled image + view
//! ```
//!
//! # One layer or several, one level or a chain
//!
//! [`upload_texture`] uploads a single-layer `D2` image, which is what a sprite
//! sheet and a glyph atlas are. [`upload_texture_layers`] uploads several layers
//! of the same size into one `D2Array` image, which is
//! topic 03 §3.2's
//! [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) page: one image, one
//! descriptor, and a layer index in the material row selecting between them.
//! [`upload_texture_mip_layers`] is the same page with every layer's mip chain
//! behind it — topic 43's filtering rung, whose chain
//! [`crate::mip`] builds on the host.
//!
//! All three go through the same body, and it records **one copy per level of
//! every layer** rather than one covering all of them. That is not caution: a
//! copy region's extent is a 2D extent on every backend here — `crcbl-dx12`
//! refuses a `depth_or_layers` other than 1 by name, because
//! `CopyTextureRegion` addresses one subresource — so the layer travels in
//! [`ImageSubresourceLayers::base_layer`], the level in
//! [`ImageSubresourceLayers::mip`], and the buffer offset says where that
//! subresource's rows start.
//!
//! # A page that starts empty
//!
//! [`upload_cleared_texture`] is the same copy for an image that is mostly
//! zeroes — an atlas when it is created. The zeroes are written by a
//! [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) on the GPU and
//! copied into every layer, and only the rectangles written over them are
//! staged from the host. See that function for why the difference is the wasm
//! heap's.
//!
//! # Several at once
//!
//! Each function above is a batch of one: it records its copies, submits them
//! and waits. A caller with many uploads to make before its first frame records
//! them all into one [`UploadBatch`] instead, and pays for one submission and
//! one wait. The batch also carries [`UploadBatch::fill`], the same staging
//! copy into a device-local *buffer*, so a renderer's start-up state rides the
//! same submission as its textures. A caller with work of its own to do before
//! its first frame — [`crate::ui_pass`]'s renderer, and `crcbl_render`'s
//! forward renderer — submits the batch with
//! [`UploadBatch::submit_deferred`] instead, which does not wait: the copies
//! run under that work, and the [`PendingUpload`] it returns frees the staging
//! once the GPU is past it.
//!
//! This is a **startup** path, not a frame path: it records its own barriers
//! and blocks on [`Device::wait_idle`], which is only legal because no graph
//! is being recorded while it runs. See this crate's docs on the one rule — the
//! two staging uploads (`crcbl_render::forward`'s cube and this) are its named
//! exceptions. Its barriers name only the image it creates, so a caller between
//! two frames — `ForwardRenderer::replace_page`
//! reloading a page — touches nothing a frame in flight reads, and the wait
//! means no frame can bind the image before its copy has landed. A deferred
//! submit has no wait, and leans on queue order instead: see [`PendingUpload`]
//! for why that holds for a frame on the same queue.
//!
//! # Why it is not in `ui_pass`
//!
//! It was, and it was `R8_UNORM` only, with the glyph atlas's labels baked in.
//! The interesting part is that the old code was *right by coincidence*: it
//! computed a row pitch from `width`, called it `row_texels`, and handed it to
//! [`BufferImageCopy::buffer_row_length`] — which really is in texels, and
//! really did equal the byte count, because `R8Unorm` is one byte per texel.
//! For `Rgba8Unorm` the two differ by four, so the pitch here is computed in
//! **bytes** and converted back to texels exactly once, at the copy.

use crcbl_hal::{
    BufferCopy, BufferDesc, BufferImageCopy, BufferUsage, CommandEncoder, CommandEncoderDesc,
    Device, Extent3d, Features, Format, HalError, ImageAspect, ImageDesc, ImageHandle,
    ImageSubresourceLayers, ImageSubresourceRange, ImageType, ImageUsage, ImageViewDesc,
    ImageViewHandle, ImageViewType, MemoryLocation, Offset3d, QueueHandle, QueueKind,
    ResourceState, SemaphoreDesc, SemaphoreKind, SemaphoreSignal, SubmitInfo,
};

use crate::mip::level_extent;

/// A texture that has been uploaded: the image, and the view callers bind.
///
/// The two travel together because they die together, and every caller that
/// kept them as two loose handles has had to remember that on both its failure
/// path and its teardown path. [`UploadedTexture::destroy`] is the one place
/// the order lives.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UploadedTexture {
    /// The device-local image the copy filled.
    pub image: ImageHandle,
    /// A full-subresource colour view of [`UploadedTexture::image`]: `D2` from
    /// [`upload_texture`], `D2Array` from [`upload_texture_layers`] and
    /// [`upload_texture_mip_layers`].
    pub view: ImageViewHandle,
}

impl UploadedTexture {
    /// Releases the view and then the image. The device must be idle.
    pub fn destroy(&self, device: &dyn Device) {
        device.destroy_image_view(self.view);
        device.destroy_image(self.image);
    }
}

/// Uploads a 2D colour texture via a staging-buffer copy, and returns the image
/// and a view onto it.
///
/// `label` names the image and the view, and is the stem of the staging
/// buffer's and the encoder's names, so a capture shows which texture an
/// upload belonged to.
///
/// `pixels` must be exactly `width * height * texel_size` bytes, tightly
/// packed; the row padding the device's copy alignment wants is added here.
/// Padding rather than packing is what makes one upload path work on both
/// backends: Vulkan takes either, WebGPU requires a 256-byte row pitch and says
/// so through
/// [`optimal_buffer_copy_offset_alignment`](crcbl_hal::Limits::optimal_buffer_copy_offset_alignment).
///
/// Every object this creates is released on every path out, including the
/// failing ones: a `?` that dropped the staging buffer on the floor would leak
/// one per failed startup, and the recorder's leak assertions would only notice
/// once something actually failed.
///
/// # Errors
///
/// [`HalError::InvalidDescriptor`] if `format` has no single colour plane, if
/// either extent is zero, or if `pixels` is not exactly the size the extent and
/// the format imply — the last of which used to be a `copy_from_slice` panic
/// naming neither number. [`HalError`] from any seam call otherwise; an extent
/// past the device's `max_image_2d` is the device's to refuse, not this
/// function's.
pub fn upload_texture(
    device: &dyn Device,
    queue: QueueHandle,
    label: &str,
    format: Format,
    width: u32,
    height: u32,
    pixels: &[u8],
) -> Result<UploadedTexture, HalError> {
    upload(
        device,
        queue,
        label,
        format,
        (width, height),
        &[&[pixels]],
        ImageViewType::D2,
    )
}

/// Uploads several equally-sized layers into one `D2Array` colour image, and
/// returns it with an array view onto every layer.
///
/// §3.2's [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) page: the index a
/// material row carries is a layer of the image this returns. One image rather
/// than one descriptor per texture is what makes the lookup need no
/// [`Features::DESCRIPTOR_INDEXING`](crcbl_hal::Features::DESCRIPTOR_INDEXING),
/// and therefore run on every backend the engine has — see
/// `crcbl_render::forward`, which builds the page this crate's only caller binds.
///
/// Every slice in `layers` must be exactly one tightly packed
/// `width * height * texel_size` image, and they become layers 0, 1, … in the
/// order given. [`upload_texture`]'s account of the label, the row padding and
/// the release-on-every-path rule applies here unchanged. The image has one
/// mip level; [`upload_texture_mip_layers`] is the form that carries a chain.
///
/// # Errors
///
/// [`upload_texture`]'s errors, plus [`HalError::InvalidDescriptor`] when
/// `layers` is empty — a zero-layer image is not a page, and it reaches the
/// device as a zero extent whose complaint names a different thing. A layer
/// count past the device's `max_image_array_layers` is the device's to refuse.
pub fn upload_texture_layers(
    device: &dyn Device,
    queue: QueueHandle,
    label: &str,
    format: Format,
    width: u32,
    height: u32,
    layers: &[&[u8]],
) -> Result<UploadedTexture, HalError> {
    let chains: Vec<[&[u8]; 1]> = layers.iter().map(|pixels| [*pixels]).collect();
    let layers: Vec<&[&[u8]]> = chains.iter().map(|chain| &chain[..]).collect();
    upload(
        device,
        queue,
        label,
        format,
        (width, height),
        &layers,
        ImageViewType::D2Array,
    )
}

/// [`upload_texture_layers`] with a mip chain behind every layer: one
/// `D2Array` image whose level count is the chain's length, and an array view
/// onto every level of every layer.
///
/// `layers[layer][level]` is level `level` of layer `layer`, tightly packed at
/// that level's extent — `width` and `height` each halved per level and never
/// below one texel, which is [`crate::mip::level_extent`] and every backend's
/// own definition. Every layer carries the same number of levels, at least one
/// and at most the full chain
/// [`Extent3d::full_mip_levels`](crcbl_hal::Extent3d::full_mip_levels) counts;
/// a shorter chain is legal and leaves the sampler's `lod_max` to the caller.
///
/// # Errors
///
/// [`upload_texture_layers`]'s errors, plus [`HalError::InvalidDescriptor`]
/// when a layer has no levels, when two layers disagree on how many, when the
/// count exceeds the full chain, or when a level is not exactly its own
/// extent's worth of texels — each naming the layer and the level.
pub fn upload_texture_mip_layers(
    device: &dyn Device,
    queue: QueueHandle,
    label: &str,
    format: Format,
    width: u32,
    height: u32,
    layers: &[&[&[u8]]],
) -> Result<UploadedTexture, HalError> {
    upload(
        device,
        queue,
        label,
        format,
        (width, height),
        layers,
        ImageViewType::D2Array,
    )
}

/// Texels written over an [`upload_cleared_texture`] image as it is created: a
/// `width` by `height` rectangle of layer `layer`, its top-left texel at `x`,
/// `y`.
#[derive(Clone, Copy, Debug)]
pub struct TexturePatch<'a> {
    /// The array layer the rectangle is written to.
    pub layer: u32,
    /// The rectangle's left column.
    pub x: u32,
    /// The rectangle's top row.
    pub y: u32,
    /// Its width in texels.
    pub width: u32,
    /// Its height in texels.
    pub height: u32,
    /// Exactly `width * height * texel_size` bytes, tightly packed, rows top to
    /// bottom.
    pub pixels: &'a [u8],
}

/// The image [`upload_cleared_texture`] creates, and what goes on it.
#[derive(Clone, Copy, Debug)]
pub struct ClearedTextureDesc<'a> {
    /// Names the image and the view, and is the stem of the buffers' and the
    /// encoder's names, as in [`upload_texture`].
    pub label: &'a str,
    /// An uncompressed format with a single colour plane.
    pub format: Format,
    /// Width of every layer, in texels.
    pub width: u32,
    /// Height of every layer, in texels.
    pub height: u32,
    /// Array layers in the image; at least one.
    pub layers: u32,
    /// `D2` or `D2Array`: the shader's declaration decides, not `layers`.
    pub view_type: ImageViewType,
    /// Rectangles written over the zeroes, in order.
    pub patches: &'a [TexturePatch<'a>],
}

/// Creates a sampled colour image whose every texel is zero, with `patches`
/// written over it, and returns it with a full view.
///
/// **For a page that is mostly empty**, which is what an atlas is when it is
/// created: [`crate::ui_pass`]'s image atlas and glyph pages. Staging such a
/// page through [`upload_texture`] builds every zero texel on the host, pads a
/// second copy of it, and writes it into a staging buffer — and on
/// `crcbl-webgpu` that write is bytes on the command stream, which lives in the
/// wasm heap, grows to hold the whole start-up frame and never gives the
/// address space back. Here the zeroes never exist on the host: one
/// device-local buffer a layer in size is zeroed by
/// [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) and copied into
/// every layer, and only the patches are staged and written. The page is
/// transparent black where nothing was patched, on every backend, rather than
/// whatever an uninitialised image held.
///
/// One mip level. The same startup rules as [`upload_texture`]: it records its
/// own barriers, blocks on [`Device::wait_idle`], and releases every buffer it
/// created on every path out.
///
/// # Errors
///
/// [`upload_texture`]'s format and extent errors;
/// [`HalError::InvalidDescriptor`] for zero layers, and for a patch that is
/// empty, is not on a layer or inside the extent, or whose `pixels` is not its
/// own size — naming the patch. [`HalError`] from any seam call otherwise.
pub fn upload_cleared_texture(
    device: &dyn Device,
    queue: QueueHandle,
    desc: &ClearedTextureDesc<'_>,
) -> Result<UploadedTexture, HalError> {
    let mut batch = UploadBatch::new(device, queue, desc.label);
    let texture = batch.cleared_texture(desc)?;
    batch.submit_one(texture)
}

/// [`upload_cleared_texture`]'s validation and staging, recorded into
/// `batch`.
fn stage_cleared_texture(
    batch: &mut UploadBatch<'_>,
    desc: &ClearedTextureDesc<'_>,
) -> Result<UploadedTexture, HalError> {
    let device = batch.device;
    let label = desc.label;
    let texel = image_texel(label, desc.format, (desc.width, desc.height))?;
    if desc.layers == 0 {
        return Err(HalError::InvalidDescriptor(format!(
            "{label}: a texture needs at least one layer"
        )));
    }
    let alignment = device
        .caps()
        .limits
        .optimal_buffer_copy_offset_alignment
        .max(1);
    let full = u64::from(desc.width) * u64::from(texel);
    let full_pitch = padded_row_pitch(full, texel, alignment);
    // Whole words: `vkCmdFillBuffer` and `crcbl-dx12`'s clear refuse a size that
    // is not a multiple of four.
    let cleared = (full_pitch * u64::from(desc.height)).next_multiple_of(CLEAR_WORD_BYTES);
    let mut patched = Vec::new();
    let mut patch_regions = Vec::with_capacity(desc.patches.len());
    for (index, patch) in desc.patches.iter().enumerate() {
        let inside = patch
            .x
            .checked_add(patch.width)
            .is_some_and(|right| right <= desc.width)
            && patch
                .y
                .checked_add(patch.height)
                .is_some_and(|bottom| bottom <= desc.height);
        if patch.width == 0 || patch.height == 0 || patch.layer >= desc.layers || !inside {
            return Err(HalError::InvalidDescriptor(format!(
                "{label}: patch {index} is {}x{} at {},{} on layer {}, which is not a non-empty \
                 rectangle inside a {}x{} image of {} layer(s)",
                patch.width,
                patch.height,
                patch.x,
                patch.y,
                patch.layer,
                desc.width,
                desc.height,
                desc.layers
            )));
        }
        if let Some(other) = desc.patches[..index]
            .iter()
            .position(|earlier| earlier.layer == patch.layer && overlaps(earlier, patch))
        {
            return Err(HalError::InvalidDescriptor(format!(
                "{label}: patch {index} overlaps patch {other} on layer {}, and a texel written \
                 twice in one upload is a synchronisation hazard",
                patch.layer
            )));
        }
        let row_bytes = u64::from(patch.width) * u64::from(texel);
        let expected = row_bytes * u64::from(patch.height);
        if patch.pixels.len() as u64 != expected {
            return Err(HalError::InvalidDescriptor(format!(
                "{label}: patch {index} is {}x{} {:?}, {expected} bytes, got {}",
                patch.width,
                patch.height,
                desc.format,
                patch.pixels.len()
            )));
        }
        let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
        let staged =
            stage_rows(row_bytes, patch.height, row_pitch, patch.pixels).ok_or_else(|| {
                HalError::InvalidDescriptor(format!(
                    "{label}: patch {index} does not fit in this host's address space"
                ))
            })?;
        patch_regions.push(StagedRegion {
            buffer_offset: patched.len() as u64,
            row_texels: u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX),
            extent: Extent3d::d2(patch.width, patch.height),
            layer: patch.layer,
            mip: 0,
            image_offset: Offset3d {
                x: i32::try_from(patch.x).unwrap_or(i32::MAX),
                y: i32::try_from(patch.y).unwrap_or(i32::MAX),
                z: 0,
            },
        });
        patched.extend_from_slice(&staged);
    }

    // The zeroes go only where no patch does, so no texel is written twice: two
    // unbarriered writes to one subresource in one command buffer are a
    // synchronisation hazard Vulkan's sync validation reports.
    let row_texels = u32::try_from(full_pitch / u64::from(texel)).unwrap_or(u32::MAX);
    let layer_regions: Vec<StagedRegion> = (0..desc.layers)
        .flat_map(|layer| {
            let covered: Vec<&TexturePatch<'_>> = desc
                .patches
                .iter()
                .filter(|patch| patch.layer == layer)
                .collect();
            uncovered(desc.width, desc.height, &covered)
                .into_iter()
                .map(move |(x, y, width, height)| StagedRegion {
                    buffer_offset: 0,
                    row_texels,
                    extent: Extent3d::d2(width, height),
                    layer,
                    mip: 0,
                    image_offset: Offset3d {
                        x: i32::try_from(x).unwrap_or(i32::MAX),
                        y: i32::try_from(y).unwrap_or(i32::MAX),
                        z: 0,
                    },
                })
        })
        .collect();

    // Device-local, because a clear writes into the buffer on the GPU: a
    // `crcbl-dx12` upload-heap buffer can never be a copy destination.
    let zero_label = format!("{label} zero");
    let zero = device.create_buffer(&BufferDesc {
        label: Some(&zero_label),
        size: cleared,
        usage: BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
        memory: MemoryLocation::DeviceLocal,
    })?;
    batch.buffers.push(zero);
    let staging = if patched.is_empty() {
        None
    } else {
        let staging = create_staging(device, label, &patched)?;
        batch.buffers.push(staging);
        Some(staging)
    };
    let zero_source = CopySource {
        buffer: zero,
        regions: &layer_regions,
    };
    let sources: Vec<CopySource<'_>> = core::iter::once(zero_source)
        .chain(staging.map(|buffer| CopySource {
            buffer,
            regions: &patch_regions,
        }))
        .collect();
    batch.record(&UploadArgs {
        label,
        format: desc.format,
        width: desc.width,
        height: desc.height,
        layer_count: desc.layers,
        mip_levels: 1,
        view_type: desc.view_type,
        cleared: Some((zero, cleared)),
        sources: &sources,
    })
}

/// Whether two patches share a texel.
fn overlaps(a: &TexturePatch<'_>, b: &TexturePatch<'_>) -> bool {
    a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height
}

/// The rectangles of a `width` by `height` layer that no patch in `covered`
/// touches, as `(x, y, width, height)`: the layer cut into horizontal bands at
/// every patch's top and bottom edge, and each band's gaps between patches.
/// The patches must not overlap and must lie inside the layer.
fn uncovered(width: u32, height: u32, covered: &[&TexturePatch<'_>]) -> Vec<(u32, u32, u32, u32)> {
    let mut edges: Vec<u32> = covered
        .iter()
        .flat_map(|patch| [patch.y, patch.y + patch.height])
        .chain([0, height])
        .collect();
    edges.sort_unstable();
    edges.dedup();
    let mut gaps = Vec::new();
    for band in edges.windows(2) {
        let (top, bottom) = (band[0], band[1]);
        let mut spans: Vec<(u32, u32)> = covered
            .iter()
            .filter(|patch| patch.y < bottom && top < patch.y + patch.height)
            .map(|patch| (patch.x, patch.x + patch.width))
            .collect();
        spans.sort_unstable();
        let mut x = 0;
        for (left, right) in spans.into_iter().chain([(width, width)]) {
            if left > x {
                gaps.push((x, top, left - x, bottom - top));
            }
            x = x.max(right);
        }
    }
    gaps
}

/// The word [`clear_buffer`](crcbl_hal::CommandEncoder::clear_buffer) zeroes in
/// on the backends that fill `u32`s, and so the unit its size is rounded to.
const CLEAR_WORD_BYTES: u64 = 4;

/// The body the public uploads share, as a batch of one.
///
/// `extent` is `(width, height)` as one argument rather than two, which is what
/// keeps this inside the argument count the public wrappers already sit at.
fn upload(
    device: &dyn Device,
    queue: QueueHandle,
    label: &str,
    format: Format,
    extent: (u32, u32),
    layers: &[&[&[u8]]],
    view_type: ImageViewType,
) -> Result<UploadedTexture, HalError> {
    let mut batch = UploadBatch::new(device, queue, label);
    let texture = batch.texture(label, format, extent, layers, view_type)?;
    batch.submit_one(texture)
}

/// Validates `layers`, stages every level of every layer into one buffer, and
/// records the copies into `batch`.
fn stage_texture(
    batch: &mut UploadBatch<'_>,
    label: &str,
    format: Format,
    extent: (u32, u32),
    layers: &[&[&[u8]]],
    view_type: ImageViewType,
) -> Result<UploadedTexture, HalError> {
    let device = batch.device;
    let (width, height) = extent;
    let texel = image_texel(label, format, extent)?;
    let layer_count = u32::try_from(layers.len()).unwrap_or(u32::MAX);
    if layer_count == 0 {
        return Err(HalError::InvalidDescriptor(format!(
            "{label}: a texture needs at least one layer of pixels"
        )));
    }
    let mip_levels = u32::try_from(layers[0].len()).unwrap_or(u32::MAX);
    let full_chain = Extent3d::d2(width, height).full_mip_levels(ImageType::D2);
    if mip_levels == 0 {
        return Err(HalError::InvalidDescriptor(format!(
            "{label}: layer 0 has no mip levels; a layer needs at least its own texels"
        )));
    }
    if mip_levels > full_chain {
        return Err(HalError::InvalidDescriptor(format!(
            "{label}: {mip_levels} mip levels for a {width}x{height} image, whose full chain \
             is {full_chain}"
        )));
    }

    let alignment = device
        .caps()
        .limits
        .optimal_buffer_copy_offset_alignment
        .max(1);

    // Every level of every layer is validated and staged in the order the
    // copies below read them: layer-major, level-minor. Each level's rows are a
    // multiple of the alignment, so stacking them puts every subresource's own
    // offset on it too — which is what lets each copy name one buffer offset.
    let mut padded = Vec::new();
    let mut regions = Vec::with_capacity(layers.len() * mip_levels as usize);
    for (layer, chain) in layers.iter().enumerate() {
        if chain.len() as u32 != mip_levels {
            return Err(HalError::InvalidDescriptor(format!(
                "{label}: layer {layer} carries {} mip levels and layer 0 carries {mip_levels}; \
                 every layer of one image has the same chain",
                chain.len()
            )));
        }
        for (level, pixels) in chain.iter().enumerate() {
            let level_width = level_extent(width, level as u32);
            let level_height = level_extent(height, level as u32);
            let row_bytes = u64::from(level_width) * u64::from(texel);
            let expected = row_bytes * u64::from(level_height);
            if pixels.len() as u64 != expected {
                return Err(HalError::InvalidDescriptor(format!(
                    "{label}: layer {layer} level {level} of a {width}x{height} {format:?} image \
                     is {level_width}x{level_height}, {expected} bytes ({texel} per texel), got {}",
                    pixels.len()
                )));
            }
            let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
            let staged =
                stage_rows(row_bytes, level_height, row_pitch, pixels).ok_or_else(|| {
                    HalError::InvalidDescriptor(format!(
                        "{label}: a staging image of {} bytes and more does not fit in this \
                         host's address space",
                        padded.len()
                    ))
                })?;
            regions.push(StagedRegion {
                buffer_offset: padded.len() as u64,
                // The copy is in texels; the pitch above is in bytes.
                // `padded_row_pitch` guarantees the division is exact.
                row_texels: u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX),
                extent: Extent3d::d2(level_width, level_height),
                layer: layer as u32,
                mip: level as u32,
                image_offset: Offset3d { x: 0, y: 0, z: 0 },
            });
            padded.extend_from_slice(&staged);
        }
    }

    let staging = create_staging(device, label, &padded)?;
    batch.buffers.push(staging);
    batch.record(&UploadArgs {
        label,
        format,
        width,
        height,
        layer_count,
        mip_levels,
        view_type,
        cleared: None,
        sources: &[CopySource {
            buffer: staging,
            regions: &regions,
        }],
    })
}

/// The bytes one texel of `format` occupies, once `format` and `extent` are
/// known to describe an image this module can stage.
///
/// # Errors
///
/// [`HalError::InvalidDescriptor`] for a format with no single colour plane, a
/// block-compressed format, or a zero extent, each naming `label`.
fn image_texel(label: &str, format: Format, (width, height): (u32, u32)) -> Result<u32, HalError> {
    // `texel_size`, not `block_size`: it is the number a `BufferImageCopy` is
    // sized against, and it is `None` for exactly the formats this path cannot
    // describe — a combined depth/stencil format, whose two planes need two
    // copies and neither of which is a `COLOR` aspect.
    let texel = format.texel_size(ImageAspect::COLOR).ok_or_else(|| {
        HalError::InvalidDescriptor(format!(
            "{label}: {format:?} has no single colour plane, so it cannot be uploaded as one \
             colour-aspect copy"
        ))
    })?;
    // A compressed format's `block_size` covers a 4×4 block, not one texel, so
    // the per-texel sizing below would be wrong by a factor of four: a BC1 row
    // is `ceil(width / 4) × 8` bytes, not `width × 8`. No caller uploads one
    // today; refuse rather than corrupt.
    if format.is_compressed() {
        return Err(HalError::InvalidDescriptor(format!(
            "{label}: {format:?} is block-compressed and this path sizes per texel; \
             it cannot be uploaded as a colour-aspect copy"
        )));
    }
    if width == 0 || height == 0 {
        return Err(HalError::InvalidDescriptor(format!(
            "{label}: texture extent {width}x{height} must be non-zero in both dimensions"
        )));
    }
    Ok(texel)
}

/// A host-visible `TRANSFER_SRC` buffer labelled `"{label} staging"` holding
/// `bytes`, destroyed again if the write fails.
fn create_staging(
    device: &dyn Device,
    label: &str,
    bytes: &[u8],
) -> Result<crcbl_hal::BufferHandle, HalError> {
    let staging_label = format!("{label} staging");
    let staging = device.create_buffer(&BufferDesc {
        label: Some(&staging_label),
        size: bytes.len() as u64,
        usage: BufferUsage::TRANSFER_SRC,
        memory: MemoryLocation::HostUpload,
    })?;
    if let Err(error) = device.write_buffer(staging, 0, bytes) {
        device.destroy_buffer(staging);
        return Err(error);
    }
    Ok(staging)
}

/// A tightly packed region of `format` texels staged for an in-frame copy: a
/// host-visible `TRANSFER_SRC` buffer holding `pixels` with its rows padded to
/// the device's copy alignment, and the row pitch in texels a
/// [`BufferImageCopy`] reading it names.
///
/// The frame-time half of what [`upload_texture`] does at start-up, without the
/// image, the barriers or the wait: the caller records the copy inside a
/// [`RenderGraph`](crate::graph::RenderGraph) copy pass, which is where a
/// barrier recorded during a frame belongs. [`ui_pass`](crate::ui_pass)'s image
/// atlas and `crcbl_render`'s sprite atlas are the callers, and each owns the
/// buffer's lifetime.
///
/// # Errors
///
/// [`HalError::InvalidDescriptor`] if `format` has no single colour plane, if
/// the region is empty or if `pixels` is not exactly `width * height` texels;
/// [`HalError`] from creating or writing the buffer, which is destroyed again
/// if the write fails.
pub fn stage_region(
    device: &dyn Device,
    label: &str,
    format: Format,
    (width, height): (u32, u32),
    pixels: &[u8],
) -> Result<(crcbl_hal::BufferHandle, u32), HalError> {
    let texel = format.texel_size(ImageAspect::COLOR).ok_or_else(|| {
        HalError::InvalidDescriptor(format!("{label}: {format:?} has no single colour plane"))
    })?;
    let row_bytes = u64::from(width) * u64::from(texel);
    if width == 0 || height == 0 || pixels.len() as u64 != row_bytes * u64::from(height) {
        return Err(HalError::InvalidDescriptor(format!(
            "{label}: a {width}x{height} {format:?} region is {} bytes, got {}",
            row_bytes * u64::from(height),
            pixels.len()
        )));
    }
    let alignment = device
        .caps()
        .limits
        .optimal_buffer_copy_offset_alignment
        .max(1);
    let row_pitch = padded_row_pitch(row_bytes, texel, alignment);
    let staged = stage_rows(row_bytes, height, row_pitch, pixels).ok_or_else(|| {
        HalError::InvalidDescriptor(format!(
            "{label}: the staged region does not fit in this host's address space"
        ))
    })?;
    let buffer = device.create_buffer(&BufferDesc {
        label: Some(label),
        size: staged.len() as u64,
        usage: BufferUsage::TRANSFER_SRC,
        memory: MemoryLocation::HostUpload,
    })?;
    if let Err(error) = device.write_buffer(buffer, 0, &staged) {
        device.destroy_buffer(buffer);
        return Err(error);
    }
    // `padded_row_pitch` returns a whole number of texels, so this is exact.
    let row_texels = u32::try_from(row_pitch / u64::from(texel)).unwrap_or(u32::MAX);
    Ok((buffer, row_texels))
}

/// The row pitch in **bytes**: at least `row_bytes`, a multiple of `alignment`,
/// and a whole number of texels.
///
/// The last of those is why this is not one `next_multiple_of` call. The copy
/// expresses its pitch in texels, so a byte pitch that is not divisible by the
/// texel size cannot be expressed at all. Every real device's alignment is a
/// power of two at least as large as any uncompressed texel, so in practice the
/// lcm *is* the alignment — this costs nothing and removes the assumption.
fn padded_row_pitch(row_bytes: u64, texel: u32, alignment: u64) -> u64 {
    let texel = u64::from(texel);
    let step = texel / gcd(texel, alignment) * alignment;
    row_bytes.next_multiple_of(step)
}

/// Greatest common divisor, for [`padded_row_pitch`]'s lcm.
fn gcd(mut a: u64, mut b: u64) -> u64 {
    while b != 0 {
        (a, b) = (b, a % b);
    }
    a
}

/// Copies `height` tightly-packed rows of `row_bytes` into a buffer whose rows
/// are `row_pitch` bytes apart, zero-filling the padding.
///
/// `None` only when the padded image does not fit in a `usize`, which on a
/// 64-bit host means the caller asked for more than the address space.
fn stage_rows(row_bytes: u64, height: u32, row_pitch: u64, pixels: &[u8]) -> Option<Vec<u8>> {
    let size = usize::try_from(row_pitch * u64::from(height)).ok()?;
    let row_bytes = usize::try_from(row_bytes).ok()?;
    let row_pitch = usize::try_from(row_pitch).ok()?;
    let mut padded = vec![0u8; size];
    for row in 0..height as usize {
        let src = row * row_bytes;
        let dst = row * row_pitch;
        padded[dst..dst + row_bytes].copy_from_slice(&pixels[src..src + row_bytes]);
    }
    Some(padded)
}

/// One subresource's place in the staging buffer: what its
/// [`BufferImageCopy`] names besides the buffer and the image.
struct StagedRegion {
    /// Where this subresource's first row starts, on the copy alignment.
    buffer_offset: u64,
    /// The padded row pitch, in texels — the unit
    /// [`BufferImageCopy::buffer_row_length`] documents.
    row_texels: u32,
    /// This level's own extent, halved from the image's per level.
    extent: Extent3d,
    layer: u32,
    mip: u32,
    /// Where in that subresource the rows land: the origin for a whole level,
    /// the rectangle's corner for a [`TexturePatch`].
    image_offset: Offset3d,
}

/// One buffer the copies read, and the regions they read from it.
struct CopySource<'a> {
    buffer: crcbl_hal::BufferHandle,
    regions: &'a [StagedRegion],
}

/// Everything [`UploadBatch::record`] needs that is not the device, the queue
/// or the bytes — one struct rather than seven positional arguments, which is what
/// `clippy::too_many_arguments` is objecting to and also what makes the two
/// `u32`s impossible to swap at the call site.
struct UploadArgs<'a> {
    label: &'a str,
    format: Format,
    width: u32,
    height: u32,
    /// Array layers in the image.
    layer_count: u32,
    /// Mip levels in the image, and in every layer's chain.
    mip_levels: u32,
    /// `D2` for one layer, `D2Array` for a page. Not derived from
    /// `layer_count`: a one-layer array view is a legitimate thing to want, and
    /// the shader's declaration is what decides which it is.
    view_type: ImageViewType,
    /// A buffer the copies zero first, and how many bytes of it, for
    /// [`upload_cleared_texture`].
    cleared: Option<(crcbl_hal::BufferHandle, u64)>,
    /// Every copy, in the order they are recorded.
    sources: &'a [CopySource<'a>],
}

/// Startup uploads recorded into one command buffer and submitted with one
/// wait.
///
/// Each texture added is created at once, its staging written at once, and its
/// copies queued behind the ones before it; each buffer [`fill`](Self::fill)ed
/// is the caller's already, and its copy joins them. Nothing reaches the device
/// until [`submit`](Self::submit). One submission rather than one per upload
/// is the point: on Mesa's ANV the first submit on a fresh device costs several
/// milliseconds and every later round trip through [`Device::wait_idle`] costs
/// more than the copies of an empty page, and a renderer's start-up — this
/// crate's [`crate::ui_pass`], and `crcbl_render`'s forward renderer with its
/// views — makes many small uploads before its first frame.
///
/// The textures are the caller's from the moment they are returned, and
/// neither they nor a filled buffer may be read until `submit` has returned
/// `Ok` — or, after [`submit_deferred`](Self::submit_deferred), by anything
/// but later work on the batch's queue until its [`PendingUpload`] retires.
/// Binding one into a bind group before then is fine: a descriptor names a
/// resource, it does not read it. The staging and zero buffers are the
/// batch's, released when it drops: after the wait if it was submitted, and
/// before any submission if an add or the caller failed first. A deferred
/// submit hands them to its [`PendingUpload`] instead.
///
/// # No encoder until the submit
///
/// The barriers and copies are kept as data and recorded into an encoder that
/// [`submit`](Self::submit) creates, records, finishes and submits in one go —
/// never one held open while the caller does other work. A batch outlives
/// whole build steps that create, finish and submit encoders of their own, and
/// [`Device::create_command_encoder`] says at most one encoder per device may
/// be recording at a time: `crcbl-webgpu` streams every command into the one
/// encoder its browser side last created, so an encoder opened here at
/// [`new`](Self::new) lost its copies to the first encoder a caller made after
/// it.
///
/// # A failed build abandons the batch
///
/// A caller building several objects into one batch destroys what it had
/// created when a later step fails, and the batch still holds copies into
/// those objects. Submitting them would be a copy into a destroyed image, so a
/// caller that rolls back something it added calls [`abandon`](Self::abandon),
/// and every later add and the submit itself refuse. Dropping the batch
/// unsubmitted is the other way out, and the ordinary one: a build that fails
/// returns its error past the batch, and nothing is submitted.
#[derive(Debug)]
pub struct UploadBatch<'a> {
    device: &'a dyn Device,
    queue: QueueHandle,
    /// The encoder's name, so a refusal after [`UploadBatch::abandon`] says
    /// which batch it was.
    label: String,
    /// Every upload added, in the order [`submit`](Self::submit) records them.
    /// [`None`] once abandoned, which is what every add and the submit check.
    uploads: Option<Vec<Upload>>,
    buffers: Vec<crcbl_hal::BufferHandle>,
}

/// One add to an [`UploadBatch`], kept as what to record rather than recorded,
/// so the batch holds no encoder open — see the type's docs.
#[derive(Debug)]
enum Upload {
    /// A texture's barriers, its zero clear and its copies; see
    /// [`record_texture`].
    Texture {
        image: ImageHandle,
        range: ImageSubresourceRange,
        /// A buffer the copies zero first, and how many bytes of it.
        cleared: Option<(crcbl_hal::BufferHandle, u64)>,
        copies: Vec<BufferImageCopy>,
    },
    /// A [`fill`](UploadBatch::fill): `copy` into a buffer that has never held
    /// anything, left in `final_state`.
    Fill {
        copy: BufferCopy,
        final_state: ResourceState,
    },
}

impl<'a> UploadBatch<'a> {
    /// An empty batch; `label` is the stem of its encoder's name.
    pub fn new(device: &'a dyn Device, queue: QueueHandle, label: &str) -> Self {
        Self {
            device,
            queue,
            label: format!("{label} upload"),
            uploads: Some(Vec::new()),
            buffers: Vec::new(),
        }
    }

    /// The queue the batch submits to, for a builder that holds the batch and
    /// still submits some work of its own.
    pub fn queue(&self) -> QueueHandle {
        self.queue
    }

    /// [`upload_texture_mip_layers`], recorded into this batch:
    /// `layers[layer][level]` at `extent`, viewed as `view_type`.
    /// [`upload_texture`]'s one image is `&[&[pixels]]` and
    /// [`ImageViewType::D2`].
    ///
    /// # Errors
    ///
    /// As [`upload_texture_mip_layers`], before anything is recorded, and
    /// [`HalError::InvalidDescriptor`] once the batch is abandoned.
    pub fn texture(
        &mut self,
        label: &str,
        format: Format,
        extent: (u32, u32),
        layers: &[&[&[u8]]],
        view_type: ImageViewType,
    ) -> Result<UploadedTexture, HalError> {
        self.recording(label)?;
        stage_texture(self, label, format, extent, layers, view_type)
    }

    /// [`upload_cleared_texture`], recorded into this batch.
    ///
    /// # Errors
    ///
    /// As [`upload_cleared_texture`], before anything is recorded, and
    /// [`HalError::InvalidDescriptor`] once the batch is abandoned.
    pub fn cleared_texture(
        &mut self,
        desc: &ClearedTextureDesc<'_>,
    ) -> Result<UploadedTexture, HalError> {
        self.recording(desc.label)?;
        stage_cleared_texture(self, desc)
    }

    /// Writes `contents` over the start of `buffer` once, before any frame
    /// exists, leaving it in `final_state` once submitted.
    ///
    /// For a **device-local** buffer whose first frame reads something real —
    /// a host write cannot reach one, and a clear cannot say anything but zero
    /// and `crcbl-dx12` refuses one outright. `buffer` must carry
    /// [`BufferUsage::TRANSFER_DST`] and must never have held anything: its
    /// contents are discarded rather than transitioned, so a buffer a frame has
    /// already written is the wrong thing to hand this.
    ///
    /// `final_state` is the state the buffer's first importer declares as its
    /// initial one, so the graph's first barrier on it names a state the buffer
    /// is really in. `label` names the staging buffer, `"{label} staging"`.
    ///
    /// # Errors
    ///
    /// [`HalError`] from creating or writing the staging buffer, which is
    /// destroyed again if the write fails, and [`HalError::InvalidDescriptor`]
    /// once the batch is abandoned. Nothing is recorded on either.
    pub fn fill(
        &mut self,
        label: &str,
        buffer: crcbl_hal::BufferHandle,
        contents: &[u8],
        final_state: ResourceState,
    ) -> Result<(), HalError> {
        self.recording(label)?;
        let staging = create_staging(self.device, label, contents)?;
        self.buffers.push(staging);
        self.uploads
            .as_mut()
            .expect("checked by `recording` above, and nothing between abandons")
            .push(Upload::Fill {
                copy: BufferCopy {
                    src: staging,
                    src_offset: 0,
                    dst: buffer,
                    dst_offset: 0,
                    size: contents.len() as u64,
                },
                final_state,
            });
        Ok(())
    }

    /// Throws away everything recorded, because the caller is about to destroy
    /// something it added — see the type's docs. Every later add and
    /// [`submit`](Self::submit) refuse; the staging buffers are still released
    /// when the batch drops.
    pub fn abandon(&mut self) {
        self.uploads = None;
    }

    /// Records every queued copy into one encoder created here, submits it and
    /// waits for the device, leaving every texture in
    /// [`ResourceState::ShaderRead`] and every filled buffer in the state its
    /// [`fill`](Self::fill) named.
    ///
    /// # Errors
    ///
    /// [`HalError`] from finishing, submitting or waiting, and
    /// [`HalError::InvalidDescriptor`] for an abandoned batch, which submits
    /// nothing. The textures and buffers stay the caller's to destroy.
    pub fn submit(mut self) -> Result<(), HalError> {
        let commands = self.finish()?;
        let submitted = self
            .device
            .submit(self.queue, &SubmitInfo::new(&[commands]))
            .and_then(|()| self.device.wait_idle());
        self.device.destroy_command_buffer(commands);
        submitted
    }

    /// [`submit`](Self::submit) without the wait: the copies are submitted
    /// and the staging and zero buffers, the command buffer and a timeline
    /// semaphore the submission signals move into the returned
    /// [`PendingUpload`], which releases them once the GPU is past them.
    ///
    /// For a start-up whose first submission is expensive — pikr measured the
    /// first one on a fresh device at 7–10 ms on an Intel iGPU under Mesa's
    /// ANV, on 2026-10-29 — and which has other work to do before its first
    /// frame: the copies run under it instead of in front of it.
    ///
    /// The textures and filled buffers may be read by any work submitted
    /// **to the same queue** after this returns, with no wait in between; see
    /// [`PendingUpload`] for why that holds on every backend. Work on another
    /// queue, or a host read, must wait for [`PendingUpload::wait`] first.
    ///
    /// # Without timeline semaphores it waits
    ///
    /// A device without [`Features::TIMELINE_SEMAPHORE`] has nothing that
    /// says when the copies are done short of [`Device::wait_idle`], so this
    /// is [`submit`](Self::submit) there, and the [`PendingUpload`] it returns
    /// holds nothing. That is the WebGPU backend's case, and it costs nothing
    /// there: `crcbl-webgpu`'s `wait_idle` does not block, because the browser
    /// keeps a destroyed buffer alive for the work already queued against it.
    ///
    /// # Errors
    ///
    /// As [`submit`](Self::submit), and [`HalError`] from creating the
    /// semaphore. On every error nothing is pending and the buffers have been
    /// released: either nothing was submitted, or (on the waiting path) the
    /// wait has already run or failed as [`submit`](Self::submit)'s does.
    pub fn submit_deferred(mut self) -> Result<PendingUpload, HalError> {
        let device = self.device;
        if !device.caps().supports(Features::TIMELINE_SEMAPHORE) {
            self.submit()?;
            return Ok(PendingUpload { in_flight: None });
        }
        if self.uploads.is_none() {
            return Err(self.abandoned(&self.label));
        }
        let semaphore = device.create_semaphore(&SemaphoreDesc {
            label: Some(&self.label),
            kind: SemaphoreKind::Timeline { initial_value: 0 },
        })?;
        let commands = match self.finish() {
            Ok(commands) => commands,
            Err(error) => {
                device.destroy_semaphore(semaphore);
                return Err(error);
            }
        };
        let signals = [SemaphoreSignal {
            semaphore,
            value: PendingUpload::LANDED,
        }];
        let submit = SubmitInfo {
            command_buffers: &[commands],
            waits: &[],
            signals: &signals,
        };
        if let Err(error) = device.submit(self.queue, &submit) {
            device.destroy_command_buffer(commands);
            device.destroy_semaphore(semaphore);
            return Err(error);
        }
        Ok(PendingUpload {
            in_flight: Some(InFlightUpload {
                semaphore,
                commands,
                buffers: std::mem::take(&mut self.buffers),
            }),
        })
    }

    /// Records every queued upload into one encoder created here and finishes
    /// it, for either submit.
    fn finish(&mut self) -> Result<crcbl_hal::CommandBufferHandle, HalError> {
        let Some(uploads) = self.uploads.take() else {
            return Err(self.abandoned(&self.label));
        };
        let mut encoder = self.device.create_command_encoder(&CommandEncoderDesc {
            label: Some(&self.label),
            queue: self.queue,
        });
        for upload in &uploads {
            upload.record(encoder.as_mut());
        }
        encoder.finish()
    }

    /// `Ok` while the batch is still recording; the refusal naming `label`
    /// once it is abandoned.
    fn recording(&self, label: &str) -> Result<(), HalError> {
        match self.uploads {
            Some(_) => Ok(()),
            None => Err(self.abandoned(label)),
        }
    }

    fn abandoned(&self, what: &str) -> HalError {
        HalError::InvalidDescriptor(format!(
            "{what}: the batch {:?} was abandoned, because something recorded into it was \
             destroyed, so nothing in it may reach the device",
            self.label
        ))
    }

    /// [`submit`](Self::submit) for a batch of the one `texture`, which is
    /// destroyed if the submission fails.
    fn submit_one(self, texture: UploadedTexture) -> Result<UploadedTexture, HalError> {
        let device = self.device;
        match self.submit() {
            Ok(()) => Ok(texture),
            Err(error) => {
                texture.destroy(device);
                Err(error)
            }
        }
    }

    /// Creates the image and the view `args` describe and queues its copies,
    /// leaving it in [`ResourceState::ShaderRead`] once submitted.
    fn record(&mut self, args: &UploadArgs<'_>) -> Result<UploadedTexture, HalError> {
        let device = self.device;
        let image = device.create_image(&ImageDesc {
            label: Some(args.label),
            image_type: ImageType::D2,
            format: args.format,
            extent: Extent3d {
                width: args.width,
                height: args.height,
                // A `D2` image's `depth_or_layers` is its array length, which
                // the seam says on the field itself.
                depth_or_layers: args.layer_count,
            },
            mip_levels: args.mip_levels,
            samples: 1,
            // `TRANSFER_SRC` as well as the copy's `TRANSFER_DST`, so a test or
            // a capture can copy a level back out — `tests/forward_e2e/page.rs`
            // reads the page's chain that way. Free on every backend: a sampled
            // image that is also a copy source costs no layout, no memory and
            // no decompression it would not already pay.
            usage: ImageUsage::TRANSFER_SRC | ImageUsage::TRANSFER_DST | ImageUsage::SAMPLED,
        })?;
        let view = match device.create_image_view(&ImageViewDesc {
            label: Some(args.label),
            image,
            view_type: args.view_type,
            format: args.format,
            range: color_range(args.mip_levels, args.layer_count),
        }) {
            Ok(view) => view,
            Err(error) => {
                device.destroy_image(image);
                return Err(error);
            }
        };
        self.uploads
            .as_mut()
            .expect("every add checks `recording` before it creates anything")
            .push(Upload::Texture {
                image,
                range: color_range(args.mip_levels, args.layer_count),
                cleared: args.cleared,
                copies: texture_copies(args, image),
            });
        Ok(UploadedTexture { image, view })
    }
}

/// Refuses any `queue` but `device`'s [`QueueKind::Graphics`] queue for an
/// upload [`UploadBatch::submit_deferred`] will not wait for: `what` names the
/// caller, as "a UI pass" or "a forward renderer's view".
///
/// The rule every deferred caller shares, held in one place. Only the queue the
/// frames are submitted to orders the copies before the frames that read them,
/// since nothing waits on the host.
///
/// # Errors
///
/// [`HalError::InvalidDescriptor`] naming both queues.
pub fn require_frame_queue(
    device: &dyn Device,
    queue: QueueHandle,
    what: &str,
) -> Result<(), HalError> {
    let graphics = device.queue(QueueKind::Graphics);
    if graphics == Some(queue) {
        return Ok(());
    }
    Err(HalError::InvalidDescriptor(format!(
        "{what} must be on the device's graphics queue ({graphics:?}), the one its frames are \
         submitted to, and was given {queue:?}: its start-up uploads are not waited for, and \
         only that queue orders them before the frames that read them"
    )))
}

impl Drop for UploadBatch<'_> {
    fn drop(&mut self) {
        for buffer in self.buffers.drain(..) {
            self.device.destroy_buffer(buffer);
        }
    }
}

/// An [`UploadBatch`] submitted by
/// [`submit_deferred`](UploadBatch::submit_deferred) and not yet known to
/// have run: what it still owns, and the timeline value that says when it may
/// go.
///
/// # Why the textures may be sampled before it retires
///
/// The batch's last barrier on each image leaves it in
/// [`ResourceState::ShaderRead`], and what reads it next is a frame submitted
/// to the same queue after it. That is ordered without a host wait on every
/// backend here:
///
/// - **Vulkan**: a pipeline barrier's second synchronisation scope is every
///   command later in *submission order* on the queue, which spans later
///   `vkQueueSubmit`s, and the image's layout is a property of the image, not
///   of the command buffer that transitioned it.
/// - **D3D12**: a resource barrier's state persists past its command list, and
///   command lists on one queue run in `ExecuteCommandLists` order. An image
///   explicitly transitioned does not decay; a buffer does, to `COMMON`, the
///   same as it does after [`UploadBatch::submit`]'s wait.
/// - **Metal**: every resource `crcbl-mtl` allocates is hazard-tracked, and the
///   driver orders tracked hazards between command buffers committed to one
///   queue.
/// - **WebGPU**: never reaches here — [`UploadBatch::submit_deferred`] waits
///   on a device without timeline semaphores, which is every browser's — and
///   `queue.submit` order is WebGPU's own guarantee anyway.
///
/// Another queue has none of these guarantees, which is why the batch's queue
/// must be the one its readers submit to.
///
/// # What it still owns
///
/// The staging and zero buffers the copies read, the command buffer
/// ([`Device::destroy_command_buffer`] may not run before its submission
/// completes) and the semaphore. [`poll`](Self::poll) releases them once the
/// semaphore has reached [`LANDED`](Self::LANDED), without blocking;
/// [`wait`](Self::wait) blocks for it. One of the two must have released them
/// before the device is destroyed: dropping a pending upload leaks them, and
/// says so in the log, because releasing a buffer the GPU may still be reading
/// is the worse failure.
#[derive(Debug)]
#[must_use = "the staging buffers live until the upload is polled or waited for"]
pub struct PendingUpload {
    /// [`None`] once released, and for an upload that waited at its submit.
    in_flight: Option<InFlightUpload>,
}

/// What a [`PendingUpload`] releases.
#[derive(Debug)]
struct InFlightUpload {
    semaphore: crcbl_hal::SemaphoreHandle,
    commands: crcbl_hal::CommandBufferHandle,
    buffers: Vec<crcbl_hal::BufferHandle>,
}

impl PendingUpload {
    /// The value the submission signals its semaphore to once its copies have
    /// run. The semaphore is the upload's own, so it is the first value.
    pub const LANDED: u64 = 1;

    /// Whether everything has been released — at once for an upload that
    /// waited at its submit.
    #[must_use]
    pub const fn is_retired(&self) -> bool {
        self.in_flight.is_none()
    }

    /// Releases everything if the copies have run, without blocking, and says
    /// whether it is now retired.
    ///
    /// # Errors
    ///
    /// [`HalError`] from reading the semaphore — a lost device. Nothing is
    /// released then.
    pub fn poll(&mut self, device: &dyn Device) -> Result<bool, HalError> {
        let Some(in_flight) = &self.in_flight else {
            return Ok(true);
        };
        if device.semaphore_value(in_flight.semaphore)? < Self::LANDED {
            return Ok(false);
        }
        self.release(device);
        Ok(true)
    }

    /// Blocks until the copies have run, then releases everything. Returns at
    /// once for one already retired.
    ///
    /// No timeout, like the [`Device::wait_idle`] it replaces: a GPU that
    /// never finishes is a lost device, which the wait reports.
    ///
    /// # Errors
    ///
    /// [`HalError`] from the wait. Nothing is released then.
    pub fn wait(&mut self, device: &dyn Device) -> Result<(), HalError> {
        let Some(in_flight) = &self.in_flight else {
            return Ok(());
        };
        let wait = crcbl_hal::SemaphoreWait {
            semaphore: in_flight.semaphore,
            value: Self::LANDED,
        };
        if !device.wait_semaphores(&[wait], u64::MAX)? {
            return Err(HalError::Backend(
                "an upload's semaphore wait with no timeout reported a timeout".to_string(),
            ));
        }
        self.release(device);
        Ok(())
    }

    fn release(&mut self, device: &dyn Device) {
        if let Some(in_flight) = self.in_flight.take() {
            for buffer in in_flight.buffers {
                device.destroy_buffer(buffer);
            }
            device.destroy_command_buffer(in_flight.commands);
            device.destroy_semaphore(in_flight.semaphore);
        }
    }
}

impl Drop for PendingUpload {
    fn drop(&mut self) {
        if let Some(in_flight) = &self.in_flight {
            crcbl_core::log::warn!(
                "PendingUpload dropped before it was polled or waited for — {} staging buffers \
                 leaked",
                in_flight.buffers.len()
            );
        }
    }
}

/// The whole of a colour image `mips` levels deep and `layers` layers deep.
const fn color_range(mips: u32, layers: u32) -> ImageSubresourceRange {
    ImageSubresourceRange {
        aspect: ImageAspect::COLOR,
        base_mip: 0,
        mip_count: mips,
        base_layer: 0,
        layer_count: layers,
    }
}

/// One copy per subresource region `args` stages, into `image`.
///
/// A region's `image_extent` is a 2D extent whatever the image is —
/// `crcbl-dx12` refuses anything else by name, because `CopyTextureRegion`
/// addresses one subresource — so the layer and the level are named by
/// `base_layer` and `mip`, and the buffer offset says where that subresource's
/// rows start.
fn texture_copies(args: &UploadArgs<'_>, image: ImageHandle) -> Vec<BufferImageCopy> {
    args.sources
        .iter()
        .flat_map(|source| source.regions.iter().map(move |region| (source, region)))
        .map(|(source, region)| BufferImageCopy {
            buffer: source.buffer,
            buffer_offset: region.buffer_offset,
            buffer_row_length: region.row_texels,
            buffer_image_height: region.extent.height,
            image,
            image_subresource: ImageSubresourceLayers {
                aspect: ImageAspect::COLOR,
                mip: region.mip,
                base_layer: region.layer,
                layer_count: 1,
            },
            image_offset: region.image_offset,
            image_extent: region.extent,
        })
        .collect()
}

impl Upload {
    /// Records this upload into `encoder`. A texture's barriers name only its
    /// image and its own zero buffer, and a fill's only its buffer, so a
    /// batch's uploads do not wait on one another.
    fn record(&self, encoder: &mut dyn CommandEncoder) {
        match self {
            Self::Texture {
                image,
                range,
                cleared,
                copies,
            } => record_texture(encoder, *image, *range, *cleared, copies),
            Self::Fill { copy, final_state } => {
                // `Undefined` as the source: the buffer has never held
                // anything, so there is no state to preserve and its contents
                // are discarded rather than transitioned.
                encoder.pipeline_barrier(&crcbl_hal::Barriers {
                    buffers: &[crcbl_hal::BufferBarrier::new(
                        copy.dst,
                        ResourceState::Undefined,
                        ResourceState::TransferDst,
                    )],
                    ..Default::default()
                });
                encoder.copy_buffer_to_buffer(copy);
                encoder.pipeline_barrier(&crcbl_hal::Barriers {
                    buffers: &[crcbl_hal::BufferBarrier::new(
                        copy.dst,
                        ResourceState::TransferDst,
                        *final_state,
                    )],
                    ..Default::default()
                });
            }
        }
    }
}

/// Records `image`'s barriers, its zero clear and `copies`, leaving it in
/// [`ResourceState::ShaderRead`].
fn record_texture(
    encoder: &mut dyn CommandEncoder,
    image: ImageHandle,
    range: ImageSubresourceRange,
    cleared: Option<(crcbl_hal::BufferHandle, u64)>,
    copies: &[BufferImageCopy],
) {
    // Undefined → TransferDst: the image has never held anything, so its old
    // contents are explicitly discarded rather than transitioned. The range
    // covers every level of every layer, so one barrier serves all the copies
    // below.
    encoder.pipeline_barrier(&crcbl_hal::Barriers {
        images: &[crcbl_hal::ImageBarrier::new(
            image,
            range,
            ResourceState::Undefined,
            ResourceState::TransferDst,
        )],
        ..Default::default()
    });

    // Outside any pass, and before the copies that read it: a clear is recorded
    // into the same command buffer, so it runs first on every backend. The
    // buffer is then moved to a copy source explicitly, because the clear left
    // it a copy destination: D3D12 promotes a buffer implicitly only out of
    // `COMMON`, which a fresh one is in and this one no longer is.
    if let Some((buffer, size)) = cleared {
        encoder.clear_buffer(buffer, 0, size);
        encoder.pipeline_barrier(&crcbl_hal::Barriers {
            buffers: &[crcbl_hal::BufferBarrier::new(
                buffer,
                ResourceState::TransferDst,
                ResourceState::TransferSrc,
            )],
            ..Default::default()
        });
    }

    for copy in copies {
        encoder.copy_buffer_to_image(copy);
    }

    encoder.pipeline_barrier(&crcbl_hal::Barriers {
        images: &[crcbl_hal::ImageBarrier::new(
            image,
            range,
            ResourceState::TransferDst,
            ResourceState::ShaderRead,
        )],
        ..Default::default()
    });
}

// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;
    use crcbl_hal::null::{Command, Event, NullInstance, Recorder};
    use crcbl_hal::{DeviceDesc, Features, Instance, QueueKind};

    /// Tier B, because its `optimal_buffer_copy_offset_alignment` is 256 —
    /// WebGPU's — and Tier A's is 4, which an `Rgba8Unorm` row satisfies for
    /// free. Padding is only exercised on the tier that asks for it.
    fn open_tier_b(recorder: &Recorder) -> (Box<dyn Device>, QueueHandle) {
        let instance = NullInstance::portable().with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        let device = instance
            .create_device(&DeviceDesc {
                label: None,
                adapter: adapter.id,
                required_features: Features::COMPUTE,
                optional_features: Features::empty(),
                compatible_surface: None,
            })
            .expect("the tier B null adapter opens");
        let queue = device.queue(QueueKind::Graphics).expect("always present");
        (device, queue)
    }

    fn open_tier_a(recorder: &Recorder) -> (Box<dyn Device>, QueueHandle) {
        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
        let adapter = instance.adapters().remove(0);
        let device = instance
            .create_device(&DeviceDesc {
                label: None,
                adapter: adapter.id,
                required_features: Features::GPU_DRIVEN,
                optional_features: Features::empty(),
                compatible_surface: None,
            })
            .expect("the null backend always opens");
        let queue = device.queue(QueueKind::Graphics).expect("always present");
        (device, queue)
    }

    fn the_copies(recorder: &Recorder) -> Vec<BufferImageCopy> {
        recorder
            .commands()
            .into_iter()
            .filter_map(|command| match command {
                Command::CopyBufferToImage(copy) => Some(copy),
                _ => None,
            })
            .collect()
    }

    fn the_copy(recorder: &Recorder) -> BufferImageCopy {
        let copies = the_copies(recorder);
        assert_eq!(
            copies.len(),
            1,
            "a single-layer upload records exactly one buffer-to-image copy"
        );
        copies[0]
    }

    fn bytes_written(recorder: &Recorder) -> usize {
        recorder
            .events()
            .into_iter()
            .find_map(|event| match event {
                Event::BufferWritten { len, .. } => Some(len),
                _ => None,
            })
            .expect("an upload writes its staging buffer once")
    }

    /// A 100-texel RGBA row: 400 bytes, which Tier B's 256-byte alignment pads
    /// to 512. Every number here is different from the one the old
    /// texels-as-bytes arithmetic would produce — that pitched 100 up to 256 —
    /// so this is what fails if a pitch is ever computed from `width` rather
    /// than `width * texel_size` again.
    const WIDTH: u32 = 100;
    const HEIGHT: u32 = 3;
    const ROW_BYTES: usize = 400;
    const PITCH: usize = 512;

    fn ramp(len: usize) -> Vec<u8> {
        // Coprime with 256, so no two bytes 256 apart are equal and a row
        // written at the wrong offset cannot compare equal by accident.
        (0..len).map(|index| (index % 251) as u8).collect()
    }

    /// The row pitch is in **bytes**, and each source row lands at its padded
    /// byte offset with zeroes after it.
    #[test]
    fn each_source_row_lands_at_its_padded_byte_offset() {
        let texel = Format::Rgba8Unorm
            .texel_size(ImageAspect::COLOR)
            .expect("rgba8 is a colour format");
        assert_eq!(texel, 4);

        let row_bytes = u64::from(WIDTH) * u64::from(texel);
        assert_eq!(row_bytes as usize, ROW_BYTES);
        let pitch = padded_row_pitch(row_bytes, texel, 256);
        assert_eq!(
            pitch as usize, PITCH,
            "400 bytes padded up to the 256-byte alignment is 512, not 256"
        );

        let pixels = ramp(ROW_BYTES * HEIGHT as usize);
        let padded = stage_rows(row_bytes, HEIGHT, pitch, &pixels).expect("fits");
        assert_eq!(padded.len(), PITCH * HEIGHT as usize);
        for row in 0..HEIGHT as usize {
            let start = row * PITCH;
            assert_eq!(
                &padded[start..start + ROW_BYTES],
                &pixels[row * ROW_BYTES..(row + 1) * ROW_BYTES],
                "row {row} must sit at byte {start}"
            );
            assert!(
                padded[start + ROW_BYTES..start + PITCH]
                    .iter()
                    .all(|&byte| byte == 0),
                "row {row}'s padding must be zero, not the next row"
            );
        }
    }

    /// And the copy is told that pitch in *texels*, which is the unit
    /// [`BufferImageCopy::buffer_row_length`] documents.
    #[test]
    fn an_rgba_upload_records_its_pitch_in_texels() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_b(&recorder);
        assert_eq!(
            device.caps().limits.optimal_buffer_copy_offset_alignment,
            256,
            "the padding this test exercises only exists on the tier that asks for it"
        );
        let pixels = ramp(ROW_BYTES * HEIGHT as usize);

        let texture = upload_texture(
            device.as_ref(),
            queue,
            "sprite atlas",
            Format::Rgba8Unorm,
            WIDTH,
            HEIGHT,
            &pixels,
        )
        .expect("the null backend accepts this");

        assert_eq!(
            bytes_written(&recorder),
            PITCH * HEIGHT as usize,
            "the staging write is the padded image, not the packed one"
        );
        let copy = the_copy(&recorder);
        assert_eq!(
            copy.buffer_row_length, 128,
            "512 bytes of pitch is 128 rgba texels, not 512"
        );
        assert_eq!(copy.buffer_image_height, HEIGHT);
        assert_eq!(copy.image_extent, Extent3d::d2(WIDTH, HEIGHT));
        assert_eq!(copy.image_offset, Offset3d { x: 0, y: 0, z: 0 });

        texture.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// A device whose alignment an `Rgba8Unorm` row already satisfies pads
    /// nothing, and the copy's pitch is then simply the width.
    #[test]
    fn an_aligned_row_is_not_padded() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        assert_eq!(device.caps().limits.optimal_buffer_copy_offset_alignment, 4);
        let pixels = vec![0u8; 5 * 3 * 4];
        let texture = upload_texture(
            device.as_ref(),
            queue,
            "tight",
            Format::Rgba8Unorm,
            5,
            3,
            &pixels,
        )
        .expect("accepted");
        assert_eq!(bytes_written(&recorder), 5 * 3 * 4);
        assert_eq!(the_copy(&recorder).buffer_row_length, 5);
        texture.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// The pitch satisfies the alignment *and* stays a whole number of texels,
    /// including when the two do not divide each other — a byte pitch the copy
    /// cannot express in texels is not a pitch.
    #[test]
    fn a_row_pitch_is_aligned_and_a_whole_number_of_texels() {
        // The ordinary cases: alignment already a multiple of the texel.
        assert_eq!(padded_row_pitch(20, 4, 256), 256);
        assert_eq!(padded_row_pitch(20, 4, 4), 20);
        assert_eq!(padded_row_pitch(5, 1, 4), 8);
        assert_eq!(padded_row_pitch(1024, 4, 256), 1024);
        // The awkward one: 6-byte alignment, 4-byte texel. 4 is not enough (it
        // is not a multiple of 6) and 6 is not enough (it is not a whole texel);
        // 12 is the first that is both.
        let pitch = padded_row_pitch(4, 4, 6);
        assert_eq!(pitch, 12);
        assert_eq!(pitch % 6, 0, "must satisfy the alignment");
        assert_eq!(pitch % 4, 0, "must be a whole number of texels");
    }

    /// **A page is one image whose layers each get their own copy**, and each
    /// copy reads the layer's own slice of the staging buffer.
    ///
    /// The offsets are what this is for. Every layer's rows are padded, so a
    /// second layer read at `width * height * texel` — the *unpadded* size —
    /// would take the tail of the first layer plus part of the second and put
    /// a plausible smear in the page. Tier B is used because its 256-byte
    /// alignment is what makes the padded and unpadded strides differ.
    #[test]
    fn a_page_copies_each_layer_from_its_own_padded_offset() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_b(&recorder);
        let layers: Vec<Vec<u8>> = (0..3).map(|_| ramp(ROW_BYTES * HEIGHT as usize)).collect();
        let refs: Vec<&[u8]> = layers.iter().map(Vec::as_slice).collect();

        let page = upload_texture_layers(
            device.as_ref(),
            queue,
            "material page",
            Format::Rgba8Unorm,
            WIDTH,
            HEIGHT,
            &refs,
        )
        .expect("the null backend accepts this");

        let layer_bytes = PITCH * HEIGHT as usize;
        assert_eq!(
            bytes_written(&recorder),
            layer_bytes * layers.len(),
            "the staging write is every layer, padded"
        );
        let copies = the_copies(&recorder);
        assert_eq!(
            copies.len(),
            layers.len(),
            "one copy per layer, because a region's extent is 2D on every backend"
        );
        for (layer, copy) in copies.iter().enumerate() {
            assert_eq!(
                copy.buffer_offset,
                (layer * layer_bytes) as u64,
                "layer {layer} must read from its own slice of the staging buffer"
            );
            assert_eq!(
                copy.image_subresource.base_layer, layer as u32,
                "layer {layer} must be written to layer {layer} of the image"
            );
            assert_eq!(copy.image_subresource.layer_count, 1);
            assert_eq!(copy.buffer_row_length, 128);
            assert_eq!(
                copy.image_extent,
                Extent3d::d2(WIDTH, HEIGHT),
                "a copy region's extent stays 2D"
            );
        }

        page.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// A page with no layers is refused here, by name.
    ///
    /// Without the guard it reaches the device as an image whose
    /// `depth_or_layers` is zero, whose complaint is about an *extent* — a
    /// different object and a message that does not say what the caller did.
    #[test]
    fn a_page_with_no_layers_is_rejected() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let error = upload_texture_layers(
            device.as_ref(),
            queue,
            "empty page",
            Format::Rgba8Unorm,
            4,
            4,
            &[],
        )
        .expect_err("a page needs a layer");
        assert!(
            error.to_string().contains("at least one layer"),
            "got: {error}"
        );
        assert_eq!(recorder.total_live_objects(), 0);
    }

    /// A short or long slice is an error naming both numbers, not a
    /// `copy_from_slice` panic naming neither — and nothing is created before
    /// it is noticed.
    #[test]
    fn a_wrong_sized_pixel_slice_is_rejected() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let before = recorder.total_live_objects();

        let short = vec![0u8; 5 * 3 * 4 - 1];
        let error = upload_texture(
            device.as_ref(),
            queue,
            "short",
            Format::Rgba8Unorm,
            5,
            3,
            &short,
        )
        .expect_err("a 59-byte slice is not a 5x3 rgba image");
        let message = error.to_string();
        assert!(
            message.contains("60") && message.contains("59"),
            "the error must name both sizes, got: {message}"
        );

        let long = vec![0u8; 5 * 3 * 4 + 1];
        upload_texture(
            device.as_ref(),
            queue,
            "long",
            Format::Rgba8Unorm,
            5,
            3,
            &long,
        )
        .expect_err("a 61-byte slice is not one either");

        assert_eq!(
            recorder.total_live_objects(),
            before,
            "a rejected upload creates nothing"
        );
    }

    /// A zero extent is refused here rather than reaching the device as a
    /// zero-sized staging buffer, which is a different error about a different
    /// object.
    #[test]
    fn a_zero_extent_is_rejected() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        for (width, height) in [(0u32, 4u32), (4, 0)] {
            let error = upload_texture(
                device.as_ref(),
                queue,
                "empty",
                Format::Rgba8Unorm,
                width,
                height,
                &[],
            )
            .expect_err("a zero extent is not a texture");
            // "texture extent", not merely "non-zero": without the guard above
            // this reaches the device as a zero-sized *buffer*, whose own error
            // also says "non-zero" and would have made this test pass while
            // naming the wrong object.
            assert!(
                error.to_string().contains("texture extent"),
                "got: {error}, which is not the extent complaint"
            );
        }
        assert_eq!(recorder.total_live_objects(), 0);
    }

    /// A combined depth/stencil format has two planes and no colour aspect, so
    /// there is no single `texel_size` to pitch against. Refused by name rather
    /// than silently pitched against `block_size`, which would be 8.
    #[test]
    fn a_depth_stencil_format_is_rejected() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let error = upload_texture(
            device.as_ref(),
            queue,
            "depth",
            Format::D32FloatS8Uint,
            4,
            4,
            &[0u8; 128],
        )
        .expect_err("a depth/stencil upload needs one copy per plane");
        assert!(error.to_string().contains("colour plane"), "got: {error}");
        assert_eq!(recorder.total_live_objects(), 0);
    }

    /// A compressed format's `block_size` covers a 4×4 block, not one texel, so
    /// the per-texel sizing here would be wrong by a factor of four — and there
    /// is no caller that needs one. Refused by name rather than silently
    /// pitched against the block size, before any device call.
    #[test]
    fn a_compressed_format_is_rejected() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        // 8x8 BC1 is 2x2 blocks of 8 bytes: the *correct* compressed size, so a
        // regression that accepted compressed uploads would pass the size check
        // and fail only here.
        let error = upload_texture(
            device.as_ref(),
            queue,
            "compressed",
            Format::Bc1RgbaUnorm,
            8,
            8,
            &[0u8; 2 * 2 * 8],
        )
        .expect_err("a BC1 upload is sized per block, not per texel");
        assert!(
            error.to_string().contains("block-compressed"),
            "got: {error}"
        );
        assert_eq!(recorder.total_live_objects(), 0);
    }

    /// A failure after the staging buffer exists releases it. `create_image`
    /// is what fails: Tier A's `max_image_2d` is 16384, and a 16385x1 R8 image
    /// is one byte per texel, so the staging allocation this must clean up is
    /// 16 KiB rather than something that would fail for its own reasons first.
    #[test]
    fn a_failed_upload_leaks_nothing() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let limit = device.caps().limits.max_image_2d;
        assert_eq!(limit, 16384);
        let before = recorder.total_live_objects();

        let width = limit + 1;
        let pixels = vec![0u8; width as usize];
        let error = upload_texture(
            device.as_ref(),
            queue,
            "too wide",
            Format::R8Unorm,
            width,
            1,
            &pixels,
        )
        .expect_err("the device refuses an image past max_image_2d");
        assert!(
            error.to_string().contains("max_image_2d"),
            "the failure must be the image, not something earlier: {error}"
        );

        assert_eq!(
            recorder.total_live_objects(),
            before,
            "the staging buffer created before the failure must be destroyed"
        );
        assert!(
            recorder
                .events()
                .iter()
                .any(|event| matches!(event, Event::BufferWritten { .. })),
            "the test is only meaningful if the staging buffer really was created \
             and written before the failure"
        );
    }

    /// **A chain is one copy per level of every layer**, each into its own mip
    /// and each from its own padded offset — level-minor, so a layer's whole
    /// chain sits together in the staging buffer.
    ///
    /// Tier B again, for the padded-versus-unpadded reason above, and a width
    /// that halves onto rows of three different pitches: 100 texels pad to 512
    /// bytes, 50 to 256, 25 to 256. A level offset computed from level 0's
    /// pitch would land the second level's rows inside the first's tail.
    #[test]
    fn a_chain_copies_each_level_into_its_own_mip_from_its_own_offset() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_b(&recorder);
        // Three of the seven levels a 100-wide image has: a partial chain is
        // legal, and each level is its own extent's worth of texels.
        let level_extents = [(WIDTH, HEIGHT), (50, 1), (25, 1)];
        let chains: Vec<Vec<Vec<u8>>> = (0..2)
            .map(|_| {
                level_extents
                    .iter()
                    .map(|&(width, height)| ramp((width * height * 4) as usize))
                    .collect()
            })
            .collect();
        let levels: Vec<Vec<&[u8]>> = chains
            .iter()
            .map(|chain| chain.iter().map(Vec::as_slice).collect())
            .collect();
        let layers: Vec<&[&[u8]]> = levels.iter().map(Vec::as_slice).collect();

        let page = upload_texture_mip_layers(
            device.as_ref(),
            queue,
            "mipped page",
            Format::Rgba8Unorm,
            WIDTH,
            HEIGHT,
            &layers,
        )
        .expect("the null backend accepts a partial chain");

        let level_bytes = [PITCH * HEIGHT as usize, 256, 256];
        let layer_bytes: usize = level_bytes.iter().sum();
        assert_eq!(
            bytes_written(&recorder),
            layer_bytes * chains.len(),
            "the staging write is every level of every layer, each padded to its own pitch"
        );
        let copies = the_copies(&recorder);
        assert_eq!(copies.len(), chains.len() * level_extents.len());
        let mut expected_offset = 0u64;
        for (index, copy) in copies.iter().enumerate() {
            let layer = index / level_extents.len();
            let level = index % level_extents.len();
            let (width, height) = level_extents[level];
            assert_eq!(
                (
                    copy.image_subresource.base_layer,
                    copy.image_subresource.mip
                ),
                (layer as u32, level as u32),
                "copy {index} is layer {layer}'s level {level}"
            );
            assert_eq!(copy.image_subresource.layer_count, 1);
            assert_eq!(
                copy.buffer_offset, expected_offset,
                "layer {layer} level {level} reads from its own slice of the staging buffer"
            );
            assert_eq!(
                copy.image_extent,
                Extent3d::d2(width, height),
                "level {level} is copied at its own extent"
            );
            assert_eq!(copy.buffer_image_height, height);
            assert_eq!(
                copy.buffer_row_length as usize * 4,
                level_bytes[level] / height as usize,
                "level {level}'s pitch is its own row padded, in texels"
            );
            expected_offset += level_bytes[level] as u64;
        }

        page.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// The single-level form is the chain form with one level, so the image it
    /// creates has one mip and the copies name it — a `mip_levels` that
    /// followed the chain length would otherwise be off by one somewhere.
    #[test]
    fn a_single_level_page_is_a_chain_of_one() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let pixels = vec![0u8; 4 * 4 * 4];
        let page = upload_texture_layers(
            device.as_ref(),
            queue,
            "flat page",
            Format::Rgba8Unorm,
            4,
            4,
            &[&pixels],
        )
        .expect("accepted");
        let copy = the_copy(&recorder);
        assert_eq!(copy.image_subresource.mip, 0);
        page.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// A chain that is ragged, too long, empty, or has a level of the wrong
    /// size is refused by name before anything is created.
    #[test]
    fn a_malformed_chain_is_rejected_naming_the_layer_and_the_level() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let before = recorder.total_live_objects();
        let level0 = vec![0u8; 4 * 4 * 4];
        let level1 = vec![0u8; 2 * 2 * 4];
        let level2 = vec![0u8; 4];
        let upload = |layers: &[&[&[u8]]]| {
            upload_texture_mip_layers(
                device.as_ref(),
                queue,
                "chain",
                Format::Rgba8Unorm,
                4,
                4,
                layers,
            )
            .expect_err("a malformed chain is not a page")
            .to_string()
        };

        let ragged = upload(&[&[&level0, &level1], &[&level0]]);
        assert!(
            ragged.contains("layer 1 carries 1 mip levels and layer 0 carries 2"),
            "got: {ragged}"
        );
        let long = upload(&[&[&level0, &level1, &level2, &level2]]);
        assert!(
            long.contains("4 mip levels") && long.contains("full chain is 3"),
            "got: {long}"
        );
        let empty = upload(&[&[]]);
        assert!(empty.contains("no mip levels"), "got: {empty}");
        let wrong = upload(&[&[&level0, &level0]]);
        assert!(
            wrong.contains("layer 0 level 1") && wrong.contains("is 2x2, 16 bytes"),
            "got: {wrong}"
        );

        assert_eq!(
            recorder.total_live_objects(),
            before,
            "a rejected chain creates nothing"
        );
    }

    /// **A cleared page is zeroed on the GPU and copied into every layer, and
    /// only its patches cross from the host** — each into its own layer at its
    /// own corner, after the zeroes it overwrites.
    ///
    /// Tier B, so the page and the patch pitch to different strides: a 100-texel
    /// RGBA row pads to 512 bytes, the 5-texel patch row to 256.
    #[test]
    fn a_cleared_page_zeroes_every_layer_and_stages_only_its_patches() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_b(&recorder);
        let before = recorder.total_live_objects();
        let pixels = ramp(5 * 2 * 4);

        let page = upload_cleared_texture(
            device.as_ref(),
            queue,
            &ClearedTextureDesc {
                label: "cleared page",
                format: Format::Rgba8Unorm,
                width: WIDTH,
                height: HEIGHT,
                layers: 3,
                view_type: ImageViewType::D2Array,
                patches: &[TexturePatch {
                    layer: 2,
                    x: 7,
                    y: 1,
                    width: 5,
                    height: 2,
                    pixels: &pixels,
                }],
            },
        )
        .expect("the null backend accepts this");

        let commands = recorder.commands();
        let clears: Vec<(crcbl_hal::BufferHandle, u64, u64)> = commands
            .iter()
            .filter_map(|command| match command {
                Command::ClearBuffer {
                    buffer,
                    offset,
                    size,
                } => Some((*buffer, *offset, *size)),
                _ => None,
            })
            .collect();
        let [(zero, 0, size)] = clears[..] else {
            panic!("expected one clear from the start of one buffer, got {clears:?}");
        };
        assert_eq!(size as usize, PITCH * HEIGHT as usize, "one padded layer");
        let first_copy = commands
            .iter()
            .position(|command| matches!(command, Command::CopyBufferToImage(_)));
        let clear_at = commands
            .iter()
            .position(|command| matches!(command, Command::ClearBuffer { .. }));
        assert!(
            clear_at < first_copy,
            "the clear must be recorded before the copies that read it"
        );

        let copies = the_copies(&recorder);
        // **Every texel of every layer is written exactly once**: by a zero
        // copy, or by the patch — never both, which sync validation reports.
        let mut writes = vec![0u8; 3 * (WIDTH * HEIGHT) as usize];
        for copy in &copies {
            let Offset3d { x, y, .. } = copy.image_offset;
            let layer = copy.image_subresource.base_layer;
            for row in 0..copy.image_extent.height {
                for column in 0..copy.image_extent.width {
                    let texel = (layer * WIDTH * HEIGHT
                        + (y as u32 + row) * WIDTH
                        + (x as u32 + column)) as usize;
                    writes[texel] += 1;
                }
            }
            if copy.buffer == zero {
                assert_eq!(copy.buffer_offset, 0);
                assert_eq!(copy.buffer_row_length, 128);
            }
        }
        assert!(
            writes.iter().all(|&count| count == 1),
            "a texel was written {} times, or not at all: {copies:?}",
            writes
                .iter()
                .copied()
                .find(|&count| count != 1)
                .unwrap_or(1)
        );
        let zeroes: Vec<_> = copies.iter().filter(|copy| copy.buffer == zero).collect();
        assert_eq!(
            zeroes.len(),
            2 + 3,
            "one copy for each unpatched layer, and the patched layer as the row \
             above its patch and the two spans beside it: {copies:?}"
        );
        let [patch] = copies
            .iter()
            .filter(|copy| copy.buffer != zero)
            .collect::<Vec<_>>()[..]
        else {
            panic!("expected one staged patch copy: {copies:?}");
        };
        let patch = *patch;
        assert_ne!(patch.buffer, zero, "a patch is staged, not cleared");
        assert_eq!(patch.buffer_offset, 0);
        assert_eq!(
            patch.buffer_row_length, 64,
            "256 bytes of pitch is 64 texels"
        );
        assert_eq!(patch.image_subresource.base_layer, 2);
        assert_eq!(patch.image_extent, Extent3d::d2(5, 2));
        assert_eq!(patch.image_offset, Offset3d { x: 7, y: 1, z: 0 });

        let writes: Vec<(crcbl_hal::BufferHandle, usize)> = recorder
            .events()
            .into_iter()
            .filter_map(|event| match event {
                Event::BufferWritten { buffer, len, .. } => Some((buffer, len)),
                _ => None,
            })
            .collect();
        assert_eq!(
            writes,
            [(patch.buffer, 256 * 2)],
            "the host writes the padded patch and nothing of the page"
        );

        page.destroy(device.as_ref());
        assert_eq!(
            recorder.total_live_objects(),
            before,
            "both buffers are released once the copies are submitted"
        );
        recorder.assert_valid();
    }

    /// A page with nothing patched creates no staging buffer and writes nothing.
    #[test]
    fn a_cleared_page_with_no_patches_writes_nothing() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let page = upload_cleared_texture(
            device.as_ref(),
            queue,
            &ClearedTextureDesc {
                label: "empty page",
                format: Format::R8Unorm,
                width: 16,
                height: 16,
                layers: 2,
                view_type: ImageViewType::D2Array,
                patches: &[],
            },
        )
        .expect("accepted");
        assert!(
            !recorder
                .events()
                .iter()
                .any(|event| matches!(event, Event::BufferWritten { .. })),
            "an unpatched page is all zeroes, and zeroes are the GPU's to write"
        );
        assert_eq!(the_copies(&recorder).len(), 2, "one copy a layer");
        page.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// A patch off its layer, outside the extent, empty, or not its own size is
    /// refused naming the patch — and so is a page with no layers — before
    /// anything is created.
    #[test]
    fn a_malformed_cleared_page_is_rejected_naming_the_patch() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let before = recorder.total_live_objects();
        let four = [0u8; 4];
        let upload = |layers: u32, patch: TexturePatch<'_>| {
            upload_cleared_texture(
                device.as_ref(),
                queue,
                &ClearedTextureDesc {
                    label: "atlas",
                    format: Format::Rgba8Unorm,
                    width: 8,
                    height: 8,
                    layers,
                    view_type: ImageViewType::D2,
                    patches: &[patch],
                },
            )
            .expect_err("a malformed page is not a texture")
            .to_string()
        };
        let texel = TexturePatch {
            layer: 0,
            x: 0,
            y: 0,
            width: 1,
            height: 1,
            pixels: &four,
        };

        let no_layers = upload(0, texel);
        assert!(no_layers.contains("at least one layer"), "got: {no_layers}");
        for (patch, why) in [
            (TexturePatch { layer: 1, ..texel }, "off the only layer"),
            (TexturePatch { x: 8, ..texel }, "right of the extent"),
            (
                TexturePatch {
                    y: u32::MAX,
                    ..texel
                },
                "overflowing the extent",
            ),
            (TexturePatch { width: 0, ..texel }, "empty"),
        ] {
            let message = upload(1, patch);
            assert!(
                message.contains("patch 0") && message.contains("inside a 8x8 image"),
                "a patch {why} got: {message}"
            );
        }
        let overlapping = upload_cleared_texture(
            device.as_ref(),
            queue,
            &ClearedTextureDesc {
                label: "atlas",
                format: Format::Rgba8Unorm,
                width: 8,
                height: 8,
                layers: 1,
                view_type: ImageViewType::D2,
                patches: &[texel, texel],
            },
        )
        .expect_err("two patches on one texel are refused")
        .to_string();
        assert!(
            overlapping.contains("patch 1 overlaps patch 0"),
            "got: {overlapping}"
        );
        let short = upload(1, TexturePatch { width: 2, ..texel });
        assert!(
            short.contains("patch 0") && short.contains("8 bytes, got 4"),
            "got: {short}"
        );

        assert_eq!(
            recorder.total_live_objects(),
            before,
            "a rejected page creates nothing"
        );
    }

    /// A failure after both buffers exist releases both: the image is what
    /// fails, one texel past Tier A's `max_image_2d`.
    #[test]
    fn a_failed_cleared_page_leaks_nothing() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let limit = device.caps().limits.max_image_2d;
        let before = recorder.total_live_objects();
        let four = [0u8; 4];

        let error = upload_cleared_texture(
            device.as_ref(),
            queue,
            &ClearedTextureDesc {
                label: "too wide",
                format: Format::R8Unorm,
                width: limit + 1,
                height: 1,
                layers: 1,
                view_type: ImageViewType::D2,
                patches: &[TexturePatch {
                    layer: 0,
                    x: 0,
                    y: 0,
                    width: 4,
                    height: 1,
                    pixels: &four,
                }],
            },
        )
        .expect_err("the device refuses an image past max_image_2d");
        assert!(
            error.to_string().contains("max_image_2d"),
            "the failure must be the image, not something earlier: {error}"
        );
        assert!(
            recorder
                .events()
                .iter()
                .any(|event| matches!(event, Event::BufferWritten { .. })),
            "only meaningful if the staging buffer really was created and written"
        );
        assert_eq!(
            recorder.total_live_objects(),
            before,
            "the zeroed and the staging buffer must both be destroyed"
        );
    }

    /// A device-local buffer of `size` bytes a fill can copy into.
    fn fill_target(device: &dyn Device, size: u64) -> crcbl_hal::BufferHandle {
        device
            .create_buffer(&BufferDesc {
                label: Some("fill target"),
                size,
                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_DST,
                memory: MemoryLocation::DeviceLocal,
            })
            .expect("the null backend allocates")
    }

    /// **A fill is a copy between two barriers on the buffer, and nothing
    /// else**: in from `Undefined`, out to the state the caller named. Neither
    /// the null backend nor the Vulkan validation layer tracks a buffer's state
    /// across submissions, so a fill that left its buffer in `TransferDst`
    /// draws correctly behind the batch's `wait_idle` and only this sees it.
    #[test]
    fn a_fill_copies_its_bytes_between_its_two_barriers() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let contents = ramp(12);
        let buffer = fill_target(device.as_ref(), contents.len() as u64);
        let before = recorder.total_live_objects();

        let mut batch = UploadBatch::new(device.as_ref(), queue, "fill");
        batch
            .fill("state", buffer, &contents, ResourceState::ShaderReadWrite)
            .expect("the null backend accepts this");
        // Read before the submit, which releases it: the bytes the copy will
        // read are the caller's, exactly.
        let [staging] = batch.buffers[..] else {
            panic!("one fill stages one buffer, got {:?}", batch.buffers);
        };
        assert_eq!(
            recorder.buffer_bytes(staging).as_deref(),
            Some(&contents[..])
        );
        batch.submit().expect("the null backend submits");

        let commands = recorder.commands();
        let [
            Command::Barrier {
                buffers: into,
                images: into_images,
                ..
            },
            Command::CopyBufferToBuffer(copy),
            Command::Barrier {
                buffers: out,
                images: out_images,
                ..
            },
        ] = &commands[..]
        else {
            panic!("expected a barrier, a copy and a barrier, got {commands:?}");
        };
        assert!(into_images.is_empty() && out_images.is_empty());
        assert_eq!(
            into[..],
            [crcbl_hal::BufferBarrier::new(
                buffer,
                ResourceState::Undefined,
                ResourceState::TransferDst
            )]
        );
        assert_eq!(
            out[..],
            [crcbl_hal::BufferBarrier::new(
                buffer,
                ResourceState::TransferDst,
                ResourceState::ShaderReadWrite
            )]
        );
        assert_eq!((copy.src, copy.src_offset), (staging, 0));
        assert_eq!((copy.dst, copy.dst_offset), (buffer, 0));
        assert_eq!(copy.size, contents.len() as u64);
        assert_eq!(
            recorder.buffer_bytes(copy.src).as_deref(),
            None,
            "the staging buffer is released once the batch has waited"
        );
        assert_eq!(
            recorder.total_live_objects(),
            before,
            "the staging buffer, the encoder and the command buffer are all released"
        );
        recorder.assert_valid();
        device.destroy_buffer(buffer);
    }

    /// **Several uploads, one submission and one wait** — the batch's point.
    #[test]
    fn a_batch_submits_every_upload_once() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let buffer = fill_target(device.as_ref(), 4);

        let mut batch = UploadBatch::new(device.as_ref(), queue, "several");
        let first = batch
            .texture(
                "one",
                Format::R8Unorm,
                (1, 1),
                &[&[&[1]]],
                ImageViewType::D2,
            )
            .expect("recorded");
        let second = batch
            .texture(
                "two",
                Format::R8Unorm,
                (1, 1),
                &[&[&[2]]],
                ImageViewType::D2,
            )
            .expect("recorded");
        batch
            .fill("state", buffer, &[0; 4], ResourceState::ShaderRead)
            .expect("recorded");
        batch.submit().expect("submitted");

        let events = recorder.events();
        let submits = events
            .iter()
            .filter(|event| matches!(event, Event::Submitted { .. }))
            .count();
        let waits = events
            .iter()
            .filter(|event| matches!(event, Event::WaitedIdle))
            .count();
        assert_eq!((submits, waits), (1, 1));
        recorder.assert_valid();
        first.destroy(device.as_ref());
        second.destroy(device.as_ref());
        device.destroy_buffer(buffer);
    }

    /// A one-texture batch on `device`, submitted with
    /// [`UploadBatch::submit_deferred`], and its staging buffer.
    fn deferred_one(
        recorder: &Recorder,
        device: &dyn Device,
        queue: QueueHandle,
    ) -> (UploadedTexture, PendingUpload, crcbl_hal::BufferHandle) {
        let mut batch = UploadBatch::new(device, queue, "deferred");
        let texture = batch
            .texture(
                "one",
                Format::R8Unorm,
                (1, 1),
                &[&[&[1]]],
                ImageViewType::D2,
            )
            .expect("recorded");
        let pending = batch.submit_deferred().expect("submitted");
        let staging = the_copies(recorder)
            .first()
            .expect("the texture's copy")
            .buffer;
        (texture, pending, staging)
    }

    /// **A deferred submit waits for nothing and frees nothing** until it is
    /// polled past its semaphore's value — and then frees the staging, the
    /// command buffer and the semaphore, once.
    #[test]
    fn a_deferred_submit_keeps_its_staging_until_polled() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let before = recorder.total_live_objects();
        let (texture, mut pending, staging) = deferred_one(&recorder, device.as_ref(), queue);

        let events = recorder.events();
        assert!(
            !events
                .iter()
                .any(|event| matches!(event, Event::WaitedIdle))
        );
        let signals: Vec<_> = events
            .iter()
            .filter_map(|event| match event {
                Event::Submitted { signals, .. } => Some(signals.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(signals.len(), 1, "one submission");
        assert_eq!(signals[0].len(), 1, "signalling one semaphore");
        assert_eq!(signals[0][0].value, PendingUpload::LANDED);
        assert!(
            recorder.buffer_size(staging).is_some(),
            "alive until polled"
        );
        assert!(!pending.is_retired());

        assert!(pending.poll(device.as_ref()).expect("polled"));
        assert_eq!(recorder.buffer_size(staging), None, "freed by the poll");
        assert!(pending.poll(device.as_ref()).expect("polled again"));
        texture.destroy(device.as_ref());
        assert_eq!(recorder.total_live_objects(), before);
        recorder.assert_valid();
    }

    /// [`PendingUpload::wait`] frees what [`PendingUpload::poll`] would.
    #[test]
    fn waiting_for_a_deferred_submit_frees_it() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let before = recorder.total_live_objects();
        let (texture, mut pending, staging) = deferred_one(&recorder, device.as_ref(), queue);
        pending.wait(device.as_ref()).expect("waited");
        assert!(pending.is_retired());
        assert_eq!(recorder.buffer_size(staging), None);
        pending
            .wait(device.as_ref())
            .expect("a second wait is a no-op");
        texture.destroy(device.as_ref());
        assert_eq!(recorder.total_live_objects(), before);
        recorder.assert_valid();
    }

    /// **Without timeline semaphores a deferred submit is the waiting one**,
    /// chosen by the capability, not by an error.
    #[test]
    fn a_deferred_submit_without_a_timeline_waits() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_b(&recorder);
        assert!(!device.caps().supports(Features::TIMELINE_SEMAPHORE));
        let (texture, pending, staging) = deferred_one(&recorder, device.as_ref(), queue);
        let waits = recorder
            .events()
            .iter()
            .filter(|event| matches!(event, Event::WaitedIdle))
            .count();
        assert_eq!(waits, 1);
        assert!(pending.is_retired());
        assert_eq!(recorder.buffer_size(staging), None);
        texture.destroy(device.as_ref());
        recorder.assert_valid();
    }

    /// An abandoned batch refuses a deferred submit as it does a waiting one,
    /// before creating a semaphore it would have to give back.
    #[test]
    fn an_abandoned_batch_refuses_a_deferred_submit() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let before = recorder.total_live_objects();
        let mut batch = UploadBatch::new(device.as_ref(), queue, "abandoned");
        let texture = batch
            .texture(
                "one",
                Format::R8Unorm,
                (1, 1),
                &[&[&[1]]],
                ImageViewType::D2,
            )
            .expect("recorded");
        texture.destroy(device.as_ref());
        batch.abandon();
        assert!(matches!(
            batch.submit_deferred(),
            Err(HalError::InvalidDescriptor(_))
        ));
        assert_eq!(recorder.total_live_objects(), before);
        assert!(
            !recorder
                .events()
                .iter()
                .any(|event| matches!(event, Event::Submitted { .. }))
        );
        recorder.assert_valid();
    }

    /// **A batch holds no encoder open while its caller records others.** A
    /// build keeps one batch across steps that create, finish and submit
    /// encoders of their own, and `crcbl-webgpu` records every command into
    /// the encoder created last — so a batch that opened its encoder in `new`
    /// had its copies land after that encoder was finished, and the browser
    /// refused them. Every one of the batch's commands must be in one command
    /// buffer, from an encoder created after the other was finished.
    #[test]
    fn a_batch_records_nothing_until_its_submit() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let buffer = fill_target(device.as_ref(), 4);

        let mut batch = UploadBatch::new(device.as_ref(), queue, "interleaved");
        let first = batch
            .texture(
                "before",
                Format::R8Unorm,
                (1, 1),
                &[&[&[1]]],
                ImageViewType::D2,
            )
            .expect("recorded");
        // Another build step's own encoder, start to finish, while the batch
        // is open.
        let mut other = device.create_command_encoder(&CommandEncoderDesc {
            label: Some("other step"),
            queue,
        });
        other.insert_debug_marker("other step");
        let other = other.finish().expect("finished");
        device
            .submit(queue, &SubmitInfo::new(&[other]))
            .expect("submitted");
        device.destroy_command_buffer(other);
        let second = batch
            .texture(
                "after",
                Format::R8Unorm,
                (1, 1),
                &[&[&[2]]],
                ImageViewType::D2,
            )
            .expect("recorded");
        batch
            .fill("state", buffer, &[0; 4], ResourceState::ShaderRead)
            .expect("recorded");
        batch.submit().expect("submitted");

        recorder.assert_valid();
        let events = recorder.events();
        let finished: Vec<_> = events
            .iter()
            .filter_map(|event| match event {
                Event::Finished {
                    label,
                    command_buffer,
                } => Some((label.clone(), *command_buffer)),
                _ => None,
            })
            .collect();
        let [(other_label, other_buffer), (batch_label, batch_buffer)] = &finished[..] else {
            panic!("expected the other step's buffer and then the batch's, got {finished:?}");
        };
        assert_eq!(other_label.as_deref(), Some("other step"));
        assert_eq!(batch_label.as_deref(), Some("interleaved upload"));
        let in_batch = |buffer| {
            events
                .iter()
                .filter(|event| {
                    matches!(event, Event::Command { command_buffer, .. } if *command_buffer == buffer)
                })
                .count()
        };
        assert_eq!(in_batch(*other_buffer), 1, "the other step's marker alone");
        assert_eq!(
            in_batch(*batch_buffer),
            recorder.commands().len() - 1,
            "every batch command is in the batch's one command buffer"
        );
        assert_eq!(
            recorder
                .commands()
                .iter()
                .filter(|command| matches!(command, Command::CopyBufferToImage(_)))
                .count(),
            2
        );
        first.destroy(device.as_ref());
        second.destroy(device.as_ref());
        device.destroy_buffer(buffer);
    }

    /// **An abandoned batch refuses everything and submits nothing**, so a
    /// caller that rolled back an image it had added cannot then submit a copy
    /// into it.
    #[test]
    fn an_abandoned_batch_refuses_to_record_or_submit() {
        let recorder = Recorder::new();
        let (device, queue) = open_tier_a(&recorder);
        let before = recorder.total_live_objects();
        let buffer = fill_target(device.as_ref(), 4);

        let mut batch = UploadBatch::new(device.as_ref(), queue, "rolled back");
        let texture = batch
            .texture(
                "gone",
                Format::R8Unorm,
                (1, 1),
                &[&[&[1]]],
                ImageViewType::D2,
            )
            .expect("recorded");
        batch.abandon();
        texture.destroy(device.as_ref());

        let refused = batch
            .texture(
                "late",
                Format::R8Unorm,
                (1, 1),
                &[&[&[1]]],
                ImageViewType::D2,
            )
            .expect_err("an abandoned batch records nothing");
        assert!(refused.to_string().contains("abandoned"), "{refused}");
        batch
            .fill("late", buffer, &[0; 4], ResourceState::ShaderRead)
            .expect_err("nor a fill");
        let refused = batch.submit().expect_err("and submits nothing");
        assert!(
            refused.to_string().contains("rolled back upload"),
            "names the batch: {refused}"
        );
        assert!(
            !recorder
                .events()
                .iter()
                .any(|event| matches!(event, Event::Submitted { .. })),
            "nothing reached the queue"
        );
        device.destroy_buffer(buffer);
        assert_eq!(
            recorder.total_live_objects(),
            before,
            "the staging buffer goes with the batch"
        );
    }
}