crcbl-hal 0.2.0

Crucible graphics HAL: backend seam traits and POD descriptors
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
//! Pipeline layouts, bind groups, and graphics/compute pipeline state.
//!
//! # No vertex input state
//!
//! [`GraphicsPipelineDesc`] has no vertex-buffer layout, and there is no
//! `bind_vertex_buffer`. **Vertex pulling is the only geometry path**: position
//! and attribute streams live in storage buffers and the vertex shader indexes
//! them (stage 2 §2.5, topic 03
//! §3.1). That is what makes a mesh three integers and lets 10 objects and
//! 10 000 objects record the same commands.
//!
//! Index buffers *do* exist ([`bind_index_buffer`](crate::CommandEncoder::bind_index_buffer)),
//! because the post-transform vertex cache is real hardware the shader cannot
//! reach.
//!
//! # Bindless-capable descriptors
//!
//! [`BindGroupLayoutEntry`] carries a `count` and [`BindingFlags`]. A backend
//! with [`Features::DESCRIPTOR_INDEXING`](crate::Features::DESCRIPTOR_INDEXING)
//! turns `count: u32::MAX` plus `VARIABLE_COUNT | PARTIALLY_BOUND |
//! UPDATE_AFTER_BIND` into a runtime-sized descriptor array; one without it sees
//! a fixed `count` and produces an ordinary texture array page. Same
//! declaration, both [`BindingModel`](crate::BindingModel)s — which is the point
//! of topic 03's "the lesser path is a constraint on data layout, not a separate
//! renderer".

use crcbl_core::Handle;

use crate::{
    BackendKind, DeviceCaps, Features, Format, HalError, ImageViewHandle, ImageViewType, Limits,
    SamplerHandle, ShaderEntry, ShaderStages, resource::BufferHandle,
};

/// Marker type for pipeline-layout handles. Uninhabited.
#[derive(Debug)]
pub enum PipelineLayout {}
/// Marker type for bind-group-layout handles. Uninhabited.
#[derive(Debug)]
pub enum BindGroupLayout {}
/// Marker type for bind-group handles. Uninhabited.
#[derive(Debug)]
pub enum BindGroup {}
/// Marker type for graphics-pipeline handles. Uninhabited.
#[derive(Debug)]
pub enum GraphicsPipeline {}
/// Marker type for compute-pipeline handles. Uninhabited.
#[derive(Debug)]
pub enum ComputePipeline {}

/// A pipeline layout.
pub type PipelineLayoutHandle = Handle<PipelineLayout>;
/// A bind-group (descriptor-set) layout.
pub type BindGroupLayoutHandle = Handle<BindGroupLayout>;
/// A bind group (descriptor set).
pub type BindGroupHandle = Handle<BindGroup>;
/// A graphics pipeline.
pub type GraphicsPipelineHandle = Handle<GraphicsPipeline>;
/// A compute pipeline.
pub type ComputePipelineHandle = Handle<ComputePipeline>;

// --- descriptors -----------------------------------------------------------

/// What a sampled image's texels mean to the shader that reads them.
///
/// Carried on [`BindingKind::SampledImage`] for the same reason
/// [`view_type`](BindingKind::SampledImage::view_type) is: WebGPU puts it in the
/// *layout*. `wgpu::BindingType::Texture` has a `sample_type`, a depth-format
/// texture is only bindable as [`Depth`](SampleType::Depth), and a layout that
/// says otherwise is refused at pipeline creation. Vulkan, Metal and D3D12 take
/// the interpretation off the view's format and ignore this — each backend's
/// conversion says where it drops it.
///
/// Three variants and not five: integer and multisampled sampled images are
/// things no shader in this engine declares, and a variant nothing constructs is
/// a variant no backend's mapping was ever checked against.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SampleType {
    /// Ordinary filterable colour texels — a `Texture2D<float4>`.
    #[default]
    Float,
    /// Float texels a hardware filter cannot blend: WebGPU's
    /// `'unfilterable-float'`.
    ///
    /// **A format's filterability is not the shader's choice, and WebGPU checks
    /// it at bind time.** `r32float`, `rg32float` and `rgba32float` are
    /// unfilterable without the `float32-filterable` feature, and a view of one
    /// handed to a slot declaring [`Float`](SampleType::Float) is refused —
    /// "None of the supported sample types (UnfilterableFloat) ... match the
    /// expected sample types (Float)" — however the shader goes on to read it.
    /// A slot of this kind may be read by `Load`/`textureLoad` and by a
    /// non-filtering sampler, and by nothing else.
    ///
    /// The other three backends take the interpretation off the view's format
    /// and ignore this exactly as they ignore [`Float`](SampleType::Float).
    UnfilterableFloat,
    /// A depth texture: HLSL's `Texture2D<float>`, WGSL's `texture_depth_2d`.
    /// WebGPU binds a depth-format view through nothing else, so this is the
    /// slot for every depth read, however the shader goes on to read it.
    ///
    /// **Fetched, with no sampler at all** — `Load`/`textureLoad`, as the SSAO
    /// pass reads its depth. Nothing else is owed; the layout carries no
    /// sampler beside it.
    ///
    /// **Through a comparison sampler** — beside a `SamplerComparisonState`,
    /// as a shadow lookup reads it. Then the [`BindingKind::Sampler`] filtering
    /// it must set its `comparison` flag, and the sampler object bound into
    /// that slot must carry a
    /// [`SamplerDesc::compare`](crate::SamplerDesc::compare) — the layout says
    /// what the shader declared, the descriptor says what the hardware does, and
    /// WebGPU checks the pair.
    Depth,
}

/// What kind of resource a binding slot holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BindingKind {
    /// A uniform buffer.
    UniformBuffer {
        /// Whether the binding takes a dynamic offset at bind time.
        ///
        /// The substitute for push constants where there are none: WebGPU has
        /// no root
        /// constants, so per-draw data becomes a dynamic offset into one large
        /// uniform buffer.
        dynamic: bool,
    },
    /// A storage buffer.
    StorageBuffer {
        /// Whether the shader only reads it. Read-only lets a backend place it
        /// more cheaply and lets the graph merge more barriers.
        ///
        /// `false` also constrains which buffers may fill the slot: every one
        /// must be in
        /// [`MemoryLocation::DeviceLocal`](crate::MemoryLocation::DeviceLocal),
        /// because D3D12 has no unordered access view of a host-visible
        /// resource. [`MemoryLocation`](crate::MemoryLocation) states the rule
        /// and the mechanism; `create_bind_group` is where it is enforced.
        read_only: bool,
        /// Whether the binding takes a dynamic offset at bind time.
        dynamic: bool,
        /// Bytes per element of the array the shader declares — `sizeof(T)`
        /// for a `StructuredBuffer<T>`, SPIR-V's `ArrayStride` on the runtime
        /// array inside the block.
        ///
        /// **D3D12 is the backend that needs it**: a structured buffer's
        /// shader resource and unordered access views carry
        /// `StructureByteStride`, and a driver addresses elements by it — a
        /// view without it aliases every element onto the first on hardware.
        /// Vulkan, Metal and WebGPU address a storage buffer by the shader's
        /// own layout and do not consume the figure.
        ///
        /// It is **checked** wherever a backend compiles an artifact that
        /// states it, so a wrong number is a refused pipeline rather than a
        /// wrong picture on one GPU: `crcbl-vk` against the SPIR-V's
        /// `ArrayStride`, `crcbl-dx12` against the DXIL's structured-buffer
        /// metadata. That is
        /// [`ComputePipelineDesc::workgroup_size`]'s arrangement turned round —
        /// a number one backend needs, carried by the seam, and held to the
        /// shader by the backends that can read it.
        ///
        /// It is also a fact about the bytes a caller writes, which the engine
        /// writes once for every backend: two targets disagreeing about it
        /// would already be wrong data on one of them.
        ///
        /// Never zero; `BindGroupLayoutDesc::check_entries` refuses it.
        stride: u32,
    },
    /// A sampled image.
    SampledImage {
        /// Dimensionality the shader declares for it — the `D2` of a
        /// `Texture2D`, the `D2Array` of a `Texture2DArray`.
        ///
        /// Carried here rather than read off the bound view because WebGPU puts
        /// it in the *layout*: `wgpu::BindingType::Texture` has a
        /// `view_dimension`, and a layout that says `D2` while the view is
        /// `D2Array` is refused at pipeline creation, not at bind time. Vulkan,
        /// Metal and D3D12 all take it from the view instead and ignore this,
        /// which each backend's conversion says where it drops it.
        ///
        /// It must match the view every [`BindingResource::ImageView`] filling
        /// this slot was created with — see
        /// [`ImageViewDesc::view_type`](crate::ImageViewDesc::view_type).
        view_type: ImageViewType,
        /// How the shader reads the texels — see [`SampleType`].
        ///
        /// It must match the format every [`BindingResource::ImageView`] filling
        /// this slot was created with: [`SampleType::Depth`] takes a depth
        /// format and nothing else.
        sample_type: SampleType,
    },
    /// A read/write storage image.
    StorageImage {
        /// Whether the shader only reads it.
        read_only: bool,
        /// Dimensionality the shader declares for it — the `D2` of a
        /// `RWTexture2D`, the `D2Array` of a `RWTexture2DArray`.
        ///
        /// Carried here rather than read off the bound view because WebGPU puts
        /// it in the *layout*: `GPUStorageTextureBindingLayout` has a
        /// `viewDimension`, and a layout that says `D2` while the view is
        /// `D2Array` is refused at pipeline creation, not at bind time. Vulkan,
        /// Metal and D3D12 all take it from the view instead and ignore this,
        /// which each backend's conversion says where it drops it.
        ///
        /// It must match the view every [`BindingResource::ImageView`] filling
        /// this slot was created with — see
        /// [`ImageViewDesc::view_type`](crate::ImageViewDesc::view_type).
        view_type: ImageViewType,
        /// Texel format the shader declares for it — the `float4` of an
        /// `RWTexture2D<float4>` narrowed to the one format it writes.
        ///
        /// Here for the same reason, and it is the field the capability turned
        /// on: `GPUStorageTextureBindingLayout.format` is a **required** member
        /// with no default, so without it there is no storage-texture layout
        /// WebGPU can be asked for at all. Vulkan, Metal and D3D12 take the
        /// format off the bound view's own descriptor and ignore this, each
        /// saying so at the arm that drops it.
        ///
        /// It must match the format every [`BindingResource::ImageView`] filling
        /// this slot was created with — see
        /// [`ImageViewDesc::format`](crate::ImageViewDesc::format).
        ///
        /// **Not every [`Format`] is legal here on every backend.** WebGPU's
        /// storage-texture format list is a short one — no sRGB encoding, no
        /// depth or stencil format, no block-compressed format — so
        /// `crcbl-webgpu` refuses the rest by name at layout creation rather
        /// than letting the browser raise a validation error against a handle
        /// that already exists.
        format: Format,
    },
    /// A sampler, separate from the image it filters.
    ///
    /// Separate samplers rather than combined image-samplers: the bindless
    /// model wants one big image array and a handful of samplers, not a
    /// combinatorial product of the two, and DX12/WebGPU have no combined type
    /// at all.
    Sampler {
        /// Whether the shader declared it as a comparison sampler — HLSL's
        /// `SamplerComparisonState`, WGSL's `sampler_comparison` — rather than
        /// an ordinary filtering one.
        ///
        /// Here for the same reason [`SampleType`] is: WebGPU puts it in the
        /// layout, as `wgpu::SamplerBindingType::Comparison`, and refuses a
        /// comparison sampler bound through a `Filtering` slot. The other three
        /// backends take it off the sampler object — which carries
        /// [`SamplerDesc::compare`](crate::SamplerDesc::compare) — and ignore
        /// this, saying so at the arm that drops it.
        ///
        /// The two must agree: a `true` here filtering a sampler created with
        /// `compare: None` is a layout describing a sampler that does not exist.
        comparison: bool,
    },
}

