crcbl-frame 0.3.0

Crucible frame core: render graph, transient pool, texture uploads and the UI pass
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
//! The render graph: passes declare what they touch, and the graph works out
//! the barriers.
//!
//! ```text
//! RenderGraph ──add_render_pass()──▶ declarations
//!      │                                  │
//!      │  compile()                       │  reads/writes of virtual resources
//!      â–¼                                  â–¼
//! CompiledGraph ──▶ ordered passes + exact barriers + layout transitions
//!      │                        │
//!      │  dump()                │  execute(device, pool, encoder)
//!      â–¼                        â–¼
//!   text a human reads    the only code in the engine that calls
//!                         `CommandEncoder::pipeline_barrier`
//! ```
//!
//! Stage 2 §2.4 states the contract in one sentence:
//! "passes declare reads/writes of virtual resources; graph compiles to ordered
//! passes + exact `sync2` barriers + image layout transitions. **No manual
//! barriers outside the graph, ever.**" The sandbox used to hand-write two image
//! barriers around its frame; it no longer contains the word.
//!
//! # Deliberately not a scheduler
//!
//! The same section's risk list says: "**Graph over-engineering.** MVP graph =
//! linear pass list with computed barriers. No multi-queue scheduling, no
//! reordering. Resist." So:
//!
//! * **Passes execute in declaration order.** There is no topological sort,
//!   because there is nothing to sort — the order the caller wrote *is* the
//!   dependency order, and a graph that reordered would have to prove it had not
//!   changed the picture.
//! * **No dead-pass culling.** Declaring a pass runs it. Culling is the feature
//!   that makes a graph unpredictable ("why did my debug pass not run?") in
//!   exchange for saving work a caller could have simply not declared.
//! * **No multi-queue scheduling.** Every pass names a queue and the barrier
//!   model carries [`QueueTransfer`], so a dedicated transfer queue is additive
//!   later — which stage 2's corrections require "from
//!   the start so a dedicated transfer queue is additive later rather than a
//!   barrier-model rewrite". Nothing *decides* to use a second queue.
//!
//! What it does do is the part that is genuinely error-prone by hand: track
//! every resource's state, emit exactly the transitions that are needed, batch
//! them into one call per pass, alias transients whose lifetimes do not overlap,
//! and return every imported resource to the state its owner requires.
//!
//! # The physical resource outlives the frame
//!
//! A graph is built and thrown away every frame. The *images* are not: a
//! steady-state frame gets the same [`ImageHandle`] out of the
//! [`TransientPool`] it got last frame, and a graph is aliasing when two of its
//! virtual images land on one of them. So state tracking is per **physical**
//! resource — and a physical resource's history does not start at this frame's
//! first pass.
//!
//! Treating it as though it did is a real bug and not a subtle one. A barrier
//! whose source state is [`ResourceState::Undefined`] carries *no source scope*
//! at all — on Vulkan it expands to `srcStageMask = NONE, srcAccessMask = NONE`
//! — so a frame that opens by transitioning its depth buffer from `Undefined`
//! orders that transition against nothing, while the previous frame's
//! depth writes to the very same image may still be in flight. Two submissions,
//! no dependency, both writing: a write-after-write hazard that
//! `CRCBL_VK_SYNC_VALIDATION=1` reports as `write_barriers: 0`, and that a
//! driver is free to resolve either way.
//!
//! So the graph asks the pool what it left each physical resource in, and the
//! first barrier that touches one names *that* as its source:
//!
//! ```text
//! frame n-1 ─ forward pass writes depth ─▶ pool remembers DepthStencilWrite
//!                                                │
//! frame n   ─ compile(&pool) ────────────────────┘
//!             first barrier: DepthStencilWrite ──▶ DepthStencilWrite
//!             (a real source scope, so the two frames are ordered)
//! ```
//!
//! Aliasing *within* a frame is the same story one scale down, and used to have
//! the same hole: handing a slot from one virtual image to the next does not
//! change which `VkImage` it is, so the incoming resource's barrier must name
//! the state the outgoing one left, not `Undefined`. Discarding contents is only
//! free when there are contents worth discarding — with one handle and one
//! description there is nothing to discard, and pretending otherwise costs the
//! source scope that made the two passes ordered.
//!
//! **Imported resources are the owner's problem**, deliberately: the graph
//! cannot know what happened to a swapchain image before it was handed one, so
//! [`ImportedImage::initial`] is a declaration and the owner is the one who has
//! to be right. See its docs for what makes `Undefined` correct there.
//!
//! It is a declaration the graph *audits*, though, wherever auditing is
//! possible. An import that says [`InitialClaim::Tracked`] is one its owner
//! keeps across frames, so the pool remembers what the last graph left it in —
//! [`ImportedImage::final_state`], which the trailing barrier reaches — and the
//! next [`RenderGraph::compile`] rejects an `initial` that disagrees. That is
//! [`GraphError::ImportStateMismatch`], and it is the compile-time form of two
//! bugs this engine has actually shipped: a readback path and a 1×1 shadow
//! placeholder, each declaring a state the image was not in on every frame
//! after the first, and each found only by a validation layer on CI. An
//! [`InitialClaim::Acquired`] import is
//! exempt because a semaphore, not a barrier, is what orders it; the variant's
//! docs say why that is a real exemption rather than an escape hatch.
//!
//! **A buffer import is audited the same way and has no exemption at all.**
//! [`ImportedBuffer::initial`] is the identical declaration about a resource
//! with no layout, which is what makes getting it wrong worse rather than
//! milder: a capture of a mislabelled image at least shows the wrong layout,
//! and a buffer whose barrier lost its source scope looks like nothing until the
//! numbers it carries are wrong. So every buffer import is checked against the
//! ledger — [`GraphError::BufferImportStateMismatch`] — and [`ImportedBuffer`]
//! carries no claim, because nothing hands this engine a buffer from behind a
//! semaphore the way a swapchain hands it an image.
//!
//! # Compilation is pure, and that is what makes it testable
//!
//! [`RenderGraph::compile`] takes no device and touches no GPU. It reads the
//! pool — a plain table of "what was this last used for" — and produces a
//! [`CompiledGraph`] whose barriers name *virtual* resources; only
//! [`CompiledGraph::execute`] resolves those to handles. That split is why
//! `docs/notes/process.md` can call the graph-compile suite a
//! non-negotiable anchor and have it mean something: the interesting half runs
//! on any machine, in microseconds, with no ICD in the room — including the
//! cross-frame half, which needs two `compile` calls against one
//! [`TransientPool::new`] and no driver at all.
//!
//! # The graph explains itself
//!
//! [`CompiledGraph::dump`] prints the pass order, every barrier with its from
//! and to states, and which transients ended up sharing a physical resource.
//! Stage 2 §2.4 asks for exactly this ("the graph must
//! be able to explain itself") and makes "graph dump readable and correct for
//! the sandbox frame" a P1 exit criterion.

use core::fmt;

use crcbl_hal::{
    Barriers, BufferBarrier, BufferHandle, BufferUsage, ClearValue, ColorAttachment,
    CommandEncoder, ComputePassDesc, DepthStencilAttachment, Device, Format, HalError, ImageAspect,
    ImageBarrier, ImageHandle, ImageSubresourceRange, ImageUsage, ImageViewHandle, LoadOp,
    QueueHandle, QueueTransfer, Rect2d, RenderPassDesc, ResourceState, StoreOp, Viewport, depth,
};

use crate::timing::PassTimers;
use crate::transient::{TransientBufferDesc, TransientImageDesc, TransientPool, TransientUse};

/// A virtual image inside one graph.
///
/// Only meaningful to the [`RenderGraph`] that issued it. Deliberately not a
/// [`Handle`](crcbl_core::Handle): a graph is built and thrown away every frame,
/// so there is no use-after-free to protect against, and a plain index keeps
/// compilation allocation-free.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ImageId(u32);

/// A virtual buffer inside one graph. See [`ImageId`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BufferId(u32);

impl ImageId {
    fn index(self) -> usize {
        self.0 as usize
    }
}

impl BufferId {
    fn index(self) -> usize {
        self.0 as usize
    }
}

/// What backs an importer's claim about [`ImportedImage::initial`].
///
/// `initial` is the one thing in a graph the graph cannot derive, and getting
/// it wrong is silent: a barrier out of a state the image is not in still
/// records, still renders, and still passes every golden — it just carries the
/// wrong source scope, and `Undefined` carries none at all. So the importer has
/// to say *how it knows*, and that answer decides whether the graph can check
/// the claim or has to take it.
///
/// **Images only, and that is a fact about the resources rather than about the
/// check.** [`ImportedBuffer::initial`] is the same declaration and is audited
/// on the same ledger, but it has no counterpart to this enum: [`Acquired`] is
/// the only reason an import escapes the audit, an acquire is what a swapchain
/// does, and a swapchain hands out images. Giving a buffer a claim field with
/// one legal value would be an escape hatch with no case behind it — and the
/// [`Acquired`] docs below are about how such a hatch is how the check gets
/// lost.
///
/// [`Acquired`]: InitialClaim::Acquired
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InitialClaim {
    /// The importer owns this image across frames, so `initial` is checkable.
    ///
    /// [`RenderGraph::compile`] looks the image up in the pool's ledger of what
    /// the last graph *left* each tracked import in, and rejects a declaration
    /// that disagrees with it — see [`GraphError::ImportStateMismatch`]. A
    /// handle the ledger has never heard of is accepted: the graph has left it
    /// in nothing, so there is nothing for the claim to contradict, and an
    /// image put into `ShaderRead` by an upload outside the graph is the
    /// ordinary case of that.
    ///
    /// The right answer for anything the importer keeps and re-imports — a
    /// shadow atlas, a 1×1 placeholder, an offscreen target it renders into
    /// twice. Both of the bugs this check exists to stop were images of exactly
    /// that kind: one declared [`ResourceState::Undefined`] on a placeholder the
    /// frame before had left in [`ResourceState::ShaderRead`], which is a
    /// write-after-read with no source scope; the other named
    /// [`ResourceState::ColorAttachment`] on an image the graph had already
    /// returned to [`ResourceState::Present`], which is an illegal old layout.
    Tracked,
    /// An acquire semaphore stands between the last use and this frame, so
    /// there is nothing left for `initial` to order against.
    ///
    /// The freshly acquired swapchain image, and only that shape. Its
    /// [`ResourceState::Undefined`] is not a lie the graph should catch: the
    /// semaphore the acquire signalled is waited on by the submission that runs
    /// this graph, so the frame is *already* ordered after everything the
    /// presentation engine and the previous frame did with the image, and the
    /// first barrier has no ordering left to carry — only a layout to reach.
    ///
    /// Which is also why the graph cannot check one. The image goes back into
    /// the presentation ring at [`ResourceState::Present`] and the window system
    /// does what it likes with it; a ledger entry saying what this frame left
    /// would be a claim about an image the engine no longer controls. So the
    /// ledger does not record these at all, and nothing reads them.
    ///
    /// **Reaching for this to quiet a rejection is how the check gets lost.** A
    /// tracked image marked `Acquired` opts out of the whole guard and reads as
    /// verified; if a declaration is refused and there is no acquire in the
    /// chain, the declaration is what is wrong.
    Acquired,
}

/// An image the graph did not create, and does not own.
///
/// The swapchain image is the canonical one: it belongs to the swapchain, it
/// arrives in an undefined layout, and it must leave in
/// [`ResourceState::Present`]. Saying that once, here, is what removes the
/// hand-written barriers from every frame loop in the engine.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImportedImage {
    /// The image itself.
    pub image: ImageHandle,
    /// A view covering what the passes will render into or sample.
    pub view: ImageViewHandle,
    /// Texel format, which fixes the subresource aspects a barrier names.
    pub format: Format,
    /// Size in pixels, which fixes the render area of any pass that attaches it.
    pub extent: (u32, u32),
    /// The state it is in when the graph starts.
    ///
    /// [`ResourceState::Undefined`] for a freshly acquired swapchain image —
    /// which discards its contents, which is free, and which is the only
    /// correct source for one.
    ///
    /// Unlike a transient, this is a **declaration the owner makes**, not
    /// something the graph can derive: the graph never created this image and
    /// has no description of it to look up. `Undefined` is right for an
    /// acquired swapchain image because the acquire's semaphore — waited on by
    /// the submission that runs this graph — already orders the frame after
    /// everything the presentation engine and the previous frame did with it,
    /// so the barrier has no ordering left to carry and only has to reach the
    /// layout. An importer with no such semaphore in the chain owes the graph
    /// the truth here instead, or it is asking for the same write-after-write
    /// the module docs describe.
    ///
    /// [`claim`](Self::claim) says which of those two an importer is, and a
    /// [`InitialClaim::Tracked`] one is checked rather than taken on trust.
    pub initial: ResourceState,
    /// How the importer knows [`initial`](Self::initial), and so whether the
    /// graph checks it. See [`InitialClaim`].
    pub claim: InitialClaim,
    /// The state the graph must leave it in.
    ///
    /// [`ResourceState::Present`] for a swapchain image. The graph emits a
    /// trailing barrier if the last pass left it somewhere else, and emits
    /// nothing if it did not — so this is what the image is in once the frame
    /// has run either way, which is exactly why it is what the ledger behind
    /// [`InitialClaim::Tracked`] records.
    pub final_state: ResourceState,
}

