vulkane 0.5.0

Vulkan API bindings generated entirely from vk.xml, with a complete safe RAII wrapper covering compute and graphics: instance/device/queue, buffer, image, sampler, render pass, framebuffer, graphics + compute pipelines, swapchain, a VMA-style sub-allocator with TLSF + linear pools and defragmentation, sync primitives (fences, binary + timeline semaphores, sync2 barriers), query pools, and optional GLSL/WGSL/HLSL→SPIR-V compilation via naga or shaderc. Supports Vulkan 1.2.175 onward — swap vk.xml and rebuild.
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
//! Integration test for the safe wrapper module.
//!
//! Validates the entire safe API end-to-end against a real Vulkan driver.
//! Skips gracefully on systems without Vulkan installed.

use vulkane::safe::{
    AccessFlags, AccessFlags2, AllocationCreateInfo, AllocationStrategy, AllocationUsage, Allocator,
    ApiVersion, Buffer, BufferCopy, BufferCreateInfo, BufferImageCopy, BufferUsage, CommandPool,
    ComputePipeline, DEBUG_UTILS_EXTENSION, DebugMessage, DebugMessageSeverity,
    DefragmentationMove, DefragmentationPlan, DescriptorPool, DescriptorPoolSize,
    DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorType, DeviceCreateInfo,
    DeviceFeatures, DeviceMemory, Fence, Format, Image, Image2dCreateInfo, ImageBarrier,
    ImageLayout, ImageUsage, ImageView, Instance, InstanceCreateInfo, KHRONOS_VALIDATION_LAYER,
    MemoryPropertyFlags, PipelineCache, PipelineLayout, PipelineStage, PipelineStage2,
    PipelineStatisticsFlags, PoolCreateInfo, PushConstantRange, QueryPool, QueueCreateInfo,
    QueueFlags, Semaphore, SemaphoreKind, ShaderModule, ShaderStageFlags, SignalSemaphore,
    SpecializationConstants, WaitSemaphore,
};

#[test]
fn test_safe_instance_creation_and_enumeration() {
    let instance = match Instance::new(InstanceCreateInfo {
        application_name: Some("vulkane test"),
        api_version: ApiVersion::V1_0,
        ..Default::default()
    }) {
        Ok(i) => i,
        Err(e) => {
            eprintln!("SKIP: Vulkan not available: {e}");
            return;
        }
    };

    // Enumeration should succeed even if there are no devices.
    let physical_devices = instance.enumerate_physical_devices().unwrap();
    println!("Found {} physical device(s)", physical_devices.len());

    for pd in &physical_devices {
        let props = pd.properties();
        assert!(!props.device_name().is_empty());
        assert!(props.api_version().major() >= 1);

        let queue_families = pd.queue_family_properties();
        assert!(
            !queue_families.is_empty(),
            "every device has at least one queue family"
        );
    }
}

#[test]
fn test_xlib_xcb_surface_constructors_callable() {
    // We can't actually open an X server from inside a Windows CI run,
    // and the platform extensions are not enabled here, so the calls
    // should land in the MissingFunction branch — proving the safe
    // wrappers are reachable, type-correct, and round-trip the right
    // diagnostic instead of UB. (On a real Linux desktop with the
    // VK_KHR_xlib_surface / VK_KHR_xcb_surface extensions enabled and
    // a valid display, the same calls would return Ok.)
    use vulkane::safe::Surface;

    let instance = match Instance::new(InstanceCreateInfo::default()) {
        Ok(i) => i,
        Err(e) => {
            eprintln!("SKIP: cannot create Vulkan instance: {e}");
            return;
        }
    };

    // Synthetic, never-dereferenced pointers — only used so the call
    // makes it past the unsafe block and into the dispatch lookup.
    let fake_display: *mut std::ffi::c_void = std::ptr::null_mut();
    let fake_window: std::ffi::c_ulong = 0;
    match unsafe { Surface::from_xlib(&instance, fake_display, fake_window) } {
        Err(vulkane::safe::Error::MissingFunction(name)) => {
            assert_eq!(name, "vkCreateXlibSurfaceKHR");
        }
        Ok(_) => {
            // If we somehow got a real surface (driver loaded the
            // extension on its own), drop it cleanly.
        }
        Err(e) => panic!("expected MissingFunction or Ok, got {e:?}"),
    }

    let fake_connection: *mut std::ffi::c_void = std::ptr::null_mut();
    let fake_xcb_window: u32 = 0;
    match unsafe { Surface::from_xcb(&instance, fake_connection, fake_xcb_window) } {
        Err(vulkane::safe::Error::MissingFunction(name)) => {
            assert_eq!(name, "vkCreateXcbSurfaceKHR");
        }
        Ok(_) => {}
        Err(e) => panic!("expected MissingFunction or Ok, got {e:?}"),
    }
}

#[test]
fn test_safe_device_creation_and_drop() {
    let instance = match Instance::new(InstanceCreateInfo::default()) {
        Ok(i) => i,
        Err(_) => {
            eprintln!("SKIP: Vulkan not available");
            return;
        }
    };

    let physicals = instance.enumerate_physical_devices().unwrap();
    let physical = match physicals.first() {
        Some(p) => p.clone(),
        None => {
            eprintln!("SKIP: no physical devices");
            return;
        }
    };

    let queue_family = physical.find_queue_family(QueueFlags::TRANSFER).unwrap();

    // Create and drop a device. The Drop impl should call vkDestroyDevice.
    let device = physical
        .create_device(DeviceCreateInfo {
            queue_create_infos: &[QueueCreateInfo {
                queue_family_index: queue_family,
                queue_priorities: vec![1.0],
            }],
            ..Default::default()
        })
        .expect("device creation should succeed");

    // Verify we can get a queue handle from it.
    let _queue = device.get_queue(queue_family, 0);

    // Verify wait_idle on a fresh device works.
    device
        .wait_idle()
        .expect("wait_idle on idle device should succeed");

    // Drop happens at end of scope.
}

#[test]
fn test_safe_buffer_with_host_visible_memory() {
    let instance = match Instance::new(InstanceCreateInfo::default()) {
        Ok(i) => i,
        Err(_) => {
            eprintln!("SKIP: Vulkan not available");
            return;
        }
    };

    let physicals = instance.enumerate_physical_devices().unwrap();
    let Some(physical) = physicals.first().cloned() else {
        eprintln!("SKIP: no physical devices");
        return;
    };

    let queue_family = physical.find_queue_family(QueueFlags::TRANSFER).unwrap();
    let device = physical
        .create_device(DeviceCreateInfo {
            queue_create_infos: &[QueueCreateInfo {
                queue_family_index: queue_family,
                queue_priorities: vec![1.0],
            }],
            ..Default::default()
        })
        .unwrap();

    // Create a buffer.
    let buffer = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 256,
            usage: BufferUsage::TRANSFER_DST,
        },
    )
    .unwrap();
    assert_eq!(buffer.size(), 256);

    // Query memory requirements.
    let req = buffer.memory_requirements();
    assert!(req.size >= 256);
    assert!(req.alignment.is_power_of_two());

    // Find a compatible host-visible memory type.
    let mem_type = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .expect("host-visible memory should be available on any platform");

    // Allocate and bind.
    let mut memory = DeviceMemory::allocate(&device, req.size, mem_type).unwrap();
    buffer.bind_memory(&memory, 0).unwrap();

    // Map, write, verify, drop.
    {
        let mut mapped = memory.map().unwrap();
        let slice = mapped.as_slice_mut();
        assert_eq!(slice.len() as u64, req.size);
        for (i, b) in slice.iter_mut().enumerate() {
            *b = (i & 0xFF) as u8;
        }
    }

    // Map again and verify the writes persisted (host-coherent so no flushes needed).
    {
        let mapped = memory.map().unwrap();
        let slice = mapped.as_slice();
        for (i, &b) in slice.iter().enumerate() {
            assert_eq!(b, (i & 0xFF) as u8, "byte {i} did not persist");
        }
    }
}

#[test]
fn test_safe_full_gpu_round_trip() {
    let instance = match Instance::new(InstanceCreateInfo::default()) {
        Ok(i) => i,
        Err(_) => {
            eprintln!("SKIP: Vulkan not available");
            return;
        }
    };

    let physicals = instance.enumerate_physical_devices().unwrap();
    let Some(physical) = physicals.first().cloned() else {
        eprintln!("SKIP: no physical devices");
        return;
    };

    let queue_family = physical.find_queue_family(QueueFlags::TRANSFER).unwrap();
    let device = physical
        .create_device(DeviceCreateInfo {
            queue_create_infos: &[QueueCreateInfo {
                queue_family_index: queue_family,
                queue_priorities: vec![1.0],
            }],
            ..Default::default()
        })
        .unwrap();
    let queue = device.get_queue(queue_family, 0);

    let buffer = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 64,
            usage: BufferUsage::TRANSFER_DST,
        },
    )
    .unwrap();

    let req = buffer.memory_requirements();
    let mem_type = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let mut memory = DeviceMemory::allocate(&device, req.size, mem_type).unwrap();
    buffer.bind_memory(&memory, 0).unwrap();

    // Pre-write so we can verify the GPU overwrote.
    {
        let mut m = memory.map().unwrap();
        m.as_slice_mut().fill(0);
    }

    // Record a fill command.
    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = pool.allocate_primary().unwrap();
    {
        let mut rec = cmd.begin().unwrap();
        rec.fill_buffer(&buffer, 0, 64, 0xCAFEBABE);
        rec.end().unwrap();
    }

    // Submit with a fence and wait.
    let fence = Fence::new(&device).unwrap();
    queue.submit(&[&cmd], Some(&fence)).unwrap();
    fence.wait(u64::MAX).unwrap();

    // Verify the GPU did the write.
    {
        let mapped = memory.map().unwrap();
        let slice = mapped.as_slice();
        let expected: [u8; 4] = 0xCAFEBABEu32.to_ne_bytes();
        for chunk in slice.chunks_exact(4) {
            assert_eq!(chunk, expected, "GPU did not write expected pattern");
        }
    }

    // Everything drops here in the correct order.
}

#[test]
fn test_api_version_encoding() {
    // ApiVersion bit-packing must match the C macro VK_MAKE_API_VERSION exactly.
    let v = ApiVersion::new(0, 1, 3, 250);
    assert_eq!(v.major(), 1);
    assert_eq!(v.minor(), 3);
    assert_eq!(v.patch(), 250);

    let v0 = ApiVersion::V1_0;
    assert_eq!(v0.major(), 1);
    assert_eq!(v0.minor(), 0);
    assert_eq!(v0.patch(), 0);
}

#[test]
fn test_queue_flags_bitor_and_contains() {
    let combined = QueueFlags::GRAPHICS | QueueFlags::COMPUTE;
    assert!(combined.contains(QueueFlags::GRAPHICS));
    assert!(combined.contains(QueueFlags::COMPUTE));
    assert!(!combined.contains(QueueFlags::TRANSFER));
}

#[test]
fn test_memory_property_flags_bitor() {
    let f = MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT;
    assert!(f.contains(MemoryPropertyFlags::HOST_VISIBLE));
    assert!(f.contains(MemoryPropertyFlags::HOST_COHERENT));
    assert!(!f.contains(MemoryPropertyFlags::DEVICE_LOCAL));
}

#[test]
fn test_buffer_usage_bitor() {
    let u = BufferUsage::TRANSFER_DST | BufferUsage::STORAGE_BUFFER;
    assert!(u.contains(BufferUsage::TRANSFER_DST));
    assert!(u.contains(BufferUsage::STORAGE_BUFFER));
    assert!(!u.contains(BufferUsage::TRANSFER_SRC));
}