bitflags::bitflags! {
    /// Descriptor-indexing behaviour for one binding.
    ///
    /// All three require [`Features::DESCRIPTOR_INDEXING`](crate::Features::DESCRIPTOR_INDEXING).
    /// A backend without it must reject a layout that sets any of them rather than
    /// silently ignoring it — a bindless array quietly downgraded to a fixed
    /// one reads garbage at index 4097.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct BindingFlags: u32 {
        /// Not every descriptor in the array has to be written before use, as
        /// long as the shader does not read the unwritten ones.
        const PARTIALLY_BOUND = 1 << 0;
        /// Descriptors may be written while command buffers referencing the set
        /// are pending — the flag that removes per-object descriptor updates
        /// from the frame loop.
        const UPDATE_AFTER_BIND = 1 << 1;
        /// The array's length is chosen when the bind group is created, up to
        /// the layout's `count`. Only legal on the last binding of a layout.
        const VARIABLE_COUNT = 1 << 2;
    }
}

/// One binding slot in a bind-group layout.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BindGroupLayoutEntry {
    /// Binding number, matching the shader's `[[binding(n)]]`.
    pub binding: u32,
    /// Stages that may access it.
    pub visibility: ShaderStages,
    /// What it holds.
    pub kind: BindingKind,
    /// Array length. `1` for a scalar binding; larger for an array; combined
    /// with [`BindingFlags::VARIABLE_COUNT`] for a bindless array, where it is
    /// the upper bound. Zero is rejected: a binding holding no descriptors is
    /// one no shader can index.
    ///
    /// [`u32::MAX`] is the sentinel for **"as many as this device can"**, not a
    /// request for 4 294 967 295 descriptors — it is the number the portable
    /// bindless declaration is written with, because the caller cannot know a
    /// device's ceiling before it opens one. Every backend resolves it through
    /// [`resolved_count`](BindGroupLayoutEntry::resolved_count), and it is the
    /// one value exempt from the
    /// [`max_bindless_descriptors`](Limits::max_bindless_descriptors) check in
    /// [`BindGroupLayoutDesc::check_entries`].
    pub count: u32,
    /// Descriptor-indexing behaviour.
    pub flags: BindingFlags,
}

impl BindGroupLayoutEntry {
    /// The descriptor count this binding is actually created with.
    ///
    /// Resolves the [`count`](Self::count) sentinel: [`u32::MAX`] becomes the
    /// device's own
    /// [`max_bindless_descriptors`](Limits::max_bindless_descriptors), and any
    /// other count is left alone. The floor of one is what keeps a device
    /// reporting no bindless descriptors at all from turning the sentinel into
    /// a zero-length array, which is a layout no backend will create.
    #[must_use]
    pub fn resolved_count(&self, limits: &Limits) -> u32 {
        if self.count == u32::MAX {
            limits.max_bindless_descriptors.max(1)
        } else {
            self.count
        }
    }
}

/// Creation parameters for a bind-group layout.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BindGroupLayoutDesc<'a> {
    /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
    pub label: Option<&'a str>,
    /// Binding slots.
    ///
    /// Order is free **except** for a slot carrying
    /// [`BindingFlags::VARIABLE_COUNT`], which must be both the last element of
    /// this slice *and* the highest [`binding`](BindGroupLayoutEntry::binding)
    /// number in it. Vulkan's rule is the second half — a runtime-sized array
    /// is only legal on the highest-numbered binding of a set — and backends
    /// check the first half too, because a `VARIABLE_COUNT` entry that is
    /// highest-numbered but not last would make every "the variable binding is
    /// `entries.last()`" reading in a backend silently wrong. Violating either
    /// is [`HalError::InvalidDescriptor`].
    ///
    /// Duplicate binding numbers are rejected.
    ///
    /// [`check_entries`](BindGroupLayoutDesc::check_entries) is where all of
    /// that is enforced, once, for every backend.
    pub entries: &'a [BindGroupLayoutEntry],
}

impl BindGroupLayoutDesc<'_> {
    /// Checks [`entries`](Self::entries) against the rules that field states
    /// and against what the device can actually express.
    ///
    /// **Every backend calls this**, and none of them states the rules again.
    /// Each used to write them out for itself, and they drifted apart on which
    /// rules were present at all and on what the refusal said — so a layout
    /// that failed by name on one backend was silently built on another. That
    /// is duplicated *knowledge*: one change to the rule has to alter every
    /// enforcement of it, which is what makes this a seam function rather than
    /// a helper.
    ///
    /// A backend still refuses what only *it* cannot express, and those checks
    /// stay where they are: D3D12's root descriptors take one GPU address, so
    /// an array of dynamic-offset buffers is refused in `crcbl-dx12`; Metal
    /// binds flat argument tables of a fixed size, so `crcbl-mtl` bounds a
    /// layout by them and refuses every [`BindingFlags`] outright.
    ///
    /// # Errors
    ///
    /// [`HalError::InvalidDescriptor`], naming the binding, for a
    /// [`count`](BindGroupLayoutEntry::count) of zero, a binding number
    /// declared twice, a [`BindingFlags::VARIABLE_COUNT`] entry that is not
    /// both last and highest-numbered, or an explicit count above
    /// [`Limits::max_bindless_descriptors`] — which the `u32::MAX` sentinel is
    /// exempt from, being a request to clamp rather than an over-large one.
    ///
    /// [`HalError::Unsupported`] when the device lacks
    /// [`Features::DESCRIPTOR_INDEXING`] and an entry sets any
    /// [`BindingFlags`], or when an entry's
    /// [`visibility`](BindGroupLayoutEntry::visibility) names a stage the
    /// device does not report — see
    /// [`ShaderStages::check_supported`](crate::ShaderStages::check_supported).
    pub fn check_entries(&self, caps: &DeviceCaps, backend: BackendKind) -> Result<(), HalError> {
        let indexing = caps.features.contains(Features::DESCRIPTOR_INDEXING);
        for (index, entry) in self.entries.iter().enumerate() {
            // Before the driver sees it. `VK_SHADER_STAGE_MESH_BIT_EXT` in a
            // set layout on a device without `meshShader` is a validation error
            // that arrives from `vkCreateDescriptorSetLayout` naming neither
            // the binding it came from nor the capability that is missing.
            entry.visibility.check_supported(caps.features, backend)?;
            if entry.count == 0 {
                return Err(HalError::InvalidDescriptor(format!(
                    "binding {} has count 0; a binding must hold at least one descriptor",
                    entry.binding
                )));
            }
            if matches!(entry.kind, BindingKind::StorageBuffer { stride: 0, .. }) {
                return Err(HalError::InvalidDescriptor(format!(
                    "binding {} is a storage buffer with a stride of 0; a storage buffer's \
                     stride is the byte size of one element of the array the shader declares",
                    entry.binding
                )));
            }
            if self.entries[..index]
                .iter()
                .any(|earlier| earlier.binding == entry.binding)
            {
                return Err(HalError::InvalidDescriptor(format!(
                    "binding {} is declared twice in one bind group layout",
                    entry.binding
                )));
            }
            if !entry.flags.is_empty() && !indexing {
                // [`BindingFlags`] is explicit that this must be loud: "a
                // bindless array quietly downgraded to a fixed one reads
                // garbage at index 4097."
                return Err(HalError::Unsupported {
                    backend,
                    what: "descriptor-indexing flags on a device without DESCRIPTOR_INDEXING",
                });
            }
            if entry.flags.contains(BindingFlags::VARIABLE_COUNT) {
                // Both halves, and each says which one it is: a layout that
                // breaks one is not the same caller bug as one that breaks the
                // other, and the reader has to know which to move.
                if index + 1 != self.entries.len() {
                    return Err(HalError::InvalidDescriptor(format!(
                        "binding {} sets VARIABLE_COUNT but is not the last entry of its layout; \
                         every \"the variable binding is `entries.last()`\" reading in a backend \
                         depends on it being last",
                        entry.binding
                    )));
                }
                if self
                    .entries
                    .iter()
                    .any(|other| other.binding > entry.binding)
                {
                    return Err(HalError::InvalidDescriptor(format!(
                        "binding {} sets VARIABLE_COUNT but is not the highest-numbered binding of \
                         its layout; a runtime-sized array is only legal on the highest-numbered \
                         binding of a set",
                        entry.binding
                    )));
                }
            }
            // `u32::MAX` is exempt: it is a request to clamp, not a request for
            // four billion descriptors, and checking it here rejected the one
            // shape the bindless model is written in — found by `crcbl-vk`'s
            // e2e suite on radv, where the ceiling is 8 388 606 and the
            // sentinel is larger. See `BindGroupLayoutEntry::resolved_count`.
            if indexing
                && entry.count != u32::MAX
                && entry.count > 1
                && entry.count > caps.limits.max_bindless_descriptors.max(1)
            {
                return Err(HalError::InvalidDescriptor(format!(
                    "binding {} asks for {} descriptors but max_bindless_descriptors is {}",
                    entry.binding, entry.count, caps.limits.max_bindless_descriptors
                )));
            }
        }
        Ok(())
    }
}

/// Storage-buffer bindings one shader stage may use on the **least capable**
/// target this engine ships to.
///
/// WebGPU's default limits fix `maxStorageBuffersPerShaderStage` at 8, and a
/// browser is entitled to offer no more. Real implementations at or near the
/// floor are ordinary rather than exotic: SwiftShader — which is what every CI
/// runner without a GPU runs — reports 10, and a desktop RDNA-3 reports 16, so a
/// pass written against the hardware in front of the author compiles there and
/// is refused everywhere it matters.
///
/// **The limit is per stage and per pipeline layout, not per bind group.** It is
/// validated at `createPipelineLayout` as a sum over every bind group layout in
/// the layout, so splitting an over-budget set across two groups does not help —
/// tried, and refused with the identical message. What has to come down is the
/// number of bindings, which is why the GPU-driven passes pack several tables
/// into one buffer.
///
/// [`check_portable_storage_buffers`] is the check; this is the number it checks
/// against.
pub const PORTABLE_STORAGE_BUFFERS_PER_STAGE: u32 = 8;