/// A buffer the graph did not create, and does not own.
///
/// The importer-owned per-frame ring is the canonical one: a cull counter, a
/// light grid, a readback slot. Each belongs to something that keeps it across
/// frames and hands the same handle back every time its turn comes round, so
/// what orders this frame's first access is a barrier out of the state the last
/// frame on that handle left it in — and [`ImportedBuffer::initial`] is where
/// that state is named.
///
/// Unlike [`ImportedImage`] there is no [`InitialClaim`] here, because there is
/// nothing for one to say. A buffer never arrives from a presentation engine,
/// so no buffer import in this engine has an acquire semaphore standing between
/// the last use and this frame; every one of them is a resource whose whole
/// history is frames of this graph, and every one is therefore checked. See
/// [`GraphError::BufferImportStateMismatch`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImportedBuffer {
    /// The buffer itself.
    pub buffer: BufferHandle,
    /// The state it is in when the graph starts.
    ///
    /// A **declaration the owner makes**, exactly as
    /// [`ImportedImage::initial`] is and for the same reason: the graph did not
    /// create this buffer and has no description of it to look up. The right
    /// answer is what the last thing to touch it left it in —
    /// [`final_state`](Self::final_state) on a buffer this graph has run with
    /// before, and whatever the upload or copy outside the graph did on one it
    /// has not.
    ///
    /// [`ResourceState::Undefined`] is the answer only when nothing has written
    /// the buffer *at all*: it names no source scope, so a barrier out of it
    /// orders this frame against nothing, and using it on a buffer another
    /// frame's dispatch or copy wrote is precisely the write-after-write the
    /// module docs describe. The graph rejects that rather than believing it,
    /// on the ledger the previous frame left — see
    /// [`GraphError::BufferImportStateMismatch`].
    pub initial: ResourceState,
    /// The state the graph must leave it in.
    ///
    /// The graph emits a trailing barrier if the last pass left it somewhere
    /// else and emits nothing if it did not, so this is what the buffer is in
    /// once the frame has run either way — which is why it is what the ledger
    /// records, and so what the next frame's `initial` has to say.
    pub final_state: ResourceState,
}

#[derive(Clone, Copy, Debug)]
enum ImageSource {
    Imported(ImportedImage),
    Transient(TransientImageDesc),
}

#[derive(Clone, Copy, Debug)]
enum BufferSource {
    Imported(ImportedBuffer),
    Transient(TransientBufferDesc),
}

#[derive(Clone, Debug)]
struct ImageNode {
    label: String,
    source: ImageSource,
}

#[derive(Clone, Debug)]
struct BufferNode {
    label: String,
    source: BufferSource,
}

impl ImageNode {
    fn format(&self) -> Format {
        match self.source {
            ImageSource::Imported(imported) => imported.format,
            ImageSource::Transient(desc) => desc.format,
        }
    }

    fn extent(&self) -> (u32, u32) {
        match self.source {
            ImageSource::Imported(imported) => imported.extent,
            ImageSource::Transient(desc) => desc.extent,
        }
    }
}

/// How a pass attaches an image, if it attaches it at all.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Attachment {
    /// A colour attachment at `index` in shader output order.
    Color {
        /// Output slot.
        index: u32,
        /// Start-of-pass behaviour.
        load: LoadOp,
        /// End-of-pass behaviour.
        store: StoreOp,
        /// Used when `load` is [`LoadOp::Clear`].
        clear: ClearValue,
    },
    /// The depth/stencil attachment.
    Depth {
        /// Start-of-pass behaviour.
        load: LoadOp,
        /// End-of-pass behaviour.
        store: StoreOp,
        /// Used when `load` is [`LoadOp::Clear`]. Defaults to the reversed-Z far
        /// plane; see [`crcbl_hal::depth`].
        clear: ClearValue,
        /// Whether the pass writes depth. `false` is a pass drawing against an
        /// existing prepass, and is the difference between
        /// [`ResourceState::DepthStencilWrite`] and
        /// [`ResourceState::DepthStencilRead`].
        write: bool,
    },
}

#[derive(Clone, Copy, Debug)]
struct ImageAccess {
    image: ImageId,
    state: ResourceState,
    attachment: Option<Attachment>,
    /// The sub-resource range this access covers. `None` means the whole image
    /// (every mip, every layer), resolved at execute time from the image's format.
    /// Passes that only touch one mip or one layer declare `Some`; the graph then
    /// emits barriers scoped to just that range rather than the full resource.
    range: Option<ImageSubresourceRange>,
}

#[derive(Clone, Copy, Debug)]
struct BufferAccess {
    buffer: BufferId,
    state: ResourceState,
}

/// Which scope a pass opens.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PassKind {
    /// A render pass, with attachments.
    Render,
    /// A compute pass, with none.
    Compute,
    /// A copy, which opens **no** scope at all.
    ///
    /// The seam's rule is that "copies, barriers and query writes are legal only
    /// *outside* any pass", so a body that copies cannot run inside either of
    /// the other two. The graph still computes this pass's barriers and orders
    /// it against its neighbours exactly as it does for them — the only
    /// difference is that [`CompiledGraph::execute`] opens nothing around the
    /// body.
    Copy,
}

impl PassKind {
    /// What this kind is called in the graph dump and in errors.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Render => "render",
            Self::Compute => "compute",
            Self::Copy => "copy",
        }
    }
}

type PassBody<'a> = Box<dyn FnOnce(&mut PassContext<'_>) + 'a>;

struct Pass<'a> {
    label: String,
    kind: PassKind,
    queue: QueueHandle,
    images: Vec<ImageAccess>,
    buffers: Vec<BufferAccess>,
    body: PassBody<'a>,
}

impl fmt::Debug for Pass<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Pass")
            .field("label", &self.label)
            .field("kind", &self.kind)
            .field("images", &self.images)
            .field("buffers", &self.buffers)
            .finish_non_exhaustive()
    }
}

/// A frame's worth of passes, before compilation.
///
/// Built fresh every frame. The lifetime is the passes' closures': they borrow
/// whatever persistent state the renderer holds, and the graph never outlives a
/// frame, so nothing has to be cloned into them.
pub struct RenderGraph<'a> {
    images: Vec<ImageNode>,
    buffers: Vec<BufferNode>,
    passes: Vec<Pass<'a>>,
    default_queue: QueueHandle,
    /// The first import that disagreed with an earlier import of the same
    /// handle, held until [`RenderGraph::compile`] can return it.
    ///
    /// Recorded where it happens because that is the only place both
    /// declarations are in hand, and answered from `compile` because that is
    /// where this file reports a graph it will not execute — the importer's
    /// signature says `ImageId`, not `Result<ImageId, _>`, and the subsystem
    /// that imports second is rarely the one that can decide who is right. The
    /// first conflict only: the rest of validation names one problem and stops.
    import_conflict: Option<GraphError>,
}

impl fmt::Debug for RenderGraph<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RenderGraph")
            .field("images", &self.images)
            .field("buffers", &self.buffers)
            .field("passes", &self.passes)
            .field("import_conflict", &self.import_conflict)
            .finish()
    }
}

impl<'a> RenderGraph<'a> {
    /// An empty graph whose passes default to `queue`.
    #[must_use]
    pub fn new(queue: QueueHandle) -> Self {
        Self {
            images: Vec::new(),
            buffers: Vec::new(),
            passes: Vec::new(),
            default_queue: queue,
            import_conflict: None,
        }
    }

    /// Declares an image the graph owns for the duration of the frame.
    ///
    /// Backed by the [`TransientPool`], and **aliased** with any other transient
    /// of the same description whose lifetime does not overlap this one.
    pub fn create_image(&mut self, label: impl Into<String>, desc: TransientImageDesc) -> ImageId {
        let id = ImageId(u32::try_from(self.images.len()).expect("a frame has few resources"));
        self.images.push(ImageNode {
            label: label.into(),
            source: ImageSource::Transient(desc),
        });
        id
    }

    /// Declares a buffer the graph owns for the duration of the frame.
    pub fn create_buffer(
        &mut self,
        label: impl Into<String>,
        desc: TransientBufferDesc,
    ) -> BufferId {
        let id = BufferId(u32::try_from(self.buffers.len()).expect("a frame has few resources"));
        self.buffers.push(BufferNode {
            label: label.into(),
            source: BufferSource::Transient(desc),
        });
        id
    }

    /// Brings an externally owned image into the graph.
    ///
    /// **One handle is one node.** Importing an image this graph already has
    /// returns the id already issued for it rather than a second one, and that
    /// is what makes two subsystems importing the same target — the base-colour
    /// page a monitor feeds and a forward pass binds, an offscreen target two
    /// renderers both draw into — the ordinary case it looks like. Two ids on
    /// one image would carry *independent* state trackers, each starting from
    /// its own declared [`initial`](ImportedImage::initial), so the graph would
    /// see nothing to order between a write through one and a read through the
    /// other and emit no barrier at all.
    ///
    /// The node keeps the **first** label. A later import naming it differently
    /// is not an error — subsystems name the same image for their own reasons —
    /// but every barrier record and [`CompiledGraph::dump`] line already names
    /// it, and a label that depended on which subsystem imported last would
    /// make the dump move under a caller reordering two unrelated imports.
    ///
    /// A repeat import whose declaration *disagrees* with the first is refused:
    /// see [`GraphError::ImportDeclarationConflict`], which
    /// [`compile`](Self::compile) returns.
    pub fn import_image(&mut self, label: impl Into<String>, imported: ImportedImage) -> ImageId {
        // A linear scan rather than a map from handle to id: a frame has few
        // resources — the same assumption the id conversion below makes — and a
        // second structure to keep in step with `images` buys nothing at this
        // size.
        let existing = self
            .images
            .iter()
            .enumerate()
            .find_map(|(index, node)| match node.source {
                ImageSource::Imported(existing) if existing.image == imported.image => {
                    Some((index, existing))
                }
                _ => None,
            });
        if let Some((index, first)) = existing {
            if let Some((field, first, second)) = image_import_conflict(&first, &imported) {
                self.record_import_conflict(GraphError::ImportDeclarationConflict {
                    resource: self.images[index].label.clone(),
                    field,
                    first,
                    second,
                });
            }
            return ImageId(u32::try_from(index).expect("a frame has few resources"));
        }
        let id = ImageId(u32::try_from(self.images.len()).expect("a frame has few resources"));
        self.images.push(ImageNode {
            label: label.into(),
            source: ImageSource::Imported(imported),
        });
        id
    }

    /// Brings an externally owned buffer into the graph.
    ///
    /// One handle is one node, exactly as [`import_image`](Self::import_image)
    /// describes and for the same reason — a second id would be a second state
    /// tracker, and a buffer written through one id and read through the other
    /// would be a read-after-write the graph never barriered. The first label
    /// wins, and a repeat import that disagrees is
    /// [`GraphError::BufferImportDeclarationConflict`].
    pub fn import_buffer(
        &mut self,
        label: impl Into<String>,
        imported: ImportedBuffer,
    ) -> BufferId {
        let existing =
            self.buffers
                .iter()
                .enumerate()
                .find_map(|(index, node)| match node.source {
                    BufferSource::Imported(existing) if existing.buffer == imported.buffer => {
                        Some((index, existing))
                    }
                    _ => None,
                });
        if let Some((index, first)) = existing {
            if let Some((field, first, second)) = buffer_import_conflict(&first, &imported) {
                self.record_import_conflict(GraphError::BufferImportDeclarationConflict {
                    resource: self.buffers[index].label.clone(),
                    field,
                    first,
                    second,
                });
            }
            return BufferId(u32::try_from(index).expect("a frame has few resources"));
        }
        let id = BufferId(u32::try_from(self.buffers.len()).expect("a frame has few resources"));
        self.buffers.push(BufferNode {
            label: label.into(),
            source: BufferSource::Imported(imported),
        });
        id
    }