#[test]
fn test_shader_module_from_spirv_bytes() {
    let instance = match Instance::new(InstanceCreateInfo::default()) {
        Ok(i) => i,
        Err(_) => return,
    };
    let physicals = instance.enumerate_physical_devices().unwrap();
    let Some(physical) = physicals.first().cloned() else {
        return;
    };
    let queue_family = physical.find_queue_family(QueueFlags::COMPUTE).unwrap();
    let device = physical
        .create_device(DeviceCreateInfo {
            queue_create_infos: &[QueueCreateInfo {
                queue_family_index: queue_family,
                queue_priorities: vec![1.0],
            }],
            ..Default::default()
        })
        .unwrap();

    // Load the pre-compiled SPIR-V from disk and create a shader module.
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let spv = std::fs::read(format!("{manifest_dir}/examples/shaders/square_buffer.spv"))
        .expect("pre-compiled square_buffer.spv must exist (run compile_shader example)");

    let shader = ShaderModule::from_spirv_bytes(&device, &spv)
        .expect("ShaderModule::from_spirv_bytes should succeed for valid SPIR-V");
    assert!(shader.raw() != 0);
}

#[test]
fn test_compute_pipeline_full_dispatch() {
    // End-to-end compute test: same as the compute_square example, in test form.
    let instance = match Instance::new(InstanceCreateInfo::default()) {
        Ok(i) => i,
        Err(_) => return,
    };
    let physicals = instance.enumerate_physical_devices().unwrap();
    let Some(physical) = physicals.first().cloned() else {
        return;
    };

    let queue_family = match physical.find_queue_family(QueueFlags::COMPUTE) {
        Some(q) => q,
        None => return,
    };
    let device = physical
        .create_device(DeviceCreateInfo {
            queue_create_infos: &[QueueCreateInfo {
                queue_family_index: queue_family,
                queue_priorities: vec![1.0],
            }],
            ..Default::default()
        })
        .unwrap();
    let queue = device.get_queue(queue_family, 0);

    // Storage buffer with 64 u32s = 256 bytes
    const N: u32 = 64;
    const SIZE: u64 = (N as u64) * 4;
    let buffer = Buffer::new(
        &device,
        BufferCreateInfo {
            size: SIZE,
            usage: BufferUsage::STORAGE_BUFFER,
        },
    )
    .unwrap();
    let req = buffer.memory_requirements();
    let mt = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let mut memory = DeviceMemory::allocate(&device, req.size, mt).unwrap();
    buffer.bind_memory(&memory, 0).unwrap();

    // Initial values: 0..64
    {
        let mut m = memory.map().unwrap();
        let bytes = m.as_slice_mut();
        for i in 0..N as usize {
            let v = i as u32;
            bytes[i * 4..(i + 1) * 4].copy_from_slice(&v.to_le_bytes());
        }
    }

    // Load shader
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let spv = std::fs::read(format!("{manifest_dir}/examples/shaders/square_buffer.spv")).unwrap();
    let shader = ShaderModule::from_spirv_bytes(&device, &spv).unwrap();

    // Descriptor layout/pool/set
    let set_layout = DescriptorSetLayout::new(
        &device,
        &[DescriptorSetLayoutBinding {
            binding: 0,
            descriptor_type: DescriptorType::STORAGE_BUFFER,
            descriptor_count: 1,
            stage_flags: ShaderStageFlags::COMPUTE,
        }],
    )
    .unwrap();
    let pool = DescriptorPool::new(
        &device,
        1,
        &[DescriptorPoolSize {
            descriptor_type: DescriptorType::STORAGE_BUFFER,
            descriptor_count: 1,
        }],
    )
    .unwrap();
    let dset = pool.allocate(&set_layout).unwrap();
    dset.write_buffer(0, DescriptorType::STORAGE_BUFFER, &buffer, 0, SIZE);

    // Pipeline
    let pipeline_layout = PipelineLayout::new(&device, &[&set_layout]).unwrap();
    let pipeline = ComputePipeline::new(&device, &pipeline_layout, &shader, "main").unwrap();

    // Record + submit
    let cmd_pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = cmd_pool.allocate_primary().unwrap();
    {
        let mut rec = cmd.begin().unwrap();
        rec.bind_compute_pipeline(&pipeline);
        rec.bind_compute_descriptor_sets(&pipeline_layout, 0, &[&dset]);
        rec.dispatch(N.div_ceil(64), 1, 1);
        // Compute -> Host barrier (compute_shader_bit -> host_bit, shader_write -> host_read)
        rec.memory_barrier(
            PipelineStage::COMPUTE_SHADER,
            PipelineStage::HOST,
            AccessFlags::SHADER_WRITE,
            AccessFlags::HOST_READ,
        );
        rec.end().unwrap();
    }
    let fence = Fence::new(&device).unwrap();
    queue.submit(&[&cmd], Some(&fence)).unwrap();
    fence.wait(u64::MAX).unwrap();

    // Verify
    {
        let m = memory.map().unwrap();
        let bytes = m.as_slice();
        for i in 0..N as usize {
            let read = u32::from_le_bytes([
                bytes[i * 4],
                bytes[i * 4 + 1],
                bytes[i * 4 + 2],
                bytes[i * 4 + 3],
            ]);
            let expected = (i as u32).wrapping_mul(i as u32);
            assert_eq!(read, expected, "element {i}: GPU did not square correctly");
        }
    }
}

// ---------------------------------------------------------------------------
// New tests for push constants, specialization constants, copy_buffer,
// dispatch_indirect, query pools, async-compute helpers, and UBO descriptors.
// ---------------------------------------------------------------------------

/// Helper: try to spin up a (instance, physical, device, queue, queue_family).
/// Returns None if no Vulkan ICD is available so tests can skip cleanly.
fn try_init_compute() -> Option<(
    Instance,
    vulkane::safe::PhysicalDevice,
    vulkane::safe::Device,
    vulkane::safe::Queue,
    u32,
)> {
    let instance = Instance::new(InstanceCreateInfo::default()).ok()?;
    let physical = instance
        .enumerate_physical_devices()
        .ok()?
        .into_iter()
        .next()?;
    let queue_family = physical.find_queue_family(QueueFlags::COMPUTE)?;
    let device = physical
        .create_device(DeviceCreateInfo {
            queue_create_infos: &[QueueCreateInfo {
                queue_family_index: queue_family,
                queue_priorities: vec![1.0],
            }],
            ..Default::default()
        })
        .ok()?;
    let queue = device.get_queue(queue_family, 0);
    Some((instance, physical, device, queue, queue_family))
}

#[test]
fn test_specialization_constants_builder() {
    // Pure host-side test of the SpecializationConstants builder. Validates
    // that map entries and the data block are laid out correctly without
    // needing a Vulkan ICD.
    let specs = SpecializationConstants::new()
        .add_u32(0, 0xDEADBEEF)
        .add_i32(1, -1)
        .add_f32(2, 1.5)
        .add_bool(3, true);

    assert_eq!(specs.len(), 4);
    assert!(!specs.is_empty());

    // The empty case
    let empty = SpecializationConstants::new();
    assert!(empty.is_empty());
    assert_eq!(empty.len(), 0);
}

#[test]
fn test_pipeline_statistics_flags_count() {
    let f = PipelineStatisticsFlags::COMPUTE_SHADER_INVOCATIONS
        | PipelineStatisticsFlags::INPUT_ASSEMBLY_VERTICES;
    assert_eq!(f.count(), 2);
    assert!(f.contains(PipelineStatisticsFlags::COMPUTE_SHADER_INVOCATIONS));
    assert!(!f.contains(PipelineStatisticsFlags::FRAGMENT_SHADER_INVOCATIONS));

    assert_eq!(PipelineStatisticsFlags::NONE.count(), 0);
}

#[test]
fn test_buffer_copy_struct() {
    // Trivial constructor sanity check — BufferCopy is a public POD.
    let r = BufferCopy {
        src_offset: 16,
        dst_offset: 32,
        size: 64,
    };
    assert_eq!(r.src_offset, 16);
    assert_eq!(r.dst_offset, 32);
    assert_eq!(r.size, 64);
}