/// Refuses a pipeline layout that would use more than
/// [`PORTABLE_STORAGE_BUFFERS_PER_STAGE`] storage buffers in any one stage.
///
/// **Nothing below the seam notices this until a device does.**
/// [`BindGroupLayoutDesc::check_entries`] counts nothing per stage and
/// [`Limits`] has no such field, so before this existed the first thing that
/// objected was a backend refusing a pipeline layout at runtime — on a browser,
/// or on a software adapter, which is to say on somebody else's machine. This
/// turns that into a failure where the layout is written.
///
/// `layouts` is every bind group layout of one pipeline layout, in set order,
/// because the limit sums across them.
///
/// # What is counted, and what is not
///
/// Only [`ShaderStages::ALL`] — vertex, fragment and compute — because those are
/// the stages WebGPU has. A binding visible only to
/// [`ShaderStages::MESH`](crate::ShaderStages::MESH) or
/// [`TASK`](crate::ShaderStages::TASK) is on a pipeline that needs
/// [`Features::MESH_SHADER`](crate::Features::MESH_SHADER), which no WebGPU
/// device reports, so it is not measured against a WebGPU limit. That is the
/// whole of the exemption: a binding those stages share with the fragment stage
/// still counts in the fragment stage.
///
/// [`BindGroupLayoutEntry::count`] is counted, not the number of entries: an
/// array of `n` storage buffers takes `n` of the budget, and the
/// [`u32::MAX`](u32::MAX) bindless sentinel therefore fails here — which is
/// correct, since a bindless storage array is not something the guaranteed limit
/// can hold.
///
/// # Errors
///
/// [`HalError::InvalidDescriptor`], naming the layout, the stage and both
/// numbers.
pub fn check_portable_storage_buffers(
    label: Option<&str>,
    layouts: &[&BindGroupLayoutDesc<'_>],
) -> Result<(), HalError> {
    for (stage, name) in [
        (ShaderStages::VERTEX, "vertex"),
        (ShaderStages::FRAGMENT, "fragment"),
        (ShaderStages::COMPUTE, "compute"),
    ] {
        let used = layouts
            .iter()
            .flat_map(|layout| layout.entries.iter())
            .filter(|entry| {
                matches!(entry.kind, BindingKind::StorageBuffer { .. })
                    && entry.visibility.contains(stage)
            })
            .fold(0u32, |total, entry| total.saturating_add(entry.count));
        if used > PORTABLE_STORAGE_BUFFERS_PER_STAGE {
            return Err(HalError::InvalidDescriptor(format!(
                "pipeline layout {} binds {used} storage buffers in the {name} stage, and a \
                 WebGPU device guarantees only {PORTABLE_STORAGE_BUFFERS_PER_STAGE}; the limit is \
                 a sum over every bind group layout in one pipeline layout, so splitting them \
                 across groups does not help — pack the data into fewer buffers instead",
                label.unwrap_or("<unlabelled>"),
            )));
        }
    }
    Ok(())
}

/// A resource being bound into a slot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BindingResource {
    /// A buffer range.
    Buffer {
        /// Buffer to bind.
        buffer: BufferHandle,
        /// Offset in bytes, respecting the relevant
        /// `min_*_buffer_offset_alignment` limit.
        offset: u64,
        /// Length in bytes. [`u64::MAX`] means "to the end of the buffer".
        size: u64,
    },
    /// An image view. The view's layout at use time is the graph's
    /// responsibility, not the bind group's.
    ImageView(ImageViewHandle),
    /// A sampler.
    Sampler(SamplerHandle),
}

impl BindingResource {
    /// Sentinel for [`BindingResource::Buffer::size`] meaning "to the end".
    pub const WHOLE_BUFFER: u64 = u64::MAX;

    /// Binds a whole buffer.
    #[must_use]
    pub const fn whole_buffer(buffer: BufferHandle) -> Self {
        Self::Buffer {
            buffer,
            offset: 0,
            size: Self::WHOLE_BUFFER,
        }
    }
}

/// One resource assignment in a bind group.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BindGroupEntry {
    /// Binding number this fills.
    pub binding: u32,
    /// Index within the binding's array; `0` for a scalar binding. This is the
    /// bindless write path: one entry per texture slot updated.
    pub array_index: u32,
    /// What to bind.
    pub resource: BindingResource,
}

/// Creation parameters for a bind group.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BindGroupDesc<'a> {
    /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
    pub label: Option<&'a str>,
    /// Layout this group conforms to.
    pub layout: BindGroupLayoutHandle,
    /// Assignments. With [`BindingFlags::PARTIALLY_BOUND`] this may cover only
    /// part of an array.
    pub entries: &'a [BindGroupEntry],
    /// Variable descriptor count. Required when the layout includes a
    /// binding with [`BindingFlags::VARIABLE_COUNT`]; tells the backend how
    /// many array elements the caller is *using* (which cannot exceed the
    /// layout's [`BindGroupLayoutEntry::count`] ceiling). `None` means
    /// "infer from entries", which matches the behaviour before this field
    /// existed and is safe for fixed-size arrays.
    pub variable_count: Option<u32>,
}

/// Checks one buffer binding's own offset against the alignment the slot it
/// fills requires.
///
/// **Every backend calls this**, for
/// [`BindGroupLayoutDesc::check_entries`]'s reason. The rule is the seam's:
/// [`Limits`] says outright that
/// [`min_uniform_buffer_offset_alignment`](Limits::min_uniform_buffer_offset_alignment)
/// and
/// [`min_storage_buffer_offset_alignment`](Limits::min_storage_buffer_offset_alignment)
/// are "alignments a binding offset must be a multiple of" rather than
/// ceilings, and a rule stated at the seam and enforced in one backend is a
/// rule that holds on one backend. Before this lived here, a misaligned offset
/// reached the driver as `VUID-VkWriteDescriptorSet-descriptorType-00327` — a
/// validation message naming a descriptor type rather than the caller's
/// binding, and only with the layers loaded.
///
/// An alignment of `1` accepts every offset, which is what a device reporting
/// no requirement means.
///
/// # A slot holding no buffer carries no rule
///
/// Sampled images, storage images and samplers take no offset, so they are
/// accepted. Callers reach here only for a [`BindingResource::Buffer`] that has
/// already been held to a buffer slot, so that arm is a default rather than a
/// decision. [`check_dynamic_offsets`] falls back the other way and says why.
///
/// # Errors
///
/// [`HalError::InvalidDescriptor`], naming the binding, the offset, the
/// alignment and the kind of slot it came from.
pub fn check_binding_offset_alignment(
    limits: &Limits,
    kind: BindingKind,
    binding: u32,
    offset: u64,
) -> Result<(), HalError> {
    let alignment = match kind {
        BindingKind::UniformBuffer { .. } => limits.min_uniform_buffer_offset_alignment,
        BindingKind::StorageBuffer { .. } => limits.min_storage_buffer_offset_alignment,
        _ => 1,
    };
    if alignment > 1 && !offset.is_multiple_of(alignment) {
        return Err(HalError::InvalidDescriptor(format!(
            "binding {binding}'s buffer offset {offset} is not a multiple of this device's \
             {alignment}-byte alignment for {kind:?}"
        )));
    }
    Ok(())
}

/// Checks the dynamic offsets a bind names against the layout that declared the
/// slots they fill.
///
/// The other half of [`check_binding_offset_alignment`]: a dynamic offset is
/// added to the descriptor's own offset before the shader sees it, so it has to
/// satisfy the same alignment, and it arrives at
/// [`bind_group`](crate::CommandEncoder::bind_group) rather than at bind-group
/// creation. Vulkan reports a violation as
/// `VUID-vkCmdBindDescriptorSets-pDynamicOffsets-01971`, which is the same
/// diagnostic problem the static rule has.
///
/// `dynamic` is the layout's **own** dynamic-offset bindings — those declaring
/// [`BindingKind::UniformBuffer`] or [`BindingKind::StorageBuffer`] with
/// `dynamic: true` — sorted by binding number, because
/// [`bind_group`](crate::CommandEncoder::bind_group) states that
/// `dynamic_offsets` is positional and in binding order. Pure, so the alignment
/// policy has a unit test rather than a GPU.
///
/// # Why the fallback arm differs from the static check's
///
/// A slot in `dynamic` is a buffer slot by construction: the caller filtered it
/// out of the layout on exactly that predicate. So the arm that is not uniform
/// is a storage buffer, and it takes the storage alignment — where
/// [`check_binding_offset_alignment`] walks a slice that legitimately holds
/// image and sampler slots and treats an unknown kind as carrying no rule. An
/// entry of some other kind reaching here is a caller that filtered wrong, and
/// checking it against an alignment is a stricter answer than waving it
/// through.
///
/// # Errors
///
/// [`HalError::InvalidDescriptor`] when the number of offsets does not match
/// the number of dynamic-offset bindings — the count is what makes the
/// positional mapping meaningful, and one too few silently shifts every later
/// offset onto the wrong slot — or when an offset is not a multiple of its
/// binding's alignment.
pub fn check_dynamic_offsets(
    limits: &Limits,
    dynamic: &[BindGroupLayoutEntry],
    offsets: &[u32],
) -> Result<(), HalError> {
    if offsets.len() != dynamic.len() {
        return Err(HalError::InvalidDescriptor(format!(
            "bind_group was given {} dynamic offset(s) but the layout declares {} \
             dynamic-offset binding(s)",
            offsets.len(),
            dynamic.len()
        )));
    }
    for (entry, offset) in dynamic.iter().zip(offsets) {
        let alignment = match entry.kind {
            BindingKind::UniformBuffer { .. } => limits.min_uniform_buffer_offset_alignment,
            _ => limits.min_storage_buffer_offset_alignment,
        };
        if alignment > 1 && !u64::from(*offset).is_multiple_of(alignment) {
            return Err(HalError::InvalidDescriptor(format!(
                "dynamic offset {offset} for binding {} is not a multiple of this device's \
                 {alignment}-byte alignment",
                entry.binding
            )));
        }
    }
    Ok(())
}

/// A push-constant / root-constant range.
///
/// Requires [`Features::PUSH_CONSTANTS`](crate::Features::PUSH_CONSTANTS).
///
/// # WebGPU has none — an obligation, not a footnote
///
/// WebGPU has no push constants at all, so a backend on it **must** report
/// [`Features::PUSH_CONSTANTS`](crate::Features::PUSH_CONSTANTS) absent and
/// `max_push_constant_size` as `0`, and **must** fail
/// [`PipelineLayoutDesc::push_constants`] loudly at layout creation rather than
/// accepting the layout and dropping every
/// [`CommandEncoder::push_constants`](crate::CommandEncoder::push_constants)
/// silently. The renderer's substitute is a dynamic-offset uniform buffer — see
/// [`BindingKind::UniformBuffer`] — which is a *data-layout* decision the
/// renderer makes up front, not something a backend can paper over per draw.
/// That is why push constants are deliberately not part of
/// [`Features::GPU_DRIVEN`](crate::Features::GPU_DRIVEN).
///
/// # Decision: the name stays
///
/// P0's seam review flagged "push constant" as Vulkan vocabulary. It is also
/// DX12's concept under the name *root constants* and Metal's under
/// `setBytes`, so it is the common cross-API term rather than a vk-only one —
/// and renaming it would not close the real gap, which is that WebGPU lacks the
/// feature entirely. That gap is a **capability fact**, and it belongs in
/// [`DeviceCaps`] where a backend declares it and a caller
/// branches on it, not in the name of a type that three of four backends
/// implement natively.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PushConstantRange {
    /// Stages that read it.
    pub stages: ShaderStages,
    /// Byte offset within the push-constant block.
    pub offset: u32,
    /// Byte size, bounded by
    /// [`Limits::max_push_constant_size`].
    pub size: u32,
}