    /// Keeps the first conflicting import for [`compile`](Self::compile) to
    /// return. Later ones are dropped: the graph is already refused, and the
    /// second declaration has to come back past `compile` once it is fixed.
    fn record_import_conflict(&mut self, error: GraphError) {
        if self.import_conflict.is_none() {
            self.import_conflict = Some(error);
        }
    }

    /// Starts declaring a render pass. Add it with
    /// [`PassBuilder::execute`].
    pub fn add_render_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
        PassBuilder::new(self, PassKind::Render, label.into())
    }

    /// Starts declaring a compute pass. Add it with
    /// [`PassBuilder::execute`].
    pub fn add_compute_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
        PassBuilder::new(self, PassKind::Compute, label.into())
    }

    /// Starts declaring a copy. Add it with [`PassBuilder::execute`].
    ///
    /// **The one way a copy happens inside a frame.** The seam only allows a
    /// copy outside a pass scope, so a body that calls
    /// [`copy_buffer_to_buffer`](CommandEncoder::copy_buffer_to_buffer) from a
    /// render or compute pass is a scope violation the null backend records —
    /// which is why this is a kind of its own rather than a convention about
    /// what a compute body may do.
    ///
    /// It is otherwise an ordinary pass: it declares what it reads in
    /// [`ResourceState::TransferSrc`] and what it writes in
    /// [`ResourceState::TransferDst`], and the graph emits the transitions
    /// around it.
    ///
    /// **Declare the destination too**, even when it is a
    /// [`MemoryLocation::HostReadback`](crcbl_hal::MemoryLocation::HostReadback)
    /// staging buffer no pass can bind and nothing else in the frame touches.
    /// A destination the graph does not know about gets no barrier, and the
    /// access it needs ordering against is not in this frame at all: it is the
    /// *previous* write to the same buffer, one turn of a ring ago, in another
    /// submission. That is a write-after-write with `write_barriers: 0`, and it
    /// is the bug `crcbl_render::cull_stats` shipped and this sentence exists to stop
    /// repeating — import it with what the last frame left it in, exactly as
    /// every other cross-frame resource here is imported.
    pub fn add_copy_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
        PassBuilder::new(self, PassKind::Copy, label.into())
    }

    /// How many passes have been declared.
    #[must_use]
    pub fn pass_count(&self) -> usize {
        self.passes.len()
    }

    /// What this graph knows about `image` before anything is realised: its
    /// format, its extent, and — for a transient only — the usage it will be
    /// created with. `None` for an id this graph never issued.
    ///
    /// For a pass that has to refuse a source *when it is declared* rather than
    /// let the device refuse the copy at execution:
    /// `crcbl_render::sprite_pass`'s atlas copies check a rendered image against the
    /// slot it is copied into here. An import carries no usage, so the second
    /// half of the answer is the importer's to have got right.
    #[must_use]
    pub fn image_facts(&self, image: ImageId) -> Option<(Format, (u32, u32), Option<ImageUsage>)> {
        let node = self.images.get(image.index())?;
        let usage = match node.source {
            ImageSource::Imported(_) => None,
            ImageSource::Transient(desc) => Some(desc.usage),
        };
        Some((node.format(), node.extent(), usage))
    }

    /// Turns declarations into an ordered pass list with exact barriers.
    ///
    /// Pure: no device, no allocation of GPU memory, no side effects. See the
    /// module docs for why that split exists.
    ///
    /// `pool` is read, never touched: it is the same [`TransientPool`]
    /// [`CompiledGraph::execute`] will realise against, and the only thing
    /// asked of it is what it left each physical transient in last frame. That
    /// is what lets the first barrier of a frame carry a source scope covering
    /// the *previous* frame's writes rather than `Undefined`, which covers
    /// nothing — see the module docs. Passing a pool the graph will not execute
    /// against is the one way to get this wrong, which is why the parameter is
    /// the pool itself rather than a detachable snapshot of it.
    ///
    /// # Errors
    ///
    /// [`GraphError`] for a graph that cannot be executed as written —
    /// conflicting accesses within one pass, a render pass with no attachments
    /// or with attachments of different sizes, a transient nothing uses, or two
    /// imports of one handle that disagree about what they imported.
    pub fn compile(self, pool: &TransientPool) -> Result<CompiledGraph<'a>, GraphError> {
        compile(self, pool)
    }
}

/// Declares one pass. `#[must_use]` because a builder that is dropped rather
/// than [`executed`](PassBuilder::execute) adds nothing to the graph, and a
/// silently missing pass is a long afternoon.
#[must_use = "a pass reaches the graph only through `execute`"]
pub struct PassBuilder<'g, 'a> {
    graph: &'g mut RenderGraph<'a>,
    kind: PassKind,
    label: String,
    queue: QueueHandle,
    images: Vec<ImageAccess>,
    buffers: Vec<BufferAccess>,
    next_color: u32,
}

impl fmt::Debug for PassBuilder<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PassBuilder")
            .field("label", &self.label)
            .field("kind", &self.kind)
            .finish_non_exhaustive()
    }
}

impl<'g, 'a> PassBuilder<'g, 'a> {
    fn new(graph: &'g mut RenderGraph<'a>, kind: PassKind, label: String) -> Self {
        let queue = graph.default_queue;
        Self {
            graph,
            kind,
            label,
            queue,
            images: Vec::new(),
            buffers: Vec::new(),
            next_color: 0,
        }
    }

    /// Runs this pass on a queue other than the graph's default.
    ///
    /// Nothing in the MVP does — uploads share the graphics+compute queue, as
    /// stage 2's corrections state rather than assume.
    /// It exists because the *barrier model* has to represent queue-family
    /// acquire/release from the start, and it does: a resource whose last user
    /// was on another queue gets a release/acquire pair rather than a plain
    /// transition.
    pub fn on_queue(mut self, queue: QueueHandle) -> Self {
        self.queue = queue;
        self
    }

    /// Attaches `image` as the next colour attachment.
    pub fn color(
        mut self,
        image: ImageId,
        load: LoadOp,
        store: StoreOp,
        clear: ClearValue,
    ) -> Self {
        let index = self.next_color;
        self.next_color += 1;
        self.images.push(ImageAccess {
            image,
            state: ResourceState::ColorAttachment,
            attachment: Some(Attachment::Color {
                index,
                load,
                store,
                clear,
            }),
            range: None,
        });
        self
    }

    /// Attaches `image` as the next colour attachment, cleared to `rgba` and
    /// stored.
    pub fn clear_color(self, image: ImageId, rgba: [f32; 4]) -> Self {
        self.color(
            image,
            LoadOp::Clear,
            StoreOp::Store,
            ClearValue::color(rgba),
        )
    }

    /// Attaches `image` as the depth attachment with depth writes on.
    pub fn depth(
        mut self,
        image: ImageId,
        load: LoadOp,
        store: StoreOp,
        clear: ClearValue,
    ) -> Self {
        self.images.push(ImageAccess {
            image,
            state: ResourceState::DepthStencilWrite,
            attachment: Some(Attachment::Depth {
                load,
                store,
                clear,
                write: true,
            }),
            range: None,
        });
        self
    }

    /// Attaches `image` as the depth attachment, cleared to the **reversed-Z**
    /// far plane and discarded at the end of the pass.
    ///
    /// [`depth::CLEAR`] rather than a literal, and discarded rather than stored
    /// because nothing reads a depth buffer after the pass that wrote it until
    /// there is a prepass to read — at which point [`PassBuilder::depth`] takes
    /// a [`StoreOp`] and says so.
    pub fn clear_depth(self, image: ImageId) -> Self {
        self.depth(
            image,
            LoadOp::Clear,
            StoreOp::Discard,
            ClearValue {
                depth: depth::CLEAR,
                ..ClearValue::default()
            },
        )
    }

    /// Attaches `image` as a **read-only** depth attachment: tested, not
    /// written.
    pub fn depth_read(mut self, image: ImageId) -> Self {
        self.images.push(ImageAccess {
            image,
            state: ResourceState::DepthStencilRead,
            attachment: Some(Attachment::Depth {
                load: LoadOp::Load,
                store: StoreOp::Store,
                clear: ClearValue::default(),
                write: false,
            }),
            range: None,
        });
        self
    }

    /// Declares that this pass samples or otherwise shader-reads `image`.
    pub fn read_image(self, image: ImageId) -> Self {
        self.use_image(image, ResourceState::ShaderRead)
    }

    /// Declares that this pass samples or otherwise shader-reads `image`,
    /// but only within the given sub-resource `range` (one mip, one layer,
    /// etc.). The barrier emitted will cover only that range.
    pub fn read_subresource(self, image: ImageId, range: ImageSubresourceRange) -> Self {
        self.use_subresource(image, ResourceState::ShaderRead, range)
    }

    /// Declares an image access in an arbitrary state — a storage-image write, a
    /// copy destination, anything the named helpers do not cover.
    pub fn use_image(mut self, image: ImageId, state: ResourceState) -> Self {
        self.images.push(ImageAccess {
            image,
            state,
            attachment: None,
            range: None,
        });
        self
    }

    /// Declares an image access confined to a specific sub-resource range.
    ///
    /// The graph emits a barrier scoped to `range` rather than the whole image.
    /// Passes that read one mip and write another on the same image declare
    /// disjoint ranges; the graph still tracks one whole-image state (emitting
    /// conservative barriers when ranges differ), which is correct for the
    /// linear pass model.
    pub fn use_subresource(
        mut self,
        image: ImageId,
        state: ResourceState,
        range: ImageSubresourceRange,
    ) -> Self {
        self.images.push(ImageAccess {
            image,
            state,
            attachment: None,
            range: Some(range),
        });
        self
    }

    /// Declares that this pass shader-reads `buffer` — a uniform block, a
    /// pulled vertex stream, an instance array.
    pub fn read_buffer(self, buffer: BufferId) -> Self {
        self.use_buffer(buffer, ResourceState::ShaderRead)
    }

    /// Declares that this pass reads `buffer` as an index buffer.
    pub fn index_buffer(self, buffer: BufferId) -> Self {
        self.use_buffer(buffer, ResourceState::IndexBuffer)
    }

    /// Declares a buffer access in an arbitrary state.
    pub fn use_buffer(mut self, buffer: BufferId, state: ResourceState) -> Self {
        self.buffers.push(BufferAccess { buffer, state });
        self
    }

    /// Adds the pass to the graph, with `body` as the recording callback.
    ///
    /// `body` runs inside the pass scope: the graph has already emitted the
    /// barriers, opened the pass and set a full-target viewport and scissor, so
    /// a body is normally a pipeline bind, a bind group and a draw. A
    /// [`PassKind::Copy`] body runs outside every scope instead — see
    /// [`RenderGraph::add_copy_pass`].
    pub fn execute(self, body: impl FnOnce(&mut PassContext<'_>) + 'a) {
        self.graph.passes.push(Pass {
            label: self.label,
            kind: self.kind,
            queue: self.queue,
            images: self.images,
            buffers: self.buffers,
            body: Box::new(body),
        });
    }
}

// --- compiled form ---------------------------------------------------------

/// A barrier the graph computed, in terms of a virtual image.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GraphImageBarrier {
    /// Image transitioned.
    pub image: ImageId,
    /// State being left.
    pub from: ResourceState,
    /// State being entered.
    pub to: ResourceState,
    /// Queue ownership transfer, when the previous user was on another queue.
    pub queue_transfer: Option<QueueTransfer>,
    /// Sub-resource range this barrier covers. `None` means the whole image,
    /// resolved at execute time from the image's format.
    pub range: Option<ImageSubresourceRange>,
}

/// A barrier the graph computed, in terms of a virtual buffer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GraphBufferBarrier {
    /// Buffer transitioned.
    pub buffer: BufferId,
    /// State being left.
    pub from: ResourceState,
    /// State being entered.
    pub to: ResourceState,
    /// Queue ownership transfer, when the previous user was on another queue.
    pub queue_transfer: Option<QueueTransfer>,
}

/// One batch of barriers, emitted as a single
/// [`pipeline_barrier`](CommandEncoder::pipeline_barrier) call.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct GraphBarriers {
    /// Image transitions, in declaration order.
    pub images: Vec<GraphImageBarrier>,
    /// Buffer transitions, in declaration order.
    pub buffers: Vec<GraphBufferBarrier>,
}

impl GraphBarriers {
    /// Whether this batch would do nothing, in which case the graph emits no
    /// call at all.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.images.is_empty() && self.buffers.is_empty()
    }

    /// How many transitions it carries.
    #[must_use]
    pub fn len(&self) -> usize {
        self.images.len() + self.buffers.len()
    }
}