#[test]
fn test_async_compute_queue_helper_returns_compute_capable() {
    let Some((_inst, physical, _dev, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    // Whatever the helper returns must support COMPUTE.
    let q = physical
        .find_dedicated_compute_queue()
        .expect("any compute device exposes a compute queue");
    let families = physical.queue_family_properties();
    assert!(
        families[q as usize]
            .queue_flags()
            .contains(QueueFlags::COMPUTE)
    );

    // The transfer-dedicated helper should also return a transfer-capable
    // family if it returns anything.
    if let Some(t) = physical.find_dedicated_transfer_queue() {
        assert!(
            families[t as usize]
                .queue_flags()
                .contains(QueueFlags::TRANSFER)
        );
    }
}

#[test]
fn test_timestamp_period_is_nonneg() {
    let Some((_inst, physical, _dev, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    // Should be a finite, non-negative number on any conformant device.
    let p = physical.timestamp_period();
    assert!(p.is_finite());
    assert!(p >= 0.0);
}

#[test]
fn test_max_push_constants_size_meets_spec_minimum() {
    let Some((_inst, physical, _dev, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    // Vulkan spec guarantees at least 128 bytes.
    let max = physical.properties().max_push_constants_size();
    assert!(max >= 128, "spec minimum is 128 bytes, got {max}");
}

#[test]
fn test_pipeline_layout_with_push_constants() {
    let Some((_inst, _physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    let set_layout = DescriptorSetLayout::new(
        &device,
        &[DescriptorSetLayoutBinding {
            binding: 0,
            descriptor_type: DescriptorType::STORAGE_BUFFER,
            descriptor_count: 1,
            stage_flags: ShaderStageFlags::COMPUTE,
        }],
    )
    .unwrap();

    let pcr = PushConstantRange {
        stage_flags: ShaderStageFlags::COMPUTE,
        offset: 0,
        size: 16,
    };

    // Both no-PCR and with-PCR variants must succeed.
    let layout_no = PipelineLayout::new(&device, &[&set_layout]).unwrap();
    let layout_pc = PipelineLayout::with_push_constants(&device, &[&set_layout], &[pcr]).unwrap();

    assert!(layout_no.raw() != 0);
    assert!(layout_pc.raw() != 0);
    assert!(layout_no.raw() != layout_pc.raw());
}

#[test]
fn test_query_pool_timestamp_creation_and_metadata() {
    let Some((_inst, physical, device, _q, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    // Skip if the chosen queue family doesn't support timestamps.
    let families = physical.queue_family_properties();
    if families[queue_family as usize].timestamp_valid_bits() == 0 {
        eprintln!("SKIP: queue family does not support timestamps");
        return;
    }

    let pool = QueryPool::timestamps(&device, 4).unwrap();
    assert_eq!(pool.query_count(), 4);
    assert!(pool.raw() != 0);
}

#[test]
fn test_copy_buffer_staging_round_trip() {
    let Some((_inst, physical, device, queue, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    // Source buffer: HOST_VISIBLE, TRANSFER_SRC.
    let src = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 256,
            usage: BufferUsage::TRANSFER_SRC,
        },
    )
    .unwrap();
    let src_req = src.memory_requirements();
    let src_mt = physical
        .find_memory_type(
            src_req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let mut src_mem = DeviceMemory::allocate(&device, src_req.size, src_mt).unwrap();
    src.bind_memory(&src_mem, 0).unwrap();

    // Pre-fill src with a pattern from the host.
    {
        let mut m = src_mem.map().unwrap();
        let bytes = m.as_slice_mut();
        for (i, b) in bytes.iter_mut().enumerate() {
            *b = (i * 3 + 1) as u8;
        }
    }

    // Destination buffer: HOST_VISIBLE (so we can read it back), TRANSFER_DST.
    let dst = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 256,
            usage: BufferUsage::TRANSFER_DST,
        },
    )
    .unwrap();
    let dst_req = dst.memory_requirements();
    let dst_mt = physical
        .find_memory_type(
            dst_req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let mut dst_mem = DeviceMemory::allocate(&device, dst_req.size, dst_mt).unwrap();
    dst.bind_memory(&dst_mem, 0).unwrap();

    // Zero out dst so we can detect that the copy actually happened.
    {
        let mut m = dst_mem.map().unwrap();
        m.as_slice_mut().fill(0);
    }

    // Record copy_buffer + memory barrier so the host read sees it.
    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = pool.allocate_primary().unwrap();
    {
        let mut rec = cmd.begin().unwrap();
        rec.copy_buffer(
            &src,
            &dst,
            &[BufferCopy {
                src_offset: 0,
                dst_offset: 0,
                size: 256,
            }],
        );
        // Transfer -> Host (transfer_bit -> host_bit, transfer_write -> host_read)
        rec.memory_barrier(
            PipelineStage::TRANSFER,
            PipelineStage::HOST,
            AccessFlags::TRANSFER_READ,
            AccessFlags::HOST_READ,
        );
        rec.end().unwrap();
    }

    let fence = Fence::new(&device).unwrap();
    queue.submit(&[&cmd], Some(&fence)).unwrap();
    fence.wait(u64::MAX).unwrap();

    // Verify the bytes were copied.
    {
        let m = dst_mem.map().unwrap();
        let bytes = m.as_slice();
        for (i, &b) in bytes.iter().enumerate() {
            assert_eq!(b, (i * 3 + 1) as u8, "byte {i} not copied correctly");
        }
    }
}

#[test]
fn test_dispatch_indirect_with_explicit_count() {
    // Build an indirect-dispatch test using the existing square_buffer
    // shader: write x=4, y=1, z=1 into an INDIRECT_BUFFER and dispatch 256
    // elements = 4 workgroups of 64.
    let Some((_inst, physical, device, queue, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    // Storage buffer.
    const N: u32 = 256;
    const SIZE: u64 = (N as u64) * 4;
    let buffer = Buffer::new(
        &device,
        BufferCreateInfo {
            size: SIZE,
            usage: BufferUsage::STORAGE_BUFFER,
        },
    )
    .unwrap();
    let req = buffer.memory_requirements();
    let mt = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let mut memory = DeviceMemory::allocate(&device, req.size, mt).unwrap();
    buffer.bind_memory(&memory, 0).unwrap();

    // Initialize with 0..256.
    {
        let mut m = memory.map().unwrap();
        let bytes = m.as_slice_mut();
        for i in 0..N as usize {
            let v = i as u32;
            bytes[i * 4..(i + 1) * 4].copy_from_slice(&v.to_le_bytes());
        }
    }

    // Indirect-dispatch buffer (3 u32s = 12 bytes).
    let indirect = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 16,
            usage: BufferUsage::INDIRECT_BUFFER,
        },
    )
    .unwrap();
    let ireq = indirect.memory_requirements();
    let imt = physical
        .find_memory_type(
            ireq.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let mut imem = DeviceMemory::allocate(&device, ireq.size, imt).unwrap();
    indirect.bind_memory(&imem, 0).unwrap();
    {
        let mut m = imem.map().unwrap();
        let b = m.as_slice_mut();
        // x=4, y=1, z=1 (workgroup counts; local_size is 64 in the shader)
        b[0..4].copy_from_slice(&4u32.to_le_bytes());
        b[4..8].copy_from_slice(&1u32.to_le_bytes());
        b[8..12].copy_from_slice(&1u32.to_le_bytes());
    }

    // Load the existing pre-compiled shader.
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let spv = std::fs::read(format!("{manifest_dir}/examples/shaders/square_buffer.spv")).unwrap();
    let shader = ShaderModule::from_spirv_bytes(&device, &spv).unwrap();

    let set_layout = DescriptorSetLayout::new(
        &device,
        &[DescriptorSetLayoutBinding {
            binding: 0,
            descriptor_type: DescriptorType::STORAGE_BUFFER,
            descriptor_count: 1,
            stage_flags: ShaderStageFlags::COMPUTE,
        }],
    )
    .unwrap();
    let dpool = DescriptorPool::new(
        &device,
        1,
        &[DescriptorPoolSize {
            descriptor_type: DescriptorType::STORAGE_BUFFER,
            descriptor_count: 1,
        }],
    )
    .unwrap();
    let dset = dpool.allocate(&set_layout).unwrap();
    dset.write_buffer(0, DescriptorType::STORAGE_BUFFER, &buffer, 0, SIZE);

    let pipeline_layout = PipelineLayout::new(&device, &[&set_layout]).unwrap();
    let pipeline = ComputePipeline::new(&device, &pipeline_layout, &shader, "main").unwrap();

    let cmd_pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = cmd_pool.allocate_primary().unwrap();
    {
        let mut rec = cmd.begin().unwrap();
        rec.bind_compute_pipeline(&pipeline);
        rec.bind_compute_descriptor_sets(&pipeline_layout, 0, &[&dset]);
        rec.dispatch_indirect(&indirect, 0);
        // Compute -> Host
        rec.memory_barrier(
            PipelineStage::COMPUTE_SHADER,
            PipelineStage::HOST,
            AccessFlags::SHADER_WRITE,
            AccessFlags::HOST_READ,
        );
        rec.end().unwrap();
    }
    let fence = Fence::new(&device).unwrap();
    queue.submit(&[&cmd], Some(&fence)).unwrap();
    fence.wait(u64::MAX).unwrap();

    // Verify squaring happened to all 256 elements.
    {
        let m = memory.map().unwrap();
        let bytes = m.as_slice();
        for i in 0..N as usize {
            let read = u32::from_le_bytes([
                bytes[i * 4],
                bytes[i * 4 + 1],
                bytes[i * 4 + 2],
                bytes[i * 4 + 3],
            ]);
            assert_eq!(
                read,
                (i as u32).wrapping_mul(i as u32),
                "indirect dispatch did not square element {i}"
            );
        }
    }
}

#[test]
fn test_query_pool_records_timestamp_around_dispatch() {
    let Some((_inst, physical, device, queue, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let families = physical.queue_family_properties();
    if families[queue_family as usize].timestamp_valid_bits() == 0 {
        eprintln!("SKIP: queue family does not support timestamps");
        return;
    }

    // Reuse compute_square setup.
    const N: u32 = 64;
    const SIZE: u64 = (N as u64) * 4;
    let buffer = Buffer::new(
        &device,
        BufferCreateInfo {
            size: SIZE,
            usage: BufferUsage::STORAGE_BUFFER,
        },
    )
    .unwrap();
    let req = buffer.memory_requirements();
    let mt = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let mut memory = DeviceMemory::allocate(&device, req.size, mt).unwrap();
    buffer.bind_memory(&memory, 0).unwrap();
    {
        let mut m = memory.map().unwrap();
        let b = m.as_slice_mut();
        for i in 0..N as usize {
            b[i * 4..(i + 1) * 4].copy_from_slice(&(i as u32).to_le_bytes());
        }
    }

    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let spv = std::fs::read(format!("{manifest_dir}/examples/shaders/square_buffer.spv")).unwrap();
    let shader = ShaderModule::from_spirv_bytes(&device, &spv).unwrap();

    let set_layout = DescriptorSetLayout::new(
        &device,
        &[DescriptorSetLayoutBinding {
            binding: 0,
            descriptor_type: DescriptorType::STORAGE_BUFFER,
            descriptor_count: 1,
            stage_flags: ShaderStageFlags::COMPUTE,
        }],
    )
    .unwrap();
    let dpool = DescriptorPool::new(
        &device,
        1,
        &[DescriptorPoolSize {
            descriptor_type: DescriptorType::STORAGE_BUFFER,
            descriptor_count: 1,
        }],
    )
    .unwrap();
    let dset = dpool.allocate(&set_layout).unwrap();
    dset.write_buffer(0, DescriptorType::STORAGE_BUFFER, &buffer, 0, SIZE);

    let pl = PipelineLayout::new(&device, &[&set_layout]).unwrap();
    let pipe = ComputePipeline::new(&device, &pl, &shader, "main").unwrap();

    // Two timestamps: before and after the dispatch.
    let qpool = QueryPool::timestamps(&device, 2).unwrap();

    let cmd_pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = cmd_pool.allocate_primary().unwrap();
    {
        let mut rec = cmd.begin().unwrap();
        // Reset is required before any timestamp can be written.
        rec.reset_query_pool(&qpool, 0, 2);
        rec.write_timestamp(PipelineStage::TOP_OF_PIPE, &qpool, 0);
        rec.bind_compute_pipeline(&pipe);
        rec.bind_compute_descriptor_sets(&pl, 0, &[&dset]);
        rec.dispatch(N.div_ceil(64), 1, 1);
        rec.write_timestamp(PipelineStage::BOTTOM_OF_PIPE, &qpool, 1);
        // Compute -> Host
        rec.memory_barrier(
            PipelineStage::COMPUTE_SHADER,
            PipelineStage::HOST,
            AccessFlags::SHADER_WRITE,
            AccessFlags::HOST_READ,
        );
        rec.end().unwrap();
    }
    let fence = Fence::new(&device).unwrap();
    queue.submit(&[&cmd], Some(&fence)).unwrap();
    fence.wait(u64::MAX).unwrap();

    // Read timestamps.
    let times = qpool.get_results_u64(0, 2).unwrap();
    assert_eq!(times.len(), 2);
    // We can't reliably assert times[1] > times[0] on every implementation
    // (Lavapipe in particular sometimes reports them equal for trivial work),
    // but we *can* assert they were both written: get_results_u64 with the
    // WAIT bit set returns success only when every requested query completed.
    // Sanity-check that the GPU actually did the squaring as well.
    {
        let m = memory.map().unwrap();
        let b = m.as_slice();
        for i in 0..N as usize {
            let v = u32::from_le_bytes([b[i * 4], b[i * 4 + 1], b[i * 4 + 2], b[i * 4 + 3]]);
            assert_eq!(v, (i as u32).wrapping_mul(i as u32));
        }
    }

    // Bonus: convert the delta to nanoseconds with timestamp_period and
    // verify it's a finite number (not NaN/Inf).
    let period = physical.timestamp_period();
    let delta_ticks = times[1].wrapping_sub(times[0]) as f64;
    let delta_ns = delta_ticks * (period as f64);
    assert!(delta_ns.is_finite());
}

#[test]
fn test_uniform_buffer_descriptor_round_trip() {
    // Verify that UNIFORM_BUFFER descriptors work end-to-end. We don't run
    // a shader here — just create the descriptor layout, pool, set, and
    // call write_buffer with UNIFORM_BUFFER. If the driver accepted the
    // write, the descriptor wiring is correct. (A shader-using UBO test
    // would need a second pre-compiled SPIR-V shader; this is sufficient
    // to validate the safe wrapper plumbing.)
    let Some((_inst, physical, device, _queue, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    // Create a small uniform buffer.
    let buffer = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 64,
            usage: BufferUsage::UNIFORM_BUFFER,
        },
    )
    .unwrap();
    let req = buffer.memory_requirements();
    let mt = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let memory = DeviceMemory::allocate(&device, req.size, mt).unwrap();
    buffer.bind_memory(&memory, 0).unwrap();

    let set_layout = DescriptorSetLayout::new(
        &device,
        &[DescriptorSetLayoutBinding {
            binding: 0,
            descriptor_type: DescriptorType::UNIFORM_BUFFER,
            descriptor_count: 1,
            stage_flags: ShaderStageFlags::COMPUTE,
        }],
    )
    .unwrap();
    let pool = DescriptorPool::new(
        &device,
        1,
        &[DescriptorPoolSize {
            descriptor_type: DescriptorType::UNIFORM_BUFFER,
            descriptor_count: 1,
        }],
    )
    .unwrap();
    let dset = pool.allocate(&set_layout).unwrap();
    dset.write_buffer(0, DescriptorType::UNIFORM_BUFFER, &buffer, 0, 64);
    assert!(dset.raw() != 0);
}

// ---------------------------------------------------------------------------
// Validation layer + debug utils + extension/layer enable lists tests
// ---------------------------------------------------------------------------

#[test]
fn test_debug_message_severity_label_and_bits() {
    assert_eq!(DebugMessageSeverity::ERROR.label(), "ERROR");
    assert_eq!(DebugMessageSeverity::WARNING.label(), "WARN");
    assert_eq!(DebugMessageSeverity::INFO.label(), "INFO");
    assert_eq!(DebugMessageSeverity::VERBOSE.label(), "VERBOSE");

    let combined = DebugMessageSeverity::WARNING_AND_ABOVE;
    assert!(combined.contains(DebugMessageSeverity::ERROR));
    assert!(combined.contains(DebugMessageSeverity::WARNING));
    assert!(!combined.contains(DebugMessageSeverity::INFO));

    let all = DebugMessageSeverity::ALL;
    assert!(all.contains(DebugMessageSeverity::VERBOSE));
    assert!(all.contains(DebugMessageSeverity::ERROR));
}

#[test]
fn test_enumerate_layer_properties_succeeds_or_skips() {
    let layers = match Instance::enumerate_layer_properties() {
        Ok(l) => l,
        Err(e) => {
            eprintln!("SKIP: cannot load Vulkan library: {e}");
            return;
        }
    };
    // The list MAY be empty on some systems (no layers installed).
    // We just assert that every entry has a non-empty name when present.
    for l in &layers {
        let n = l.name();
        assert!(!n.is_empty(), "layer name should not be empty");
        // spec_version should be a valid api version (major >= 1).
        assert!(l.spec_version().major() >= 1);
    }
    println!("Found {} instance layer(s)", layers.len());
}

#[test]
fn test_enumerate_instance_extension_properties() {
    let exts = match Instance::enumerate_extension_properties() {
        Ok(e) => e,
        Err(e) => {
            eprintln!("SKIP: cannot load Vulkan library: {e}");
            return;
        }
    };
    // Conformant Vulkan implementations always expose at least one
    // instance extension (VK_KHR_get_physical_device_properties2 on
    // Vulkan 1.0 implementations, or many more on 1.1+).
    assert!(!exts.is_empty(), "expected at least one instance extension");
    for e in &exts {
        assert!(!e.name().is_empty());
    }
}

#[test]
fn test_physical_device_enumerate_extension_properties() {
    let Some((_inst, physical, _dev, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let exts = physical.enumerate_extension_properties().unwrap();
    // Lavapipe and every conformant ICD expose at least a handful of
    // device extensions; just assert names look sane.
    for e in &exts {
        assert!(!e.name().is_empty());
    }
}

#[test]
fn test_instance_with_no_layers_or_extensions() {
    // Building an instance with empty enable lists must succeed
    // (it's the default behaviour).
    let info = InstanceCreateInfo {
        application_name: Some("vulkane-empty-lists"),
        enabled_layers: &[],
        enabled_extensions: &[],
        ..InstanceCreateInfo::default()
    };
    if let Ok(_inst) = Instance::new(info) {
        // OK.
    } else {
        eprintln!("SKIP: no Vulkan ICD");
    }
}

#[test]
fn test_instance_with_unknown_layer_fails_cleanly() {
    let info = InstanceCreateInfo {
        application_name: Some("vulkane-bad-layer"),
        enabled_layers: &["VK_LAYER_THIS_DOES_NOT_EXIST_zzz"],
        ..InstanceCreateInfo::default()
    };
    let result = Instance::new(info);
    // We can't be sure no Vulkan ICD is present here. If the loader is
    // present we expect ERROR_LAYER_NOT_PRESENT (or similar). If the
    // loader is missing entirely we get LibraryLoad — also acceptable.
    match result {
        Ok(_) => panic!("loader should not have accepted a fake layer"),
        Err(e) => {
            // Just print it; either Vk(LayerNotPresent) or LibraryLoad.
            eprintln!("OK: enabling fake layer rejected with: {e}");
        }
    }
}

#[test]
fn test_instance_with_validation_when_available() {
    // If the validation layer is installed and the debug-utils extension
    // is available, build an instance with the convenience constructor and
    // verify our callback fires when we trigger a validation error.
    let layers = match Instance::enumerate_layer_properties() {
        Ok(l) => l,
        Err(_) => {
            eprintln!("SKIP: no Vulkan loader");
            return;
        }
    };
    if !layers.iter().any(|l| l.name() == KHRONOS_VALIDATION_LAYER) {
        eprintln!("SKIP: validation layer not installed");
        return;
    }
    let exts = Instance::enumerate_extension_properties().unwrap();
    if !exts.iter().any(|e| e.name() == DEBUG_UTILS_EXTENSION) {
        eprintln!("SKIP: debug utils extension not present");
        return;
    }

    use std::sync::Arc as StdArc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    let counter = StdArc::new(AtomicUsize::new(0));
    let counter_cb = StdArc::clone(&counter);

    let info = InstanceCreateInfo {
        application_name: Some("vulkane-validation"),
        enabled_layers: &[KHRONOS_VALIDATION_LAYER],
        enabled_extensions: &[DEBUG_UTILS_EXTENSION],
        debug_callback: Some(Box::new(move |msg: &DebugMessage<'_>| {
            // Only count WARN/ERROR so we don't spam on every INFO.
            if msg.severity.contains(DebugMessageSeverity::WARNING)
                || msg.severity.contains(DebugMessageSeverity::ERROR)
            {
                counter_cb.fetch_add(1, Ordering::Relaxed);
            }
        })),
        ..InstanceCreateInfo::default()
    };

    let instance = match Instance::new(info) {
        Ok(i) => i,
        Err(e) => {
            eprintln!("SKIP: validation instance creation failed: {e}");
            return;
        }
    };

    // The act of *creating* the instance with VK_EXT_debug_utils enabled
    // is enough to assert the messenger plumbing is wired correctly. We
    // don't try to provoke a validation error here because trying to
    // misuse Vulkan from inside the safe wrapper requires Either dropping
    // to raw bindings (out of scope for this test) or relying on the
    // layer's own startup messages, which vary by version.
    //
    // Just touch the counter to silence the unused-Send warning and drop.
    let _ = counter.load(Ordering::Relaxed);
    drop(instance);
}

#[test]
fn test_instance_validation_constructor_when_available() {
    // The InstanceCreateInfo::validation() convenience should produce a
    // working instance when validation is available, or fail cleanly
    // otherwise. Either outcome is acceptable here — we just want to
    // verify the constructor path compiles and runs.
    let layers = Instance::enumerate_layer_properties().ok();
    let has_validation = layers
        .as_ref()
        .map(|ls| ls.iter().any(|l| l.name() == KHRONOS_VALIDATION_LAYER))
        .unwrap_or(false);

    if !has_validation {
        eprintln!("SKIP: validation layer not installed");
        return;
    }
    match Instance::new(InstanceCreateInfo::validation()) {
        Ok(_inst) => {}
        Err(e) => eprintln!("validation() constructor returned err: {e}"),
    }
}

// ---------------------------------------------------------------------------
// Image tests: 2D storage image creation, layout transitions, and a full
// buffer -> image -> compute -> image -> buffer round trip.
// ---------------------------------------------------------------------------

#[test]
fn test_image_usage_bitor_and_format_constants() {
    let usage = ImageUsage::STORAGE | ImageUsage::TRANSFER_DST | ImageUsage::TRANSFER_SRC;
    assert!(usage.contains(ImageUsage::STORAGE));
    assert!(usage.contains(ImageUsage::TRANSFER_DST));
    assert!(usage.contains(ImageUsage::TRANSFER_SRC));
    assert!(!usage.contains(ImageUsage::SAMPLED));

    // Format constants are just sanity checks that the wrapper exists.
    assert_ne!(Format::R8_UNORM, Format::R32_UINT);
    assert_ne!(ImageLayout::UNDEFINED, ImageLayout::GENERAL);
}

#[test]
fn test_buffer_image_copy_full_2d_helper() {
    let r = BufferImageCopy::full_2d(64, 32);
    assert_eq!(r.image_extent, [64, 32, 1]);
    assert_eq!(r.image_offset, [0, 0, 0]);
    assert_eq!(r.buffer_offset, 0);
    assert_eq!(r.buffer_row_length, 0);
    assert_eq!(r.buffer_image_height, 0);
}

#[test]
fn test_image_2d_creation_and_memory_binding() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    let image = Image::new_2d(
        &device,
        Image2dCreateInfo {
            format: Format::R32_UINT,
            width: 64,
            height: 64,
            usage: ImageUsage::STORAGE | ImageUsage::TRANSFER_DST | ImageUsage::TRANSFER_SRC,
        },
    )
    .unwrap();
    assert_eq!(image.format(), Format::R32_UINT);
    assert_eq!(image.width(), 64);
    assert_eq!(image.height(), 64);
    assert!(image.raw() != 0);

    let req = image.memory_requirements();
    assert!(req.size >= 64 * 64 * 4);
    assert!(req.alignment.is_power_of_two());

    // Try to find a device-local memory type. If unavailable, fall back to
    // host-visible (Lavapipe sometimes lacks DEVICE_LOCAL).
    let mt = physical
        .find_memory_type(req.memory_type_bits, MemoryPropertyFlags::DEVICE_LOCAL)
        .or_else(|| {
            physical.find_memory_type(req.memory_type_bits, MemoryPropertyFlags::HOST_VISIBLE)
        })
        .expect("some memory type should back the image");
    let memory = DeviceMemory::allocate(&device, req.size, mt).unwrap();
    image.bind_memory(&memory, 0).unwrap();

    // ImageView creation should also succeed.
    let view = ImageView::new_2d_color(&image).unwrap();
    assert!(view.raw() != 0);
}

#[test]
fn test_image_buffer_round_trip_via_layout_transitions() {
    // Validates: layout transitions, buffer -> image copy, image -> buffer
    // copy. We don't run a shader here — just verify that the bytes survive
    // a round trip through an image's storage on the GPU.
    let Some((_inst, physical, device, queue, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    const W: u32 = 16;
    const H: u32 = 16;
    const PIXEL_BYTES: u64 = 4; // R32_UINT
    const BUF_SIZE: u64 = (W as u64) * (H as u64) * PIXEL_BYTES;

    // Source staging buffer pre-filled from the host.
    let src = Buffer::new(
        &device,
        BufferCreateInfo {
            size: BUF_SIZE,
            usage: BufferUsage::TRANSFER_SRC,
        },
    )
    .unwrap();
    let src_req = src.memory_requirements();
    let src_mt = physical
        .find_memory_type(
            src_req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let mut src_mem = DeviceMemory::allocate(&device, src_req.size, src_mt).unwrap();
    src.bind_memory(&src_mem, 0).unwrap();
    {
        let mut m = src_mem.map().unwrap();
        let bytes = m.as_slice_mut();
        for i in 0..(W * H) as usize {
            let v = (i as u32).wrapping_mul(0x9E3779B1u32);
            bytes[i * 4..(i + 1) * 4].copy_from_slice(&v.to_le_bytes());
        }
    }

    // The image: STORAGE so it could be used for compute, TRANSFER_DST and
    // TRANSFER_SRC for the round trip.
    let image = Image::new_2d(
        &device,
        Image2dCreateInfo {
            format: Format::R32_UINT,
            width: W,
            height: H,
            usage: ImageUsage::STORAGE | ImageUsage::TRANSFER_DST | ImageUsage::TRANSFER_SRC,
        },
    )
    .unwrap();
    let img_req = image.memory_requirements();
    // Use the most-permissive memory type the driver allows.
    let img_mt = physical
        .find_memory_type(img_req.memory_type_bits, MemoryPropertyFlags::DEVICE_LOCAL)
        .or_else(|| {
            physical.find_memory_type(img_req.memory_type_bits, MemoryPropertyFlags::HOST_VISIBLE)
        })
        .expect("some memory type should back the image");
    let img_mem = DeviceMemory::allocate(&device, img_req.size, img_mt).unwrap();
    image.bind_memory(&img_mem, 0).unwrap();

    // Destination readback buffer.
    let dst = Buffer::new(
        &device,
        BufferCreateInfo {
            size: BUF_SIZE,
            usage: BufferUsage::TRANSFER_DST,
        },
    )
    .unwrap();
    let dst_req = dst.memory_requirements();
    let dst_mt = physical
        .find_memory_type(
            dst_req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();
    let mut dst_mem = DeviceMemory::allocate(&device, dst_req.size, dst_mt).unwrap();
    dst.bind_memory(&dst_mem, 0).unwrap();
    {
        // Zero so we can detect overwrite.
        let mut m = dst_mem.map().unwrap();
        m.as_slice_mut().fill(0);
    }

    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = pool.allocate_primary().unwrap();
    {
        let mut rec = cmd.begin().unwrap();
        // 1) UNDEFINED -> TRANSFER_DST_OPTIMAL
        rec.image_barrier(
            PipelineStage::TOP_OF_PIPE,
            PipelineStage::TRANSFER,
            ImageBarrier::color(&image, ImageLayout::UNDEFINED, ImageLayout::TRANSFER_DST_OPTIMAL, AccessFlags::NONE, AccessFlags::TRANSFER_WRITE),
        );
        // 2) Copy buffer -> image
        rec.copy_buffer_to_image(
            &src,
            &image,
            ImageLayout::TRANSFER_DST_OPTIMAL,
            &[BufferImageCopy::full_2d(W, H)],
        );
        // 3) TRANSFER_DST -> TRANSFER_SRC_OPTIMAL
        rec.image_barrier(
            PipelineStage::TRANSFER,
            PipelineStage::TRANSFER,
            ImageBarrier::color(&image, ImageLayout::TRANSFER_DST_OPTIMAL, ImageLayout::TRANSFER_SRC_OPTIMAL, AccessFlags::TRANSFER_WRITE, AccessFlags::TRANSFER_READ),
        );
        // 4) Copy image -> buffer
        rec.copy_image_to_buffer(
            &image,
            ImageLayout::TRANSFER_SRC_OPTIMAL,
            &dst,
            &[BufferImageCopy::full_2d(W, H)],
        );
        // 5) Transfer -> Host barrier so the host read sees the bytes.
        rec.memory_barrier(
            PipelineStage::TRANSFER,
            PipelineStage::HOST,
            AccessFlags::TRANSFER_WRITE,
            AccessFlags::HOST_READ,
        );
        rec.end().unwrap();
    }

    let fence = Fence::new(&device).unwrap();
    queue.submit(&[&cmd], Some(&fence)).unwrap();
    fence.wait(u64::MAX).unwrap();

    // Verify every pixel survived the round trip.
    {
        let m = dst_mem.map().unwrap();
        let b = m.as_slice();
        for i in 0..(W * H) as usize {
            let read = u32::from_le_bytes([b[i * 4], b[i * 4 + 1], b[i * 4 + 2], b[i * 4 + 3]]);
            let expected = (i as u32).wrapping_mul(0x9E3779B1u32);
            assert_eq!(read, expected, "pixel {i} did not survive image round trip");
        }
    }
}

#[test]
fn test_storage_image_descriptor_wiring() {
    // Validates that allocating a STORAGE_IMAGE descriptor and pointing it
    // at an ImageView round-trips through the safe wrapper without errors.
    // We don't dispatch a shader here — that would need a shipped .spv file.
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    let image = Image::new_2d(
        &device,
        Image2dCreateInfo {
            format: Format::R32_UINT,
            width: 8,
            height: 8,
            usage: ImageUsage::STORAGE,
        },
    )
    .unwrap();
    let req = image.memory_requirements();
    let mt = physical
        .find_memory_type(req.memory_type_bits, MemoryPropertyFlags::DEVICE_LOCAL)
        .or_else(|| {
            physical.find_memory_type(req.memory_type_bits, MemoryPropertyFlags::HOST_VISIBLE)
        })
        .unwrap();
    let memory = DeviceMemory::allocate(&device, req.size, mt).unwrap();
    image.bind_memory(&memory, 0).unwrap();
    let view = ImageView::new_2d_color(&image).unwrap();

    let set_layout = DescriptorSetLayout::new(
        &device,
        &[DescriptorSetLayoutBinding {
            binding: 0,
            descriptor_type: DescriptorType::STORAGE_IMAGE,
            descriptor_count: 1,
            stage_flags: ShaderStageFlags::COMPUTE,
        }],
    )
    .unwrap();
    let pool = DescriptorPool::new(
        &device,
        1,
        &[DescriptorPoolSize {
            descriptor_type: DescriptorType::STORAGE_IMAGE,
            descriptor_count: 1,
        }],
    )
    .unwrap();
    let dset = pool.allocate(&set_layout).unwrap();
    dset.write_storage_image(0, &view, ImageLayout::GENERAL);
    assert!(dset.raw() != 0);
}

// ---------------------------------------------------------------------------
// Timeline semaphore + binary semaphore + pipeline cache + sync2 tests
// ---------------------------------------------------------------------------

#[test]
fn test_binary_semaphore_creation_and_drop() {
    let Some((_inst, _physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let s = Semaphore::binary(&device).unwrap();
    assert_eq!(s.kind(), SemaphoreKind::Binary);
    assert!(s.raw() != 0);
}

#[test]
fn test_timeline_semaphore_host_signal_and_wait() {
    let Some((_inst, _physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    let sem = match Semaphore::timeline(&device, 5) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("SKIP: timeline semaphores not supported: {e}");
            return;
        }
    };
    assert_eq!(sem.kind(), SemaphoreKind::Timeline);

    // Initial value 5 should be readable.
    assert_eq!(sem.current_value().unwrap(), 5);

    // Signal to a higher value from the host.
    sem.signal_value(10).unwrap();
    assert_eq!(sem.current_value().unwrap(), 10);

    // wait_value should return immediately because the value is already >= 10.
    sem.wait_value(10, 0).unwrap();
}

#[test]
fn test_timeline_semaphore_gpu_signal_then_host_wait() {
    let Some((_inst, _physical, device, queue, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let sem = match Semaphore::timeline(&device, 0) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("SKIP: timeline semaphores not supported: {e}");
            return;
        }
    };

    // Submit an empty command buffer that signals the timeline to value 1.
    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = pool.allocate_primary().unwrap();
    {
        let rec = cmd.begin().unwrap();
        rec.end().unwrap();
    }
    queue
        .submit_with_sync(
            &[&cmd],
            &[],
            &[SignalSemaphore {
                semaphore: &sem,
                value: 1,
                device_index: 0,
            }],
            None,
        )
        .unwrap();

    // Wait on the host for the GPU to reach value 1.
    sem.wait_value(1, u64::MAX).unwrap();
    assert!(sem.current_value().unwrap() >= 1);
}

#[test]
fn test_timeline_semaphore_chained_dispatches() {
    // Two-pass compute: pass A signals timeline to 1, pass B waits on
    // value 1 before running. Validates that the safe wrapper threads the
    // wait/signal correctly through submit_with_sync.
    let Some((_inst, _physical, device, queue, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let sem = match Semaphore::timeline(&device, 0) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("SKIP: timeline semaphores not supported: {e}");
            return;
        }
    };

    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd_a = pool.allocate_primary().unwrap();
    {
        let rec = cmd_a.begin().unwrap();
        rec.end().unwrap();
    }
    let mut cmd_b = pool.allocate_primary().unwrap();
    {
        let rec = cmd_b.begin().unwrap();
        rec.end().unwrap();
    }

    // Pass A: signals timeline -> 1
    queue
        .submit_with_sync(
            &[&cmd_a],
            &[],
            &[SignalSemaphore {
                semaphore: &sem,
                value: 1,
                device_index: 0,
            }],
            None,
        )
        .unwrap();

    // Pass B: waits on timeline >= 1, signals -> 2.
    queue
        .submit_with_sync(
            &[&cmd_b],
            &[WaitSemaphore {
                semaphore: &sem,
                value: 1,
                dst_stage_mask: PipelineStage::TOP_OF_PIPE,
                device_index: 0,
            }],
            &[SignalSemaphore {
                semaphore: &sem,
                value: 2,
                device_index: 0,
            }],
            None,
        )
        .unwrap();

    // Wait for the whole chain on the host.
    sem.wait_value(2, u64::MAX).unwrap();
    assert!(sem.current_value().unwrap() >= 2);
}

#[test]
fn test_pipeline_cache_create_serialize_reuse() {
    let Some((_inst, _physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    // Create an empty cache, then serialize.
    let cache_a = PipelineCache::new(&device).unwrap();
    let bytes = cache_a.data().unwrap();
    // The cache header alone is non-empty on every conformant
    // implementation; if we got something, it should be at least the
    // 16-byte VkPipelineCacheHeaderVersionOne header. (Some software
    // implementations may return 0 for an empty cache; tolerate that
    // case.)
    println!("Pipeline cache (empty) -> {} bytes", bytes.len());

    // Now reuse those bytes when constructing a second cache.
    let cache_b = PipelineCache::with_data(&device, &bytes).unwrap();
    assert!(cache_b.raw() != 0);
}

#[test]
fn test_specialization_constants_baked_into_pipeline() {
    // Validate that ComputePipeline::with_specialization runs end-to-end
    // for a shader that doesn't actually consume any spec constants. The
    // build path is the same with or without populated entries; this just
    // exercises the code path that builds VkSpecializationInfo.
    let Some((_inst, _physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let spv = std::fs::read(format!("{manifest_dir}/examples/shaders/square_buffer.spv")).unwrap();
    let shader = ShaderModule::from_spirv_bytes(&device, &spv).unwrap();

    let set_layout = DescriptorSetLayout::new(
        &device,
        &[DescriptorSetLayoutBinding {
            binding: 0,
            descriptor_type: DescriptorType::STORAGE_BUFFER,
            descriptor_count: 1,
            stage_flags: ShaderStageFlags::COMPUTE,
        }],
    )
    .unwrap();
    let layout = PipelineLayout::new(&device, &[&set_layout]).unwrap();

    // The shader doesn't reference any spec constants, but Vulkan accepts
    // a non-empty SpecializationInfo with extra entries — they're simply
    // ignored. Verify the build path works.
    let specs = SpecializationConstants::new()
        .add_u32(99, 1234)
        .add_f32(100, 2.5);
    let pipe =
        ComputePipeline::with_specialization(&device, &layout, &shader, "main", &specs).unwrap();
    assert!(pipe.raw() != 0);
}

#[test]
fn test_sync2_memory_barrier_when_supported() {
    let Some((_inst, _physical, device, queue, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };

    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = pool.allocate_primary().unwrap();
    let supported = {
        let mut rec = cmd.begin().unwrap();
        let s2 = rec.memory_barrier2(
            PipelineStage2::COMPUTE_SHADER,
            PipelineStage2::HOST,
            AccessFlags2::SHADER_WRITE,
            AccessFlags2::HOST_READ,
        );
        rec.end().unwrap();
        s2
    };
    match supported {
        Ok(()) => {
            // Sync2 supported — submit and verify completion.
            let fence = Fence::new(&device).unwrap();
            queue.submit(&[&cmd], Some(&fence)).unwrap();
            fence.wait(u64::MAX).unwrap();
        }
        Err(e) => {
            eprintln!("SKIP: sync2 not supported: {e}");
        }
    }
}

// ---------------------------------------------------------------------------
// Sub-allocator (Allocator) integration tests
// ---------------------------------------------------------------------------

#[test]
fn test_allocator_creation_and_statistics_start_zero() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let alloc = Allocator::new(&device, &physical).unwrap();
    let stats = alloc.statistics();
    assert_eq!(stats.allocation_bytes, 0);
    assert_eq!(stats.allocation_count, 0);
    assert_eq!(stats.block_bytes, 0);
    assert_eq!(stats.block_count, 0);
}

#[test]
fn test_allocator_create_buffer_pool_path() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    let (buffer, allocation) = allocator
        .create_buffer(
            BufferCreateInfo {
                size: 4096,
                usage: BufferUsage::STORAGE_BUFFER,
            },
            AllocationCreateInfo {
                usage: AllocationUsage::HostVisible,
                ..Default::default()
            },
        )
        .unwrap();

    assert!(allocation.size() >= 4096);
    assert!(allocation.memory() != 0);

    let stats = allocator.statistics();
    assert_eq!(stats.allocation_count, 1);
    assert!(stats.allocation_bytes >= 4096);
    assert!(stats.block_count >= 1);

    allocator.free(allocation);
    drop(buffer);

    let stats = allocator.statistics();
    assert_eq!(stats.allocation_count, 0);
    assert_eq!(stats.allocation_bytes, 0);
    // Block stays around — pool keeps the underlying VkDeviceMemory until
    // the Allocator drops.
    assert!(stats.block_count >= 1);
}

#[test]
fn test_allocator_many_buffers_share_one_block() {
    // Allocating many small buffers should reuse the same underlying
    // VkDeviceMemory block — the whole point of sub-allocation.
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    let mut buffers = Vec::new();
    let mut allocations = Vec::new();
    let mut last_memory_handle = 0u64;
    let mut shared_count = 0u32;
    for _ in 0..32 {
        let (b, a) = allocator
            .create_buffer(
                BufferCreateInfo {
                    size: 1024,
                    usage: BufferUsage::STORAGE_BUFFER,
                },
                AllocationCreateInfo {
                    usage: AllocationUsage::HostVisible,
                    ..Default::default()
                },
            )
            .unwrap();
        if a.memory() == last_memory_handle {
            shared_count += 1;
        }
        last_memory_handle = a.memory();
        buffers.push(b);
        allocations.push(a);
    }

    // Most buffers should share the same VkDeviceMemory.
    assert!(
        shared_count >= 28,
        "expected at least 28 shared, got {shared_count}"
    );

    let stats = allocator.statistics();
    assert_eq!(stats.allocation_count, 32);
    // We should have only one block for all 32 small allocations.
    assert!(
        stats.block_count <= 2,
        "expected <=2 blocks for 32 small allocations, got {}",
        stats.block_count
    );

    for a in allocations.drain(..) {
        allocator.free(a);
    }
    drop(buffers);
}

#[test]
fn test_allocator_dedicated_for_huge_buffer() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    // Force the dedicated path with the explicit flag.
    let (buffer, alloc) = allocator
        .create_buffer(
            BufferCreateInfo {
                size: 4096,
                usage: BufferUsage::STORAGE_BUFFER,
            },
            AllocationCreateInfo {
                usage: AllocationUsage::HostVisible,
                dedicated: true,
                ..Default::default()
            },
        )
        .unwrap();
    assert_eq!(alloc.offset(), 0);

    let stats = allocator.statistics();
    assert_eq!(stats.dedicated_allocation_count, 1);

    allocator.free(alloc);
    drop(buffer);
    let stats = allocator.statistics();
    assert_eq!(stats.dedicated_allocation_count, 0);
}

#[test]
fn test_allocator_per_allocation_device_mask_forces_dedicated() {
    // Even on a single-device group, supplying device_mask = Some(mask)
    // must force the dedicated path (so the chained
    // VkMemoryAllocateFlagsInfo with VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT
    // is honored). On a single-device group the only valid mask is 0b1,
    // which is what default_device_mask() returns.
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();
    let mask = device.default_device_mask();

    let stats_before = allocator.statistics();

    let (buffer, alloc) = allocator
        .create_buffer(
            BufferCreateInfo {
                size: 4096,
                usage: BufferUsage::STORAGE_BUFFER,
            },
            AllocationCreateInfo {
                usage: AllocationUsage::DeviceLocal,
                device_mask: Some(mask),
                ..Default::default()
            },
        )
        .unwrap();

    let stats = allocator.statistics();
    assert_eq!(
        stats.dedicated_allocation_count,
        stats_before.dedicated_allocation_count + 1,
        "device_mask=Some(_) must force a dedicated allocation"
    );
    // A dedicated allocation always sits at offset 0 in its own VkDeviceMemory.
    assert_eq!(alloc.offset(), 0);

    allocator.free(alloc);
    drop(buffer);
}

#[test]
fn test_allocator_device_mask_rejects_custom_pool() {
    // Custom pools have their device mask fixed at block creation time;
    // combining them with per-allocation device_mask must error rather
    // than silently ignoring the mask.
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    // Pick any host-visible memory type for the pool.
    let mem_props = physical.memory_properties();
    let mem_type = (0..mem_props.type_count())
        .find(|&i| {
            mem_props
                .memory_type(i)
                .property_flags()
                .contains(vulkane::safe::MemoryPropertyFlags::HOST_VISIBLE)
        })
        .expect("expected at least one host-visible memory type");

    let pool = allocator
        .create_pool(vulkane::safe::PoolCreateInfo {
            memory_type_index: mem_type,
            strategy: vulkane::safe::AllocationStrategy::FreeList,
            block_size: 1024 * 1024,
            max_block_count: 0,
        })
        .unwrap();

    let mask = device.default_device_mask();
    let result = allocator.create_buffer(
        BufferCreateInfo {
            size: 4096,
            usage: BufferUsage::STORAGE_BUFFER,
        },
        AllocationCreateInfo {
            usage: AllocationUsage::HostVisible,
            pool: Some(pool),
            device_mask: Some(mask),
            ..Default::default()
        },
    );
    match result {
        Err(vulkane::safe::Error::InvalidArgument(_)) => {}
        Ok(_) => panic!("expected InvalidArgument when combining device_mask with a pool"),
        Err(e) => panic!("expected InvalidArgument, got {e:?}"),
    }

    allocator.destroy_pool(pool);
}

#[test]
fn test_allocator_create_image_2d_via_pool() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    let (image, alloc) = allocator
        .create_image_2d(
            Image2dCreateInfo {
                format: Format::R32_UINT,
                width: 32,
                height: 32,
                usage: ImageUsage::STORAGE,
            },
            AllocationCreateInfo {
                usage: AllocationUsage::DeviceLocal,
                ..Default::default()
            },
        )
        .unwrap();
    assert!(alloc.size() >= 32 * 32 * 4);
    let _view = ImageView::new_2d_color(&image).unwrap();

    allocator.free(alloc);
    drop(image);
}

#[test]
fn test_allocator_persistent_mapped_pointer() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    let (buffer, alloc) = allocator
        .create_buffer(
            BufferCreateInfo {
                size: 256,
                usage: BufferUsage::TRANSFER_DST,
            },
            AllocationCreateInfo {
                usage: AllocationUsage::HostVisible,
                mapped: true,
                ..Default::default()
            },
        )
        .unwrap();
    let ptr = alloc
        .mapped_ptr()
        .expect("HostVisible + mapped should give a pointer");
    // Write a pattern via the persistent mapping. Safety: pointer is
    // valid for the size of the allocation, and host-coherent so no
    // explicit flush is needed.
    unsafe {
        let bytes = std::slice::from_raw_parts_mut(ptr as *mut u8, alloc.size() as usize);
        for (i, b) in bytes.iter_mut().enumerate() {
            *b = (i & 0xFF) as u8;
        }
        // Read back via a fresh slice from the same pointer.
        let bytes = std::slice::from_raw_parts(ptr as *const u8, alloc.size() as usize);
        for (i, &b) in bytes.iter().enumerate() {
            assert_eq!(b, (i & 0xFF) as u8);
        }
    }

    allocator.free(alloc);
    drop(buffer);
}

#[test]
fn test_allocator_peak_bytes_tracks_high_watermark() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    let (b1, a1) = allocator
        .create_buffer(
            BufferCreateInfo {
                size: 8 * 1024,
                usage: BufferUsage::STORAGE_BUFFER,
            },
            AllocationCreateInfo {
                usage: AllocationUsage::HostVisible,
                ..Default::default()
            },
        )
        .unwrap();
    let (b2, a2) = allocator
        .create_buffer(
            BufferCreateInfo {
                size: 16 * 1024,
                usage: BufferUsage::STORAGE_BUFFER,
            },
            AllocationCreateInfo {
                usage: AllocationUsage::HostVisible,
                ..Default::default()
            },
        )
        .unwrap();

    let peak_after_two = allocator.statistics().peak_allocation_bytes;
    assert!(peak_after_two >= 24 * 1024);

    allocator.free(a2);
    drop(b2);
    let peak_after_one_freed = allocator.statistics().peak_allocation_bytes;
    // Peak does not regress when one is freed.
    assert_eq!(peak_after_two, peak_after_one_freed);

    allocator.free(a1);
    drop(b1);
}

// Note: the previous "buffer_device_address_returns_or_skips" test has
// been replaced by `test_device_features_buffer_device_address_round_trip`
// below, which actually enables the bufferDeviceAddress feature at
// device creation and exercises the full call. The defanged version is
// no longer needed.

#[test]
fn test_memory_budget_query_succeeds_or_skips() {
    let Some((_inst, physical, _device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let Some(budget) = physical.memory_budget() else {
        eprintln!("SKIP: vkGetPhysicalDeviceMemoryProperties2 not loaded");
        return;
    };
    // The structure is valid even if VK_EXT_memory_budget wasn't enabled
    // — the heap_count comes from the Vulkan-1.0-mandatory memory props,
    // and the budget/usage values just stay zero. We just assert the
    // structural shape here; meaningful budget reads require enabling
    // the extension at instance creation time.
    assert!(budget.heap_count > 0);
    println!(
        "Memory heaps: {}; total budget reported: {} bytes (0 if extension not enabled)",
        budget.heap_count,
        budget.total_budget()
    );
}

// NOTE: We do not have a runtime test for
// PhysicalDevice::cooperative_matrix_properties() because calling
// vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR without the
// VK_KHR_cooperative_matrix instance extension enabled is undefined
// behaviour on some implementations (notably Mesa Lavapipe, which is
// what our Linux CI uses). Until the safe wrapper supports a way to
// track which instance extensions were actually enabled, the API
// surface remains untested at runtime — but the wrapper itself
// compiles and the host-side checks (function-pointer presence,
// VkResult::SUCCESS guard) are in place.

// ---------------------------------------------------------------------------
// DeviceFeatures + features-enabled tests
// ---------------------------------------------------------------------------

/// Helper that creates an Instance + PhysicalDevice + Device with the
/// requested feature set enabled. Returns None on devices/drivers that
/// don't support the requested features so callers can skip cleanly.
fn try_init_with_features(
    features: DeviceFeatures,
) -> Option<(
    Instance,
    vulkane::safe::PhysicalDevice,
    vulkane::safe::Device,
    vulkane::safe::Queue,
    u32,
)> {
    let instance = Instance::new(InstanceCreateInfo::default()).ok()?;
    let physical = instance
        .enumerate_physical_devices()
        .ok()?
        .into_iter()
        .next()?;
    let queue_family = physical.find_queue_family(QueueFlags::COMPUTE)?;
    let device = physical
        .create_device(DeviceCreateInfo {
            queue_create_infos: &[QueueCreateInfo {
                queue_family_index: queue_family,
                queue_priorities: vec![1.0],
            }],
            enabled_features: Some(&features),
            ..Default::default()
        })
        .ok()?;
    let queue = device.get_queue(queue_family, 0);
    Some((instance, physical, device, queue, queue_family))
}

#[test]
fn test_device_features_default_creates_normally() {
    // A DeviceFeatures::default() with no flags set must successfully
    // create a device on every conformant Vulkan implementation.
    let features = DeviceFeatures::default();
    let Some((_inst, _physical, device, _q, _qf)) = try_init_with_features(features) else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    assert!(!device.raw().is_null());
}

#[test]
fn test_device_features_buffer_device_address_round_trip() {
    // Enable bufferDeviceAddress and verify Buffer::device_address()
    // returns a non-zero address when called against a buffer with
    // SHADER_DEVICE_ADDRESS usage.
    let features = DeviceFeatures::default().with_buffer_device_address();
    let Some((_inst, physical, device, _q, _qf)) = try_init_with_features(features) else {
        eprintln!("SKIP: bufferDeviceAddress not supported by device");
        return;
    };

    // Skip if Lavapipe (or any conformant Vulkan 1.0 ICD) doesn't expose
    // the function pointer at the loaded device level.
    let buffer = match Buffer::new(
        &device,
        BufferCreateInfo {
            size: 4096,
            usage: BufferUsage::STORAGE_BUFFER | BufferUsage::SHADER_DEVICE_ADDRESS,
        },
    ) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("SKIP: SHADER_DEVICE_ADDRESS buffer creation failed: {e}");
            return;
        }
    };
    let req = buffer.memory_requirements();
    // VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT requires the
    // VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT flag, which vulkane's
    // DeviceMemory::allocate doesn't currently set. Until that lands,
    // some drivers reject the bind. So we may also skip here.
    let mt = physical
        .find_memory_type(req.memory_type_bits, MemoryPropertyFlags::DEVICE_LOCAL)
        .or_else(|| {
            physical.find_memory_type(req.memory_type_bits, MemoryPropertyFlags::HOST_VISIBLE)
        })
        .unwrap();
    let memory = match DeviceMemory::allocate(&device, req.size, mt) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("SKIP: vkAllocateMemory rejected the device-address buffer: {e}");
            return;
        }
    };
    if let Err(e) = buffer.bind_memory(&memory, 0) {
        eprintln!("SKIP: vkBindBufferMemory rejected the device-address buffer: {e}");
        return;
    }
    match buffer.device_address() {
        Ok(addr) => {
            assert!(
                addr != 0,
                "device_address() returned zero on a feature-enabled device"
            );
            println!("Buffer device address: 0x{addr:x}");
        }
        Err(e) => {
            // Some implementations require additional flags we don't yet
            // pass; this is acceptable.
            eprintln!("SKIP: vkGetBufferDeviceAddress returned: {e}");
        }
    }
}

#[test]
fn test_device_features_timeline_semaphore_round_trip() {
    let features = DeviceFeatures::default().with_timeline_semaphore();
    let Some((_inst, _physical, device, queue, queue_family)) = try_init_with_features(features)
    else {
        eprintln!("SKIP: timelineSemaphore not supported");
        return;
    };

    let sem = match Semaphore::timeline(&device, 0) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("SKIP: timeline semaphore creation failed: {e}");
            return;
        }
    };
    assert_eq!(sem.kind(), SemaphoreKind::Timeline);
    assert_eq!(sem.current_value().unwrap(), 0);

    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = pool.allocate_primary().unwrap();
    {
        let rec = cmd.begin().unwrap();
        rec.end().unwrap();
    }
    queue
        .submit_with_sync(
            &[&cmd],
            &[],
            &[SignalSemaphore {
                semaphore: &sem,
                value: 42,
                device_index: 0,
            }],
            None,
        )
        .unwrap();

    sem.wait_value(42, u64::MAX).unwrap();
    assert!(sem.current_value().unwrap() >= 42);
    println!(
        "Timeline semaphore reached value {}",
        sem.current_value().unwrap()
    );
}

#[test]
fn test_device_features_synchronization2_round_trip() {
    let features = DeviceFeatures::default().with_synchronization2();
    let Some((_inst, _physical, device, queue, queue_family)) = try_init_with_features(features)
    else {
        eprintln!("SKIP: synchronization2 not supported");
        return;
    };

    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = pool.allocate_primary().unwrap();
    let supported = {
        let mut rec = cmd.begin().unwrap();
        let res = rec.memory_barrier2(
            PipelineStage2::COMPUTE_SHADER,
            PipelineStage2::HOST,
            AccessFlags2::SHADER_WRITE,
            AccessFlags2::HOST_READ,
        );
        rec.end().unwrap();
        res
    };
    match supported {
        Ok(()) => {
            let fence = Fence::new(&device).unwrap();
            queue.submit(&[&cmd], Some(&fence)).unwrap();
            fence.wait(u64::MAX).unwrap();
        }
        Err(e) => {
            // Even with the feature enabled, vkCmdPipelineBarrier2 might
            // not be loaded on Vulkan 1.0/1.1 devices that lack
            // VK_KHR_synchronization2 as an extension. Acceptable.
            eprintln!("SKIP: vkCmdPipelineBarrier2 not loaded: {e}");
        }
    }
}

#[test]
fn test_supported_features_query_succeeds() {
    let Some((_inst, physical, _device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let _features = physical.supported_features();
    // Just verify the call doesn't crash; the bit-set returned varies
    // by hardware. We don't assert any specific bit is set because
    // even Lavapipe exposes very few core 1.0 features by default.
}

// ---------------------------------------------------------------------------
// Custom pool + linear pool tests
// ---------------------------------------------------------------------------

#[test]
fn test_allocator_custom_freelist_pool_round_trip() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    // Pick a host-visible memory type for the pool.
    let dummy_buf = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 256,
            usage: BufferUsage::STORAGE_BUFFER,
        },
    )
    .unwrap();
    let req = dummy_buf.memory_requirements();
    drop(dummy_buf);
    let mt = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();

    let pool = allocator
        .create_pool(PoolCreateInfo {
            memory_type_index: mt,
            strategy: AllocationStrategy::FreeList,
            block_size: 1024 * 1024, // 1 MiB pool block
            max_block_count: 0,
        })
        .unwrap();

    // Allocate several buffers from the custom pool.
    let mut allocations = Vec::new();
    let mut buffers = Vec::new();
    for _ in 0..8 {
        let (b, a) = allocator
            .create_buffer(
                BufferCreateInfo {
                    size: 4096,
                    usage: BufferUsage::STORAGE_BUFFER,
                },
                AllocationCreateInfo {
                    pool: Some(pool),
                    ..Default::default()
                },
            )
            .unwrap();
        buffers.push(b);
        allocations.push(a);
    }

    let pool_stats = allocator.pool_statistics(pool).unwrap();
    assert_eq!(pool_stats.allocation_count, 8);
    assert!(pool_stats.allocation_bytes >= 8 * 4096);
    // All 8 allocations should fit in the 1 MiB block.
    assert_eq!(pool_stats.block_count, 1);

    for a in allocations.drain(..) {
        allocator.free(a);
    }
    drop(buffers);

    let pool_stats = allocator.pool_statistics(pool).unwrap();
    assert_eq!(pool_stats.allocation_count, 0);

    allocator.destroy_pool(pool);
    // After destruction the pool handle is unknown.
    assert!(allocator.pool_statistics(pool).is_none());
}

#[test]
fn test_allocator_linear_pool_supports_reset() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    // Pick a host-visible memory type.
    let dummy_buf = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 256,
            usage: BufferUsage::STORAGE_BUFFER,
        },
    )
    .unwrap();
    let req = dummy_buf.memory_requirements();
    drop(dummy_buf);
    let mt = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();

    let pool = allocator
        .create_pool(PoolCreateInfo {
            memory_type_index: mt,
            strategy: AllocationStrategy::Linear,
            block_size: 64 * 1024, // 64 KiB linear block
            max_block_count: 0,
        })
        .unwrap();

    // Bump-allocate a bunch of small chunks. They should not be returned
    // individually — only via reset_pool.
    let mut buffers = Vec::new();
    let mut allocations = Vec::new();
    for _ in 0..10 {
        let (b, a) = allocator
            .create_buffer(
                BufferCreateInfo {
                    size: 1024,
                    usage: BufferUsage::STORAGE_BUFFER,
                },
                AllocationCreateInfo {
                    pool: Some(pool),
                    ..Default::default()
                },
            )
            .unwrap();
        buffers.push(b);
        allocations.push(a);
    }

    let stats_before = allocator.pool_statistics(pool).unwrap();
    assert_eq!(stats_before.allocation_count, 10);

    // Drop the buffers (which calls vkDestroyBuffer) before reset.
    drop(buffers);

    // Reset the pool — all 10 allocations are reclaimed in one shot.
    allocator.reset_pool(pool);
    let stats_after = allocator.pool_statistics(pool).unwrap();
    assert_eq!(stats_after.allocation_count, 0);
    assert_eq!(stats_after.allocation_bytes, 0);

    // We can keep allocating into the same pool after reset.
    let (b2, a2) = allocator
        .create_buffer(
            BufferCreateInfo {
                size: 2048,
                usage: BufferUsage::STORAGE_BUFFER,
            },
            AllocationCreateInfo {
                pool: Some(pool),
                ..Default::default()
            },
        )
        .unwrap();

    let stats_post = allocator.pool_statistics(pool).unwrap();
    assert_eq!(stats_post.allocation_count, 1);

    drop(b2);
    drop(a2);
    // Don't bother freeing — the destroy_pool below will reclaim everything.
    allocator.destroy_pool(pool);
}

#[test]
fn test_allocator_linear_pool_full_returns_error() {
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    let dummy_buf = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 256,
            usage: BufferUsage::STORAGE_BUFFER,
        },
    )
    .unwrap();
    let req = dummy_buf.memory_requirements();
    drop(dummy_buf);
    let mt = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();

    // Tiny linear pool — only one tiny block.
    let pool = allocator
        .create_pool(PoolCreateInfo {
            memory_type_index: mt,
            strategy: AllocationStrategy::Linear,
            block_size: 4096,
            max_block_count: 1,
        })
        .unwrap();

    // First allocation succeeds.
    let r1 = allocator.create_buffer(
        BufferCreateInfo {
            size: 2048,
            usage: BufferUsage::STORAGE_BUFFER,
        },
        AllocationCreateInfo {
            pool: Some(pool),
            ..Default::default()
        },
    );
    assert!(r1.is_ok());

    // Second allocation might fit (2048 + 2048 = 4096) — depends on
    // alignment. If it does fit, the third should fail.
    let _r2 = allocator.create_buffer(
        BufferCreateInfo {
            size: 2048,
            usage: BufferUsage::STORAGE_BUFFER,
        },
        AllocationCreateInfo {
            pool: Some(pool),
            ..Default::default()
        },
    );

    // Third allocation: even if r2 succeeded, we're definitely over the
    // 4 KiB block limit now, and max_block_count = 1 prevents growth.
    let r3 = allocator.create_buffer(
        BufferCreateInfo {
            size: 4096,
            usage: BufferUsage::STORAGE_BUFFER,
        },
        AllocationCreateInfo {
            pool: Some(pool),
            ..Default::default()
        },
    );
    assert!(
        r3.is_err(),
        "expected linear pool to refuse over-budget allocation"
    );

    allocator.destroy_pool(pool);
}

#[test]
fn test_allocator_defragmentation_compacts_fragmented_pool() {
    // Create a custom FreeList pool, allocate alternating large/small
    // buffers, free every other one to create holes, then build a defrag
    // plan and verify that:
    //   - the plan is non-empty (there's something to compact)
    //   - applying the plan does not invalidate live Allocation handles
    //     (memory() / offset() return new positions but size() / id()
    //     are stable)
    //   - the post-defrag positions are contiguous from offset 0
    //   - the pool can still allocate from the freed space afterward
    let Some((_inst, physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let allocator = Allocator::new(&device, &physical).unwrap();

    // Pick a host-visible memory type for predictability.
    let dummy_buf = Buffer::new(
        &device,
        BufferCreateInfo {
            size: 256,
            usage: BufferUsage::STORAGE_BUFFER,
        },
    )
    .unwrap();
    let req = dummy_buf.memory_requirements();
    drop(dummy_buf);
    let mt = physical
        .find_memory_type(
            req.memory_type_bits,
            MemoryPropertyFlags::HOST_VISIBLE | MemoryPropertyFlags::HOST_COHERENT,
        )
        .unwrap();

    let pool = allocator
        .create_pool(PoolCreateInfo {
            memory_type_index: mt,
            strategy: AllocationStrategy::FreeList,
            block_size: 256 * 1024, // 256 KiB
            max_block_count: 1,
        })
        .unwrap();

    // Allocate 8 buffers of varying sizes with user_data tags.
    let mut buffers: Vec<(Buffer, vulkane::safe::Allocation)> = Vec::new();
    for i in 0..8 {
        let (b, a) = allocator
            .create_buffer(
                BufferCreateInfo {
                    size: 4096 * (i as u64 + 1),
                    usage: BufferUsage::STORAGE_BUFFER,
                },
                AllocationCreateInfo {
                    pool: Some(pool),
                    user_data: 100 + i as u64,
                    ..Default::default()
                },
            )
            .unwrap();
        buffers.push((b, a));
    }

    // Free every odd-indexed allocation to create holes.
    let mut survivors: Vec<vulkane::safe::Allocation> = Vec::new();
    for (i, (buffer, alloc)) in buffers.into_iter().enumerate() {
        if i % 2 == 1 {
            // free it.
            drop(buffer);
            allocator.free(alloc);
        } else {
            // Keep this one alive across defrag.
            drop(buffer);
            survivors.push(alloc);
        }
    }

    // Snapshot pre-defrag IDs / sizes / user_data.
    let pre: Vec<(u64, u64, u64)> = survivors
        .iter()
        .map(|a| (a.id(), a.size(), a.user_data()))
        .collect();

    // Build the defragmentation plan.
    let plan = allocator.build_defragmentation_plan(pool);
    assert!(
        !plan.total_layout().is_empty(),
        "defrag plan should include all 4 surviving allocations"
    );

    // Sanity-check the move list: every move's user_data should match
    // one of our survivors.
    for m in &plan.moves {
        assert!(
            survivors.iter().any(|a| a.user_data() == m.user_data),
            "move user_data {} should match a surviving allocation",
            m.user_data
        );
    }

    // Apply the plan. (We don't actually issue GPU copies here — this
    // test only verifies the bookkeeping side of defrag, not data
    // integrity. A full GPU-copy test would need a command buffer +
    // submit + fence-wait per move.)
    allocator.apply_defragmentation_plan(plan);

    // Post-defrag: every survivor still has its original id, size, and
    // user_data, but offset() may have changed. The positions should be
    // monotonically increasing from 0.
    let mut last_offset: u64 = 0;
    for (i, alloc) in survivors.iter().enumerate() {
        assert_eq!(alloc.id(), pre[i].0, "id should be stable across defrag");
        assert_eq!(
            alloc.size(),
            pre[i].1,
            "size should be stable across defrag"
        );
        assert_eq!(
            alloc.user_data(),
            pre[i].2,
            "user_data should be stable across defrag"
        );
        let off = alloc.offset();
        assert!(
            off >= last_offset,
            "post-defrag offsets should be monotonically increasing (got {off} after {last_offset})"
        );
        last_offset = off + alloc.size();
    }

    // After defrag, we should be able to allocate something large in
    // the freed-up space — proves the TLSF state was rebuilt.
    let (_b, post_alloc) = allocator
        .create_buffer(
            BufferCreateInfo {
                size: 64 * 1024,
                usage: BufferUsage::STORAGE_BUFFER,
            },
            AllocationCreateInfo {
                pool: Some(pool),
                ..Default::default()
            },
        )
        .expect("post-defrag allocation should succeed");
    assert!(post_alloc.size() >= 64 * 1024);

    // Cleanup.
    drop(survivors);
    drop(post_alloc);
    allocator.destroy_pool(pool);
}

#[test]
fn test_enumerate_physical_device_groups() {
    let instance = match Instance::new(InstanceCreateInfo::default()) {
        Ok(i) => i,
        Err(e) => {
            eprintln!("SKIP: cannot create Vulkan instance: {e}");
            return;
        }
    };
    let groups = match instance.enumerate_physical_device_groups() {
        Ok(g) => g,
        Err(e) => {
            eprintln!("SKIP: enumerate_physical_device_groups returned: {e}");
            return;
        }
    };
    println!("Found {} physical device group(s)", groups.len());
    for (i, group) in groups.iter().enumerate() {
        assert!(group.count() >= 1, "every group has at least one device");
        println!(
            "  group {i}: {} device(s), subset_allocation={}",
            group.count(),
            group.supports_subset_allocation()
        );
        for pd in group.physical_devices() {
            assert!(!pd.properties().device_name().is_empty());
        }
    }
}

#[test]
fn test_device_singleton_group_unification() {
    // Verify that a device created via the legacy
    // physical.create_device(...) path internally exposes a length-1
    // physical-device group, matching the device-group representation.
    let Some((_inst, _physical, device, _q, _qf)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    assert_eq!(
        device.physical_device_count(),
        1,
        "single-physical-device path should produce a length-1 group"
    );
    let handles = device.physical_device_handles();
    assert_eq!(handles.len(), 1);
    // The default device mask for a 1-device group is 0b1.
    assert_eq!(device.default_device_mask(), 0b1);
}

#[test]
fn test_submit_with_groups_default_mask_round_trip() {
    // On any single-device group (i.e. all CI hardware), submit_with_groups
    // with the default per-CB mask must succeed and behave identically to
    // submit_with_sync. This exercises the VkDeviceGroupSubmitInfo
    // pNext-chaining path: we explicitly pass Some(&[mask]), which forces
    // the chain to be added.
    let Some((_inst, _physical, device, queue, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = pool.allocate_primary().unwrap();
    {
        let rec = cmd.begin().unwrap();
        rec.end().unwrap();
    }
    let fence = Fence::new(&device).unwrap();
    let mask = device.default_device_mask();

    queue
        .submit_with_groups(&[&cmd], Some(&[mask]), &[], &[], Some(&fence))
        .unwrap();

    // The fence must signal exactly as it would for the non-group path.
    // (wait() returns SUCCESS only when the fence has actually become
    // signaled.)
    fence.wait(u64::MAX).unwrap();
}

#[test]
fn test_submit_with_groups_rejects_mask_length_mismatch() {
    let Some((_inst, _physical, device, queue, queue_family)) = try_init_compute() else {
        eprintln!("SKIP: no Vulkan ICD");
        return;
    };
    let pool = CommandPool::new(&device, queue_family).unwrap();
    let mut cmd = pool.allocate_primary().unwrap();
    {
        let rec = cmd.begin().unwrap();
        rec.end().unwrap();
    }

    // 1 CB, 2 masks → must error.
    let result = queue.submit_with_groups(&[&cmd], Some(&[1u32, 2u32]), &[], &[], None);
    match result {
        Err(vulkane::safe::Error::InvalidArgument(_)) => {}
        Ok(_) => panic!("expected InvalidArgument when mask len differs from CB count"),
        Err(e) => panic!("expected InvalidArgument, got {e:?}"),
    }
}

#[test]
fn test_device_create_via_physical_device_group() {
    // Verify that PhysicalDeviceGroup::create_device works for
    // singleton groups (we can't reliably test multi-device on most CI
    // hardware) and that the resulting Device exposes the same fields.
    let instance = match Instance::new(InstanceCreateInfo::default()) {
        Ok(i) => i,
        Err(_) => {
            eprintln!("SKIP: no Vulkan ICD");
            return;
        }
    };
    let Some(group) = instance
        .enumerate_physical_device_groups()
        .ok()
        .and_then(|gs| gs.into_iter().next())
    else {
        eprintln!("SKIP: no physical device groups");
        return;
    };
    let Some(physical) = group.physical_devices().first() else {
        eprintln!("SKIP: empty physical device group");
        return;
    };
    let queue_family = physical.find_queue_family(QueueFlags::TRANSFER).unwrap();
    let device = group
        .create_device(DeviceCreateInfo {
            queue_create_infos: &[QueueCreateInfo {
                queue_family_index: queue_family,
                queue_priorities: vec![1.0],
            }],
            ..Default::default()
        })
        .unwrap();
    assert_eq!(device.physical_device_count(), group.count());
    assert!(device.default_device_mask() != 0);
}

#[test]
fn test_defragmentation_move_struct_round_trip() {
    let m = DefragmentationMove {
        allocation_id: 42,
        user_data: 0xDEAD_BEEF,
        size: 1024,
        src_memory: 0x1000,
        src_offset: 0,
        dst_memory: 0x2000,
        dst_offset: 256,
    };
    assert_eq!(m.allocation_id, 42);
    assert_eq!(m.user_data, 0xDEAD_BEEF);
    assert_eq!(m.size, 1024);
    let _plan = DefragmentationPlan::default();
}