/// Creation parameters for a pipeline layout.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PipelineLayoutDesc<'a> {
    /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
    pub label: Option<&'a str>,
    /// Bind-group layouts, in set order.
    pub bind_group_layouts: &'a [BindGroupLayoutHandle],
    /// Push-constant range, if any.
    pub push_constants: Option<PushConstantRange>,
}

// --- fixed-function state --------------------------------------------------

/// How vertices assemble into primitives.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PrimitiveTopology {
    /// Independent points.
    PointList,
    /// Independent line segments.
    LineList,
    /// Connected line segments.
    LineStrip,
    /// Independent triangles. The engine's default and, with vertex pulling,
    /// effectively the only one used for geometry.
    #[default]
    TriangleList,
    /// Connected triangles.
    TriangleStrip,
}

/// Which winding is front-facing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FrontFace {
    /// Counter-clockwise in framebuffer space.
    #[default]
    Ccw,
    /// Clockwise in framebuffer space.
    Cw,
}

/// Which faces to discard.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CullMode {
    /// Keep everything.
    #[default]
    None,
    /// Discard front faces.
    Front,
    /// Discard back faces.
    Back,
}

/// Fill mode.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PolygonMode {
    /// Solid.
    #[default]
    Fill,
    /// Wireframe. Requires
    /// [`Features::POLYGON_MODE_LINE`](crate::Features::POLYGON_MODE_LINE).
    Line,
}

/// Rasteriser and primitive-assembly state.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct PrimitiveState {
    /// Assembly mode.
    pub topology: PrimitiveTopology,
    /// Winding treated as front-facing.
    pub front_face: FrontFace,
    /// Faces discarded.
    pub cull_mode: CullMode,
    /// Fill mode.
    pub polygon_mode: PolygonMode,
    /// Clamp depth instead of clipping at the near/far planes. Requires
    /// [`Features::DEPTH_CLAMP`](crate::Features::DEPTH_CLAMP); shadow passes
    /// want it so casters behind the near plane still write depth.
    pub depth_clamp: bool,
}

/// A comparison function.
///
/// Named by the **comparison performed**, never by what it means for
/// visibility: `Greater` means `Greater`. Under this engine's reversed-Z that
/// happens to be the "closer" test, but a name like `CloserOrEqual` would bake a
/// depth convention into the vocabulary and become a lie the day someone writes
/// a stencil or shadow comparison. See [`crate::depth`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CompareOp {
    /// Always fails.
    Never,
    /// Passes when the incoming value is less than the stored one.
    Less,
    /// Passes on equality.
    Equal,
    /// Passes when less than or equal.
    LessOrEqual,
    /// Passes when greater. **The engine's depth test** under reversed-Z.
    #[default]
    Greater,
    /// Passes on inequality.
    NotEqual,
    /// Passes when greater than or equal. The depth test for a second pass that
    /// must match a prepass exactly under reversed-Z.
    GreaterOrEqual,
    /// Always passes.
    Always,
}

/// Stencil operation on a test outcome.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum StencilOp {
    /// Leave the value alone.
    #[default]
    Keep,
    /// Write zero.
    Zero,
    /// Write the reference value the pass last set with
    /// [`set_stencil_reference`](crate::CommandEncoder::set_stencil_reference).
    Replace,
    /// Bitwise invert.
    Invert,
    /// Increment, clamping at the maximum.
    IncrementClamp,
    /// Decrement, clamping at zero.
    DecrementClamp,
    /// Increment, wrapping.
    IncrementWrap,
    /// Decrement, wrapping.
    DecrementWrap,
}

/// Stencil state for one facing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct StencilFaceState {
    /// Comparison against the reference value the pass last set with
    /// [`set_stencil_reference`](crate::CommandEncoder::set_stencil_reference).
    pub compare: CompareOp,
    /// Applied when the stencil test fails.
    pub fail_op: StencilOp,
    /// Applied when the stencil test passes but depth fails.
    pub depth_fail_op: StencilOp,
    /// Applied when both pass.
    pub pass_op: StencilOp,
}

/// Stencil state.
///
/// # There is no reference value here, deliberately
///
/// The value [`StencilFaceState::compare`] tests against — and the value
/// [`StencilOp::Replace`] writes — is **pass state**, set with
/// [`set_stencil_reference`](crate::CommandEncoder::set_stencil_reference).
/// This struct carries no field for it, because two of the four APIs behind
/// this seam have no pipeline member to fill: WebGPU sets the reference on the
/// render pass encoder and Metal on the command encoder. A pipeline field would
/// therefore be honoured by D3D12 and Vulkan and dropped by the other two, and
/// the same recorded command stream would draw differently depending on which
/// backend replayed it.
///
/// The rule every backend implements instead:
///
/// * A render pass opens holding
///   [`stencil::INITIAL_REFERENCE`](crate::stencil::INITIAL_REFERENCE).
/// * **Binding a graphics pipeline does not disturb the current reference** — a
///   `set_stencil_reference` before a bind is still in force after it.
///
/// [`Capability::StencilReference`](crate::Capability::StencilReference) is the
/// backend's declaration that it does both.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct StencilState {
    /// Front-facing primitives.
    pub front: StencilFaceState,
    /// Back-facing primitives.
    pub back: StencilFaceState,
    /// Bits read by the comparison.
    pub read_mask: u32,
    /// Bits the operations may write.
    pub write_mask: u32,
}

/// Polygon depth offset.
///
/// # Reversed-Z changes the sign
///
/// With depth increasing towards the viewer, pushing a polygon *away* from the
/// camera — the usual shadow-acne fix — needs a **negative** `constant`, the
/// opposite of every conventional-Z code sample. The magnitude also differs: a
/// float depth buffer's precision varies across the range, so a constant bias
/// tuned for a unorm buffer is meaningless here. Tune against the reversed-Z
/// buffer, not against a tutorial.
///
/// # The constant counts units, so it is an `i32`
///
/// `constant` is a *count* of the depth buffer's minimum resolvable
/// difference, and the two backends that name that count in their own API name
/// it as an integer: D3D12's `D3D12_RASTERIZER_DESC::DepthBias` and WebGPU's
/// `GPUDepthBias` are both signed 32-bit. WebGPU will not even take a
/// non-integer — its `[EnforceRange] long` conversion throws rather than
/// rounding — so a fraction is not a smaller nudge there, it is a refused
/// pipeline. Vulkan and Metal spell the same count as a float
/// (`depthBiasConstantFactor`, `setDepthBias:slopeScale:clamp:`), and an `f32`
/// represents every integer up to its 24-bit significand exactly, so widening
/// an `i32` bias for those two loses nothing at any magnitude a depth bias is
/// tuned to. [`slope_scale`](Self::slope_scale) is the knob that varies
/// continuously; this one steps.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct DepthBias {
    /// Constant offset, counted in the depth buffer's minimum resolvable
    /// differences. See the type docs on why this is not a float.
    pub constant: i32,
    /// Offset scaled by the polygon's depth slope.
    pub slope_scale: f32,
    /// Maximum magnitude. Requires
    /// [`Features::DEPTH_BIAS_CLAMP`](crate::Features::DEPTH_BIAS_CLAMP);
    /// `0.0` disables clamping.
    pub clamp: f32,
}

/// Depth and stencil state.
///
/// [`Default`] is **reversed-Z**: [`CompareOp::Greater`] against a
/// [`Format::D32Float`] buffer cleared to [`depth::CLEAR`](crate::depth::CLEAR)
/// = `0.0`, with depth writes on. Getting this default wrong is exactly the
/// class of mistake that is free to prevent now and costs a re-bless of every
/// golden image later.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DepthStencilState {
    /// Depth attachment format.
    pub format: Format,
    /// Whether depth is written.
    pub depth_write: bool,
    /// Depth comparison. `Greater` under reversed-Z.
    pub depth_compare: CompareOp,
    /// Stencil state, if the attachment has a stencil plane.
    pub stencil: Option<StencilState>,
    /// Polygon depth offset; see [`DepthBias`] on the sign.
    pub bias: DepthBias,
}

impl Default for DepthStencilState {
    /// Reversed-Z: `D32_SFLOAT`, depth writes on, `GREATER`, no stencil.
    fn default() -> Self {
        Self {
            format: Format::D32Float,
            depth_write: true,
            depth_compare: CompareOp::Greater,
            stencil: None,
            bias: DepthBias::default(),
        }
    }
}

impl DepthStencilState {
    /// Depth-test-only state for a pass drawing against an existing prepass.
    ///
    /// [`CompareOp::GreaterOrEqual`] with writes off, which is the correct pair
    /// under reversed-Z: the fragment's depth must *equal* the prepass value to
    /// survive, and equality is only reachable through the `OrEqual`.
    #[must_use]
    pub fn equal_depth_read_only(format: Format) -> Self {
        Self {
            format,
            depth_write: false,
            depth_compare: CompareOp::GreaterOrEqual,
            stencil: None,
            bias: DepthBias::default(),
        }
    }
}

/// Multisampling state.
///
/// # Every sample is covered, and there is no knob to say otherwise
///
/// Vulkan's `pSampleMask`, D3D12's `SampleMask` and WebGPU's
/// `GPUMultisampleState.mask` all suppress individual samples per pipeline;
/// `MTLRenderPipelineDescriptor` has no counterpart at all, and Metal's only
/// related knob — `alphaToCoverageEnabled`, which this struct does carry —
/// *derives* coverage from the shader rather than masking it. A seam field one
/// parity backend cannot honour is a field whose meaning changes with the
/// backend, so there is none: every pipeline rasterises with all of its samples
/// covered, and the three backends that have a mask pass "all bits set"
/// explicitly. Coverage a caller wants to vary belongs in the shader, where
/// [`alpha_to_coverage`](Self::alpha_to_coverage) already puts it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MultisampleState {
    /// Samples per pixel; `1` disables MSAA.
    pub samples: u32,
    /// Derive coverage from the fragment shader's alpha output.
    pub alpha_to_coverage: bool,
}

impl Default for MultisampleState {
    /// No multisampling. The engine's AA plan is FXAA at P7 and TAA post-MVP
    /// (topic 18), so MSAA is available but never the default.
    fn default() -> Self {
        Self {
            samples: 1,
            alpha_to_coverage: false,
        }
    }
}

/// A blend factor.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BlendFactor {
    /// `0`.
    Zero,
    /// `1`.
    One,
    /// Source colour.
    Src,
    /// `1 - source colour`.
    OneMinusSrc,
    /// Source alpha.
    SrcAlpha,
    /// `1 - source alpha`.
    OneMinusSrcAlpha,
    /// Destination colour.
    Dst,
    /// `1 - destination colour`.
    OneMinusDst,
    /// Destination alpha.
    DstAlpha,
    /// `1 - destination alpha`.
    OneMinusDstAlpha,
}