/// One pass, after compilation.
pub struct CompiledPass<'a> {
    label: String,
    kind: PassKind,
    queue: QueueHandle,
    /// Barriers emitted **before** this pass opens.
    barriers: GraphBarriers,
    /// Barriers emitted **after** this pass closes: the release half of a
    /// queue-ownership transfer whose acquire a later pass records. Empty in
    /// every single-queue frame, which is every frame the MVP runs.
    release_barriers: GraphBarriers,
    images: Vec<ImageAccess>,
    buffers: Vec<BufferAccess>,
    render_area: Rect2d,
    body: PassBody<'a>,
}

impl fmt::Debug for CompiledPass<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompiledPass")
            .field("label", &self.label)
            .field("kind", &self.kind)
            .field("barriers", &self.barriers)
            .finish_non_exhaustive()
    }
}

impl CompiledPass<'_> {
    /// The pass's name, as it appears in captures and in the dump.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Whether it is a render or a compute pass.
    #[must_use]
    pub const fn kind(&self) -> PassKind {
        self.kind
    }

    /// The barriers emitted immediately before it.
    #[must_use]
    pub const fn barriers(&self) -> &GraphBarriers {
        &self.barriers
    }

    /// The barriers emitted immediately after it — the release half of any
    /// queue-ownership transfer a later pass acquires. See
    /// [`crcbl_hal::QueueTransfer`] on why a transfer is two barriers.
    #[must_use]
    pub const fn release_barriers(&self) -> &GraphBarriers {
        &self.release_barriers
    }

    /// The queue it was declared on.
    ///
    /// Always the graph's default in the MVP — uploads share the
    /// graphics+compute queue — but the field is what makes a second queue
    /// additive rather than a barrier-model rewrite, which
    /// stage 2's corrections require from the start.
    #[must_use]
    pub const fn queue(&self) -> QueueHandle {
        self.queue
    }

    /// The region a render pass covers. Zero-sized for a compute pass.
    #[must_use]
    pub const fn render_area(&self) -> Rect2d {
        self.render_area
    }

    /// Whether it declared a read of `buffer`.
    ///
    /// Compilation walks passes in declaration order and never reorders them,
    /// so a pass that omits the declaration still runs after the barrier the
    /// first reader earned — the omission is invisible in the compiled
    /// barriers. This is what lets a test assert the declaration itself.
    #[must_use]
    pub fn reads_buffer(&self, buffer: BufferId) -> bool {
        self.buffers
            .iter()
            .any(|access| access.buffer == buffer && access.state == ResourceState::ShaderRead)
    }
}

/// Which physical resource a virtual one ended up on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Slot {
    /// Externally owned; no pool involvement.
    Imported,
    /// Index into the compiled graph's transient slot list.
    Transient(usize),
}

/// A compiled graph: ordered passes, exact barriers, and a transient plan.
pub struct CompiledGraph<'a> {
    images: Vec<ImageNode>,
    buffers: Vec<BufferNode>,
    passes: Vec<CompiledPass<'a>>,
    /// Barriers returning imported resources to their required final states.
    final_barriers: GraphBarriers,
    image_slots: Vec<Slot>,
    buffer_slots: Vec<Slot>,
    transient_images: Vec<TransientImageDesc>,
    transient_buffers: Vec<TransientBufferDesc>,
    /// What this frame leaves each physical transient image in, parallel to
    /// `transient_images`. Handed to the pool by
    /// [`CompiledGraph::execute`] so the *next* frame's first barrier has a
    /// source scope; computed here because compilation is what knows it.
    transient_image_end: Vec<TransientUse>,
    /// The same for buffers.
    transient_buffer_end: Vec<TransientUse>,
    /// What this frame leaves each [`InitialClaim::Tracked`] import in, which
    /// is [`ImportedImage::final_state`] because the trailing barrier is what
    /// reaches it. Handed to the pool by [`CompiledGraph::execute`], where the
    /// next frame's [`RenderGraph::compile`] checks a declaration against it.
    imported_image_end: Vec<(ImageHandle, ResourceState)>,
    /// The same for every imported buffer, which is all of them: a buffer
    /// import has no [`InitialClaim::Acquired`] counterpart to leave out.
    imported_buffer_end: Vec<(BufferHandle, ResourceState)>,
}

impl fmt::Debug for CompiledGraph<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompiledGraph")
            .field("passes", &self.passes)
            .field("final_barriers", &self.final_barriers)
            .field("transient_images", &self.transient_images)
            .field("transient_buffers", &self.transient_buffers)
            .finish_non_exhaustive()
    }
}

impl<'a> CompiledGraph<'a> {
    /// The compiled passes, in execution order.
    #[must_use]
    pub fn passes(&self) -> &[CompiledPass<'a>] {
        &self.passes
    }

    /// The barriers emitted after the last pass, returning imported resources to
    /// the states their owners require.
    #[must_use]
    pub const fn final_barriers(&self) -> &GraphBarriers {
        &self.final_barriers
    }

    /// How many physical images the transients were packed onto.
    ///
    /// Lower than the number of transients declared exactly when aliasing
    /// happened, which is what makes the saving assertable.
    #[must_use]
    pub fn physical_image_count(&self) -> usize {
        self.transient_images.len()
    }

    /// How many physical buffers the transients were packed onto.
    #[must_use]
    pub fn physical_buffer_count(&self) -> usize {
        self.transient_buffers.len()
    }

    /// Whether two virtual images share one physical image.
    #[must_use]
    pub fn images_alias(&self, first: ImageId, second: ImageId) -> bool {
        matches!(
            (
                self.image_slots.get(first.index()),
                self.image_slots.get(second.index())
            ),
            (Some(Slot::Transient(a)), Some(Slot::Transient(b))) if a == b
        )
    }

    /// Every barrier the frame will emit, batch by batch, ending with the final
    /// batch. The shape a test asserts on.
    #[must_use]
    pub fn barrier_batches(&self) -> Vec<&GraphBarriers> {
        self.passes
            .iter()
            .flat_map(|pass| [&pass.barriers, &pass.release_barriers])
            .chain(core::iter::once(&self.final_barriers))
            .filter(|batch| !batch.is_empty())
            .collect()
    }

    /// The graph, as text a human reads.
    ///
    /// Stage 2 §2.4's debug-tools principle: "the graph
    /// must be able to explain itself", and its exit criteria require the dump
    /// to be "readable and correct for the sandbox frame". Every line is derived
    /// from the compiled form rather than re-walked from the declarations, so a
    /// dump that says a barrier happened is evidence that it will.
    #[must_use]
    pub fn dump(&self) -> String {
        let mut out = String::new();
        self.write_dump(&mut out).expect("writing to a String");
        out
    }

    fn write_dump(&self, out: &mut impl fmt::Write) -> fmt::Result {
        let aliased = self
            .image_slots
            .iter()
            .filter(|slot| matches!(slot, Slot::Transient(_)))
            .count()
            .saturating_sub(self.transient_images.len());
        writeln!(
            out,
            "render graph: {} pass(es), {} transient image(s) on {} physical, \
             {} transient buffer(s) on {} physical, {} barrier(s)",
            self.passes.len(),
            self.transient_image_users(),
            self.transient_images.len(),
            self.transient_buffer_users(),
            self.transient_buffers.len(),
            self.passes
                .iter()
                .map(|pass| pass.barriers.len() + pass.release_barriers.len())
                .sum::<usize>()
                + self.final_barriers.len(),
        )?;
        if aliased > 0 {
            writeln!(out, "  aliasing saved {aliased} physical image(s)")?;
        }

        for (index, pass) in self.passes.iter().enumerate() {
            self.write_barriers(out, &pass.barriers, &format!("[{index}] "))?;
            writeln!(
                out,
                "[{index}] {} pass {:?}  {}x{}",
                pass.kind.name(),
                pass.label,
                pass.render_area.width,
                pass.render_area.height
            )?;
            for access in &pass.images {
                let node = &self.images[access.image.index()];
                let role = match access.attachment {
                    Some(Attachment::Color {
                        index, load, store, ..
                    }) => {
                        format!("color[{index}] load={load:?} store={store:?}")
                    }
                    Some(Attachment::Depth {
                        load, store, write, ..
                    }) => format!(
                        "depth load={load:?} store={store:?} write={}",
                        if write { "yes" } else { "no" }
                    ),
                    None => "sampled/storage".to_string(),
                };
                writeln!(
                    out,
                    "        image  {:<20} {:<20} {role} [{}]",
                    node.label,
                    format!("{:?}", access.state),
                    self.slot_note(self.image_slots[access.image.index()]),
                )?;
            }
            for access in &pass.buffers {
                let node = &self.buffers[access.buffer.index()];
                writeln!(
                    out,
                    "        buffer {:<20} {:<20} [{}]",
                    node.label,
                    format!("{:?}", access.state),
                    self.slot_note(self.buffer_slots[access.buffer.index()]),
                )?;
            }
            self.write_barriers(out, &pass.release_barriers, &format!("[{index}] release "))?;
        }

        self.write_barriers(out, &self.final_barriers, "[final] ")?;
        Ok(())
    }

    fn transient_image_users(&self) -> usize {
        self.image_slots
            .iter()
            .filter(|slot| matches!(slot, Slot::Transient(_)))
            .count()
    }

    fn transient_buffer_users(&self) -> usize {
        self.buffer_slots
            .iter()
            .filter(|slot| matches!(slot, Slot::Transient(_)))
            .count()
    }

    fn slot_note(&self, slot: Slot) -> String {
        match slot {
            Slot::Imported => "imported".to_string(),
            Slot::Transient(index) => format!("transient #{index}"),
        }
    }

    fn write_barriers(
        &self,
        out: &mut impl fmt::Write,
        barriers: &GraphBarriers,
        prefix: &str,
    ) -> fmt::Result {
        if barriers.is_empty() {
            return Ok(());
        }
        writeln!(out, "{prefix}barriers ({})", barriers.len())?;
        for barrier in &barriers.images {
            writeln!(
                out,
                "        image  {:<20} {:>18} -> {:<18}{}",
                self.images[barrier.image.index()].label,
                format!("{:?}", barrier.from),
                format!("{:?}", barrier.to),
                queue_note(barrier.queue_transfer),
            )?;
        }
        for barrier in &barriers.buffers {
            writeln!(
                out,
                "        buffer {:<20} {:>18} -> {:<18}{}",
                self.buffers[barrier.buffer.index()].label,
                format!("{:?}", barrier.from),
                format!("{:?}", barrier.to),
                queue_note(barrier.queue_transfer),
            )?;
        }
        Ok(())
    }

