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
//! The recorded stream: what [`NullBackend`](super) saw, in order.
//!
//! This is the half of the null backend that makes it a *test tool* rather than
//! a compile check. A no-op backend proves the seam has no leaks; a recording
//! one lets a test assert "this frame emitted these passes in this order, with
//! these barriers between them, and leaked nothing" — which is precisely the
//! graph-compile suite `docs/notes/process.md`'s anchor list asks for against
//! NullBackend.
//!
//! # Getting at it
//!
//! A [`Recorder`] is a cheap `Arc` handle. Make one, hand a clone to
//! [`NullInstance::with_recorder`](super::NullInstance::with_recorder), then run
//! the frame entirely through `dyn Instance` / `dyn Device` and read the stream
//! back afterwards. The test never names a backend type after construction,
//! which is the property the integration suite exists to check.
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use core::fmt;
use core::ops::Range;
use crcbl_core::{Handle, Pool};
use crate::{
AdapterId, BindGroupHandle, BindGroupLayoutEntry, BindGroupLayoutHandle, BufferBarrier,
BufferCopy, BufferHandle, BufferImageCopy, CommandBufferHandle, ComputePipelineHandle,
DepthStencilAttachment, DrawIndirect, DrawIndirectCount, GraphicsPipelineHandle, ImageBarrier,
ImageCopy, ImageHandle, IndexFormat, MemoryLocation, PushConstantRange, QuerySetHandle,
QueueHandle, Rect2d, SemaphoreSignal, SemaphoreWait, ShaderSources, ShaderStages,
SwapchainHandle, Viewport,
};
/// One pipeline as [`Recorder::pipelines_created`] reports it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PipelineRecord {
/// The descriptor's label.
pub label: Option<String>,
/// Each set's declared entries, in set order.
pub sets: Vec<Vec<BindGroupLayoutEntry>>,
/// The layout's push-constant range, if it declared one.
pub push_constants: Option<PushConstantRange>,
/// Every stage the pipeline runs, in pipeline order: vertex then fragment,
/// task then mesh then fragment, or the one compute stage.
pub stages: Vec<StageRecord>,
}
/// One stage of a [`PipelineRecord`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StageRecord {
/// The single stage this entry runs at.
pub stage: ShaderStages,
/// The entry point the stage names.
pub entry_point: String,
/// The DXIL container its module offered for that entry point, or `None`
/// for a module created without DXIL.
pub dxil: Option<Vec<u8>>,
}
/// Every kind of object the null backend tracks.
///
/// The tag half of a handle: `Handle<T>` distinguishes kinds at compile time,
/// and this distinguishes them at lookup time so two kinds can reuse the same
/// slot index without colliding.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ObjectKind {
/// A buffer.
Buffer,
/// An image.
Image,
/// An image view.
ImageView,
/// A sampler.
Sampler,
/// A shader module.
ShaderModule,
/// A bind-group layout.
BindGroupLayout,
/// A bind group.
BindGroup,
/// A pipeline layout.
PipelineLayout,
/// A graphics pipeline.
GraphicsPipeline,
/// A compute pipeline.
ComputePipeline,
/// A query set.
QuerySet,
/// A semaphore.
Semaphore,
/// A finished command buffer.
CommandBuffer,
/// A presentation surface.
Surface,
/// A swapchain.
Swapchain,
/// An in-flight readback request.
Readback,
}
impl ObjectKind {
/// Every kind, in declaration order. Indexing this array by `kind as usize`
/// is how the backend's pool table is addressed.
pub const ALL: [Self; 16] = [
Self::Buffer,
Self::Image,
Self::ImageView,
Self::Sampler,
Self::ShaderModule,
Self::BindGroupLayout,
Self::BindGroup,
Self::PipelineLayout,
Self::GraphicsPipeline,
Self::ComputePipeline,
Self::QuerySet,
Self::Semaphore,
Self::CommandBuffer,
Self::Surface,
Self::Swapchain,
Self::Readback,
];
/// A short lowercase name, used in errors and in [`fmt::Display`].
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Buffer => "buffer",
Self::Image => "image",
Self::ImageView => "image view",
Self::Sampler => "sampler",
Self::ShaderModule => "shader module",
Self::BindGroupLayout => "bind group layout",
Self::BindGroup => "bind group",
Self::PipelineLayout => "pipeline layout",
Self::GraphicsPipeline => "graphics pipeline",
Self::ComputePipeline => "compute pipeline",
Self::QuerySet => "query set",
Self::Semaphore => "semaphore",
Self::CommandBuffer => "command buffer",
Self::Surface => "surface",
Self::Swapchain => "swapchain",
Self::Readback => "readback",
}
}
}
impl fmt::Display for ObjectKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
/// One recorded command, with every borrowed field owned.
///
/// Mirrors [`CommandEncoder`](crate::CommandEncoder) one-to-one. Slices and
/// `&str`s become `Vec`s and `String`s so the stream outlives the descriptors
/// that produced it; `push_constants` keeps only the byte count, because a test
/// asserting on push-constant *contents* is asserting on shader ABI, not on the
/// command stream.
#[derive(Clone, Debug, PartialEq)]
pub enum Command {
/// [`begin_debug_label`](crate::CommandEncoder::begin_debug_label).
BeginDebugLabel(String),
/// [`end_debug_label`](crate::CommandEncoder::end_debug_label).
EndDebugLabel,
/// [`insert_debug_marker`](crate::CommandEncoder::insert_debug_marker).
DebugMarker(String),
/// [`pipeline_barrier`](crate::CommandEncoder::pipeline_barrier).
Barrier {
/// Buffer transitions.
buffers: Vec<BufferBarrier>,
/// Image transitions.
images: Vec<ImageBarrier>,
/// Whether a global barrier was requested.
global: bool,
},
/// [`copy_buffer_to_buffer`](crate::CommandEncoder::copy_buffer_to_buffer).
CopyBufferToBuffer(BufferCopy),
/// [`copy_buffer_to_image`](crate::CommandEncoder::copy_buffer_to_image).
CopyBufferToImage(BufferImageCopy),
/// [`copy_image_to_buffer`](crate::CommandEncoder::copy_image_to_buffer).
CopyImageToBuffer(BufferImageCopy),
/// [`copy_image_to_image`](crate::CommandEncoder::copy_image_to_image).
CopyImageToImage(ImageCopy),
/// [`fill_buffer`](crate::CommandEncoder::clear_buffer).
ClearBuffer {
/// Buffer zeroed.
buffer: BufferHandle,
/// Byte offset.
offset: u64,
/// Byte length.
size: u64,
},
/// [`begin_render_pass`](crate::CommandEncoder::begin_render_pass).
BeginRenderPass {
/// Pass label, if the caller gave one.
label: Option<String>,
/// Colour attachments.
color_attachments: Vec<crate::ColorAttachment>,
/// Depth/stencil attachment.
depth_stencil_attachment: Option<DepthStencilAttachment>,
/// Region rendered.
render_area: Rect2d,
/// Timestamps bracketing the pass, if the caller asked for them.
timestamp_writes: Option<crate::PassTimestampWrites>,
},
/// [`end_render_pass`](crate::CommandEncoder::end_render_pass).
EndRenderPass,
/// [`set_viewport`](crate::CommandEncoder::set_viewport).
SetViewport(Viewport),
/// [`set_scissor`](crate::CommandEncoder::set_scissor).
SetScissor(Rect2d),
/// [`set_stencil_reference`](crate::CommandEncoder::set_stencil_reference).
SetStencilReference(u32),
/// [`bind_graphics_pipeline`](crate::CommandEncoder::bind_graphics_pipeline).
BindGraphicsPipeline(GraphicsPipelineHandle),
/// [`bind_index_buffer`](crate::CommandEncoder::bind_index_buffer).
BindIndexBuffer {
/// Buffer bound.
buffer: BufferHandle,
/// Byte offset.
offset: u64,
/// Index width.
format: IndexFormat,
},
/// [`bind_group`](crate::CommandEncoder::bind_group).
BindGroup {
/// Set index.
slot: u32,
/// Group bound.
group: BindGroupHandle,
/// Dynamic offsets supplied.
dynamic_offsets: Vec<u32>,
},
/// [`push_constants`](crate::CommandEncoder::push_constants).
PushConstants {
/// Stages written.
stages: ShaderStages,
/// Byte offset within the block.
offset: u32,
/// Bytes written.
len: usize,
},
/// [`draw`](crate::CommandEncoder::draw).
Draw {
/// Vertex range.
vertices: Range<u32>,
/// Instance range.
instances: Range<u32>,
},
/// [`draw_indexed`](crate::CommandEncoder::draw_indexed).
DrawIndexed {
/// Index range.
indices: Range<u32>,
/// Value added to each index.
base_vertex: i32,
/// Instance range.
instances: Range<u32>,
},
/// [`draw_indirect`](crate::CommandEncoder::draw_indirect).
DrawIndirect(DrawIndirect),
/// [`draw_indexed_indirect`](crate::CommandEncoder::draw_indexed_indirect).
DrawIndexedIndirect(DrawIndirect),
/// [`draw_indirect_count`](crate::CommandEncoder::draw_indirect_count).
DrawIndirectCount(DrawIndirectCount),
/// [`draw_indexed_indirect_count`](crate::CommandEncoder::draw_indexed_indirect_count).
DrawIndexedIndirectCount(DrawIndirectCount),
/// [`draw_mesh_tasks`](crate::CommandEncoder::draw_mesh_tasks).
DrawMeshTasks {
/// Workgroups on X.
x: u32,
/// Workgroups on Y.
y: u32,
/// Workgroups on Z.
z: u32,
},
/// [`draw_mesh_tasks_indirect`](crate::CommandEncoder::draw_mesh_tasks_indirect).
///
/// The workgroup counts are **not** here, because they are not the CPU's:
/// what a test can assert is the buffer and the offset the driver would
/// read them from, and the contents are the producing pass's to check.
DrawMeshTasksIndirect(DrawIndirect),
/// [`begin_compute_pass`](crate::CommandEncoder::begin_compute_pass).
BeginComputePass {
/// Pass label, if the caller gave one.
label: Option<String>,
/// Timestamps bracketing the pass, if the caller asked for them.
timestamp_writes: Option<crate::PassTimestampWrites>,
},
/// [`end_compute_pass`](crate::CommandEncoder::end_compute_pass).
EndComputePass,
/// [`bind_compute_pipeline`](crate::CommandEncoder::bind_compute_pipeline).
BindComputePipeline(ComputePipelineHandle),
/// [`dispatch`](crate::CommandEncoder::dispatch).
Dispatch {
/// Workgroups on X.
x: u32,
/// Workgroups on Y.
y: u32,
/// Workgroups on Z.
z: u32,
},
/// [`dispatch_indirect`](crate::CommandEncoder::dispatch_indirect).
DispatchIndirect {
/// Argument buffer.
args: BufferHandle,
/// Byte offset.
offset: u64,
},
/// [`reset_query_set`](crate::CommandEncoder::reset_query_set).
ResetQuerySet {
/// Query set.
set: QuerySetHandle,
/// Query range.
range: Range<u32>,
},
/// [`resolve_query_set`](crate::CommandEncoder::resolve_query_set).
ResolveQuerySet {
/// Query set.
set: QuerySetHandle,
/// Query range.
range: Range<u32>,
/// Destination buffer.
dst: BufferHandle,
/// Byte offset in the destination.
dst_offset: u64,
},
}
impl Command {
/// A stable variant name.
///
/// Lets a test assert the *shape* of a frame — `["BeginComputePass",
/// "Dispatch", "EndComputePass", "BeginRenderPass", …]` — without spelling
/// out every handle and descriptor, which is usually the assertion worth
/// making.
#[must_use]
pub const fn name(&self) -> &'static str {
match self {
Self::BeginDebugLabel(_) => "BeginDebugLabel",
Self::EndDebugLabel => "EndDebugLabel",
Self::DebugMarker(_) => "DebugMarker",
Self::Barrier { .. } => "Barrier",
Self::CopyBufferToBuffer(_) => "CopyBufferToBuffer",
Self::CopyBufferToImage(_) => "CopyBufferToImage",
Self::CopyImageToBuffer(_) => "CopyImageToBuffer",
Self::CopyImageToImage(_) => "CopyImageToImage",
Self::ClearBuffer { .. } => "ClearBuffer",
Self::BeginRenderPass { .. } => "BeginRenderPass",
Self::EndRenderPass => "EndRenderPass",
Self::SetViewport(_) => "SetViewport",
Self::SetScissor(_) => "SetScissor",
Self::SetStencilReference(_) => "SetStencilReference",
Self::BindGraphicsPipeline(_) => "BindGraphicsPipeline",
Self::BindIndexBuffer { .. } => "BindIndexBuffer",
Self::BindGroup { .. } => "BindGroup",
Self::PushConstants { .. } => "PushConstants",
Self::Draw { .. } => "Draw",
Self::DrawIndexed { .. } => "DrawIndexed",
Self::DrawIndirect(_) => "DrawIndirect",
Self::DrawIndexedIndirect(_) => "DrawIndexedIndirect",
Self::DrawIndirectCount(_) => "DrawIndirectCount",
Self::DrawIndexedIndirectCount(_) => "DrawIndexedIndirectCount",
Self::DrawMeshTasks { .. } => "DrawMeshTasks",
Self::DrawMeshTasksIndirect(_) => "DrawMeshTasksIndirect",
Self::BeginComputePass { .. } => "BeginComputePass",
Self::EndComputePass => "EndComputePass",
Self::BindComputePipeline(_) => "BindComputePipeline",
Self::Dispatch { .. } => "Dispatch",
Self::DispatchIndirect { .. } => "DispatchIndirect",
Self::ResetQuerySet { .. } => "ResetQuerySet",
Self::ResolveQuerySet { .. } => "ResolveQuerySet",
}
}
/// The pass this command opens, if it opens one.
///
/// `("render" | "compute", label)`.
#[must_use]
pub fn opens_pass(&self) -> Option<(&'static str, Option<&str>)> {
match self {
Self::BeginRenderPass { label, .. } => Some(("render", label.as_deref())),
Self::BeginComputePass { label, .. } => Some(("compute", label.as_deref())),
_ => None,
}
}
}
/// A device-level event, interleaved with the commands in one ordered stream.
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
/// An object was created.
Created {
/// What kind.
kind: ObjectKind,
/// Its label, if it had one.
label: Option<String>,
},
/// An object was destroyed.
Destroyed {
/// What kind.
kind: ObjectKind,
},
/// The host wrote into a mappable buffer.
BufferWritten {
/// Buffer written.
buffer: BufferHandle,
/// Byte offset.
offset: u64,
/// Bytes written.
len: usize,
},
/// A readback was requested.
ReadbackRequested {
/// Buffer to be read.
buffer: BufferHandle,
/// Byte offset.
offset: u64,
/// Bytes requested.
size: u64,
},
/// The host read from a readback buffer — emitted by the poll that
/// completes a request.
BufferRead {
/// Buffer read.
buffer: BufferHandle,
/// Byte offset.
offset: u64,
/// Bytes read.
len: usize,
},
/// A recorded command. Emitted when its encoder is finished, in record
/// order, immediately before the [`Event::Finished`] for that buffer.
Command {
/// Command buffer it belongs to.
command_buffer: CommandBufferHandle,
/// The command.
command: Command,
},
/// An encoder produced a command buffer.
Finished {
/// Encoder label.
label: Option<String>,
/// Resulting command buffer.
command_buffer: CommandBufferHandle,
},
/// Work was submitted to a queue.
Submitted {
/// Queue submitted to.
queue: QueueHandle,
/// Command buffers, in execution order.
command_buffers: Vec<CommandBufferHandle>,
/// Waits performed first.
waits: Vec<SemaphoreWait>,
/// Signals performed on completion.
signals: Vec<SemaphoreSignal>,
},
/// A swapchain image was acquired.
Acquired {
/// Swapchain acquired from.
swapchain: SwapchainHandle,
/// Image index within the ring.
index: u32,
},
/// A swapchain image was presented.
Presented {
/// Swapchain presented.
swapchain: SwapchainHandle,
/// The number the caller gave this present, from
/// [`PresentInfo::present_id`](crate::PresentInfo::present_id).
present_id: Option<u64>,
},
/// The caller asked to wait for a numbered present with
/// [`Device::wait_until_presented`](crate::Device::wait_until_presented).
///
/// Recorded even though nothing is ever waited *for*: there is no display
/// behind this backend, so the call returns without blocking whether or not
/// the device advertises
/// [`Features::PRESENT_FEEDBACK`](crate::Features::PRESENT_FEEDBACK). The
/// event is the request, which is what a test of a frame loop's pacing
/// needs to see.
PresentWaited {
/// Swapchain the wait named.
swapchain: SwapchainHandle,
/// Present the caller waited for.
present_id: u64,
/// Whether the wait was answered with
/// [`SurfaceError::Timeout`](crate::SurfaceError::Timeout) instead of
/// with the frame, which only
/// [`Recorder::report_present_wait_timeouts`] makes true.
///
/// Here because the request alone cannot carry the difference: a caller
/// that renders the frame anyway — which is what the seam asks of one —
/// leaves the same acquire and the same present behind it either way,
/// so a test of that policy could not tell an injection that landed
/// from one that silently did nothing.
timed_out: bool,
},
/// A swapchain was reconfigured (resize, present-mode change).
Reconfigured {
/// Swapchain reconfigured.
swapchain: SwapchainHandle,
/// New size in pixels.
extent: (u32, u32),
},
/// [`Device::wait_idle`](crate::Device::wait_idle) was called.
WaitedIdle,
}
/// A rule the recorded stream broke.
///
/// The null backend never panics on one of these and never fails the call: it
/// records the violation and carries on, so a test sees the *whole* frame's
/// worth of problems rather than only the first. Check with
/// [`Recorder::validation_errors`] or [`Recorder::assert_valid`].
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ValidationError {
/// A command legal only inside a render or compute pass was recorded
/// outside one.
#[error("`{command}` requires an open {expected} pass")]
OutsidePass {
/// Command name, from [`Command::name`].
command: &'static str,
/// Which pass kind it needed.
expected: &'static str,
},
/// A command legal only outside a pass was recorded inside one. Copies,
/// barriers and query writes are all in this group — Vulkan forbids them
/// inside dynamic rendering.
#[error("`{command}` is not allowed inside a pass")]
InsidePass {
/// Command name, from [`Command::name`].
command: &'static str,
},
/// A pass was opened while another was open. Passes do not nest.
#[error("`{command}` opened a pass while another was already open")]
NestedPass {
/// Command name, from [`Command::name`].
command: &'static str,
},
/// A pass was closed that had not been opened, or closed as the wrong kind.
#[error("`{command}` closed a pass that was not open")]
UnopenedPass {
/// Command name, from [`Command::name`].
command: &'static str,
},
/// An encoder was finished with a pass still open.
#[error("command buffer finished with a pass still open")]
UnclosedPass,
/// A command referenced a handle owned by a different device — the
/// recorded-stream counterpart of
/// [`HalError::ForeignObject`](crate::HalError::ForeignObject).
#[error("`{command}` referenced a {kind} handle {bits:#x} owned by another device")]
ForeignHandle {
/// Command name, from [`Command::name`].
command: &'static str,
/// Kind expected.
kind: ObjectKind,
/// Packed handle bits.
bits: u64,
},
/// A pass asked for both of its timestamps in the same query.
///
/// WebGPU requires `beginningOfPassWriteIndex` and `endOfPassWriteIndex` to
/// differ, and a pass that wrote both ends into one query would report the
/// second over the first on every other backend — so the pair measures
/// nothing wherever it is accepted. See
/// [`PassTimestampWrites`](crate::PassTimestampWrites).
#[error("`{command}` writes both of its timestamps into query {index}")]
CoincidentTimestamps {
/// Command name, from [`Command::name`].
command: &'static str,
/// The query both writes named.
index: u32,
},
/// A pass's timestamp write named a query past the end of its set.
#[error("`{command}` writes a timestamp into query {index} of a {count}-query set")]
TimestampOutOfRange {
/// Command name, from [`Command::name`].
command: &'static str,
/// The query the pass named.
index: u32,
/// How many queries the set holds.
count: u32,
},
/// An indirect draw's arguments break one of the rules
/// [`crate::indirect`] states for stepping an array of argument structures:
/// a four-byte-aligned offset, a stride no smaller than one structure, and
/// structures that fit inside the buffer.
///
/// `message` is the seam's own refusal, verbatim, and the same string
/// [`CommandEncoder::finish`](crate::CommandEncoder::finish) returns inside
/// a [`HalError::InvalidDescriptor`](crate::HalError::InvalidDescriptor) —
/// a recording method returns `()` and cannot report one inline, so this
/// draw is both recorded here and remembered for the boundary. None of
/// these mistakes is one an API reports usefully: a misaligned indirect
/// offset is `VUID-vkCmdDrawIndirect-offset-02710`, which has no error code
/// at all — the driver reads the arguments from the wrong bytes.
#[error("`{command}` was given indirect arguments the seam refuses: {message}")]
InvalidIndirectArguments {
/// Command name, from [`Command::name`].
command: &'static str,
/// The seam's refusal, unchanged.
message: String,
},
/// A bind's dynamic offsets break one of the rules
/// [`check_dynamic_offsets`](crate::check_dynamic_offsets) states: one
/// offset per dynamic-offset binding the layout declares, in binding
/// order, each a multiple of the alignment its slot requires.
///
/// `message` is the seam's own refusal, verbatim, and the same string
/// [`CommandEncoder::finish`](crate::CommandEncoder::finish) returns inside
/// a [`HalError::InvalidDescriptor`](crate::HalError::InvalidDescriptor) —
/// [`InvalidIndirectArguments`](Self::InvalidIndirectArguments)'s
/// arrangement, for its reason: `bind_group` returns `()` and cannot report
/// one inline. Neither mistake is one an API reports usefully. A misaligned
/// dynamic offset is `VUID-vkCmdBindDescriptorSets-pDynamicOffsets-01971`,
/// and a miscounted one is not a violation at all — the offsets are
/// positional, so one too few silently shifts every later offset onto the
/// wrong slot and the shader reads the wrong bytes.
#[error("`{command}` was given dynamic offsets the seam refuses: {message}")]
InvalidDynamicOffsets {
/// Command name, from [`Command::name`].
command: &'static str,
/// The seam's refusal, unchanged.
message: String,
},
/// A command referenced a handle that was never created or has been
/// destroyed.
#[error("`{command}` referenced a dead {kind} handle {bits:#x}")]
DeadHandle {
/// Command name, from [`Command::name`].
command: &'static str,
/// Kind expected.
kind: ObjectKind,
/// Packed handle bits.
bits: u64,
},
}
/// Backend-side detail attached to a tracked object.
#[derive(Debug)]
pub(super) enum Detail {
/// Nothing beyond the label.
None,
/// A buffer: its size, where it lives, and its contents when mappable.
Buffer {
size: u64,
memory: MemoryLocation,
bytes: Vec<u8>,
},
/// An image: the mip and array-layer counts a view of it is checked
/// against.
///
/// **The shape [`ImageViewDesc::check`](crate::ImageViewDesc::check) needs
/// and this backend had nowhere to hold.** `create_image` filed
/// [`Detail::None`], so the reference backend could not state the seam's
/// own subresource rule at all — the same shape as the acquire slot in
/// [`Detail::Swapchain`]'s `acquired`.
///
/// `layers` is the **array-layer** count, which is `1` for an
/// [`ImageType::D3`](crate::ImageType) image however deep it is — see
/// `create_image`, which resolves it.
///
/// `format` is here for the same reason the counts are: without it the
/// reference backend could not state the seam's rule that a view's format
/// equals its image's, and three backends disagreed about that rule
/// unchecked until 2026-09-03.
Image {
format: crate::Format,
mip_levels: u32,
layers: u32,
},
/// An in-flight readback: what it covers and how many more polls report
/// `Pending` before it completes.
Readback {
buffer: BufferHandle,
offset: u64,
size: u64,
polls_remaining: u32,
},
/// A bind-group layout: the declared slots a bind group is checked against.
BindGroupLayout {
entries: Vec<BindGroupLayoutEntry>,
/// Whether any slot carries
/// [`BindingFlags::UPDATE_AFTER_BIND`](crate::BindingFlags::UPDATE_AFTER_BIND),
/// which is what makes `update_bind_group` legal.
update_after_bind: bool,
/// The binding number carrying
/// [`BindingFlags::VARIABLE_COUNT`](crate::BindingFlags::VARIABLE_COUNT),
/// if any.
variable_binding: Option<u32>,
},
/// A bind group: the layout it conforms to, resolved at creation.
BindGroup {
layout: BindGroupLayoutHandle,
update_after_bind: bool,
},
/// A shader module: the DXIL container it offered per entry point.
///
/// Empty for a module created without DXIL, which is every call site that
/// ships only the other three artifacts — so this is a *claim* to check
/// rather than a requirement, and only a module that made one is held to
/// it. See `check_stage`.
///
/// The bytes are kept, not just the names, because
/// [`Recorder::pipelines_created`] hands each stage its container: the
/// registers a D3D12 root signature must name are read out of it.
ShaderModule { dxil: Vec<(String, Vec<u8>)> },
/// A pipeline layout: every set's declared entries, in set order, and the
/// push-constant range — what [`Recorder::pipelines_created`] reports for
/// each pipeline built against it.
PipelineLayout {
sets: Vec<Vec<BindGroupLayoutEntry>>,
push_constants: Option<PushConstantRange>,
},
/// A raster graphics pipeline: the entry point its **vertex** stage names.
///
/// **What `create_graphics_pipeline` used to throw away.** It filed
/// [`Detail::None`], so the one thing a pipeline is — which code runs when
/// it is bound — was the one thing the reference backend did not record, and
/// a caller that pointed a pass at the wrong entry point of a module it had
/// legitimately created drew the wrong geometry with nothing anywhere saying
/// so. It is the vertex stage rather than both because that is the stage
/// that differs between two pipelines built from one module — see
/// `crcbl_render::forward`'s colour pipeline and its depth-only twin, whose
/// fragment stages are the same entry point and `None` respectively.
///
/// A **mesh** pipeline files [`Detail::None`] still, and that is not an
/// omission: it has no vertex stage to name. The two share one pool because
/// the seam gives them one handle type, so a reader of
/// [`Recorder::graphics_pipeline_vertex_entries`] sees the raster ones alone.
GraphicsPipeline { vertex_entry: String },
/// A query set: how many queries it holds, so a range can be checked.
QuerySet { count: u32 },
/// A semaphore: whether it is a timeline, and the value it holds.
///
/// `value` starts at
/// [`SemaphoreKind::Timeline::initial_value`](crate::SemaphoreKind::Timeline)
/// and moves when the host signals it *or* when a submission signalling it
/// is accepted — work that never executes has already finished, so a
/// submission's signals land at once. That is what lets
/// [`wait_semaphores`](crate::Device::wait_semaphores) answer against this
/// field rather than reporting every wait satisfied.
Semaphore { timeline: bool, value: u64 },
/// A swapchain: its image ring and rotation state.
Swapchain {
extent: (u32, u32),
images: Vec<ImageHandle>,
/// One whole-image view per ring image, owned by the swapchain and
/// handed out through [`AcquiredFrame::view`](crate::AcquiredFrame::view).
views: Vec<crate::ImageViewHandle>,
acquire_semaphores: Vec<Option<Handle<crate::Semaphore>>>,
present_semaphores: Vec<Option<Handle<crate::Semaphore>>>,
next: u32,
/// The ring index handed out by the last
/// [`acquire_next_frame`](crate::Device::acquire_next_frame) and not yet
/// presented, if any.
///
/// This backend models the seam's rules with no driver in the room, and
/// "a present needs a frame to present" is one it could not state
/// without somewhere to remember the acquire. `crcbl-vk`, `crcbl-mtl`
/// and `crcbl-dx12` each keep the same slot and each refuse a present
/// that finds it empty; this is that slot.
///
/// Cleared by `reconfigure_swapchain` as well as by a present, because
/// a reconfigure destroys the ring the index pointed into — presenting
/// across one is a use-after-free, not a stale number.
acquired: Option<u32>,
},
}
/// One tracked object.
///
/// `owner` is the id of the [`NullInstance`](super::NullInstance) or null
/// device that created it. Every lookup checks it, which is how the backend
/// detects a handle crossing from one instance or device to another — see
/// [`crate::device`] for the obligation this discharges. It is a side-table
/// field precisely because a [`Handle`] has no room for it.
#[derive(Debug)]
pub(super) struct Object {
pub(super) label: Option<String>,
pub(super) owner: u64,
pub(super) detail: Detail,
}
/// The null backend's shared state: object pools plus the recorded stream.
#[derive(Debug)]
pub(super) struct State {
pub(super) pools: Vec<Pool<Object>>,
pub(super) events: Vec<Event>,
pub(super) validation: Vec<ValidationError>,
/// How many `poll_readback` calls report `Pending` before a request
/// completes. See [`Recorder::set_readback_latency`].
pub(super) readback_latency: u32,
/// How many `PendingDevice::poll` calls report `Pending` before a device
/// request completes. See [`Recorder::set_device_latency`].
pub(super) device_latency: u32,
/// One entry per `create_shader_module`, surviving the module's
/// destruction. See [`Recorder::shader_modules_created`].
pub(super) shader_modules_created: Vec<(Option<String>, ShaderSources)>,
/// Every bind-group layout created, with its label — a log rather than a
/// lookup, for [`shader_modules_created`](Self::shader_modules_created)'s
/// reason exactly: a caller destroys its layouts once its pipelines exist,
/// so by the time a test can assert anything the handles are dead.
///
/// What it is for: the **binding numbers** a caller declared, which is the
/// one thing about a layout no other observable carries and which
/// `crcbl-mtl` turns into Metal argument-table indices by counting. See
/// [`Recorder::bind_group_layouts_created`].
pub(super) bind_group_layouts_created: Vec<(Option<String>, Vec<BindGroupLayoutEntry>)>,
/// Every pipeline created, with its layout and stages resolved — a log for
/// the same reason as the two above. See [`Recorder::pipelines_created`].
pub(super) pipelines_created: Vec<PipelineRecord>,
/// Queued out-of-band device errors. See [`Recorder::report_device_error`].
pub(super) device_errors: std::collections::VecDeque<String>,
/// How many `reconfigure_swapchain` calls fail before succeeding again. See
/// [`Recorder::fail_next_reconfigures`].
pub(super) reconfigure_failures: u32,
/// Whether the surface has moved under the swapchain, so every presentation
/// call reports [`SurfaceError::OutOfDate`](crate::SurfaceError::OutOfDate)
/// until a reconfigure clears it. See
/// [`Recorder::report_swapchain_out_of_date`].
pub(super) swapchain_out_of_date: bool,
/// How many `acquire_next_frame` calls hand back a frame marked
/// [`suboptimal`](crate::AcquiredFrame::suboptimal). See
/// [`Recorder::report_suboptimal_acquires`].
pub(super) suboptimal_acquires: u32,
/// The extent every acquire reports instead of the configured one. See
/// [`Recorder::clamp_acquired_extent_to`].
pub(super) clamped_extent: Option<(u32, u32)>,
/// How many `wait_until_presented` calls report
/// [`SurfaceError::Timeout`](crate::SurfaceError::Timeout). See
/// [`Recorder::report_present_wait_timeouts`].
pub(super) present_wait_timeouts: u32,
/// Adapters whose `surface_caps` refuses every surface, permanently. See
/// [`Recorder::refuse_surface_on`].
pub(super) refused_adapters: std::collections::BTreeSet<AdapterId>,
/// Why the device is lost, once it is — and never cleared, which is what
/// separates it from `device_errors`. See [`Recorder::lose_device`].
pub(super) lost_device: Option<String>,
}
impl State {
fn new() -> Self {
Self {
pools: (0..ObjectKind::ALL.len()).map(|_| Pool::new()).collect(),
events: Vec::new(),
validation: Vec::new(),
readback_latency: 0,
device_latency: 0,
shader_modules_created: Vec::new(),
bind_group_layouts_created: Vec::new(),
pipelines_created: Vec::new(),
device_errors: std::collections::VecDeque::new(),
reconfigure_failures: 0,
swapchain_out_of_date: false,
suboptimal_acquires: 0,
clamped_extent: None,
present_wait_timeouts: 0,
refused_adapters: std::collections::BTreeSet::new(),
lost_device: None,
}
}
pub(super) fn pool(&mut self, kind: ObjectKind) -> &mut Pool<Object> {
&mut self.pools[kind as usize]
}
pub(super) fn insert<T>(&mut self, kind: ObjectKind, object: Object) -> Handle<T> {
let label = object.label.clone();
let handle = self.pool(kind).insert(object);
self.events.push(Event::Created { kind, label });
handle.cast()
}
/// Builds and inserts an object owned by `owner`.
pub(super) fn insert_owned<T>(
&mut self,
kind: ObjectKind,
owner: u64,
label: Option<String>,
detail: Detail,
) -> Handle<T> {
self.insert(
kind,
Object {
label,
owner,
detail,
},
)
}
pub(super) fn get(&self, kind: ObjectKind, bits: u64) -> Option<&Object> {
Handle::from_bits(bits).and_then(|handle| self.pools[kind as usize].get(handle))
}
pub(super) fn get_mut(&mut self, kind: ObjectKind, bits: u64) -> Option<&mut Object> {
Handle::from_bits(bits).and_then(|handle| self.pools[kind as usize].get_mut(handle))
}
pub(super) fn remove(&mut self, kind: ObjectKind, bits: u64) {
if let Some(handle) = Handle::from_bits(bits)
&& self.pool(kind).remove(handle).is_some()
{
self.events.push(Event::Destroyed { kind });
}
}
pub(super) fn is_live(&self, kind: ObjectKind, bits: u64) -> bool {
self.get(kind, bits).is_some()
}
/// Whether the object is live *and* owned by `owner`.
pub(super) fn is_owned_by(&self, kind: ObjectKind, bits: u64, owner: u64) -> bool {
self.get(kind, bits)
.is_some_and(|object| object.owner == owner)
}
}
/// A shared, cloneable view of a null backend's recorded stream.
///
/// Cheap to clone (one `Arc` bump). Hand one clone to
/// [`NullInstance::with_recorder`](super::NullInstance::with_recorder) and keep
/// the other to assert on.
#[derive(Clone, Debug)]
pub struct Recorder {
state: Arc<Mutex<State>>,
}
impl Default for Recorder {
fn default() -> Self {
Self::new()
}
}
impl Recorder {
/// A fresh, empty recorder.
#[must_use]
pub fn new() -> Self {
Self {
state: Arc::new(Mutex::new(State::new())),
}
}
/// Locks the shared state, ignoring poisoning.
///
/// A poisoned mutex here means a test panicked while holding it. The state
/// is a plain log with no invariant a panic could have broken halfway, and
/// turning every subsequent access into a second panic would bury the first
/// one's message.
pub(super) fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Every event so far, in order.
#[must_use]
pub fn events(&self) -> Vec<Event> {
self.lock().events.clone()
}
/// Every recorded command, in record order, across all command buffers.
#[must_use]
pub fn commands(&self) -> Vec<Command> {
self.lock()
.events
.iter()
.filter_map(|event| match event {
Event::Command { command, .. } => Some(command.clone()),
_ => None,
})
.collect()
}
/// [`Command::name`] for every recorded command, in order.
///
/// The compact assertion: `assert_eq!(recorder.command_names(), ["BeginComputePass", …])`.
#[must_use]
pub fn command_names(&self) -> Vec<&'static str> {
self.lock()
.events
.iter()
.filter_map(|event| match event {
Event::Command { command, .. } => Some(command.name()),
_ => None,
})
.collect()
}
/// The label of every pass opened, in order, with unlabelled passes
/// rendered as `"<unlabelled render>"` / `"<unlabelled compute>"`.
///
/// This is the "did this frame emit these passes in this order" assertion
/// the graph suite is built around.
#[must_use]
pub fn pass_labels(&self) -> Vec<String> {
self.lock()
.events
.iter()
.filter_map(|event| match event {
Event::Command { command, .. } => command.opens_pass(),
_ => None,
})
.map(|(kind, label)| {
label.map_or_else(|| format!("<unlabelled {kind}>"), ToOwned::to_owned)
})
.collect()
}
/// Every rule the recorded stream broke.
#[must_use]
pub fn validation_errors(&self) -> Vec<ValidationError> {
self.lock().validation.clone()
}
/// Panics if the stream broke any rule, listing every violation.
///
/// # Panics
///
/// If [`Recorder::validation_errors`] is non-empty.
pub fn assert_valid(&self) {
let errors = self.validation_errors();
assert!(
errors.is_empty(),
"null backend recorded {} validation error(s):\n{}",
errors.len(),
errors
.iter()
.map(|error| format!(" - {error}"))
.collect::<Vec<_>>()
.join("\n")
);
}
/// How many objects of `kind` are still alive.
///
/// The leak assertion: a frame that creates and destroys transients should
/// end where it started.
#[must_use]
pub fn live_objects(&self, kind: ObjectKind) -> usize {
self.lock().pools[kind as usize].len()
}
/// What a mappable buffer currently holds, or `None` if the handle names
/// nothing this recorder created.
///
/// [`Event::BufferWritten`] says an upload happened, at an offset, of a
/// length — which catches a write that went to the wrong slot and cannot
/// catch one that went to the right slot with the wrong bytes. A producer
/// that packs a record into a storage buffer is exactly that case: the
/// field order, the endianness and the stride are all invisible in the
/// event and all decidable here, by decoding what landed with the same
/// layout the shader reads it with.
///
/// Only [`MemoryLocation::HostUpload`]
/// buffers hold anything: the null backend executes no copies, so a
/// device-local buffer's contents are whatever nothing wrote to it. It is
/// therefore evidence about the *host's* writes, and a copy this backend
/// recorded but did not perform leaves no trace in it.
#[must_use]
pub fn buffer_bytes(&self, buffer: BufferHandle) -> Option<Vec<u8>> {
let state = self.lock();
match &state.get(ObjectKind::Buffer, buffer.to_bits())?.detail {
Detail::Buffer { bytes, .. } => Some(bytes.clone()),
_ => unreachable!("a buffer handle always carries buffer detail"),
}
}
/// The size `buffer` was created with, whatever memory it lives in — `None`
/// for a handle that is not a live buffer.
///
/// [`buffer_bytes`](Self::buffer_bytes) holds contents for mappable memory
/// only, so it cannot say how large a device-local buffer is. That size is
/// what a test of an allocation's **cost** asserts on: a buffer whose length
/// grew with the wrong input is correct in every byte it holds.
#[must_use]
pub fn buffer_size(&self, buffer: BufferHandle) -> Option<u64> {
let state = self.lock();
match &state.get(ObjectKind::Buffer, buffer.to_bits())?.detail {
Detail::Buffer { size, .. } => Some(*size),
_ => unreachable!("a buffer handle always carries buffer detail"),
}
}
/// Every shader module created so far, as `(label, formats the descriptor
/// carried)`, in creation order.
///
/// The no-GPU assertion for the seam's "offer every artifact you have"
/// rule. A call site that stopped passing its WGSL keeps working on Vulkan
/// and keeps working here, so nothing but a backend that actually reads the
/// WGSL would notice — which is how the WGSL artifacts sat unused from P5.3
/// to P5.9. This notices, in the plain test suite.
///
/// A log rather than a lookup on the handle, because a caller that builds
/// pipelines destroys its modules immediately afterwards — by the time a
/// test can assert anything, every handle it would ask about is dead.
/// [`clear`](Self::clear) drops it with the rest of the stream.
#[must_use]
pub fn shader_modules_created(&self) -> Vec<(Option<String>, ShaderSources)> {
self.lock().shader_modules_created.clone()
}
/// Every bind-group layout created, label and declared entries, in order.
///
/// The assertion this exists for is about **which binding numbers a layout
/// declares**, and it is not cosmetic on one backend: `crcbl-mtl` gives a
/// resource the next index in its Metal argument table by counting the
/// same-table entries of this list, so two layouts for one shader that
/// declare different subsets of its bindings place every resource above the
/// difference at different indices — silently, and only there.
#[must_use]
pub fn bind_group_layouts_created(&self) -> Vec<(Option<String>, Vec<BindGroupLayoutEntry>)> {
self.lock().bind_group_layouts_created.clone()
}
/// Every pipeline created so far — raster, mesh and compute — with the
/// entries of every set its layout declared and the DXIL container each
/// stage was given, in creation order.
///
/// **What pairs a layout with the shaders it serves.** A bind-group layout
/// on its own says nothing about which artifact reads it, and the registers
/// a D3D12 root signature names have to agree with the ones compiled into
/// every container of every pipeline built on it. This is the one place
/// both halves are in hand without a device: `crcbl-dx12` runs the
/// renderer against this recorder and checks each record's layout against
/// each stage's container.
///
/// A log rather than a live lookup, for
/// [`shader_modules_created`](Self::shader_modules_created)'s reason: the
/// modules and layouts a pipeline was built from are destroyed as soon as
/// it exists.
#[must_use]
pub fn pipelines_created(&self) -> Vec<PipelineRecord> {
self.lock().pipelines_created.clone()
}
/// Every **live** raster graphics pipeline, as `(label, the entry point its
/// vertex stage names)`.
///
/// **The no-GPU answer to "which code does this pass run?"** Two pipelines
/// built from one module differ in exactly that name, and nothing else about
/// them is observable without a device: they take the same layout, they are
/// bound by the same call, and a pass driven with the wrong one of the two
/// still records a legal frame. `crcbl_render::forward`'s colour pipeline and
/// its depth-only twin are that pair — `vertexMain` against
/// `depthVertexMain`, the second reading topic 43
/// §2's position stream alone — and pointing the depth one back at the
/// colour one's stage is a change no golden, no validation rule and no
/// timing measurement on a desktop adapter reports.
///
/// **Match on the label, not the position.** The order is the pipeline
/// pool's slot order, which is creation order only until a destroyed
/// pipeline's slot is reused — and a caller that rebuilds one pipeline of
/// several does exactly that (`crcbl_render::forward`'s wireframe twin is
/// one). The labels are the descriptors' own.
///
/// A live lookup rather than a creation log, unlike
/// [`shader_modules_created`](Self::shader_modules_created): a caller
/// destroys its modules as soon as its pipelines exist, and keeps the
/// pipelines for as long as it draws.
///
/// Mesh pipelines are not listed — they have no vertex stage to name.
#[must_use]
pub fn graphics_pipeline_vertex_entries(&self) -> Vec<(Option<String>, String)> {
let state = self.lock();
state.pools[ObjectKind::GraphicsPipeline as usize]
.iter()
.filter_map(|(_, object)| match &object.detail {
Detail::GraphicsPipeline { vertex_entry } => {
Some((object.label.clone(), vertex_entry.clone()))
}
_ => None,
})
.collect()
}
/// Total live objects across every kind.
#[must_use]
pub fn total_live_objects(&self) -> usize {
let state = self.lock();
state.pools.iter().map(Pool::len).sum()
}
/// Drops the recorded stream, keeping live objects.
///
/// Call between frames so per-frame assertions do not have to skip past the
/// setup.
pub fn clear(&self) {
let mut state = self.lock();
state.events.clear();
state.validation.clear();
state.shader_modules_created.clear();
state.bind_group_layouts_created.clear();
state.pipelines_created.clear();
}
/// Makes the next `poll_readback` calls report
/// [`Pending`](crate::ReadbackState::Pending) `polls` times before
/// completing.
///
/// The null backend executes nothing, so a readback would otherwise be
/// ready on its first poll and a caller's poll *loop* would never be
/// exercised. Setting a latency simulates WebGPU's deferred `mapAsync` and
/// Vulkan's fence-not-yet-signalled, which is the difference between
/// testing that a screenshot path compiles and testing that it waits.
///
/// Applies to readbacks requested after this call. Default `0`.
pub fn set_readback_latency(&self, polls: u32) {
self.lock().readback_latency = polls;
}
/// Makes the next device requests report
/// [`Pending`](crate::DeviceRequestState::Pending) `polls` times before
/// handing over the device.
///
/// The sibling of [`set_readback_latency`](Self::set_readback_latency), and
/// there for the same reason: the null backend opens a device instantly, so
/// a request would otherwise be ready on its first poll and a caller's
/// **poll loop** — the rAF-driven start-up path that
/// the browser needs — would never be exercised. Setting a
/// latency simulates WebGPU's deferred `requestDevice` promise on a machine
/// with no browser and no GPU.
///
/// Applies to devices requested after this call. Default `0`, which is what
/// `Instance::create_device` sees: it
/// completes on the first poll.
pub fn set_device_latency(&self, polls: u32) {
self.lock().device_latency = polls;
}
/// Queues an error for [`Device::take_error`](crate::Device::take_error) to
/// report, as if the driver had raised it outside any call.
///
/// The sibling of [`set_device_latency`](Self::set_device_latency), and
/// there for the same reason: the null backend never fails, so a caller's
/// **handling** of an out-of-band failure would otherwise never run. This
/// simulates the one case that actually produces them — WebGPU delivering a
/// pipeline's compilation failure to the device's error channel a turn of
/// the event loop after the call that made it returned an object.
///
/// Each queued error is reported once, oldest first.
pub fn report_device_error(&self, message: impl Into<String>) {
self.lock().device_errors.push_back(message.into());
}
/// Takes the oldest queued device error, if any. The backend's half of
/// [`report_device_error`](Self::report_device_error).
pub(super) fn take_device_error(&self) -> Option<String> {
self.lock().device_errors.pop_front()
}
/// Makes the next `reconfigure_swapchain` call(s) fail with
/// [`SurfaceError::Hal(HalError::OutOfDeviceMemory)`](crate::SurfaceError::Hal),
/// as if rebuilding the swapchain ran out of memory.
///
/// The sibling of [`set_device_latency`](Self::set_device_latency), and
/// there for the same reason: the null backend never fails, so a caller's
/// **error path** would otherwise never run. A settings screen that applies
/// a pacing change mid-run is the caller this exists for — it has to roll
/// the request, the effective pacing and the swapchain mode back together
/// when the rebuild fails, and a backend that cannot fail makes that
/// rollback unobservable.
///
/// Consumed one per reconfigure; after `times` failures the backend
/// succeeds again. Default `0`.
pub fn fail_next_reconfigures(&self, times: u32) {
self.lock().reconfigure_failures = times;
}
/// Consumes one reconfigure failure, if any are owed. The backend's half of
/// [`fail_next_reconfigures`](Self::fail_next_reconfigures).
pub(super) fn take_reconfigure_failure(&self) -> bool {
let mut state = self.lock();
if state.reconfigure_failures > 0 {
state.reconfigure_failures -= 1;
true
} else {
false
}
}
/// Makes every presentation call report
/// [`SurfaceError::OutOfDate`](crate::SurfaceError::OutOfDate) until the
/// swapchain is reconfigured, as if the window had just been resized.
///
/// The sibling of [`fail_next_reconfigures`](Self::fail_next_reconfigures),
/// and there for the same reason: the null backend never fails, so a
/// caller's **resize path** would otherwise never run. This is the one that
/// was missing hardest — every `SurfaceError` this backend built was
/// [`SurfaceError::Hal`](crate::SurfaceError::Hal), so the variant the seam
/// calls expected traffic could not be produced here at all, and the frame
/// loop's reconfigure-and-retry arms were reachable only on a real driver
/// while someone dragged a window edge.
///
/// **Latched rather than counted**, because that is what a driver does: a
/// swapchain whose surface moved is out of date on `acquire_next_frame`, on
/// `present` and on `wait_until_presented` alike, and stays out of date
/// until it is rebuilt. So a caller that handles it clears it *by* handling
/// it and a caller that does not spins, which is the difference worth being
/// able to test. `reconfigure_swapchain` is what clears it — a *failed*
/// reconfigure does not, since it rebuilt nothing.
///
/// [`SurfaceError::Lost`](crate::SurfaceError::Lost) and
/// [`Timeout`](crate::SurfaceError::Timeout) get no injector: neither is
/// recoverable traffic, so no caller in this workspace does anything with
/// them that an assertion could see.
pub fn report_swapchain_out_of_date(&self) {
self.lock().swapchain_out_of_date = true;
}
/// Makes the next `acquire_next_frame` call(s) hand back a frame marked
/// [`suboptimal`](crate::AcquiredFrame::suboptimal), as if the surface had
/// moved under a swapchain that still presents.
///
/// The gentler sibling of
/// [`report_swapchain_out_of_date`](Self::report_swapchain_out_of_date):
/// out of date means the three presentation calls *refuse*, suboptimal
/// means they all still work and the frame merely no longer matches the
/// surface it is going to. `crcbl-vk` reads it off `VK_SUBOPTIMAL_KHR` and
/// `crcbl-mtl` off a drawable whose size moved; this backend has no window
/// system to disagree with, so the field was a hardcoded `false` here and
/// the engine's reconfigure-*after*-present policy — the arm in
/// `crcbl/src/engine.rs`'s `submit_and_present` that keeps a stale-extent
/// frame from being presented forever — was reachable from no test in the
/// workspace.
///
/// **Counted rather than latched, and that is the opposite of its sibling
/// on purpose.** An out-of-date swapchain refuses everything, so a caller
/// that ignores it makes no progress and a latch is what a driver does. A
/// suboptimal one presents fine, and the engine answers it by
/// reconfiguring — so a latch here would rebuild the swapchain on every
/// frame for as long as the loop ran, and a test that drove such a loop
/// would hang rather than fail. A count cannot: it runs out.
///
/// Consumed one per acquire, and only by an acquire that actually handed a
/// frame out — one refused by the out-of-date latch or a dead handle
/// spends nothing. After `times` frames the backend reports optimal ones
/// again. Default `0`.
pub fn report_suboptimal_acquires(&self, times: u32) {
self.lock().suboptimal_acquires = times;
}
/// Makes every `acquire_next_frame` report `extent` rather than the extent
/// the swapchain was configured at, as if a compositor had chosen a size of
/// its own.
///
/// **Applied where the platform applies it: when the ring is built.** The
/// swapchain's images are created at the clamped size and the swapchain
/// records it, so an acquire reports it without a second rule of its own.
/// Clamping only the *reported* number would have produced a swapchain
/// holding images of one size and answering with another — a fixture no
/// window system produces, and one that would make a render area derived
/// from those images disagree for the fixture's reasons rather than the
/// caller's.
///
/// **A standing rule, not a count, and unlike its two siblings above.** A
/// compositor that clamps does not stop clamping; the engine answers by
/// adopting the answer, after which the sizes agree and its branch stops
/// firing on its own. So a standing rule cannot make a driven loop spin the
/// way a latched suboptimal would — and it is what lets a test see the
/// branch fire once and then stay quiet, which a one-shot could not show.
///
/// This backend has no window system to clamp against, so the acquired
/// extent was always the configured one and `crcbl/src/engine.rs`'s
/// "obligation 3: the answer, not the request" branch — the one that writes
/// the compositor's chosen size back into the config — was reachable from
/// no test in this workspace, and from no device it can run headlessly.
///
/// Default `None`, which reports the configured extent.
pub fn clamp_acquired_extent_to(&self, extent: (u32, u32)) {
self.lock().clamped_extent = Some(extent);
}
/// The clamp an acquire should report instead of its configured extent, if
/// one is set. The backend's half of
/// [`clamp_acquired_extent_to`](Self::clamp_acquired_extent_to).
pub(super) fn clamped_extent(&self) -> Option<(u32, u32)> {
self.lock().clamped_extent
}
/// Consumes one suboptimal acquire, if any are owed. The backend's half of
/// [`report_suboptimal_acquires`](Self::report_suboptimal_acquires).
pub(super) fn take_suboptimal_acquire(&self) -> bool {
let mut state = self.lock();
if state.suboptimal_acquires > 0 {
state.suboptimal_acquires -= 1;
true
} else {
false
}
}
/// Makes the next `wait_until_presented` call(s) report
/// [`SurfaceError::Timeout`](crate::SurfaceError::Timeout), as if the
/// compositor had still not got the numbered frame onto the display when
/// the caller's deadline passed.
///
/// **Only on a device that advertises
/// [`Features::PRESENT_FEEDBACK`](crate::Features::PRESENT_FEEDBACK)** —
/// see [`NullInstance::with_present_feedback`](super::NullInstance::with_present_feedback),
/// since no preset does. The seam promises that a device *without* the
/// capability answers the wait immediately and never refuses it, so a
/// timeout there would be this backend breaking the one contract it exists
/// to police. A wait on such a device therefore spends nothing: what was
/// injected is still owed to the first device that can honour it, rather
/// than being eaten by a device that could not.
///
/// Why it was missing: there is no display here to be late, so this backend
/// could only ever return `Ok`, and a frame loop's timed-out-wait arm — in
/// `crcbl/src/engine.rs`'s `acquire`, the one that renders the frame anyway
/// rather than skipping it — was reachable on no backend in this workspace.
///
/// **Counted rather than latched**, following
/// [`report_suboptimal_acquires`](Self::report_suboptimal_acquires) and for
/// a different reason than its sibling's. A latch here would not run away —
/// the engine's answer to a timeout is to carry on, so nothing would spin —
/// but nothing would ever clear it either: a resize is cleared by the
/// rebuild that answers it, while a caller has no action that makes a
/// stalled display catch up. A latched device is one whose presents can
/// never be waited on again, which is not what the seam calls this —
/// "expected traffic on a stalled compositor … render it and let the next
/// wait catch up". A count is the only shape in which *the next wait
/// catching up* is something a test can watch happen.
///
/// Consumed one per wait, and only by a wait that got as far as being
/// answered: one refused by the out-of-date latch or by a dead handle
/// spends nothing. After `times` waits the device answers them again.
/// Default `0`.
pub fn report_present_wait_timeouts(&self, times: u32) {
self.lock().present_wait_timeouts = times;
}
/// Consumes one present-wait timeout, if any are owed. The backend's half
/// of [`report_present_wait_timeouts`](Self::report_present_wait_timeouts).
pub(super) fn take_present_wait_timeout(&self) -> bool {
let mut state = self.lock();
if state.present_wait_timeouts > 0 {
state.present_wait_timeouts -= 1;
true
} else {
false
}
}
/// Makes [`Instance::surface_caps`](crate::Instance::surface_caps) refuse
/// every surface on `adapter`, as if that GPU had no path to the display
/// the surface belongs to.
///
/// The refusal is
/// [`HalError::Unsupported`](crate::HalError::Unsupported) — the same
/// variant `crcbl-vk` returns when no queue family on a physical device can
/// present to a surface, deliberately, because the engine's answer to it is
/// "not this one, try the next" and a test of that answer should be handed
/// the error shape a real driver produces.
///
/// Why it was missing: `NullInstance::adapters` reported one adapter and
/// nothing made it refuse, so `crcbl/src/engine.rs`'s `start_device` could
/// only ever take the first adapter it was offered. That loop is not
/// decoration — `crates/crcbl/tests/windowed_e2e.rs` records a discrete
/// RADV GPU that enumerates first under Xvfb and cannot present at all,
/// while the software rasteriser behind it can — and it was reachable on no
/// backend in this workspace. Pair this with
/// [`NullInstance::with_adapters`](super::NullInstance::with_adapters),
/// which is what gives a refusal somewhere to fall through *to*.
///
/// **Latched rather than counted, and for a reason neither of the counted
/// injectors has: this is a property of a pairing, not an event.** An
/// adapter with no path to a display does not acquire one, so there is
/// nothing for a count to run out of — where a suboptimal frame and a
/// stalled compositor are both conditions that pass. And a count would be
/// spent by the very walk it exists to steer: start-up asks each adapter
/// once, then the engine asks the *chosen* adapter again on every resize,
/// so a one-shot refusal would leave the adapter it had just rejected
/// answering the next question. Latched, the answer is the same at every
/// call, which is the only shape in which "this adapter is not the one" is
/// a fact rather than a moment.
///
/// Nothing clears it, as nothing clears [`lose_device`](Self::lose_device).
/// It is keyed by adapter, so the adapters left out of it go on serving.
///
/// Only `surface_caps` refuses; a device requested from a refused adapter
/// still opens. The engine only ever requests one from the adapter that
/// just served it a `SurfaceCaps`, so refusing there would be surface
/// nothing exercises.
pub fn refuse_surface_on(&self, adapter: AdapterId) {
self.lock().refused_adapters.insert(adapter);
}
/// Whether `adapter` has been refused. The backend's half of
/// [`refuse_surface_on`](Self::refuse_surface_on).
pub(super) fn refuses_surface(&self, adapter: AdapterId) -> bool {
self.lock().refused_adapters.contains(&adapter)
}
/// Loses the device, permanently: every later call that resolves a handle —
/// and [`Device::wait_idle`](crate::Device::wait_idle), which resolves none
/// — fails with [`HalError::DeviceLost`](crate::HalError::DeviceLost)
/// carrying `message`.
///
/// The sibling of [`report_device_error`](Self::report_device_error) and
/// deliberately its opposite. That one is *recoverable and one-shot*: it
/// models a browser delivering a compilation failure late, and taking it
/// clears it. This one models a TDR, a GPU hang or a browser reclaiming the
/// context — everything created from the device is dead and nothing brings
/// it back — which is a state the null backend could not express, so the
/// engine's policy for it (`docs/backlog.md`: device loss surfaces, it does
/// not self-heal) had no test on any backend.
///
/// Nothing clears it. A test that wants a device again opens one.
///
/// Object *destruction* still works, as it does on a real driver: a caller
/// tearing down after a lost device must be able to release what it holds.
/// Creation calls that name no handle — `create_buffer` and the rest — also
/// still succeed, because no caller in this workspace reaches one after a
/// loss and failing them would be surface nothing exercises.
pub fn lose_device(&self, message: impl Into<String>) {
self.lock().lost_device = Some(message.into());
}
/// Records a validation error. Used by the backend; exposed so a test can
/// check its own harness if it needs to.
pub(super) fn push_validation(&self, error: ValidationError) {
self.lock().validation.push(error);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn object_kind_table_is_complete_and_ordered() {
for (index, kind) in ObjectKind::ALL.iter().enumerate() {
assert_eq!(
*kind as usize, index,
"ALL must be in declaration order: pool lookup indexes by `kind as usize`"
);
assert!(!kind.name().is_empty());
}
}
#[test]
fn a_fresh_recorder_is_empty_and_valid() {
let recorder = Recorder::new();
assert!(recorder.events().is_empty());
assert!(recorder.commands().is_empty());
assert!(recorder.pass_labels().is_empty());
assert_eq!(recorder.total_live_objects(), 0);
recorder.assert_valid();
}
#[test]
fn pass_labels_name_unlabelled_passes_by_kind() {
let mut state = State::new();
let cb: CommandBufferHandle =
state.insert_owned(ObjectKind::CommandBuffer, 1, None, Detail::None);
state.events.push(Event::Command {
command_buffer: cb,
command: Command::BeginComputePass {
label: None,
timestamp_writes: None,
},
});
state.events.push(Event::Command {
command_buffer: cb,
command: Command::BeginRenderPass {
label: Some("gbuffer".into()),
color_attachments: Vec::new(),
depth_stencil_attachment: None,
render_area: Rect2d::from_size(1, 1),
timestamp_writes: None,
},
});
let recorder = Recorder {
state: Arc::new(Mutex::new(state)),
};
assert_eq!(
recorder.pass_labels(),
vec!["<unlabelled compute>".to_string(), "gbuffer".to_string()]
);
}
#[test]
fn clear_drops_events_but_keeps_objects() {
let mut state = State::new();
let _: BufferHandle =
state.insert_owned(ObjectKind::Buffer, 1, Some("kept".into()), Detail::None);
let recorder = Recorder {
state: Arc::new(Mutex::new(state)),
};
assert_eq!(recorder.events().len(), 1);
recorder.clear();
assert!(recorder.events().is_empty());
assert_eq!(recorder.live_objects(ObjectKind::Buffer), 1);
}
#[test]
fn destroyed_handles_stop_resolving() {
let mut state = State::new();
let buffer: BufferHandle = state.insert_owned(ObjectKind::Buffer, 1, None, Detail::None);
assert!(state.is_live(ObjectKind::Buffer, buffer.to_bits()));
state.remove(ObjectKind::Buffer, buffer.to_bits());
assert!(!state.is_live(ObjectKind::Buffer, buffer.to_bits()));
// Same bits under a different kind never resolve either.
assert!(!state.is_live(ObjectKind::Image, buffer.to_bits()));
}
/// The mechanism `crate::device`'s rule 3 obliges backends to provide: the
/// same handle bits under two owners must not resolve for the wrong one.
#[test]
fn ownership_is_checked_independently_of_liveness() {
let mut state = State::new();
let buffer: BufferHandle = state.insert_owned(ObjectKind::Buffer, 7, None, Detail::None);
assert!(state.is_live(ObjectKind::Buffer, buffer.to_bits()));
assert!(state.is_owned_by(ObjectKind::Buffer, buffer.to_bits(), 7));
assert!(
!state.is_owned_by(ObjectKind::Buffer, buffer.to_bits(), 8),
"a live handle owned by someone else must be rejected, not accepted"
);
state.remove(ObjectKind::Buffer, buffer.to_bits());
assert!(!state.is_owned_by(ObjectKind::Buffer, buffer.to_bits(), 7));
}
/// One of every [`Command`] variant.
///
/// The `match` at the end is what keeps the list honest: it is exhaustive,
/// so a variant added to `Command` stops this module compiling until
/// someone comes here — which is the point at which the list beside it is
/// impossible to miss. A sampled list has no such moment; this one used to
/// hold five of them.
fn every_command_variant() -> Vec<Command> {
fn handle<T>() -> Handle<T> {
Handle::from_bits(1 << 32).expect("generation 1 is a real generation")
}
let layers = crate::ImageSubresourceLayers {
aspect: crate::ImageAspect::COLOR,
mip: 0,
base_layer: 0,
layer_count: 1,
};
let region = BufferImageCopy {
buffer: handle(),
buffer_offset: 0,
buffer_row_length: 0,
buffer_image_height: 0,
image: handle(),
image_subresource: layers,
image_offset: crate::Offset3d::default(),
image_extent: crate::Extent3d::d2(1, 1),
};
let indirect = DrawIndirect {
args: handle(),
offset: 0,
draw_count: 1,
stride: 16,
};
let indirect_count = DrawIndirectCount {
args: handle(),
args_offset: 0,
count_buffer: handle(),
count_offset: 0,
max_draw_count: 1,
stride: 16,
};
let samples = vec![
Command::BeginDebugLabel("label".into()),
Command::EndDebugLabel,
Command::DebugMarker("marker".into()),
Command::Barrier {
buffers: Vec::new(),
images: Vec::new(),
global: true,
},
Command::CopyBufferToBuffer(BufferCopy {
src: handle(),
src_offset: 0,
dst: handle(),
dst_offset: 0,
size: 4,
}),
Command::CopyBufferToImage(region),
Command::CopyImageToBuffer(region),
Command::CopyImageToImage(ImageCopy {
src: handle(),
src_subresource: layers,
src_offset: crate::Offset3d::default(),
dst: handle(),
dst_subresource: layers,
dst_offset: crate::Offset3d::default(),
extent: crate::Extent3d::d2(1, 1),
}),
Command::ClearBuffer {
buffer: handle(),
offset: 0,
size: 4,
},
Command::BeginRenderPass {
label: None,
color_attachments: Vec::new(),
depth_stencil_attachment: None,
render_area: Rect2d::from_size(1, 1),
timestamp_writes: None,
},
Command::EndRenderPass,
Command::SetViewport(Viewport::default()),
Command::SetScissor(Rect2d::from_size(1, 1)),
Command::SetStencilReference(0),
Command::BindGraphicsPipeline(handle()),
Command::BindIndexBuffer {
buffer: handle(),
offset: 0,
format: IndexFormat::Uint32,
},
Command::BindGroup {
slot: 0,
group: handle(),
dynamic_offsets: Vec::new(),
},
Command::PushConstants {
stages: ShaderStages::VERTEX,
offset: 0,
len: 4,
},
Command::Draw {
vertices: 0..3,
instances: 0..1,
},
Command::DrawIndexed {
indices: 0..3,
base_vertex: 0,
instances: 0..1,
},
Command::DrawIndirect(indirect),
Command::DrawIndexedIndirect(indirect),
Command::DrawIndirectCount(indirect_count),
Command::DrawIndexedIndirectCount(indirect_count),
Command::DrawMeshTasks { x: 1, y: 1, z: 1 },
Command::DrawMeshTasksIndirect(indirect),
Command::BeginComputePass {
label: None,
timestamp_writes: Some(crate::PassTimestampWrites {
set: handle(),
beginning_of_pass: 0,
end_of_pass: 1,
}),
},
Command::EndComputePass,
Command::BindComputePipeline(handle()),
Command::Dispatch { x: 1, y: 1, z: 1 },
Command::DispatchIndirect {
args: handle(),
offset: 0,
},
Command::ResetQuerySet {
set: handle(),
range: 0..1,
},
Command::ResolveQuerySet {
set: handle(),
range: 0..1,
dst: handle(),
dst_offset: 0,
},
];
for command in &samples {
match command {
Command::BeginDebugLabel(_)
| Command::EndDebugLabel
| Command::DebugMarker(_)
| Command::Barrier { .. }
| Command::CopyBufferToBuffer(_)
| Command::CopyBufferToImage(_)
| Command::CopyImageToBuffer(_)
| Command::CopyImageToImage(_)
| Command::ClearBuffer { .. }
| Command::BeginRenderPass { .. }
| Command::EndRenderPass
| Command::SetViewport(_)
| Command::SetScissor(_)
| Command::SetStencilReference(_)
| Command::BindGraphicsPipeline(_)
| Command::BindIndexBuffer { .. }
| Command::BindGroup { .. }
| Command::PushConstants { .. }
| Command::Draw { .. }
| Command::DrawIndexed { .. }
| Command::DrawIndirect(_)
| Command::DrawIndexedIndirect(_)
| Command::DrawIndirectCount(_)
| Command::DrawIndexedIndirectCount(_)
| Command::DrawMeshTasks { .. }
| Command::DrawMeshTasksIndirect(_)
| Command::BeginComputePass { .. }
| Command::EndComputePass
| Command::BindComputePipeline(_)
| Command::Dispatch { .. }
| Command::DispatchIndirect { .. }
| Command::ResetQuerySet { .. }
| Command::ResolveQuerySet { .. } => {}
}
}
samples
}
/// A duplicated name would make every `command_names()` assertion in the
/// suite ambiguous — two different commands would read as the same one, and
/// an expected stream would match a wrong one.
#[test]
fn command_names_are_unique_per_variant() {
let samples = every_command_variant();
let mut names: Vec<_> = samples.iter().map(Command::name).collect();
let count = names.len();
assert!(names.iter().all(|name| !name.is_empty()));
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), count, "two variants share a name");
}
/// The other half of the same claim: a variant that opens a pass says so,
/// and every other variant says it does not.
#[test]
fn only_the_two_begin_commands_open_a_pass() {
for command in every_command_variant() {
let expected = match command.name() {
"BeginRenderPass" => Some("render"),
"BeginComputePass" => Some("compute"),
_ => None,
};
assert_eq!(
command.opens_pass().map(|(kind, _)| kind),
expected,
"{}",
command.name()
);
}
}
#[test]
fn validation_errors_render_readably() {
let error = ValidationError::OutsidePass {
command: "Draw",
expected: "render",
};
assert_eq!(error.to_string(), "`Draw` requires an open render pass");
let error = ValidationError::DeadHandle {
command: "BindGroup",
kind: ObjectKind::BindGroup,
bits: 0x1_0000_0002,
};
assert!(error.to_string().contains("bind group"), "{error}");
}
}