/// How blended terms combine.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BlendOp {
    /// `src * src_factor + dst * dst_factor`.
    #[default]
    Add,
    /// `src * src_factor - dst * dst_factor`.
    Subtract,
    /// `dst * dst_factor - src * src_factor`.
    ReverseSubtract,
    /// Component-wise minimum; factors are ignored.
    Min,
    /// Component-wise maximum; factors are ignored.
    Max,
}

/// Blend state for one colour target.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BlendState {
    /// Colour source factor.
    pub color_src: BlendFactor,
    /// Colour destination factor.
    pub color_dst: BlendFactor,
    /// Colour combine operation.
    pub color_op: BlendOp,
    /// Alpha source factor.
    pub alpha_src: BlendFactor,
    /// Alpha destination factor.
    pub alpha_dst: BlendFactor,
    /// Alpha combine operation.
    pub alpha_op: BlendOp,
}

impl BlendState {
    /// Straight alpha blending: `src * a + dst * (1 - a)`.
    #[must_use]
    pub const fn alpha() -> Self {
        Self {
            color_src: BlendFactor::SrcAlpha,
            color_dst: BlendFactor::OneMinusSrcAlpha,
            color_op: BlendOp::Add,
            alpha_src: BlendFactor::One,
            alpha_dst: BlendFactor::OneMinusSrcAlpha,
            alpha_op: BlendOp::Add,
        }
    }

    /// Premultiplied alpha: `src + dst * (1 - a)`. The correct mode for
    /// composited UI and for particle atlases authored premultiplied.
    #[must_use]
    pub const fn premultiplied() -> Self {
        Self {
            color_src: BlendFactor::One,
            color_dst: BlendFactor::OneMinusSrcAlpha,
            color_op: BlendOp::Add,
            alpha_src: BlendFactor::One,
            alpha_dst: BlendFactor::OneMinusSrcAlpha,
            alpha_op: BlendOp::Add,
        }
    }

    /// Additive: `src + dst`.
    #[must_use]
    pub const fn additive() -> Self {
        Self {
            color_src: BlendFactor::One,
            color_dst: BlendFactor::One,
            color_op: BlendOp::Add,
            alpha_src: BlendFactor::One,
            alpha_dst: BlendFactor::One,
            alpha_op: BlendOp::Add,
        }
    }
}

bitflags::bitflags! {
    /// Which colour channels a target writes.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct ColorWrites: u32 {
        /// Red.
        const R = 1 << 0;
        /// Green.
        const G = 1 << 1;
        /// Blue.
        const B = 1 << 2;
        /// Alpha.
        const A = 1 << 3;
        /// All four.
        const ALL = Self::R.bits() | Self::G.bits() | Self::B.bits() | Self::A.bits();
    }
}

/// One colour attachment's pipeline state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColorTargetState {
    /// Attachment format. For the engine's main pass this is
    /// [`Format::Rgba16Float`] — HDR from P1.
    pub format: Format,
    /// Blend state; `None` disables blending.
    pub blend: Option<BlendState>,
    /// Channels written.
    pub write_mask: ColorWrites,
}

impl ColorTargetState {
    /// An opaque target with all channels written and no blending.
    #[must_use]
    pub const fn opaque(format: Format) -> Self {
        Self {
            format,
            blend: None,
            write_mask: ColorWrites::ALL,
        }
    }
}

/// The viewport transform.
///
/// # `depth` is a range, not a direction
///
/// [`Default`] keeps `depth_min: 0.0, depth_max: 1.0` even though the engine is
/// reversed-Z. Reversed depth is produced by the **projection matrix** (swap the
/// near and far terms, infinite far plane), *not* by setting `depth_min: 1.0,
/// depth_max: 0.0`. Flipping the viewport instead is a well-known trap: it
/// produces visually similar output while throwing away the entire precision
/// benefit, because the float depth buffer's dense exponent range near 0.0 ends
/// up mapped to the far plane again.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Viewport {
    /// Left edge in pixels.
    pub x: f32,
    /// Top edge in pixels.
    pub y: f32,
    /// Width in pixels.
    pub width: f32,
    /// Height in pixels.
    pub height: f32,
    /// Near end of the depth range. See the type docs before changing it.
    pub depth_min: f32,
    /// Far end of the depth range. See the type docs before changing it.
    pub depth_max: f32,
}

impl Viewport {
    /// A viewport covering a `width` × `height` target with the standard
    /// `0.0..=1.0` depth range.
    #[must_use]
    pub fn from_size(width: u32, height: u32) -> Self {
        Self {
            x: 0.0,
            y: 0.0,
            width: width as f32,
            height: height as f32,
            depth_min: 0.0,
            depth_max: 1.0,
        }
    }
}

impl Default for Viewport {
    fn default() -> Self {
        Self::from_size(0, 0)
    }
}

// --- pipelines -------------------------------------------------------------

/// Creation parameters for a graphics pipeline.
///
/// Dynamic-rendering shaped: attachment *formats* are declared here, actual
/// attachments at [`begin_render_pass`](crate::CommandEncoder::begin_render_pass).
/// There is no render-pass or framebuffer object to keep compatible.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GraphicsPipelineDesc<'a> {
    /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
    pub label: Option<&'a str>,
    /// Resource layout.
    pub layout: PipelineLayoutHandle,
    /// Vertex stage. Reads geometry from storage buffers — see the module docs
    /// on vertex pulling.
    pub vertex: ShaderEntry<'a>,
    /// Fragment stage; `None` for a depth-only pass (shadow maps, prepass).
    pub fragment: Option<ShaderEntry<'a>>,
    /// Rasteriser state.
    pub primitive: PrimitiveState,
    /// Depth/stencil state; `None` for a pass with no depth attachment.
    /// Defaults to reversed-Z when present — see [`DepthStencilState`].
    pub depth_stencil: Option<DepthStencilState>,
    /// Multisampling state.
    pub multisample: MultisampleState,
    /// Colour attachment formats and blend state, in attachment order.
    pub color_targets: &'a [ColorTargetState],
}

/// Creation parameters for a **mesh** pipeline — the primary geometry path.
///
/// Topic 03 §3.5 makes mesh shading the geometry
/// path the engine reaches for first, with the indirect draws in
/// [`GeometryPath`](crate::GeometryPath) as what a device without
/// [`Features::MESH_SHADER`](crate::Features::MESH_SHADER) falls back to.
///
/// # Decision: a sibling descriptor, the *same* handle type
///
/// This is a separate descriptor from [`GraphicsPipelineDesc`] but it produces
/// a [`GraphicsPipelineHandle`], is bound with
/// [`bind_graphics_pipeline`](crate::CommandEncoder::bind_graphics_pipeline)
/// and destroyed with
/// [`destroy_graphics_pipeline`](crate::Device::destroy_graphics_pipeline).
/// Both halves of that were deliberate.
///
/// **A separate descriptor, because the field sets are disjoint where it
/// matters.** A mesh pipeline has no vertex stage, and the only honest way to
/// express that on [`GraphicsPipelineDesc`] would be to make
/// [`vertex`](GraphicsPipelineDesc::vertex) an `Option` and add `mesh` and
/// `task` beside it — three optional stage slots of which exactly two
/// combinations are legal, checked at run time, in a type every existing caller
/// would have to be edited for. There is also nothing for
/// [`PrimitiveState::topology`] to mean here: the topology is fixed by the mesh
/// shader's own `[outputtopology(…)]`, and there is no primitive assembly to
/// configure because there are no input primitives to assemble.
///
/// **The same handle, because on all three native APIs a mesh pipeline is the
/// same kind of object as a raster one.** Vulkan builds it with
/// `vkCreateGraphicsPipelines` and binds it at
/// `VK_PIPELINE_BIND_POINT_GRAPHICS`; D3D12 produces an `ID3D12PipelineState`
/// bound by `SetPipelineState`; Metal produces an `MTLRenderPipelineState` from
/// an `MTLMeshRenderPipelineDescriptor`. A distinct `MeshPipelineHandle` would
/// buy one thing — making "bind a raster pipeline, then
/// [`draw_mesh_tasks`](crate::CommandEncoder::draw_mesh_tasks)" a type error —
/// and this seam does not track that kind of pairing anywhere else either
/// ([`draw`](crate::CommandEncoder::draw) after binding nothing is equally
/// unchecked, and is left to the validation layer). It would cost a second
/// handle type, a second destroy, a second bind, and a second pool in every
/// backend, all aliasing one driver object.
///
/// # No vertex input, in a stronger sense than everywhere else
///
/// The module docs above say the seam has no vertex-buffer layout because
/// vertex pulling is the only geometry path. A mesh shader takes that further:
/// there is no vertex *stage*, no `SV_VertexID`, and no index buffer in play —
/// the mesh stage writes its vertices and its index triples into output arrays
/// and says how many of each it produced.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MeshPipelineDesc<'a> {
    /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
    pub label: Option<&'a str>,
    /// Resource layout.
    pub layout: PipelineLayoutHandle,
    /// Task stage, if any. Runs first and chooses how many mesh workgroups to
    /// launch, which is where per-cluster culling will live (§3.5).
    ///
    /// Requires [`Features::TASK_SHADER`](crate::Features::TASK_SHADER) — a
    /// device may have the mesh stage without it, which is why the seam reports
    /// the two separately.
    pub task: Option<ShaderEntry<'a>>,
    /// Invocations per **task** workgroup — the same numbers the task stage's
    /// own `[numthreads(x, y, z)]` declares. Ignored when
    /// [`task`](Self::task) is `None`, and
    /// [`check_workgroup_sizes`](Self::check_workgroup_sizes) checks it only
    /// then.
    ///
    /// Here for [`mesh_workgroup_size`](Self::mesh_workgroup_size)'s reason.
    pub task_workgroup_size: [u32; 3],
    /// Mesh stage. Emits vertices and primitives; there is no vertex stage.
    pub mesh: ShaderEntry<'a>,
    /// Invocations per **mesh** workgroup — the same numbers the mesh stage's
    /// own `[numthreads(x, y, z)]` declares.
    ///
    /// # Why this is on the descriptor, exactly as it is for compute
    ///
    /// [`ComputePipelineDesc::workgroup_size`] gives the whole argument and it
    /// is the same one here, one stage along: SPIR-V, DXIL and WGSL bake the
    /// declared size into the module — `vkCmdDrawMeshTasksEXT` and
    /// `DispatchMesh` therefore take workgroup *counts* and nothing else —
    /// while **MSL has nowhere to declare it**. Slang's Metal target drops the
    /// `[numthreads(…)]` entirely: `msl/mesh_shader.metal` emits
    /// `[[mesh]] void meshMain(uint3 index [[thread_position_in_grid]], …)`
    /// with no thread count anywhere in the artifact, and
    /// `drawMeshThreadgroups:threadsPerObjectThreadgroup:threadsPerMeshThreadgroup:`
    /// takes both sizes at the **call**. A Metal backend holding only a module
    /// and an entry point has no number to pass and cannot draw at all.
    ///
    /// So this is the second field of this seam `crcbl-mtl` is the reason for,
    /// and it carries the same obligation: **take it from the crate that owns
    /// the shader source rather than writing a literal**, because a value that
    /// disagrees with the `[numthreads(…)]` is invisible on the three backends
    /// that read the size out of the module and launches the wrong number of
    /// threads only on Metal.
    pub mesh_workgroup_size: [u32; 3],
    /// Fragment stage; `None` for a depth-only pass, as on
    /// [`GraphicsPipelineDesc`].
    pub fragment: Option<ShaderEntry<'a>>,
    /// Rasteriser state. [`PrimitiveState::topology`] is **ignored**: the mesh
    /// shader's `[outputtopology(…)]` decides it, and there is no input
    /// assembly. Everything else — winding, culling, fill mode, depth clamp —
    /// applies exactly as it does to a raster pipeline.
    pub primitive: PrimitiveState,
    /// Depth/stencil state; `None` for a pass with no depth attachment.
    pub depth_stencil: Option<DepthStencilState>,
    /// Multisampling state.
    pub multisample: MultisampleState,
    /// Colour attachment formats and blend state, in attachment order.
    pub color_targets: &'a [ColorTargetState],
}