    /// Records the whole frame into `encoder`.
    ///
    /// Realises the transients out of `pool`, then for each pass in order:
    /// emits its barrier batch as one call, opens the pass — naming the two
    /// queries `timers` gave it, which the backend samples where the pass opens
    /// and closes — sets a full-target viewport and scissor, runs the body and
    /// closes the pass. A [`PassKind::Copy`] is the exception twice over: its
    /// body runs with no scope open at all, because that is the only place the
    /// seam permits a copy, and having no scope it has no boundary to time.
    /// Finally emits the barriers that return
    /// imported resources to their required states, and tells `pool` what this
    /// frame left each physical transient in — which is what the *next* frame's
    /// first barrier uses as its source scope.
    ///
    /// `pool` must be the one [`RenderGraph::compile`] was given, or the
    /// barriers name states the resources are not in.
    ///
    /// The encoder is left outside any pass, with nothing to clean up.
    ///
    /// # Errors
    ///
    /// [`GraphError::Hal`] if the pool could not create a transient. Nothing
    /// else can fail here — everything checkable was checked at compile time.
    pub fn execute(
        self,
        device: &dyn Device,
        pool: &mut TransientPool,
        encoder: &mut dyn CommandEncoder,
        mut timers: Option<&mut PassTimers>,
    ) -> Result<(), GraphError> {
        let realised = self.realise(device, pool)?;
        let Self {
            images,
            passes,
            final_barriers,
            transient_images,
            transient_buffers,
            transient_image_end,
            transient_buffer_end,
            imported_image_end,
            imported_buffer_end,
            ..
        } = self;

        if let Some(timers) = timers.as_deref_mut() {
            timers.begin_frame(device, encoder, &passes);
        }

        for (index, pass) in passes.into_iter().enumerate() {
            emit(encoder, &images, &realised, &pass.barriers);
            // The pass's own boundaries, not a call around it: the seam takes a
            // timestamp only where a pass opens and closes, so the barriers just
            // emitted are outside what this pass will report.
            let timestamp_writes = timers
                .as_deref()
                .and_then(|timers| timers.pass_writes(index));

            match pass.kind {
                PassKind::Render => {
                    let (colors, depth_stencil) = attachments(&realised, &pass.images);
                    encoder.begin_render_pass(&RenderPassDesc {
                        label: Some(&pass.label),
                        color_attachments: &colors,
                        depth_stencil_attachment: depth_stencil,
                        render_area: pass.render_area,
                        timestamp_writes,
                    });
                    // Dynamic state, set by the graph rather than by every pass
                    // body: a pipeline that baked a viewport in would have to be
                    // rebuilt on every resize, and every body would otherwise
                    // repeat the same two lines with the same chance of using
                    // the wrong extent.
                    encoder.set_viewport(&Viewport::from_size(
                        pass.render_area.width,
                        pass.render_area.height,
                    ));
                    encoder.set_scissor(&pass.render_area);
                }
                PassKind::Compute => {
                    encoder.begin_compute_pass(&ComputePassDesc {
                        label: Some(&pass.label),
                        timestamp_writes,
                    });
                }
                // Nothing is opened: a copy is only legal outside every scope.
                PassKind::Copy => {}
            }

            {
                let mut context = PassContext {
                    device,
                    encoder,
                    realised: &realised,
                    render_area: pass.render_area,
                };
                (pass.body)(&mut context);
            }

            match pass.kind {
                PassKind::Render => encoder.end_render_pass(),
                PassKind::Compute => encoder.end_compute_pass(),
                PassKind::Copy => {}
            }
            // The release half of any queue-ownership transfer a later pass
            // acquires. Outside the pass scope, because the seam only allows
            // barriers there.
            emit(encoder, &images, &realised, &pass.release_barriers);
        }

        emit(encoder, &images, &realised, &final_barriers);

        // The handover to the next frame. It happens after the commands are
        // recorded rather than during compilation because a graph that is
        // compiled and dropped ran nothing, and a pool that remembered a frame
        // that never happened would order the following frame against writes
        // the GPU never performed.
        for (slot, desc) in transient_images.iter().enumerate() {
            pool.set_image_use(
                *desc,
                ordinal(&transient_images, slot),
                transient_image_end[slot],
            );
        }
        for (slot, desc) in transient_buffers.iter().enumerate() {
            pool.set_buffer_use(
                *desc,
                ordinal(&transient_buffers, slot),
                transient_buffer_end[slot],
            );
        }
        // The same handover for the imports the owner says it tracks, and for
        // the same reason one turn further out: the next graph's `compile` is
        // what reads these, and it reads them to *refuse* a declaration that
        // disagrees rather than to barrier against them.
        for (image, state) in imported_image_end {
            pool.set_imported_image_use(image, state);
        }
        for (buffer, state) in imported_buffer_end {
            pool.set_imported_buffer_use(buffer, state);
        }
        Ok(())
    }

    fn realise(
        &self,
        device: &dyn Device,
        pool: &mut TransientPool,
    ) -> Result<Realised, GraphError> {
        pool.begin_frame();
        let mut physical_images = Vec::with_capacity(self.transient_images.len());
        for desc in &self.transient_images {
            physical_images.push(pool.image(device, *desc)?);
        }
        let mut physical_buffers = Vec::with_capacity(self.transient_buffers.len());
        for desc in &self.transient_buffers {
            physical_buffers.push(pool.buffer(device, *desc)?);
        }

        let images = self
            .images
            .iter()
            .zip(&self.image_slots)
            .map(|(node, slot)| match (slot, node.source) {
                (Slot::Imported, ImageSource::Imported(imported)) => {
                    (imported.image, imported.view)
                }
                (Slot::Transient(index), _) => physical_images[*index],
                // Unreachable: `compile` assigns `Imported` only to imported
                // nodes. Stated as a panic rather than an `unwrap` so the
                // invariant is named where it is relied on.
                (Slot::Imported, ImageSource::Transient(_)) => {
                    unreachable!("a transient image was assigned the imported slot")
                }
            })
            .collect();
        let buffers = self
            .buffers
            .iter()
            .zip(&self.buffer_slots)
            .map(|(node, slot)| match (slot, node.source) {
                (Slot::Imported, BufferSource::Imported(imported)) => imported.buffer,
                (Slot::Transient(index), _) => physical_buffers[*index],
                (Slot::Imported, BufferSource::Transient(_)) => {
                    unreachable!("a transient buffer was assigned the imported slot")
                }
            })
            .collect();

        Ok(Realised { images, buffers })
    }
}

fn queue_note(transfer: Option<QueueTransfer>) -> String {
    transfer.map_or_else(String::new, |transfer| {
        format!("  queue {:?} -> {:?}", transfer.from, transfer.to)
    })
}

/// Virtual resources resolved to real handles, for the duration of one
/// [`CompiledGraph::execute`].
#[derive(Debug)]
struct Realised {
    images: Vec<(ImageHandle, ImageViewHandle)>,
    buffers: Vec<BufferHandle>,
}

/// What a pass body is handed.
///
/// It has an encoder already inside the pass scope, the device (for the rare
/// body that has to build something against a transient's handle), and a way to
/// turn a virtual id into the handle it landed on.
#[derive(Debug)]
pub struct PassContext<'a> {
    device: &'a dyn Device,
    encoder: &'a mut dyn CommandEncoder,
    realised: &'a Realised,
    render_area: Rect2d,
}

impl PassContext<'_> {
    /// The encoder, already inside this pass's scope.
    pub fn encoder(&mut self) -> &mut dyn CommandEncoder {
        self.encoder
    }

    /// The device, for a body that must create something against a transient's
    /// handle — a bind group naming a graph-owned image view, typically.
    #[must_use]
    pub fn device(&self) -> &dyn Device {
        self.device
    }

    /// The handle a virtual image landed on.
    ///
    /// # Panics
    ///
    /// If `id` came from a different graph.
    #[must_use]
    pub fn image(&self, id: ImageId) -> ImageHandle {
        self.realised.images[id.index()].0
    }

    /// The view of a virtual image.
    ///
    /// Stable frame to frame while the graph's shape is, which is what lets a
    /// caller cache a bind group against it and rebuild only on a resize.
    ///
    /// # Panics
    ///
    /// If `id` came from a different graph.
    #[must_use]
    pub fn image_view(&self, id: ImageId) -> ImageViewHandle {
        self.realised.images[id.index()].1
    }

    /// The handle a virtual buffer landed on.
    ///
    /// # Panics
    ///
    /// If `id` came from a different graph.
    #[must_use]
    pub fn buffer(&self, id: BufferId) -> BufferHandle {
        self.realised.buffers[id.index()]
    }

    /// The region this pass renders, in pixels. The viewport and scissor are
    /// already set to it.
    #[must_use]
    pub const fn render_area(&self) -> Rect2d {
        self.render_area
    }
}

fn emit(
    encoder: &mut dyn CommandEncoder,
    images: &[ImageNode],
    realised: &Realised,
    barriers: &GraphBarriers,
) {
    if barriers.is_empty() {
        return;
    }
    let image_barriers: Vec<ImageBarrier> = barriers
        .images
        .iter()
        .map(|barrier| ImageBarrier {
            image: realised.images[barrier.image.index()].0,
            range: barrier.range.unwrap_or_else(|| {
                ImageSubresourceRange::all(images[barrier.image.index()].format())
            }),
            from: barrier.from,
            to: barrier.to,
            queue_transfer: barrier.queue_transfer,
        })
        .collect();
    let buffer_barriers: Vec<BufferBarrier> = barriers
        .buffers
        .iter()
        .map(|barrier| BufferBarrier {
            buffer: realised.buffers[barrier.buffer.index()],
            from: barrier.from,
            to: barrier.to,
            queue_transfer: barrier.queue_transfer,
        })
        .collect();
    encoder.pipeline_barrier(&Barriers {
        buffers: &buffer_barriers,
        images: &image_barriers,
        global: false,
    });
}

fn attachments(
    realised: &Realised,
    accesses: &[ImageAccess],
) -> (Vec<ColorAttachment>, Option<DepthStencilAttachment>) {
    let mut colors: Vec<(u32, ColorAttachment)> = Vec::new();
    let mut depth_stencil = None;
    for access in accesses {
        let view = realised.images[access.image.index()].1;
        match access.attachment {
            Some(Attachment::Color {
                index,
                load,
                store,
                clear,
            }) => colors.push((
                index,
                ColorAttachment {
                    view,
                    resolve: None,
                    load,
                    store,
                    clear,
                },
            )),
            Some(Attachment::Depth {
                load,
                store,
                clear,
                write,
            }) => {
                depth_stencil = Some(DepthStencilAttachment {
                    view,
                    // `PassBuilder::depth_read` declares
                    // `ResourceState::DepthStencilRead`, which puts the image in
                    // a *different* layout from a written depth attachment. The
                    // backend cannot infer that from the ops, so the pass's own
                    // `write` flag is what tells it.
                    read_only: !write,
                    depth_load: load,
                    depth_store: store,
                    // No stencil plane in anything the engine renders yet; a
                    // `D32_SFLOAT` attachment has none to load or store.
                    stencil_load: LoadOp::DontCare,
                    stencil_store: StoreOp::Discard,
                    clear,
                });
            }
            None => {}
        }
    }
    // Attachment order in the descriptor is shader-output order, which is the
    // `index` a caller gave — not the order it happened to declare them in.
    colors.sort_by_key(|(index, _)| *index);
    (
        colors
            .into_iter()
            .map(|(_, attachment)| attachment)
            .collect(),
        depth_stencil,
    )
}

// --- compilation -----------------------------------------------------------

/// Why a graph could not be compiled.
#[derive(Debug, thiserror::Error)]
pub enum GraphError {
    /// One pass declared two different states for the same resource.
    #[error(
        "pass `{pass}` accesses `{resource}` as both {first:?} and {second:?}; a resource is in \
         one state per pass, so this needs two passes or one state"
    )]
    ConflictingAccess {
        /// Pass label.
        pass: String,
        /// Resource label.
        resource: String,
        /// The first state declared.
        first: ResourceState,
        /// The second, incompatible state.
        second: ResourceState,
    },
    /// A render pass attached nothing.
    #[error(
        "render pass `{pass}` has no attachments; a pass that renders nowhere is a declaration \
         mistake, not an optimisation"
    )]
    NoAttachments {
        /// Pass label.
        pass: String,
    },
    /// A render pass attached images of different sizes.
    #[error(
        "render pass `{pass}` attaches `{first}` at {first_extent:?} and `{second}` at \
         {second_extent:?}; every attachment must be the same size"
    )]
    AttachmentExtentMismatch {
        /// Pass label.
        pass: String,
        /// The first attachment's label.
        first: String,
        /// Its size.
        first_extent: (u32, u32),
        /// The disagreeing attachment's label.
        second: String,
        /// Its size.
        second_extent: (u32, u32),
    },
    /// A render pass attached two depth images.
    #[error("render pass `{pass}` attaches more than one depth image")]
    DuplicateDepthAttachment {
        /// Pass label.
        pass: String,
    },
    /// One pass declared the same resource twice over the same subrange.
    ///
    /// `.color(image, ..).color(image, ..)` used to be accepted and produced
    /// two colour attachments over one view — two shader outputs writing the
    /// same pixels, in an order nothing defines. A pass that genuinely touches
    /// two parts of one image declares two *different* subresource ranges.
    #[error(
        "pass `{pass}` declares `{resource}` twice over the same subrange; a resource is declared \
         once per pass, and two attachments over one view is not a second attachment"
    )]
    DuplicateDeclaration {
        /// Pass label.
        pass: String,
        /// Resource label.
        resource: String,
    },
    /// A pass named a mip level or array layer the image does not have.
    #[error(
        "pass `{pass}` uses `{resource}` at mip {base_mip}+{mip_count} / layer \
         {base_layer}+{layer_count}, but the image has {mip_levels} mip level(s) and \
         {layers} layer(s); a barrier on a subresource that does not exist covers nothing"
    )]
    SubresourceOutOfRange {
        /// Pass label.
        pass: String,
        /// Resource label.
        resource: String,
        /// First mip named.
        base_mip: u32,
        /// Mip levels named.
        mip_count: u32,
        /// First layer named.
        base_layer: u32,
        /// Layers named.
        layer_count: u32,
        /// Mip levels the image has.
        mip_levels: u32,
        /// Array layers the image has.
        layers: u32,
    },
    /// A pass that opens no render scope attached something.
    #[error("{kind} pass `{pass}` attaches `{resource}`; only a render pass has attachments")]
    AttachmentOutsideRenderPass {
        /// Which kind of pass declared it — [`PassKind::name`].
        kind: &'static str,
        /// Pass label.
        pass: String,
        /// Resource label.
        resource: String,
    },
    /// A transient was declared and never used, so it has no lifetime and no
    /// reason to exist.
    #[error(
        "`{resource}` is a transient no pass reads or writes; either a pass forgot to declare it \
         or the resource should not have been created"
    )]
    UnusedTransient {
        /// Resource label.
        resource: String,
    },
    /// An [`InitialClaim::Tracked`] import declared a state the last graph did
    /// not leave the image in.
    ///
    /// The whole point of the claim: the owner said it tracks this image across
    /// frames, and the pool remembers what the previous graph's trailing
    /// barrier actually reached. When those disagree the first barrier of this
    /// frame names a source scope the GPU never visits — and if the declaration
    /// is [`ResourceState::Undefined`] it names no source scope at all, so the
    /// transition orders against nothing while the previous frame is still
    /// reading the same image.
    #[error(
        "`{resource}` is imported as {declared:?}, but the last graph left it in {left:?}; a \
         barrier out of a state the image is not in carries the wrong source scope — declare \
         what was left, or say `InitialClaim::Acquired` if a semaphore already orders this frame"
    )]
    ImportStateMismatch {
        /// Resource label.
        resource: String,
        /// What the import declared as [`ImportedImage::initial`].
        declared: ResourceState,
        /// What the last graph to execute against this pool left it in.
        left: ResourceState,
    },
    /// A buffer import declared a state the last graph did not leave it in.
    ///
    /// [`GraphError::ImportStateMismatch`] for a resource with no layout, and
    /// its own variant rather than the same one because the two answers a reader
    /// needs differ. An image has a way out — say [`InitialClaim::Acquired`] and
    /// mean it — and telling a buffer's importer to reach for a field
    /// [`ImportedBuffer`] does not have would send them looking for an escape
    /// that is not there and should not be. What is left when that clause goes
    /// is the whole of the advice: declare what the last frame left.
    #[error(
        "`{resource}` is imported as {declared:?}, but the last graph left it in {left:?}; a \
         barrier out of a state the buffer is not in carries the wrong source scope, and \
         `Undefined` carries none at all — declare what was left"
    )]
    BufferImportStateMismatch {
        /// Resource label.
        resource: String,
        /// What the import declared as [`ImportedBuffer::initial`].
        declared: ResourceState,
        /// What the last graph to execute against this pool left it in.
        left: ResourceState,
    },
    /// One image handle was imported twice with declarations that disagree.
    ///
    /// [`RenderGraph::import_image`] hands the second importer the id the first
    /// one got, because one handle has to be one node with one state tracker
    /// for the graph to barrier between two passes that reach it through
    /// different ids. That leaves exactly one thing it cannot do quietly: two
    /// declarations that are not the same declaration. Keeping the first would
    /// be the graph ignoring the second — silently sampling through a view it
    /// was not handed, or barriering out of a state the other importer says the
    /// image is not in — so the frame is refused instead and the two importers
    /// have to agree.
    #[error(
        "`{resource}` is imported more than once with different declarations: `{field}` is \
         {first} in one and {second} in the other; one handle is one node with one state \
         tracker, so the graph cannot honour both — import it once and share the id"
    )]
    ImportDeclarationConflict {
        /// Resource label — the **first** import's, which is the one the node
        /// kept.
        resource: String,
        /// Which field of [`ImportedImage`] disagreed.
        field: ImportField,
        /// What the first import declared it as, [`Debug`](fmt::Debug)-printed.
        first: String,
        /// What the later import declared it as.
        second: String,
    },
    /// One buffer handle was imported twice with declarations that disagree.
    ///
    /// [`GraphError::ImportDeclarationConflict`] for a resource with no layout,
    /// and a variant of its own for the same reason
    /// [`GraphError::BufferImportStateMismatch`] is one: the message names the
    /// resource kind, and a caller matching on the error is usually looking at
    /// one kind of resource.
    #[error(
        "`{resource}` is imported more than once with different declarations: `{field}` is \
         {first} in one and {second} in the other; one handle is one node with one state \
         tracker, so the graph cannot honour both — import it once and share the id"
    )]
    BufferImportDeclarationConflict {
        /// Resource label — the **first** import's, which is the one the node
        /// kept.
        resource: String,
        /// Which field of [`ImportedBuffer`] disagreed.
        field: ImportField,
        /// What the first import declared it as, [`Debug`](fmt::Debug)-printed.
        first: String,
        /// What the later import declared it as.
        second: String,
    },
    /// The seam refused something at execution time.
    #[error(transparent)]
    Hal(#[from] HalError),
}

/// Which field of a repeated import declaration disagreed with the first one.
///
/// Carried by [`GraphError::ImportDeclarationConflict`] and
/// [`GraphError::BufferImportDeclarationConflict`] so a caller can tell the
/// kinds of disagreement apart without parsing a message: two subsystems
/// disagreeing about the state an image arrives in is a synchronisation bug in
/// one of them, and two disagreeing about which view they bind is usually one
/// of them importing the wrong thing entirely.
///
/// It spells [`ImportedImage`]'s fields, of which an [`ImportedBuffer`] has
/// only [`Initial`](Self::Initial) and [`FinalState`](Self::FinalState); the
/// handle itself is absent because it is what the two declarations are matched
/// on, so it cannot be what they differ in. [`Display`](fmt::Display) prints
/// the field's name as it is spelled in the struct, so a message points at
/// something a reader can go and look at.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImportField {
    /// [`ImportedImage::view`].
    View,
    /// [`ImportedImage::format`].
    Format,
    /// [`ImportedImage::extent`].
    Extent,
    /// [`ImportedImage::initial`] or [`ImportedBuffer::initial`].
    Initial,
    /// [`ImportedImage::claim`].
    Claim,
    /// [`ImportedImage::final_state`] or [`ImportedBuffer::final_state`].
    FinalState,
}

impl fmt::Display for ImportField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::View => "view",
            Self::Format => "format",
            Self::Extent => "extent",
            Self::Initial => "initial",
            Self::Claim => "claim",
            Self::FinalState => "final_state",
        })
    }
}

/// The first field two declarations of one imported image disagree about.
///
/// First rather than all of them, because that is how the rest of this file
/// reports: one problem named, and the fixed declaration comes back past
/// `compile` anyway. Compares the values and formats only what it returns —
/// deciding "same declaration" off the printed text would make two handles that
/// happen to print alike into one.
fn image_import_conflict(
    first: &ImportedImage,
    second: &ImportedImage,
) -> Option<(ImportField, String, String)> {
    // Binds nothing; it is here so that adding a field to `ImportedImage` stops
    // compiling until this function has decided about it. A field the
    // comparison forgets is a disagreement reported as agreement, which is the
    // one failure this whole check exists to prevent — and the six blocks below
    // look alike enough that a missing seventh would read as complete.
    let ImportedImage {
        image: _,
        view: _,
        format: _,
        extent: _,
        initial: _,
        claim: _,
        final_state: _,
    } = first;
    if first.view != second.view {
        return Some((
            ImportField::View,
            format!("{:?}", first.view),
            format!("{:?}", second.view),
        ));
    }
    if first.format != second.format {
        return Some((
            ImportField::Format,
            format!("{:?}", first.format),
            format!("{:?}", second.format),
        ));
    }
    if first.extent != second.extent {
        return Some((
            ImportField::Extent,
            format!("{:?}", first.extent),
            format!("{:?}", second.extent),
        ));
    }
    if first.initial != second.initial {
        return Some((
            ImportField::Initial,
            format!("{:?}", first.initial),
            format!("{:?}", second.initial),
        ));
    }
    if first.claim != second.claim {
        return Some((
            ImportField::Claim,
            format!("{:?}", first.claim),
            format!("{:?}", second.claim),
        ));
    }
    if first.final_state != second.final_state {
        return Some((
            ImportField::FinalState,
            format!("{:?}", first.final_state),
            format!("{:?}", second.final_state),
        ));
    }
    None
}

/// The first field two declarations of one imported buffer disagree about. See
/// [`image_import_conflict`]; a buffer declaration is the two state fields and
/// the handle they are about.
fn buffer_import_conflict(
    first: &ImportedBuffer,
    second: &ImportedBuffer,
) -> Option<(ImportField, String, String)> {
    // See [`image_import_conflict`]: binds nothing, and stops compiling when
    // `ImportedBuffer` grows a field this comparison has not decided about.
    let ImportedBuffer {
        buffer: _,
        initial: _,
        final_state: _,
    } = first;
    if first.initial != second.initial {
        return Some((
            ImportField::Initial,
            format!("{:?}", first.initial),
            format!("{:?}", second.initial),
        ));
    }
    if first.final_state != second.final_state {
        return Some((
            ImportField::FinalState,
            format!("{:?}", first.final_state),
            format!("{:?}", second.final_state),
        ));
    }
    None
}

/// Array layers a [`TransientImageDesc`] image has. The pool creates them
/// single-layer, and the description has no field to say otherwise.
const TRANSIENT_LAYERS: u32 = 1;

/// Per-physical-resource tracking during compilation.
///
/// Keyed on the *physical* resource, and seeded from what that resource was
/// last used for — [`ImportedImage::initial`] for an import, the pool's memory
/// of the previous frame for a transient. There is no "and now the slot is
/// fresh" case: a slot handed from one virtual resource to another is the same
/// object, in the state the previous one left it, and the module docs explain
/// why pretending otherwise loses the barrier.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Tracked {
    state: ResourceState,
    queue: Option<QueueHandle>,
    /// Index of the pass in *this* graph that last used it, which is where the
    /// release half of a queue-ownership transfer has to be recorded.
    last_pass: Option<usize>,
}

impl Tracked {
    const fn carried(last: TransientUse) -> Self {
        Self {
            state: last.state,
            queue: last.queue,
            last_pass: None,
        }
    }

    const fn declared(state: ResourceState) -> Self {
        Self {
            state,
            queue: None,
            last_pass: None,
        }
    }

    const fn end(self) -> TransientUse {
        TransientUse {
            state: self.state,
            queue: self.queue,
        }
    }
}

/// A half-open mip × layer rectangle of one image.
///
/// The unit of image state tracking. Whole-image is just the rectangle covering
/// everything — the graph does not need a second representation for it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Subrect {
    mips: (u32, u32),
    layers: (u32, u32),
}

impl Subrect {
    /// The rectangle a resource with unknown extents starts at. Imported
    /// images do not say how many levels or layers they have, and every access
    /// to one in this engine covers the whole thing.
    const UNBOUNDED: Self = Self {
        mips: (0, u32::MAX),
        layers: (0, u32::MAX),
    };

    const fn bounded(mip_levels: u32, layers: u32) -> Self {
        Self {
            mips: (0, mip_levels),
            layers: (0, layers),
        }
    }

    const fn is_empty(self) -> bool {
        self.mips.0 >= self.mips.1 || self.layers.0 >= self.layers.1
    }

    fn intersect(self, other: Self) -> Self {
        Self {
            mips: (self.mips.0.max(other.mips.0), self.mips.1.min(other.mips.1)),
            layers: (
                self.layers.0.max(other.layers.0),
                self.layers.1.min(other.layers.1),
            ),
        }
    }

    /// `self` minus `cut`, as up to four disjoint rectangles.
    ///
    /// `cut` must already be an intersection with `self`, so the pieces tile
    /// the difference exactly.
    fn subtract(self, cut: Self) -> Vec<Self> {
        let mut out = Vec::new();
        if cut.mips.0 > self.mips.0 {
            out.push(Self {
                mips: (self.mips.0, cut.mips.0),
                layers: self.layers,
            });
        }
        if self.mips.1 > cut.mips.1 {
            out.push(Self {
                mips: (cut.mips.1, self.mips.1),
                layers: self.layers,
            });
        }
        if cut.layers.0 > self.layers.0 {
            out.push(Self {
                mips: cut.mips,
                layers: (self.layers.0, cut.layers.0),
            });
        }
        if self.layers.1 > cut.layers.1 {
            out.push(Self {
                mips: cut.mips,
                layers: (cut.layers.1, self.layers.1),
            });
        }
        out
    }

    fn to_range(self, aspect: crcbl_hal::ImageAspect) -> ImageSubresourceRange {
        ImageSubresourceRange {
            aspect,
            base_mip: self.mips.0,
            mip_count: if self.mips.1 == u32::MAX {
                ImageSubresourceRange::ALL
            } else {
                self.mips.1 - self.mips.0
            },
            base_layer: self.layers.0,
            layer_count: if self.layers.1 == u32::MAX {
                ImageSubresourceRange::ALL
            } else {
                self.layers.1 - self.layers.0
            },
        }
    }
}