/// Creation parameters for a compute pipeline.
///
/// # Why the workgroup size is here at all
///
/// SPIR-V, DXIL and WGSL each bake it into the module — `[numthreads(…)]` in
/// the Slang source becomes `OpExecutionMode … LocalSize`, a DXIL metadata
/// entry, and `@workgroup_size(…)` respectively — so Vulkan and D3D12 need no
/// such field. **Metal has nowhere to declare it.** MSL's `[[kernel]]` carries
/// no thread count, and `dispatchThreadgroups:threadsPerThreadgroup:` takes it
/// at the *call*, which means a Metal backend with only a module and an entry
/// point has no number to pass and cannot dispatch at all. Carrying it on the
/// descriptor is what makes the compute half of this seam expressible on every
/// backend rather than on three of the four.
///
/// The cost is a second place the number lives, and
/// [`workgroup_size`](Self::workgroup_size) says where to take it from so the
/// two cannot be written independently.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ComputePipelineDesc<'a> {
    /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
    pub label: Option<&'a str>,
    /// Resource layout.
    pub layout: PipelineLayoutHandle,
    /// Compute stage.
    pub compute: ShaderEntry<'a>,
    /// Invocations per workgroup, in the three dimensions — the same numbers
    /// the shader's own `[numthreads(x, y, z)]` declares.
    ///
    /// **Take it from the crate that owns the shader source rather than
    /// writing a literal.** `crcbl-shaders` publishes a `WORKGROUP_SIZE` beside
    /// every compute shader it compiles, checked against the `[numthreads(…)]`
    /// in the `.slang` file by that module's own test, so
    /// `[crcbl_shaders::cull::WORKGROUP_SIZE, 1, 1]` is one number in one place.
    /// A hand-written value that disagrees with the shader is the failure this
    /// field introduces, and it is invisible on the backends that read the size
    /// out of the module: only Metal would launch the wrong number of threads.
    ///
    /// A backend that *can* see the declared size checks this against it and
    /// fails by name — `crcbl-vk` does, from the SPIR-V it is compiling.
    /// [`check_workgroup_size`](Self::check_workgroup_size) is the half every
    /// backend can perform.
    pub workgroup_size: [u32; 3],
}

impl MeshPipelineDesc<'_> {
    /// Checks [`mesh_workgroup_size`](Self::mesh_workgroup_size), and
    /// [`task_workgroup_size`](Self::task_workgroup_size) when there is a task
    /// stage to launch.
    ///
    /// **Takes no [`Limits`], unlike
    /// [`ComputePipelineDesc::check_workgroup_size`], because the seam models
    /// no mesh or task workgroup ceiling** — and borrowing the compute one
    /// would be wrong in both directions: Vulkan reports
    /// `maxTaskWorkGroupSize` and `maxMeshWorkGroupSize` separately from
    /// compute's, and D3D12 caps a mesh `[numthreads(…)]` product at 128
    /// whatever a compute one may be. So this is the half every backend can
    /// perform with nothing to consult, and the device's own ceiling stays the
    /// backend's to check where it can see one — `crcbl-mtl` does, against the
    /// `maxTotalThreadsPerObjectThreadgroup` and
    /// `maxTotalThreadsPerMeshThreadgroup` the built `MTLRenderPipelineState`
    /// reports, because on Metal exceeding it is a raise and a raise aborts the
    /// process.
    ///
    /// # Errors
    ///
    /// [`HalError::InvalidDescriptor`], naming the stage and the dimension.
    pub fn check_workgroup_sizes(&self) -> Result<(), HalError> {
        workgroup_invocations(self.mesh_workgroup_size, "mesh_workgroup_size")?;
        if self.task.is_some() {
            workgroup_invocations(self.task_workgroup_size, "task_workgroup_size")?;
        }
        Ok(())
    }
}

/// A declared workgroup size multiplied out, or why it describes no workgroup.
///
/// The half of a workgroup-size check that needs no device to make: a zero
/// extent runs nothing and no shader declares one, and a product that overflows
/// a `u32` is a number no API has a field for. `what` names the field, because
/// a mesh pipeline has two of them and the message has to say which.
fn workgroup_invocations(size: [u32; 3], what: &str) -> Result<u32, HalError> {
    for (axis, extent) in size.into_iter().enumerate() {
        if extent == 0 {
            return Err(HalError::InvalidDescriptor(format!(
                "{what} {size:?} is zero in dimension {axis}: a workgroup with no invocations runs \
                 nothing, and no shader declares one"
            )));
        }
    }
    size[0]
        .checked_mul(size[1])
        .and_then(|product| product.checked_mul(size[2]))
        .ok_or_else(|| {
            HalError::InvalidDescriptor(format!(
                "{what} {size:?} overflows a u32 when multiplied out"
            ))
        })
}