/// `ALL` means "every remaining", so it resolves against the image's own size.
fn subrect_of(range: ImageSubresourceRange, bounds: Subrect) -> Subrect {
    let mip_end = if range.mip_count == ImageSubresourceRange::ALL {
        bounds.mips.1
    } else {
        range.base_mip.saturating_add(range.mip_count)
    };
    let layer_end = if range.layer_count == ImageSubresourceRange::ALL {
        bounds.layers.1
    } else {
        range.base_layer.saturating_add(range.layer_count)
    };
    Subrect {
        mips: (range.base_mip, mip_end),
        layers: (range.base_layer, layer_end),
    }
}

/// One transition the tracker decided is needed.
#[derive(Clone, Copy, Debug)]
struct SubBarrier {
    from: ResourceState,
    queue_transfer: Option<QueueTransfer>,
    /// The part of the image it covers, or `None` when the whole access range
    /// is in one state and the access's own range already describes it.
    rect: Option<Subrect>,
    /// Pass that last used this part, for the release half of a transfer.
    last_pass: Option<usize>,
}

/// Per-**subresource** image state.
///
/// A whole-image tracker was wrong in a way that only a per-mip pass could
/// notice, and did: writing mip 0 and then mip 1 produced a barrier on mip 1
/// whose `from` was the state mip 0 had been left in, which mip 1 had never
/// been in. A barrier that names a source state its subresource never occupied
/// is a barrier the driver is free to interpret as covering nothing.
#[derive(Clone, Debug)]
struct ImageTracker {
    bounds: Subrect,
    /// Disjoint rectangles tiling `bounds`, each with the state of that part.
    segments: Vec<(Subrect, Tracked)>,
}

impl ImageTracker {
    fn new(bounds: Subrect, tracked: Tracked) -> Self {
        Self {
            bounds,
            segments: vec![(bounds, tracked)],
        }
    }

    /// Applies an access covering `rect`, returning the barriers it needs.
    fn transition(
        &mut self,
        rect: Subrect,
        want: ResourceState,
        queue: QueueHandle,
        pass: usize,
    ) -> Vec<SubBarrier> {
        let mut outside: Vec<(Subrect, Tracked)> = Vec::new();
        let mut inside: Vec<(Subrect, Tracked)> = Vec::new();
        for (segment, tracked) in self.segments.drain(..) {
            let overlap = segment.intersect(rect);
            if overlap.is_empty() {
                outside.push((segment, tracked));
                continue;
            }
            outside.extend(
                segment
                    .subtract(overlap)
                    .into_iter()
                    .map(|piece| (piece, tracked)),
            );
            inside.push((overlap, tracked));
        }

        let mut barriers = Vec::new();
        for (piece, tracked) in &inside {
            let queue_transfer = match tracked.queue {
                Some(previous) if previous != queue => Some(QueueTransfer {
                    from: previous,
                    to: queue,
                }),
                _ => None,
            };
            // A queue-family transfer is a barrier even between two identical
            // states: ownership has to move, or the second queue reads memory
            // the first has not released.
            if ResourceState::needs_barrier(tracked.state, want) || queue_transfer.is_some() {
                barriers.push(SubBarrier {
                    from: tracked.state,
                    queue_transfer,
                    rect: Some(*piece),
                    last_pass: tracked.last_pass,
                });
            }
        }

        // The common case: every part of the access was in one state, so the
        // access's own declared range describes the barrier exactly and there
        // is no reason to spell out the pieces.
        if barriers.len() == inside.len()
            && barriers.windows(2).all(|pair| {
                pair[0].from == pair[1].from && pair[0].queue_transfer == pair[1].queue_transfer
            })
        {
            barriers.truncate(1.min(barriers.len()));
            if let Some(first) = barriers.first_mut() {
                first.rect = None;
            }
        }

        let entered = Tracked {
            state: want,
            queue: Some(queue),
            last_pass: Some(pass),
        };
        self.segments = outside;
        for (piece, tracked) in inside {
            // A read that needed no barrier stays in the state it was in — two
            // reads of the same kind are the same state by definition.
            let state = if ResourceState::needs_barrier(tracked.state, want) {
                want
            } else {
                tracked.state
            };
            self.segments.push((piece, Tracked { state, ..entered }));
        }
        self.coalesce();
        barriers
    }

    /// Collapses back to one segment once the whole image agrees again, so a
    /// frame of whole-image passes never grows the list.
    fn coalesce(&mut self) {
        let Some((_, first)) = self.segments.first().copied() else {
            return;
        };
        if self.segments.iter().all(|(_, tracked)| *tracked == first) {
            self.segments = vec![(self.bounds, first)];
        }
    }

    /// The state of the base subresource.
    ///
    /// [`TransientUse`] holds one state per resource, so a frame that leaves an
    /// image in mixed states can only hand the pool the one the next frame's
    /// whole-image barrier will name — which is the base level's.
    fn end(&self) -> TransientUse {
        self.segments
            .iter()
            .find(|(rect, _)| {
                rect.mips.0 == self.bounds.mips.0 && rect.layers.0 == self.bounds.layers.0
            })
            .or_else(|| self.segments.first())
            .map_or_else(TransientUse::default, |(_, tracked)| tracked.end())
    }
}

/// How many earlier entries of `descs` carry the same description as `descs[at]`.
///
/// The pool hands out the *n*-th resource of a description for the *n*-th
/// request, and [`CompiledGraph::realise`] requests them in slot order — so this
/// is the number that turns "physical slot 3" into "the pool entry slot 3 will
/// get", both before it has been realised and after.
fn ordinal<D: PartialEq>(descs: &[D], at: usize) -> usize {
    descs[..at]
        .iter()
        .filter(|other| **other == descs[at])
        .count()
}

fn compile<'a>(
    graph: RenderGraph<'a>,
    pool: &TransientPool,
) -> Result<CompiledGraph<'a>, GraphError> {
    let RenderGraph {
        images,
        buffers,
        passes,
        default_queue: _,
        import_conflict,
    } = graph;

    // First, because it is the earliest thing that went wrong: every check
    // below runs against a node whose declaration is already known to have been
    // contradicted, so any error they found would be about the wrong half.
    if let Some(conflict) = import_conflict {
        return Err(conflict);
    }
    validate(&images, &buffers, &passes)?;
    validate_imports(&images, &buffers, pool)?;

    let image_lifetimes = lifetimes(passes.len(), passes.iter().map(|pass| &pass.images), |a| {
        a.image.0
    });
    let buffer_lifetimes = lifetimes(passes.len(), passes.iter().map(|pass| &pass.buffers), |a| {
        a.buffer.0
    });

    // Aliasing: pack transients onto as few physical resources as their
    // lifetimes allow.
    let mut transient_images = Vec::new();
    let image_slots = assign(
        &images,
        &image_lifetimes,
        |node| match node.source {
            ImageSource::Transient(desc) => Some(desc),
            ImageSource::Imported(_) => None,
        },
        |node| node.label.clone(),
        &mut transient_images,
    )?;
    let mut transient_buffers = Vec::new();
    let buffer_slots = assign(
        &buffers,
        &buffer_lifetimes,
        |node| match node.source {
            BufferSource::Transient(desc) => Some(desc),
            BufferSource::Imported(_) => None,
        },
        |node| node.label.clone(),
        &mut transient_buffers,
    )?;

    // State tracking is per **physical** resource, because that is what a
    // barrier actually names. Imported resources get one tracker each (keyed by
    // their own id); transients share one per physical slot.
    //
    // Every tracker starts where its resource actually is. For an import that
    // is what the owner declared; for a transient it is what the pool remembers
    // of the last frame that used the very same handle, which is the whole of
    // the cross-frame fix.
    let mut image_state: Vec<ImageTracker> = images
        .iter()
        .zip(&image_slots)
        .map(|(node, slot)| match (slot, node.source) {
            (Slot::Imported, ImageSource::Imported(imported)) => {
                ImageTracker::new(Subrect::UNBOUNDED, Tracked::declared(imported.initial))
            }
            _ => ImageTracker::new(
                Subrect::UNBOUNDED,
                Tracked::declared(ResourceState::Undefined),
            ),
        })
        .collect();
    let mut transient_image_state: Vec<ImageTracker> = (0..transient_images.len())
        .map(|slot| {
            let desc = transient_images[slot];
            ImageTracker::new(
                // A transient is a single-layer 2D image whose level count the
                // description now states, so a range naming a level it does not
                // have is a compile error rather than a barrier on nothing.
                Subrect::bounded(desc.mip_levels.max(1), 1),
                Tracked::carried(pool.image_use(desc, ordinal(&transient_images, slot))),
            )
        })
        .collect();
    let mut buffer_state: Vec<Tracked> = buffers
        .iter()
        .zip(&buffer_slots)
        .map(|(node, slot)| Tracked {
            state: match (slot, node.source) {
                (Slot::Imported, BufferSource::Imported(imported)) => imported.initial,
                _ => ResourceState::Undefined,
            },
            queue: None,
            last_pass: None,
        })
        .collect();
    let mut transient_buffer_state: Vec<Tracked> = (0..transient_buffers.len())
        .map(|slot| {
            Tracked::carried(
                pool.buffer_use(transient_buffers[slot], ordinal(&transient_buffers, slot)),
            )
        })
        .collect();

    let mut compiled: Vec<CompiledPass<'a>> = Vec::with_capacity(passes.len());
    for (index, pass) in passes.into_iter().enumerate() {
        let mut barriers = GraphBarriers::default();

        for access in &pass.images {
            let node = &images[access.image.index()];
            let aspect = access
                .range
                .map_or_else(|| ImageAspect::of(node.format()), |range| range.aspect);
            let tracked = tracker(
                image_slots[access.image.index()],
                access.image.0,
                &mut image_state,
                &mut transient_image_state,
            );
            let rect = access
                .range
                .map_or(tracked.bounds, |range| subrect_of(range, tracked.bounds));
            for sub in tracked.transition(rect, access.state, pass.queue, index) {
                let range = match sub.rect {
                    None => access.range,
                    Some(piece) => Some(piece.to_range(aspect)),
                };
                let barrier = GraphImageBarrier {
                    image: access.image,
                    from: sub.from,
                    to: access.state,
                    queue_transfer: sub.queue_transfer,
                    range,
                };
                // A transfer is *two* barriers with identical fields: a release
                // on the source queue and an acquire on the destination
                // (`crcbl_hal::QueueTransfer`). The release goes after the last
                // pass that used the resource, which is the only point at which
                // the source queue is finished with it.
                if sub.queue_transfer.is_some()
                    && let Some(source) = sub.last_pass
                {
                    compiled[source].release_barriers.images.push(barrier);
                }
                barriers.images.push(barrier);
            }
        }
        for access in &pass.buffers {
            let tracked = tracker(
                buffer_slots[access.buffer.index()],
                access.buffer.0,
                &mut buffer_state,
                &mut transient_buffer_state,
            );
            if let Some(barrier) = transition(tracked, access.state, pass.queue, index) {
                let compiled_barrier = GraphBufferBarrier {
                    buffer: access.buffer,
                    from: barrier.0,
                    to: access.state,
                    queue_transfer: barrier.1,
                };
                if barrier.1.is_some()
                    && let Some(source) = barrier.2
                {
                    compiled[source]
                        .release_barriers
                        .buffers
                        .push(compiled_barrier);
                }
                barriers.buffers.push(compiled_barrier);
            }
        }

        let render_area = render_area(&images, &pass)?;
        compiled.push(CompiledPass {
            label: pass.label,
            kind: pass.kind,
            queue: pass.queue,
            barriers,
            release_barriers: GraphBarriers::default(),
            images: pass.images,
            buffers: pass.buffers,
            render_area,
            body: pass.body,
        });
    }

    // Return every imported resource to the state its owner requires. This is
    // the barrier that used to be hand-written after the render pass in
    // `apps/sandbox`, and the reason it can be computed rather than remembered.
    let mut final_barriers = GraphBarriers::default();
    for (index, node) in images.iter().enumerate() {
        let ImageSource::Imported(imported) = node.source else {
            continue;
        };
        let tracker = &image_state[index];
        let aspect = ImageAspect::of(imported.format);
        let whole = tracker.segments.len() == 1;
        // `!=` rather than `needs_barrier`: this transition guards nothing —
        // the graph is finished with the resource — so its only job is to leave
        // the layout its owner asked for. A write-after-write between two passes
        // is a hazard and gets a barrier; a write followed by *nothing* is not.
        for (rect, tracked) in &tracker.segments {
            if tracked.state != imported.final_state {
                final_barriers.images.push(GraphImageBarrier {
                    image: ImageId(u32::try_from(index).expect("a frame has few resources")),
                    from: tracked.state,
                    to: imported.final_state,
                    queue_transfer: None,
                    range: if whole {
                        None
                    } else {
                        Some(rect.to_range(aspect))
                    },
                });
            }
        }
    }
    for (index, node) in buffers.iter().enumerate() {
        let BufferSource::Imported(imported) = node.source else {
            continue;
        };
        let tracked = buffer_state[index];
        if tracked.state != imported.final_state {
            final_barriers.buffers.push(GraphBufferBarrier {
                buffer: BufferId(u32::try_from(index).expect("a frame has few resources")),
                from: tracked.state,
                to: imported.final_state,
                queue_transfer: None,
            });
        }
    }

    // What the pool is told once these commands are actually recorded. Read off
    // the trackers rather than re-derived, so the state the next frame barriers
    // against is by construction the state this frame's last barrier reached.
    let transient_image_end = transient_image_state
        .iter()
        .map(ImageTracker::end)
        .collect();
    let transient_buffer_end = transient_buffer_state.iter().map(|t| t.end()).collect();
    // Read off the declaration rather than off the tracker, because the loop
    // above has just made them the same thing: every segment of an imported
    // image that is not already at `final_state` gets a trailing barrier into
    // it, so `final_state` is where the image is once this frame has run.
    //
    // One entry per handle rather than per import call, and one trailing
    // barrier for the same reason: `RenderGraph::import_image` gives a repeat
    // import the id the first one got, so there is no second node here to
    // barrier the image somewhere else and then overwrite the ledger with it.
    let imported_image_end = images
        .iter()
        .filter_map(|node| match node.source {
            ImageSource::Imported(imported) if imported.claim == InitialClaim::Tracked => {
                Some((imported.image, imported.final_state))
            }
            _ => None,
        })
        .collect();
    // And every imported buffer, for the same reason off the same loop, with no
    // subset to select: there is no buffer whose declaration the graph takes on
    // trust, so there is none whose ending state it has no business recording.
    let imported_buffer_end = buffers
        .iter()
        .filter_map(|node| match node.source {
            BufferSource::Imported(imported) => Some((imported.buffer, imported.final_state)),
            BufferSource::Transient(_) => None,
        })
        .collect();

    Ok(CompiledGraph {
        images,
        buffers,
        passes: compiled,
        final_barriers,
        image_slots,
        buffer_slots,
        transient_images,
        transient_buffers,
        transient_image_end,
        transient_buffer_end,
        imported_image_end,
        imported_buffer_end,
    })
}