impl ComputePipelineDesc<'_> {
    /// Checks [`workgroup_size`](Self::workgroup_size) against what the device
    /// can actually launch.
    ///
    /// Every backend calls this, because none of them gets a usable diagnostic
    /// from below: Vulkan reports an over-large size as a VUID against
    /// `vkCreateComputePipelines` naming neither the number nor the dimension,
    /// and Metal raises an Objective-C exception at the dispatch — which aborts
    /// the process rather than returning an error at all.
    ///
    /// # Errors
    ///
    /// [`HalError::InvalidDescriptor`], naming the dimension and the limit it
    /// exceeded.
    pub fn check_workgroup_size(&self, limits: &Limits) -> Result<(), HalError> {
        let size = self.workgroup_size;
        // The zero and overflow halves are shared with
        // `MeshPipelineDesc::check_workgroup_sizes`; the per-axis ceiling below
        // is compute's own and has no mesh equivalent in `Limits`.
        let invocations = workgroup_invocations(size, "workgroup_size")?;
        for (axis, (extent, max)) in size
            .into_iter()
            .zip(limits.max_compute_workgroup_size)
            .enumerate()
        {
            if extent > max {
                return Err(HalError::InvalidDescriptor(format!(
                    "workgroup_size {size:?} exceeds this device's \
                     max_compute_workgroup_size {:?} in dimension {axis}",
                    limits.max_compute_workgroup_size
                )));
            }
        }
        if invocations > limits.max_compute_invocations_per_workgroup {
            return Err(HalError::InvalidDescriptor(format!(
                "workgroup_size {size:?} is {invocations} invocations, over this device's \
                 max_compute_invocations_per_workgroup {}",
                limits.max_compute_invocations_per_workgroup
            )));
        }
        Ok(())
    }
}

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

    /// The locked decision from stage 2 (`docs/notes/backends.md`). If this test
    /// fails, someone changed the depth convention — that invalidates every
    /// golden image in the repo, so it needs a deliberate re-bless, not a
    /// test edit.
    #[test]
    fn depth_defaults_are_reversed_z() {
        let state = DepthStencilState::default();
        assert_eq!(state.depth_compare, CompareOp::Greater);
        assert_eq!(state.format, Format::D32Float);
        assert!(state.depth_write);
        assert_eq!(CompareOp::default(), CompareOp::Greater);
    }

    #[test]
    fn equal_depth_pass_uses_greater_or_equal_with_writes_off() {
        let state = DepthStencilState::equal_depth_read_only(Format::D32Float);
        assert_eq!(state.depth_compare, CompareOp::GreaterOrEqual);
        assert!(!state.depth_write);
    }

    /// Reversed-Z lives in the projection matrix; the viewport depth range
    /// stays 0..1. See [`Viewport`] for why conflating them is a trap.
    #[test]
    fn viewport_depth_range_is_not_inverted() {
        let viewport = Viewport::from_size(1920, 1080);
        assert_eq!(viewport.depth_min, 0.0);
        assert_eq!(viewport.depth_max, 1.0);
        assert!(viewport.depth_min < viewport.depth_max);
        assert_eq!(Viewport::default().depth_min, 0.0);
    }

    /// The clear value and the compare op have to agree: with `Greater`, the
    /// cleared buffer must hold the *failing* extreme, or nothing draws.
    #[test]
    fn clear_depth_agrees_with_the_default_compare_op() {
        assert_eq!(depth::CLEAR, 0.0);
        assert_eq!(depth::NEAR, 1.0);
        let state = DepthStencilState::default();
        assert_eq!(state.depth_compare, CompareOp::Greater);
        const {
            assert!(
                depth::NEAR > depth::CLEAR,
                "geometry at the near plane must beat the cleared far value"
            );
        }
    }

    /// **The storage-buffer budget is per stage and summed across bind group
    /// layouts**, and going one over is refused.
    ///
    /// Falsified by the arms below rather than asserted: a layout at exactly the
    /// floor passes, the same layout with one more binding fails, and a 7+7
    /// *split* fails too — which is the whole point, because splitting is what
    /// an author reaches for first and it is what a device also refuses.
    #[test]
    fn a_pipeline_layout_over_the_portable_storage_budget_is_refused() {
        let storage = |binding: u32, visibility: ShaderStages| BindGroupLayoutEntry {
            binding,
            visibility,
            kind: BindingKind::StorageBuffer {
                read_only: true,
                dynamic: false,
                stride: 4,
            },
            count: 1,
            flags: BindingFlags::empty(),
        };
        let compute: Vec<BindGroupLayoutEntry> = (0..PORTABLE_STORAGE_BUFFERS_PER_STAGE)
            .map(|binding| storage(binding, ShaderStages::COMPUTE))
            .collect();
        let at_the_floor = BindGroupLayoutDesc {
            label: Some("at the floor"),
            entries: &compute,
        };
        check_portable_storage_buffers(at_the_floor.label, &[&at_the_floor])
            .expect("exactly the guaranteed number is legal");

        let mut over = compute.clone();
        over.push(storage(
            PORTABLE_STORAGE_BUFFERS_PER_STAGE,
            ShaderStages::COMPUTE,
        ));
        let over = BindGroupLayoutDesc {
            label: Some("one over"),
            entries: &over,
        };
        let error = check_portable_storage_buffers(over.label, &[&over]).expect_err("one over");
        assert!(error.to_string().contains("one over"), "{error}");
        assert!(error.to_string().contains("compute"), "{error}");

        // Split across two groups, which is what the limit does *not* forgive.
        let (first, second) = compute.split_at(4);
        let mut tail = second.to_vec();
        tail.push(storage(
            PORTABLE_STORAGE_BUFFERS_PER_STAGE,
            ShaderStages::COMPUTE,
        ));
        let first = BindGroupLayoutDesc {
            label: Some("split"),
            entries: first,
        };
        let second = BindGroupLayoutDesc {
            label: Some("split"),
            entries: &tail,
        };
        check_portable_storage_buffers(Some("split"), &[&first, &second])
            .expect_err("the limit sums over every bind group layout in the pipeline layout");

        // The graphics stages are counted apart from each other: eight in the
        // vertex stage and eight in the fragment stage is sixteen bindings and
        // still legal.
        let graphics: Vec<BindGroupLayoutEntry> = (0..PORTABLE_STORAGE_BUFFERS_PER_STAGE)
            .map(|binding| storage(binding, ShaderStages::VERTEX))
            .chain((0..PORTABLE_STORAGE_BUFFERS_PER_STAGE).map(|binding| {
                storage(
                    binding + PORTABLE_STORAGE_BUFFERS_PER_STAGE,
                    ShaderStages::FRAGMENT,
                )
            }))
            .collect();
        let graphics = BindGroupLayoutDesc {
            label: Some("both stages"),
            entries: &graphics,
        };
        check_portable_storage_buffers(graphics.label, &[&graphics])
            .expect("the budget is per stage");
    }

    /// A mesh-stage binding is not measured against a WebGPU limit, because no
    /// WebGPU device has a mesh stage — but one it *shares* with the fragment
    /// stage still counts there.
    #[test]
    fn the_mesh_stages_are_outside_the_webgpu_budget_and_the_fragment_stage_is_not() {
        let storage = |binding: u32, visibility: ShaderStages| BindGroupLayoutEntry {
            binding,
            visibility,
            kind: BindingKind::StorageBuffer {
                read_only: true,
                dynamic: false,
                stride: 4,
            },
            count: 1,
            flags: BindingFlags::empty(),
        };
        let mesh_only: Vec<BindGroupLayoutEntry> = (0..PORTABLE_STORAGE_BUFFERS_PER_STAGE * 2)
            .map(|binding| storage(binding, ShaderStages::MESH.union(ShaderStages::TASK)))
            .collect();
        let mesh_only = BindGroupLayoutDesc {
            label: Some("mesh path"),
            entries: &mesh_only,
        };
        check_portable_storage_buffers(mesh_only.label, &[&mesh_only])
            .expect("a mesh pipeline is never a WebGPU pipeline");

        let shared: Vec<BindGroupLayoutEntry> = (0..PORTABLE_STORAGE_BUFFERS_PER_STAGE + 1)
            .map(|binding| storage(binding, ShaderStages::MESH.union(ShaderStages::FRAGMENT)))
            .collect();
        let shared = BindGroupLayoutDesc {
            label: Some("shared with the fragment stage"),
            entries: &shared,
        };
        let error = check_portable_storage_buffers(shared.label, &[&shared])
            .expect_err("the fragment half is still a WebGPU stage");
        assert!(error.to_string().contains("fragment"), "{error}");
    }

    /// An array binding spends its whole length, so the bindless sentinel is
    /// refused — which is the truth about it rather than a technicality.
    #[test]
    fn an_array_of_storage_buffers_spends_its_whole_count() {
        let entries = [BindGroupLayoutEntry {
            binding: 0,
            visibility: ShaderStages::COMPUTE,
            kind: BindingKind::StorageBuffer {
                read_only: true,
                dynamic: false,
                stride: 4,
            },
            count: PORTABLE_STORAGE_BUFFERS_PER_STAGE + 1,
            flags: BindingFlags::empty(),
        }];
        let desc = BindGroupLayoutDesc {
            label: Some("an array"),
            entries: &entries,
        };
        check_portable_storage_buffers(desc.label, &[&desc]).expect_err("nine descriptors");
    }

    #[test]
    fn blend_presets_differ_only_where_they_should() {
        let alpha = BlendState::alpha();
        let premul = BlendState::premultiplied();
        assert_eq!(alpha.color_src, BlendFactor::SrcAlpha);
        assert_eq!(premul.color_src, BlendFactor::One);
        assert_eq!(alpha.color_dst, premul.color_dst);
        assert_eq!(BlendState::additive().color_dst, BlendFactor::One);
    }

    #[test]
    fn color_writes_all_covers_four_channels() {
        assert_eq!(ColorWrites::ALL.bits().count_ones(), 4);
        assert!(ColorWrites::ALL.contains(ColorWrites::A));
    }

    #[test]
    fn opaque_target_has_no_blending() {
        let target = ColorTargetState::opaque(Format::Rgba16Float);
        assert!(target.blend.is_none());
        assert_eq!(target.write_mask, ColorWrites::ALL);
        assert!(target.format.is_hdr_capable(), "P1 renders to RGBA16F");
    }

    #[test]
    fn primitive_defaults_are_the_common_case() {
        let primitive = PrimitiveState::default();
        assert_eq!(primitive.topology, PrimitiveTopology::TriangleList);
        assert_eq!(primitive.polygon_mode, PolygonMode::Fill);
        assert_eq!(
            primitive.cull_mode,
            CullMode::None,
            "culling must be asked for: the default cannot know the winding of \
             imported geometry"
        );
    }

    /// A workgroup size no device could launch is refused, and the message
    /// names the dimension.
    ///
    /// **What turns it red.** Dropping the zero check — a `[0, 1, 1]` pipeline
    /// builds on every backend and dispatches nothing, which is exactly the
    /// silent no-op this field exists to make impossible. Comparing against the
    /// wrong axis, or against the total only — the `z` case passes its own
    /// dimension's limit and fails on the product, and the `x` case is the
    /// reverse. Accepting the size that satisfies both limits — the last case,
    /// which is what every real shader here looks like.
    #[test]
    fn a_workgroup_size_the_device_cannot_launch_is_refused_by_dimension() {
        let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
        let layout: PipelineLayoutHandle = pool.insert(0).cast();
        let module: crate::ShaderModuleHandle = pool.insert(0).cast();
        let desc = |workgroup_size| ComputePipelineDesc {
            label: Some("guard"),
            layout,
            compute: ShaderEntry {
                module,
                entry_point: "computeMain",
            },
            workgroup_size,
        };
        let limits = Limits::minimum();

        let zero = desc([0, 1, 1])
            .check_workgroup_size(&limits)
            .expect_err("a workgroup of no invocations");
        assert!(zero.to_string().contains("zero in dimension 0"), "{zero}");

        let wide = desc([limits.max_compute_workgroup_size[0] + 1, 1, 1])
            .check_workgroup_size(&limits)
            .expect_err("over the per-dimension limit");
        assert!(
            wide.to_string().contains("dimension 0"),
            "the dimension must be named: {wide}"
        );

        // Under every per-dimension limit and still too many threads, which is
        // the case a per-axis check alone would let through.
        let deep = [8, 8, limits.max_compute_workgroup_size[2]];
        assert!(
            deep.iter()
                .zip(limits.max_compute_workgroup_size)
                .all(|(extent, max)| *extent <= max),
            "this case must be legal on every axis or it proves nothing"
        );
        let total = desc(deep)
            .check_workgroup_size(&limits)
            .expect_err("over the invocation total");
        assert!(
            total.to_string().contains("invocations"),
            "the total must be named: {total}"
        );

        desc([64, 1, 1])
            .check_workgroup_size(&limits)
            .expect("the size every compute shader in this workspace declares");
    }

    fn caps(features: Features) -> DeviceCaps {
        DeviceCaps {
            features,
            limits: Limits::desktop(),
        }
    }

    fn binding(binding: u32, flags: BindingFlags, count: u32) -> BindGroupLayoutEntry {
        BindGroupLayoutEntry {
            binding,
            visibility: ShaderStages::VERTEX,
            kind: BindingKind::StorageBuffer {
                read_only: true,
                dynamic: false,
                stride: 4,
            },
            count,
            flags,
        }
    }

    fn check(entries: &[BindGroupLayoutEntry], caps: &DeviceCaps) -> Result<(), HalError> {
        BindGroupLayoutDesc {
            label: Some("guard"),
            entries,
        }
        .check_entries(caps, BackendKind::Null)
    }

    /// A legal layout passes — the half without which every rejection below is
    /// satisfied by a checker that refuses everything.
    ///
    /// The triangle's own layout is one read-only storage buffer with no flags,
    /// and it must be legal on **both** tiers: vertex pulling is not a Tier A
    /// feature, it is the engine's only geometry path.
    #[test]
    fn the_vertex_pulling_layout_is_legal_on_both_tiers() {
        let entries = [binding(0, BindingFlags::empty(), 1)];
        check(&entries, &caps(Features::GPU_DRIVEN)).expect("Tier A");
        check(&entries, &caps(Features::empty())).expect("Tier B too");

        // And the shape the bindless model is actually written in, on a device
        // that reports the feature.
        let bindless = [
            binding(0, BindingFlags::empty(), 1),
            BindGroupLayoutEntry {
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    sample_type: SampleType::Float,
                },
                ..binding(
                    1,
                    BindingFlags::VARIABLE_COUNT
                        | BindingFlags::PARTIALLY_BOUND
                        | BindingFlags::UPDATE_AFTER_BIND,
                    u32::MAX,
                )
            },
        ];
        check(&bindless, &caps(Features::GPU_DRIVEN))
            .expect("u32::MAX is a request to clamp, not an over-large request");
    }

    /// A binding holding no descriptors is one no shader can index, and wgpu
    /// spells "no count" and "a count of one" the same way — so a zero would
    /// arrive there as an ordinary scalar binding.
    #[test]
    fn a_zero_count_is_refused_by_binding_number() {
        let error = check(
            &[binding(3, BindingFlags::empty(), 0)],
            &caps(Features::GPU_DRIVEN),
        )
        .expect_err("a binding holding nothing");
        assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
        let text = error.to_string();
        for expected in ["binding 3", "count 0"] {
            assert!(text.contains(expected), "{expected:?} missing from {text}");
        }
    }

    /// Two entries claiming one binding number is a caller bug, and which of
    /// the two wins is not something the seam decides.
    #[test]
    fn a_duplicated_binding_number_is_refused() {
        let entries = [
            binding(3, BindingFlags::empty(), 1),
            binding(3, BindingFlags::empty(), 1),
        ];
        let error = check(&entries, &caps(Features::GPU_DRIVEN)).expect_err("binding 3 twice");
        assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
        assert!(error.to_string().contains("twice"), "{error}");
    }

    /// The seam's rule, and the reason it exists: "a bindless array quietly
    /// downgraded to a fixed one reads garbage at index 4097".
    ///
    /// Every flag individually, because one standing for the others is a
    /// reading the loop would hide.
    #[test]
    fn a_device_without_descriptor_indexing_refuses_the_flags_rather_than_ignoring_them() {
        for flag in [
            BindingFlags::PARTIALLY_BOUND,
            BindingFlags::UPDATE_AFTER_BIND,
            BindingFlags::VARIABLE_COUNT,
        ] {
            assert!(!flag.is_empty(), "{flag:?} would prove nothing");
            let entries = [binding(0, flag, 4)];
            let error = check(&entries, &caps(Features::empty()))
                .expect_err("a device without the feature");
            assert!(
                matches!(error, HalError::Unsupported { backend, .. } if backend == BackendKind::Null),
                "{flag:?}: {error:?}"
            );
            check(&entries, &caps(Features::GPU_DRIVEN))
                .unwrap_or_else(|error| panic!("{flag:?} on a device reporting it: {error}"));
        }
    }

    /// A binding visible to a mesh stage is legal on a device that reports the
    /// stage and nowhere else. `GPU_DRIVEN` carries neither mesh flag, which is
    /// what makes the refusing half a real device rather than a contrived one.
    #[test]
    fn a_mesh_visible_binding_needs_the_matching_capability() {
        for (stage, feature) in [
            (ShaderStages::MESH, Features::MESH_SHADER),
            (ShaderStages::TASK, Features::TASK_SHADER),
        ] {
            let entries = [BindGroupLayoutEntry {
                visibility: stage,
                ..binding(0, BindingFlags::empty(), 1)
            }];
            let error = check(&entries, &caps(Features::GPU_DRIVEN))
                .expect_err("GPU_DRIVEN carries neither mesh flag");
            assert!(
                matches!(error, HalError::Unsupported { .. }),
                "{stage:?}: {error}"
            );
            check(&entries, &caps(Features::GPU_DRIVEN | feature))
                .unwrap_or_else(|error| panic!("{stage:?} on a device reporting it: {error}"));
        }
    }

    /// Both halves of the `VARIABLE_COUNT` rule, and each refusal says which
    /// half it is.
    ///
    /// **What turns it red.** Checking only "last in the slice" accepts the
    /// second case, which every driver refuses. Checking only "highest
    /// numbered" accepts the first, which leaves `entries.last()` pointing at
    /// the wrong entry in every backend that reads it that way. Checking
    /// neither accepts the layout the third case builds legally, so the passing
    /// half is what keeps the two apart.
    #[test]
    fn variable_count_must_be_both_last_and_highest_numbered() {
        let tier_a = caps(Features::GPU_DRIVEN);

        // Highest-numbered, but not last in the slice.
        let entries = [
            binding(7, BindingFlags::VARIABLE_COUNT, 8),
            binding(2, BindingFlags::empty(), 1),
        ];
        let error = check(&entries, &tier_a).expect_err("not the last entry");
        assert!(
            error.to_string().contains("not the last entry"),
            "the half that failed must be named: {error}"
        );

        // Last in the slice, but binding 2 sits below binding 7.
        let entries = [
            binding(7, BindingFlags::empty(), 1),
            binding(2, BindingFlags::VARIABLE_COUNT, 8),
        ];
        let error = check(&entries, &tier_a).expect_err("not the highest binding number");
        assert!(
            error
                .to_string()
                .contains("not the highest-numbered binding"),
            "the half that failed must be named: {error}"
        );

        // Both halves satisfied.
        let entries = [
            binding(2, BindingFlags::empty(), 1),
            binding(7, BindingFlags::VARIABLE_COUNT, 8),
        ];
        check(&entries, &tier_a).expect("last and highest");
    }

    /// The sentinel is exempt from the ceiling it is about to be clamped to;
    /// an explicit count above it is still a caller bug.
    ///
    /// **What turns it red.** Dropping the `u32::MAX` exemption — the sentinel
    /// is larger than any real device's ceiling, so the portable bindless
    /// declaration would be refused on every one of them. Dropping the ceiling
    /// check — an explicit over-large count reaches the driver as a VUID naming
    /// neither the binding nor the limit.
    #[test]
    fn the_count_ceiling_exempts_the_sentinel_and_nothing_else() {
        let tier_a = caps(Features::GPU_DRIVEN);
        let ceiling = tier_a.limits.max_bindless_descriptors;
        assert!(ceiling > 1, "a ceiling of {ceiling} would prove nothing");

        check(&[binding(0, BindingFlags::empty(), u32::MAX)], &tier_a)
            .expect("the sentinel is a request to clamp");
        check(&[binding(0, BindingFlags::empty(), ceiling)], &tier_a).expect("exactly the ceiling");

        let error = check(&[binding(0, BindingFlags::empty(), ceiling + 1)], &tier_a)
            .expect_err("one past the ceiling is not a sentinel");
        assert!(
            error.to_string().contains("max_bindless_descriptors"),
            "the limit must be named: {error}"
        );
    }

    /// The sentinel resolves to what the device can do, and never to zero.
    ///
    /// **What turns it red.** Resolving `u32::MAX` verbatim — which is what
    /// `crcbl-wgpu` did, and wgpu refused the layout outright. Clamping an
    /// ordinary count as well, which would silently shrink a fixed array.
    /// Dropping the floor of one, which turns the sentinel into a zero-length
    /// array on a device reporting no bindless descriptors at all.
    #[test]
    fn the_sentinel_resolves_to_the_devices_own_ceiling() {
        let desktop = Limits::desktop();
        assert!(desktop.max_bindless_descriptors > 1);
        assert_eq!(
            binding(0, BindingFlags::VARIABLE_COUNT, u32::MAX).resolved_count(&desktop),
            desktop.max_bindless_descriptors
        );
        assert_eq!(
            binding(0, BindingFlags::empty(), 16).resolved_count(&desktop),
            16,
            "an explicit count is left alone"
        );

        let minimum = Limits::minimum();
        assert_eq!(minimum.max_bindless_descriptors, 0);
        assert_eq!(
            binding(0, BindingFlags::empty(), u32::MAX).resolved_count(&minimum),
            1,
            "a device with no bindless ceiling still owes a creatable binding"
        );
    }

    /// A dynamic-offset slot of one kind, for the two checks below.
    fn dynamic_slot(binding: u32, uniform: bool) -> BindGroupLayoutEntry {
        BindGroupLayoutEntry {
            binding,
            visibility: ShaderStages::ALL,
            kind: if uniform {
                BindingKind::UniformBuffer { dynamic: true }
            } else {
                BindingKind::StorageBuffer {
                    read_only: true,
                    dynamic: true,
                    stride: 4,
                }
            },
            count: 1,
            flags: BindingFlags::empty(),
        }
    }

    /// The two [`Limits`] fields that are an alignment rather than a ceiling.
    /// A misaligned binding offset used to reach the driver as a VU violation
    /// naming a descriptor type instead of an `InvalidDescriptor` naming the
    /// binding.
    #[test]
    fn a_binding_offset_is_checked_against_its_own_kinds_alignment() {
        let limits = Limits::desktop();
        assert_eq!(limits.min_uniform_buffer_offset_alignment, 64);
        assert_eq!(limits.min_storage_buffer_offset_alignment, 16);
        let uniform = BindingKind::UniformBuffer { dynamic: false };
        let storage = BindingKind::StorageBuffer {
            read_only: true,
            dynamic: false,
            stride: 4,
        };

        // The accepting half: without it every rejection below is satisfied by
        // a check that refuses everything.
        check_binding_offset_alignment(&limits, uniform, 0, 128).expect("128 is a multiple of 64");
        check_binding_offset_alignment(&limits, storage, 1, 32).expect("32 is a multiple of 16");

        // 32 is a legal *storage* offset and an illegal uniform one, which is
        // exactly why one shared alignment would be wrong.
        let error = check_binding_offset_alignment(&limits, uniform, 0, 32)
            .expect_err("32 is not a multiple of 64");
        let text = error.to_string();
        assert!(text.contains("binding 0"), "{text}");
        assert!(text.contains("64-byte"), "{text}");

        let error = check_binding_offset_alignment(&limits, storage, 1, 8)
            .expect_err("8 is not a multiple of 16");
        assert!(error.to_string().contains("binding 1"), "{error}");
    }

    /// An image or sampler slot takes no offset, so it carries no rule — and a
    /// device reporting an alignment of 1 requires nothing of any slot. Both
    /// halves accept, which is what keeps the check from being one that
    /// refuses everything.
    #[test]
    fn an_alignment_of_one_and_a_slotless_kind_accept_every_offset() {
        let limits = Limits::desktop();
        let sampler = BindingKind::Sampler { comparison: false };
        check_binding_offset_alignment(&limits, sampler, 0, 3)
            .expect("a sampler slot takes no offset");

        let mut unaligned = limits;
        unaligned.min_uniform_buffer_offset_alignment = 1;
        unaligned.min_storage_buffer_offset_alignment = 1;
        for kind in [
            BindingKind::UniformBuffer { dynamic: false },
            BindingKind::StorageBuffer {
                read_only: false,
                dynamic: false,
                stride: 4,
            },
        ] {
            check_binding_offset_alignment(&unaligned, kind, 7, 3)
                .expect("an alignment of 1 accepts every offset");
        }
    }

    /// The bind-time half of the same rule: a dynamic offset is added to the
    /// descriptor's own offset, so it satisfies the same alignment.
    #[test]
    fn dynamic_offsets_are_checked_against_the_right_alignment() {
        let limits = Limits::desktop();
        let slots = [dynamic_slot(0, true), dynamic_slot(1, false)];

        check_dynamic_offsets(&limits, &slots, &[128, 32]).expect("both are aligned");

        let error = check_dynamic_offsets(&limits, &slots, &[32, 32])
            .expect_err("32 is not a multiple of 64");
        assert!(error.to_string().contains("binding 0"), "{error}");

        let error = check_dynamic_offsets(&limits, &slots, &[128, 8])
            .expect_err("8 is not a multiple of 16");
        assert!(error.to_string().contains("binding 1"), "{error}");

        let mut unaligned = limits;
        unaligned.min_uniform_buffer_offset_alignment = 1;
        unaligned.min_storage_buffer_offset_alignment = 1;
        check_dynamic_offsets(&unaligned, &slots, &[3, 7])
            .expect("an alignment of 1 accepts every offset");
    }

    /// A count mismatch is a caller bug too: `dynamic_offsets` is positional,
    /// so one too few silently shifts every later offset onto the wrong slot.
    #[test]
    fn the_offset_count_must_match_the_layouts_dynamic_bindings() {
        let limits = Limits::desktop();
        let slots = [dynamic_slot(0, true)];
        assert!(check_dynamic_offsets(&limits, &slots, &[]).is_err());
        assert!(check_dynamic_offsets(&limits, &slots, &[0, 0]).is_err());
        check_dynamic_offsets(&limits, &[], &[]).expect("no dynamic bindings, no offsets");
        check_dynamic_offsets(&limits, &slots, &[0]).expect("one binding, one aligned offset");
    }

    #[test]
    fn whole_buffer_binding_uses_the_sentinel() {
        let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
        let buffer: BufferHandle = pool.insert(0).cast();
        let BindingResource::Buffer { offset, size, .. } = BindingResource::whole_buffer(buffer)
        else {
            panic!("wrong variant");
        };
        assert_eq!(offset, 0);
        assert_eq!(size, BindingResource::WHOLE_BUFFER);
    }
}