fn tracker<'s, T>(
    slot: Slot,
    id: u32,
    per_resource: &'s mut [T],
    per_slot: &'s mut [T],
) -> &'s mut T {
    match slot {
        Slot::Imported => &mut per_resource[id as usize],
        Slot::Transient(index) => &mut per_slot[index],
    }
}

/// Decides whether a transition is needed, and updates the tracker.
///
/// Returns `(from, queue_transfer)` when a barrier must be emitted.
///
/// There is no special case for a physical slot changing hands. It used to
/// start such a transition from [`ResourceState::Undefined`], on the argument
/// that the outgoing resource's pixels are garbage to the incoming one and
/// discarding them is free. The pixels are indeed garbage — but `Undefined` on
/// this seam does not only mean "discard", it means "no source scope", and the
/// outgoing resource's *writes* are not garbage: they are in flight. Naming the
/// real previous state costs nothing here (one handle, one description, so
/// there is no layout change and nothing to decompress) and is the difference
/// between the two uses being ordered and racing.
fn transition(
    tracked: &mut Tracked,
    want: ResourceState,
    queue: QueueHandle,
    pass: usize,
) -> Option<(ResourceState, Option<QueueTransfer>, Option<usize>)> {
    let queue_transfer = match tracked.queue {
        Some(previous) if previous != queue => Some(QueueTransfer {
            from: previous,
            to: queue,
        }),
        _ => None,
    };
    let from = tracked.state;
    let source_pass = tracked.last_pass;
    tracked.queue = Some(queue);
    tracked.last_pass = Some(pass);

    // A queue-family transfer is a barrier even between two identical states:
    // ownership has to move, or the second queue reads memory the first has not
    // released.
    if !ResourceState::needs_barrier(from, want) && queue_transfer.is_none() {
        return None;
    }
    tracked.state = want;
    Some((from, queue_transfer, source_pass))
}

/// First and last pass index that touches each resource.
fn lifetimes<'p, A: 'p, I>(
    pass_count: usize,
    accesses: impl Iterator<Item = I>,
    id_of: impl Fn(&A) -> u32,
) -> Vec<Option<(usize, usize)>>
where
    I: IntoIterator<Item = &'p A>,
{
    let mut spans: Vec<Option<(usize, usize)>> = Vec::new();
    for (pass, list) in accesses.enumerate() {
        debug_assert!(pass < pass_count);
        for access in list {
            let id = id_of(access) as usize;
            if spans.len() <= id {
                spans.resize(id + 1, None);
            }
            spans[id] = Some(match spans[id] {
                Some((first, last)) => (first.min(pass), last.max(pass)),
                None => (pass, pass),
            });
        }
    }
    spans
}

/// Packs transients onto physical slots, reusing one whose lifetime has ended.
fn assign<N, D: Copy + PartialEq>(
    nodes: &[N],
    spans: &[Option<(usize, usize)>],
    desc_of: impl Fn(&N) -> Option<D>,
    label_of: impl Fn(&N) -> String,
    physical: &mut Vec<D>,
) -> Result<Vec<Slot>, GraphError> {
    // `free_from[slot]` is the first pass at which the slot is available again.
    let mut free_from: Vec<usize> = Vec::new();
    let mut slots = Vec::with_capacity(nodes.len());

    // Ordered by first use so a single left-to-right sweep is optimal for the
    // interval-packing problem this is: identical descriptions, no preemption.
    let mut order: Vec<usize> = (0..nodes.len()).collect();
    order.sort_by_key(|index| {
        spans
            .get(*index)
            .copied()
            .flatten()
            .map_or(usize::MAX, |s| s.0)
    });

    slots.resize(nodes.len(), Slot::Imported);
    for index in order {
        let Some(desc) = desc_of(&nodes[index]) else {
            continue;
        };
        let Some((first, last)) = spans.get(index).copied().flatten() else {
            return Err(GraphError::UnusedTransient {
                resource: label_of(&nodes[index]),
            });
        };
        let reused =
            (0..physical.len()).find(|slot| physical[*slot] == desc && free_from[*slot] <= first);
        let slot = match reused {
            Some(slot) => slot,
            None => {
                physical.push(desc);
                free_from.push(0);
                physical.len() - 1
            }
        };
        free_from[slot] = last + 1;
        slots[index] = Slot::Transient(slot);
    }
    Ok(slots)
}

/// Checks every checkable import against what the last graph left it in.
///
/// The half of validation that needs the pool, which is why it is not inside
/// [`validate`]: everything there is a property of the declarations alone, and
/// this is a property of the declarations *and* the frames before them.
///
/// Every buffer import is checkable and only a [`InitialClaim::Tracked`] image
/// is — see [`ImportedBuffer`] for why the asymmetry belongs to the resources
/// rather than to this function.
///
/// Silence for a resource the ledger has never heard of is deliberate and is
/// not a hole. The ledger records what a graph left, so an absent entry means no
/// graph has left this one in anything — an image an upload put into
/// [`ResourceState::ShaderRead`] before any frame ran is the ordinary case, and
/// there is no previous frame for the declaration to be wrong about.
fn validate_imports(
    images: &[ImageNode],
    buffers: &[BufferNode],
    pool: &TransientPool,
) -> Result<(), GraphError> {
    for node in images {
        let ImageSource::Imported(imported) = node.source else {
            continue;
        };
        if imported.claim != InitialClaim::Tracked {
            continue;
        }
        let Some(left) = pool.imported_image_use(imported.image) else {
            continue;
        };
        if left != imported.initial {
            return Err(GraphError::ImportStateMismatch {
                resource: node.label.clone(),
                declared: imported.initial,
                left,
            });
        }
    }
    for node in buffers {
        let BufferSource::Imported(imported) = node.source else {
            continue;
        };
        let Some(left) = pool.imported_buffer_use(imported.buffer) else {
            continue;
        };
        if left != imported.initial {
            return Err(GraphError::BufferImportStateMismatch {
                resource: node.label.clone(),
                declared: imported.initial,
                left,
            });
        }
    }
    Ok(())
}

fn validate(
    images: &[ImageNode],
    buffers: &[BufferNode],
    passes: &[Pass<'_>],
) -> Result<(), GraphError> {
    for pass in passes {
        let mut seen_depth = false;
        for (position, access) in pass.images.iter().enumerate() {
            if pass.kind != PassKind::Render && access.attachment.is_some() {
                return Err(GraphError::AttachmentOutsideRenderPass {
                    kind: pass.kind.name(),
                    pass: pass.label.clone(),
                    resource: images[access.image.index()].label.clone(),
                });
            }
            if matches!(access.attachment, Some(Attachment::Depth { .. })) {
                if seen_depth {
                    return Err(GraphError::DuplicateDepthAttachment {
                        pass: pass.label.clone(),
                    });
                }
                seen_depth = true;
            }
            // A transient states how many levels and layers it has, so a range
            // naming one it does not is a mistake the graph can name here
            // rather than a barrier on nothing three passes later. An import
            // does not say, so there is nothing to check.
            if let (Some(range), ImageSource::Transient(desc)) =
                (access.range, images[access.image.index()].source)
            {
                let mip_levels = desc.mip_levels.max(1);
                let mips_ok = range.mip_count == ImageSubresourceRange::ALL
                    || range.base_mip.saturating_add(range.mip_count) <= mip_levels;
                let layers_ok = range.layer_count == ImageSubresourceRange::ALL
                    || range.base_layer.saturating_add(range.layer_count) <= TRANSIENT_LAYERS;
                if !mips_ok || !layers_ok || range.base_mip >= mip_levels {
                    return Err(GraphError::SubresourceOutOfRange {
                        pass: pass.label.clone(),
                        resource: images[access.image.index()].label.clone(),
                        base_mip: range.base_mip,
                        mip_count: range.mip_count,
                        base_layer: range.base_layer,
                        layer_count: range.layer_count,
                        mip_levels,
                        layers: TRANSIENT_LAYERS,
                    });
                }
            }
            for other in &pass.images[position + 1..] {
                if other.image != access.image {
                    continue;
                }
                if other.state != access.state {
                    return Err(GraphError::ConflictingAccess {
                        pass: pass.label.clone(),
                        resource: images[access.image.index()].label.clone(),
                        first: access.state,
                        second: other.state,
                    });
                }
                if other.range == access.range {
                    return Err(GraphError::DuplicateDeclaration {
                        pass: pass.label.clone(),
                        resource: images[access.image.index()].label.clone(),
                    });
                }
            }
        }
        for (position, access) in pass.buffers.iter().enumerate() {
            for other in &pass.buffers[position + 1..] {
                if other.buffer != access.buffer {
                    continue;
                }
                if other.state != access.state {
                    return Err(GraphError::ConflictingAccess {
                        pass: pass.label.clone(),
                        resource: buffers[access.buffer.index()].label.clone(),
                        first: access.state,
                        second: other.state,
                    });
                }
                return Err(GraphError::DuplicateDeclaration {
                    pass: pass.label.clone(),
                    resource: buffers[access.buffer.index()].label.clone(),
                });
            }
        }
    }
    Ok(())
}

fn render_area(images: &[ImageNode], pass: &Pass<'_>) -> Result<Rect2d, GraphError> {
    if pass.kind != PassKind::Render {
        return Ok(Rect2d::from_size(0, 0));
    }
    let mut area: Option<(&str, (u32, u32))> = None;
    for access in &pass.images {
        if access.attachment.is_none() {
            continue;
        }
        let node = &images[access.image.index()];
        let extent = node.extent();
        match area {
            None => area = Some((&node.label, extent)),
            Some((first, first_extent)) if first_extent != extent => {
                return Err(GraphError::AttachmentExtentMismatch {
                    pass: pass.label.clone(),
                    first: first.to_string(),
                    first_extent,
                    second: node.label.clone(),
                    second_extent: extent,
                });
            }
            Some(_) => {}
        }
    }
    match area {
        Some((_, (width, height))) => Ok(Rect2d::from_size(width, height)),
        None => Err(GraphError::NoAttachments {
            pass: pass.label.clone(),
        }),
    }
}

impl TransientBufferDesc {
    /// A device-local storage buffer of `size` bytes.
    #[must_use]
    pub const fn storage(size: u64) -> Self {
        Self {
            size,
            usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_DST),
        }
    }
}