stipple 0.0.3

Stipple: a cross-platform, self-drawn UI toolkit in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
//! Raw Vulkan FFI foundation — no `ash`/`vulkano`, just `libvulkan` and the
//! Vulkan C structs, matching the "close to the OS" policy.
//!
//! This is the entry point for a future GPU-native Vulkan render backend: it
//! creates a `VkInstance` and enumerates the physical devices, returning their
//! names. The full offscreen pipeline (device + queues, image + memory, render
//! pass, SPIR-V pipeline, command buffers, readback) builds on this. It runs
//! headlessly under Mesa's **lavapipe** software Vulkan ICD in CI.

#![allow(unsafe_code, non_snake_case, non_upper_case_globals)]

use core::ffi::{c_char, c_void};

type VkInstance = *mut c_void;
type VkPhysicalDevice = *mut c_void;
type VkResult = i32;

type VkDevice = *mut c_void;
type VkQueue = *mut c_void;

const VK_SUCCESS: VkResult = 0;
const VK_STRUCTURE_TYPE_APPLICATION_INFO: i32 = 0;
const VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO: i32 = 1;
const VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO: i32 = 2;
const VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO: i32 = 3;
const VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO: i32 = 5;
const VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO: i32 = 14;
const VK_QUEUE_GRAPHICS_BIT: u32 = 0x1;
// VkQueueFamilyProperties is 24 bytes; queueFlags is its first u32.
const QUEUE_FAMILY_PROPS_SIZE: usize = 24;
const VK_FORMAT_R8G8B8A8_UNORM: u32 = 37;
const VK_IMAGE_TYPE_2D: u32 = 1;
const VK_IMAGE_TILING_OPTIMAL: u32 = 0;
const VK_IMAGE_USAGE_TRANSFER_SRC_BIT: u32 = 0x1;
const VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT: u32 = 0x10;
const VK_SHARING_MODE_EXCLUSIVE: u32 = 0;
const VK_IMAGE_LAYOUT_UNDEFINED: u32 = 0;
const VK_SAMPLE_COUNT_1_BIT: u32 = 1;
const VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT: u32 = 0x1;
// VkPhysicalDeviceMemoryProperties: memoryTypeCount (u32) then memoryTypes[32]
// of VkMemoryType { propertyFlags: u32, heapIndex: u32 } (8 bytes each).
const MEM_TYPES_OFFSET: usize = 4;
const MEM_TYPE_STRIDE: usize = 8;

const VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO: i32 = 15;
const VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO: i32 = 37;
const VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO: i32 = 38;
const VK_IMAGE_VIEW_TYPE_2D: u32 = 1;
const VK_IMAGE_ASPECT_COLOR_BIT: u32 = 0x1;
const VK_ATTACHMENT_LOAD_OP_CLEAR: u32 = 1;
const VK_ATTACHMENT_STORE_OP_STORE: u32 = 0;
const VK_ATTACHMENT_LOAD_OP_DONT_CARE: u32 = 2;
const VK_ATTACHMENT_STORE_OP_DONT_CARE: u32 = 1;
const VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: u32 = 2;
const VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: u32 = 6;
const VK_PIPELINE_BIND_POINT_GRAPHICS: u32 = 0;
const VK_COMPONENT_SWIZZLE_IDENTITY: u32 = 0;

const VK_STRUCTURE_TYPE_SUBMIT_INFO: i32 = 4;
const VK_STRUCTURE_TYPE_FENCE_CREATE_INFO: i32 = 8;
const VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO: i32 = 39;
const VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO: i32 = 40;
const VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO: i32 = 42;
const VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO: i32 = 43;
const VK_COMMAND_BUFFER_LEVEL_PRIMARY: u32 = 0;
const VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT: u32 = 0x1;
const VK_SUBPASS_CONTENTS_INLINE: u32 = 0;
const VK_TRUE: u32 = 1;

const VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO: i32 = 12;
const VK_BUFFER_USAGE_TRANSFER_DST_BIT: u32 = 0x2;
const VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT: u32 = 0x2;
const VK_MEMORY_PROPERTY_HOST_COHERENT_BIT: u32 = 0x4;

const VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO: i32 = 16;
const VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO: i32 = 18;
const VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO: i32 = 19;
const VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO: i32 = 20;
const VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO: i32 = 22;
const VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO: i32 = 23;
const VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO: i32 = 24;
const VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO: i32 = 26;
const VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO: i32 = 28;
const VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO: i32 = 30;
const VK_SHADER_STAGE_VERTEX_BIT: u32 = 0x1;
const VK_SHADER_STAGE_FRAGMENT_BIT: u32 = 0x10;
const VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST: u32 = 3;
const VK_POLYGON_MODE_FILL: u32 = 0;
const VK_CULL_MODE_NONE: u32 = 0;
const VK_FRONT_FACE_COUNTER_CLOCKWISE: u32 = 0;
const VK_COLOR_COMPONENT_RGBA: u32 = 0x1 | 0x2 | 0x4 | 0x8;
// VK_API_VERSION_1_0 = VK_MAKE_API_VERSION(0, 1, 0, 0) = 1 << 22.
const VK_API_VERSION_1_0: u32 = 1 << 22;
// VkPhysicalDeviceProperties.deviceName follows five u32 fields (apiVersion,
// driverVersion, vendorID, deviceID, deviceType) → byte offset 20, length 256.
const DEVICE_NAME_OFFSET: usize = 20;
const VK_MAX_PHYSICAL_DEVICE_NAME_SIZE: usize = 256;

#[repr(C)]
struct VkApplicationInfo {
    sType: i32,
    pNext: *const c_void,
    pApplicationName: *const c_char,
    applicationVersion: u32,
    pEngineName: *const c_char,
    engineVersion: u32,
    apiVersion: u32,
}

#[repr(C)]
struct VkInstanceCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    pApplicationInfo: *const VkApplicationInfo,
    enabledLayerCount: u32,
    ppEnabledLayerNames: *const *const c_char,
    enabledExtensionCount: u32,
    ppEnabledExtensionNames: *const *const c_char,
}

#[repr(C)]
struct VkDeviceQueueCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    queueFamilyIndex: u32,
    queueCount: u32,
    pQueuePriorities: *const f32,
}

#[repr(C)]
struct VkDeviceCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    queueCreateInfoCount: u32,
    pQueueCreateInfos: *const VkDeviceQueueCreateInfo,
    enabledLayerCount: u32,
    ppEnabledLayerNames: *const *const c_char,
    enabledExtensionCount: u32,
    ppEnabledExtensionNames: *const *const c_char,
    pEnabledFeatures: *const c_void,
}

type VkImage = u64;
type VkDeviceMemory = u64;
type VkImageView = u64;
type VkRenderPass = u64;
type VkFramebuffer = u64;
type VkCommandPool = u64;
type VkFence = u64;
type VkBuffer = u64;
type VkShaderModule = u64;
type VkPipelineLayout = u64;
type VkPipeline = u64;
// VkCommandBuffer is a *dispatchable* handle (pointer-sized), not a u64 like the
// non-dispatchable handles above.
type VkCommandBuffer = *mut c_void;

#[repr(C)]
struct VkExtent3D {
    width: u32,
    height: u32,
    depth: u32,
}

#[repr(C)]
struct VkImageCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    imageType: u32,
    format: u32,
    extent: VkExtent3D,
    mipLevels: u32,
    arrayLayers: u32,
    samples: u32,
    tiling: u32,
    usage: u32,
    sharingMode: u32,
    queueFamilyIndexCount: u32,
    pQueueFamilyIndices: *const u32,
    initialLayout: u32,
}

#[repr(C)]
struct VkMemoryRequirements {
    size: u64,
    alignment: u64,
    memoryTypeBits: u32,
}

#[repr(C)]
struct VkMemoryAllocateInfo {
    sType: i32,
    pNext: *const c_void,
    allocationSize: u64,
    memoryTypeIndex: u32,
}

#[repr(C)]
struct VkComponentMapping {
    r: u32,
    g: u32,
    b: u32,
    a: u32,
}

#[repr(C)]
struct VkImageSubresourceRange {
    aspectMask: u32,
    baseMipLevel: u32,
    levelCount: u32,
    baseArrayLayer: u32,
    layerCount: u32,
}

#[repr(C)]
struct VkImageViewCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    image: VkImage,
    viewType: u32,
    format: u32,
    components: VkComponentMapping,
    subresourceRange: VkImageSubresourceRange,
}

#[repr(C)]
struct VkAttachmentDescription {
    flags: u32,
    format: u32,
    samples: u32,
    loadOp: u32,
    storeOp: u32,
    stencilLoadOp: u32,
    stencilStoreOp: u32,
    initialLayout: u32,
    finalLayout: u32,
}

#[repr(C)]
struct VkAttachmentReference {
    attachment: u32,
    layout: u32,
}

#[repr(C)]
struct VkSubpassDescription {
    flags: u32,
    pipelineBindPoint: u32,
    inputAttachmentCount: u32,
    pInputAttachments: *const VkAttachmentReference,
    colorAttachmentCount: u32,
    pColorAttachments: *const VkAttachmentReference,
    pResolveAttachments: *const VkAttachmentReference,
    pDepthStencilAttachment: *const VkAttachmentReference,
    preserveAttachmentCount: u32,
    pPreserveAttachments: *const u32,
}

#[repr(C)]
struct VkRenderPassCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    attachmentCount: u32,
    pAttachments: *const VkAttachmentDescription,
    subpassCount: u32,
    pSubpasses: *const VkSubpassDescription,
    dependencyCount: u32,
    pDependencies: *const c_void,
}

#[repr(C)]
struct VkFramebufferCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    renderPass: VkRenderPass,
    attachmentCount: u32,
    pAttachments: *const VkImageView,
    width: u32,
    height: u32,
    layers: u32,
}

#[repr(C)]
struct VkCommandPoolCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    queueFamilyIndex: u32,
}

#[repr(C)]
struct VkCommandBufferAllocateInfo {
    sType: i32,
    pNext: *const c_void,
    commandPool: VkCommandPool,
    level: u32,
    commandBufferCount: u32,
}

#[repr(C)]
struct VkCommandBufferBeginInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    pInheritanceInfo: *const c_void,
}

#[repr(C)]
struct VkOffset2D {
    x: i32,
    y: i32,
}

#[repr(C)]
struct VkExtent2D {
    width: u32,
    height: u32,
}

#[repr(C)]
struct VkRect2D {
    offset: VkOffset2D,
    extent: VkExtent2D,
}

/// `VkClearValue` is a union; for a color attachment its largest relevant member
/// is `VkClearColorValue { float32: [f32; 4] }` (16 bytes), which is what we use.
#[repr(C)]
struct VkClearValue {
    float32: [f32; 4],
}

#[repr(C)]
struct VkRenderPassBeginInfo {
    sType: i32,
    pNext: *const c_void,
    renderPass: VkRenderPass,
    framebuffer: VkFramebuffer,
    renderArea: VkRect2D,
    clearValueCount: u32,
    pClearValues: *const VkClearValue,
}

#[repr(C)]
struct VkSubmitInfo {
    sType: i32,
    pNext: *const c_void,
    waitSemaphoreCount: u32,
    pWaitSemaphores: *const u64,
    pWaitDstStageMask: *const u32,
    commandBufferCount: u32,
    pCommandBuffers: *const VkCommandBuffer,
    signalSemaphoreCount: u32,
    pSignalSemaphores: *const u64,
}

#[repr(C)]
struct VkFenceCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
}

#[repr(C)]
struct VkBufferCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    size: u64,
    usage: u32,
    sharingMode: u32,
    queueFamilyIndexCount: u32,
    pQueueFamilyIndices: *const u32,
}

#[repr(C)]
struct VkImageSubresourceLayers {
    aspectMask: u32,
    mipLevel: u32,
    baseArrayLayer: u32,
    layerCount: u32,
}

#[repr(C)]
struct VkOffset3D {
    x: i32,
    y: i32,
    z: i32,
}

#[repr(C)]
struct VkBufferImageCopy {
    bufferOffset: u64,
    bufferRowLength: u32,
    bufferImageHeight: u32,
    imageSubresource: VkImageSubresourceLayers,
    imageOffset: VkOffset3D,
    imageExtent: VkExtent3D,
}

#[repr(C)]
struct VkShaderModuleCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    codeSize: usize,
    pCode: *const u32,
}

#[repr(C)]
struct VkPipelineShaderStageCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    stage: u32,
    module: VkShaderModule,
    pName: *const c_char,
    pSpecializationInfo: *const c_void,
}

#[repr(C)]
struct VkPipelineVertexInputStateCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    vertexBindingDescriptionCount: u32,
    pVertexBindingDescriptions: *const c_void,
    vertexAttributeDescriptionCount: u32,
    pVertexAttributeDescriptions: *const c_void,
}

#[repr(C)]
struct VkPipelineInputAssemblyStateCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    topology: u32,
    primitiveRestartEnable: u32,
}

#[repr(C)]
struct VkViewport {
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    minDepth: f32,
    maxDepth: f32,
}

#[repr(C)]
struct VkPipelineViewportStateCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    viewportCount: u32,
    pViewports: *const VkViewport,
    scissorCount: u32,
    pScissors: *const VkRect2D,
}

#[repr(C)]
struct VkPipelineRasterizationStateCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    depthClampEnable: u32,
    rasterizerDiscardEnable: u32,
    polygonMode: u32,
    cullMode: u32,
    frontFace: u32,
    depthBiasEnable: u32,
    depthBiasConstantFactor: f32,
    depthBiasClamp: f32,
    depthBiasSlopeFactor: f32,
    lineWidth: f32,
}

#[repr(C)]
struct VkPipelineMultisampleStateCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    rasterizationSamples: u32,
    sampleShadingEnable: u32,
    minSampleShading: f32,
    pSampleMask: *const u32,
    alphaToCoverageEnable: u32,
    alphaToOneEnable: u32,
}

#[repr(C)]
struct VkPipelineColorBlendAttachmentState {
    blendEnable: u32,
    srcColorBlendFactor: u32,
    dstColorBlendFactor: u32,
    colorBlendOp: u32,
    srcAlphaBlendFactor: u32,
    dstAlphaBlendFactor: u32,
    alphaBlendOp: u32,
    colorWriteMask: u32,
}

#[repr(C)]
struct VkPipelineColorBlendStateCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    logicOpEnable: u32,
    logicOp: u32,
    attachmentCount: u32,
    pAttachments: *const VkPipelineColorBlendAttachmentState,
    blendConstants: [f32; 4],
}

#[repr(C)]
struct VkPipelineLayoutCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    setLayoutCount: u32,
    pSetLayouts: *const u64,
    pushConstantRangeCount: u32,
    pPushConstantRanges: *const c_void,
}

#[repr(C)]
struct VkGraphicsPipelineCreateInfo {
    sType: i32,
    pNext: *const c_void,
    flags: u32,
    stageCount: u32,
    pStages: *const VkPipelineShaderStageCreateInfo,
    pVertexInputState: *const VkPipelineVertexInputStateCreateInfo,
    pInputAssemblyState: *const VkPipelineInputAssemblyStateCreateInfo,
    pTessellationState: *const c_void,
    pViewportState: *const VkPipelineViewportStateCreateInfo,
    pRasterizationState: *const VkPipelineRasterizationStateCreateInfo,
    pMultisampleState: *const VkPipelineMultisampleStateCreateInfo,
    pDepthStencilState: *const c_void,
    pColorBlendState: *const VkPipelineColorBlendStateCreateInfo,
    pDynamicState: *const c_void,
    layout: VkPipelineLayout,
    renderPass: VkRenderPass,
    subpass: u32,
    basePipelineHandle: VkPipeline,
    basePipelineIndex: i32,
}

#[link(name = "vulkan")]
unsafe extern "C" {
    fn vkCreateInstance(
        pCreateInfo: *const VkInstanceCreateInfo,
        pAllocator: *const c_void,
        pInstance: *mut VkInstance,
    ) -> VkResult;
    fn vkDestroyInstance(instance: VkInstance, pAllocator: *const c_void);
    fn vkEnumeratePhysicalDevices(
        instance: VkInstance,
        pPhysicalDeviceCount: *mut u32,
        pPhysicalDevices: *mut VkPhysicalDevice,
    ) -> VkResult;
    // Writes a VkPhysicalDeviceProperties (~824 bytes); we hand it a generous
    // byte buffer and read only `deviceName` out of it.
    fn vkGetPhysicalDeviceProperties(physicalDevice: VkPhysicalDevice, pProperties: *mut c_void);
    fn vkGetPhysicalDeviceQueueFamilyProperties(
        physicalDevice: VkPhysicalDevice,
        pQueueFamilyPropertyCount: *mut u32,
        pQueueFamilyProperties: *mut c_void,
    );
    fn vkCreateDevice(
        physicalDevice: VkPhysicalDevice,
        pCreateInfo: *const VkDeviceCreateInfo,
        pAllocator: *const c_void,
        pDevice: *mut VkDevice,
    ) -> VkResult;
    fn vkDestroyDevice(device: VkDevice, pAllocator: *const c_void);
    fn vkGetDeviceQueue(
        device: VkDevice,
        queueFamilyIndex: u32,
        queueIndex: u32,
        pQueue: *mut VkQueue,
    );
    fn vkCreateImage(
        device: VkDevice,
        pCreateInfo: *const VkImageCreateInfo,
        pAllocator: *const c_void,
        pImage: *mut VkImage,
    ) -> VkResult;
    fn vkDestroyImage(device: VkDevice, image: VkImage, pAllocator: *const c_void);
    fn vkGetImageMemoryRequirements(
        device: VkDevice,
        image: VkImage,
        pMemoryRequirements: *mut VkMemoryRequirements,
    );
    // Writes a VkPhysicalDeviceMemoryProperties (~520 bytes); we hand it a
    // generous byte buffer and read the memoryType property flags out of it.
    fn vkGetPhysicalDeviceMemoryProperties(
        physicalDevice: VkPhysicalDevice,
        pMemoryProperties: *mut c_void,
    );
    fn vkAllocateMemory(
        device: VkDevice,
        pAllocateInfo: *const VkMemoryAllocateInfo,
        pAllocator: *const c_void,
        pMemory: *mut VkDeviceMemory,
    ) -> VkResult;
    fn vkFreeMemory(device: VkDevice, memory: VkDeviceMemory, pAllocator: *const c_void);
    fn vkBindImageMemory(
        device: VkDevice,
        image: VkImage,
        memory: VkDeviceMemory,
        memoryOffset: u64,
    ) -> VkResult;
    fn vkCreateImageView(
        device: VkDevice,
        pCreateInfo: *const VkImageViewCreateInfo,
        pAllocator: *const c_void,
        pView: *mut VkImageView,
    ) -> VkResult;
    fn vkDestroyImageView(device: VkDevice, imageView: VkImageView, pAllocator: *const c_void);
    fn vkCreateRenderPass(
        device: VkDevice,
        pCreateInfo: *const VkRenderPassCreateInfo,
        pAllocator: *const c_void,
        pRenderPass: *mut VkRenderPass,
    ) -> VkResult;
    fn vkDestroyRenderPass(device: VkDevice, renderPass: VkRenderPass, pAllocator: *const c_void);
    fn vkCreateFramebuffer(
        device: VkDevice,
        pCreateInfo: *const VkFramebufferCreateInfo,
        pAllocator: *const c_void,
        pFramebuffer: *mut VkFramebuffer,
    ) -> VkResult;
    fn vkDestroyFramebuffer(
        device: VkDevice,
        framebuffer: VkFramebuffer,
        pAllocator: *const c_void,
    );
    fn vkCreateCommandPool(
        device: VkDevice,
        pCreateInfo: *const VkCommandPoolCreateInfo,
        pAllocator: *const c_void,
        pCommandPool: *mut VkCommandPool,
    ) -> VkResult;
    fn vkDestroyCommandPool(
        device: VkDevice,
        commandPool: VkCommandPool,
        pAllocator: *const c_void,
    );
    fn vkAllocateCommandBuffers(
        device: VkDevice,
        pAllocateInfo: *const VkCommandBufferAllocateInfo,
        pCommandBuffers: *mut VkCommandBuffer,
    ) -> VkResult;
    fn vkBeginCommandBuffer(
        commandBuffer: VkCommandBuffer,
        pBeginInfo: *const VkCommandBufferBeginInfo,
    ) -> VkResult;
    fn vkEndCommandBuffer(commandBuffer: VkCommandBuffer) -> VkResult;
    fn vkCmdBeginRenderPass(
        commandBuffer: VkCommandBuffer,
        pRenderPassBegin: *const VkRenderPassBeginInfo,
        contents: u32,
    );
    fn vkCmdEndRenderPass(commandBuffer: VkCommandBuffer);
    fn vkQueueSubmit(
        queue: VkQueue,
        submitCount: u32,
        pSubmits: *const VkSubmitInfo,
        fence: VkFence,
    ) -> VkResult;
    fn vkCreateFence(
        device: VkDevice,
        pCreateInfo: *const VkFenceCreateInfo,
        pAllocator: *const c_void,
        pFence: *mut VkFence,
    ) -> VkResult;
    fn vkDestroyFence(device: VkDevice, fence: VkFence, pAllocator: *const c_void);
    fn vkWaitForFences(
        device: VkDevice,
        fenceCount: u32,
        pFences: *const VkFence,
        waitAll: u32,
        timeout: u64,
    ) -> VkResult;
    fn vkCreateBuffer(
        device: VkDevice,
        pCreateInfo: *const VkBufferCreateInfo,
        pAllocator: *const c_void,
        pBuffer: *mut VkBuffer,
    ) -> VkResult;
    fn vkDestroyBuffer(device: VkDevice, buffer: VkBuffer, pAllocator: *const c_void);
    fn vkGetBufferMemoryRequirements(
        device: VkDevice,
        buffer: VkBuffer,
        pMemoryRequirements: *mut VkMemoryRequirements,
    );
    fn vkBindBufferMemory(
        device: VkDevice,
        buffer: VkBuffer,
        memory: VkDeviceMemory,
        memoryOffset: u64,
    ) -> VkResult;
    fn vkCmdCopyImageToBuffer(
        commandBuffer: VkCommandBuffer,
        srcImage: VkImage,
        srcImageLayout: u32,
        dstBuffer: VkBuffer,
        regionCount: u32,
        pRegions: *const VkBufferImageCopy,
    );
    fn vkMapMemory(
        device: VkDevice,
        memory: VkDeviceMemory,
        offset: u64,
        size: u64,
        flags: u32,
        ppData: *mut *mut c_void,
    ) -> VkResult;
    fn vkUnmapMemory(device: VkDevice, memory: VkDeviceMemory);
    fn vkCreateShaderModule(
        device: VkDevice,
        pCreateInfo: *const VkShaderModuleCreateInfo,
        pAllocator: *const c_void,
        pShaderModule: *mut VkShaderModule,
    ) -> VkResult;
    fn vkDestroyShaderModule(
        device: VkDevice,
        shaderModule: VkShaderModule,
        pAllocator: *const c_void,
    );
    fn vkCreatePipelineLayout(
        device: VkDevice,
        pCreateInfo: *const VkPipelineLayoutCreateInfo,
        pAllocator: *const c_void,
        pPipelineLayout: *mut VkPipelineLayout,
    ) -> VkResult;
    fn vkDestroyPipelineLayout(
        device: VkDevice,
        pipelineLayout: VkPipelineLayout,
        pAllocator: *const c_void,
    );
    fn vkCreateGraphicsPipelines(
        device: VkDevice,
        pipelineCache: u64,
        createInfoCount: u32,
        pCreateInfos: *const VkGraphicsPipelineCreateInfo,
        pAllocator: *const c_void,
        pPipelines: *mut VkPipeline,
    ) -> VkResult;
    fn vkDestroyPipeline(device: VkDevice, pipeline: VkPipeline, pAllocator: *const c_void);
    fn vkCmdBindPipeline(
        commandBuffer: VkCommandBuffer,
        pipelineBindPoint: u32,
        pipeline: VkPipeline,
    );
    fn vkCmdDraw(
        commandBuffer: VkCommandBuffer,
        vertexCount: u32,
        instanceCount: u32,
        firstVertex: u32,
        firstInstance: u32,
    );
}

/// Create a Vulkan instance and return the name of each physical device the
/// loader exposes (e.g. `"llvmpipe (LLVM ...)"` under lavapipe). Errors if no
/// Vulkan loader/ICD is reachable.
pub fn devices() -> Result<Vec<String>, String> {
    unsafe {
        let app = VkApplicationInfo {
            sType: VK_STRUCTURE_TYPE_APPLICATION_INFO,
            pNext: core::ptr::null(),
            pApplicationName: c"stipple".as_ptr(),
            applicationVersion: 0,
            pEngineName: c"stipple".as_ptr(),
            engineVersion: 0,
            apiVersion: VK_API_VERSION_1_0,
        };
        let create = VkInstanceCreateInfo {
            sType: VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            pApplicationInfo: &app,
            enabledLayerCount: 0,
            ppEnabledLayerNames: core::ptr::null(),
            enabledExtensionCount: 0,
            ppEnabledExtensionNames: core::ptr::null(),
        };
        let mut instance: VkInstance = core::ptr::null_mut();
        let r = vkCreateInstance(&create, core::ptr::null(), &mut instance);
        if r != VK_SUCCESS {
            return Err(format!("vkCreateInstance failed ({r})"));
        }

        let mut count: u32 = 0;
        vkEnumeratePhysicalDevices(instance, &mut count, core::ptr::null_mut());
        let mut handles: Vec<VkPhysicalDevice> = vec![core::ptr::null_mut(); count as usize];
        if count > 0 {
            vkEnumeratePhysicalDevices(instance, &mut count, handles.as_mut_ptr());
        }

        let mut names = Vec::with_capacity(handles.len());
        for dev in handles {
            // A 2 KiB buffer comfortably exceeds sizeof(VkPhysicalDeviceProperties).
            let mut props = vec![0u8; 2048];
            vkGetPhysicalDeviceProperties(dev, props.as_mut_ptr() as *mut c_void);
            let name =
                &props[DEVICE_NAME_OFFSET..DEVICE_NAME_OFFSET + VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
            let end = name.iter().position(|&b| b == 0).unwrap_or(name.len());
            names.push(String::from_utf8_lossy(&name[..end]).into_owned());
        }

        vkDestroyInstance(instance, core::ptr::null());
        Ok(names)
    }
}

/// A live Vulkan instance + logical device on the first physical device, with a
/// graphics queue family selected. Owns the raw handles; callers destroy them
/// via [`Gpu::destroy`] once done (we keep this manual rather than wiring `Drop`,
/// to keep the FFI surface explicit).
struct Gpu {
    instance: VkInstance,
    phys: VkPhysicalDevice,
    device: VkDevice,
    family: u32,
}

impl Gpu {
    /// Create an instance, pick the first physical device, find a graphics queue
    /// family, and create a logical device with one queue from it.
    unsafe fn create() -> Result<Gpu, String> {
        unsafe {
            let app = VkApplicationInfo {
                sType: VK_STRUCTURE_TYPE_APPLICATION_INFO,
                pNext: core::ptr::null(),
                pApplicationName: c"stipple".as_ptr(),
                applicationVersion: 0,
                pEngineName: c"stipple".as_ptr(),
                engineVersion: 0,
                apiVersion: VK_API_VERSION_1_0,
            };
            let create = VkInstanceCreateInfo {
                sType: VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                pApplicationInfo: &app,
                enabledLayerCount: 0,
                ppEnabledLayerNames: core::ptr::null(),
                enabledExtensionCount: 0,
                ppEnabledExtensionNames: core::ptr::null(),
            };
            let mut instance: VkInstance = core::ptr::null_mut();
            if vkCreateInstance(&create, core::ptr::null(), &mut instance) != VK_SUCCESS {
                return Err("vkCreateInstance failed".into());
            }

            let mut count: u32 = 0;
            vkEnumeratePhysicalDevices(instance, &mut count, core::ptr::null_mut());
            if count == 0 {
                vkDestroyInstance(instance, core::ptr::null());
                return Err("no Vulkan physical devices".into());
            }
            let mut handles: Vec<VkPhysicalDevice> = vec![core::ptr::null_mut(); count as usize];
            vkEnumeratePhysicalDevices(instance, &mut count, handles.as_mut_ptr());
            let phys = handles[0];

            // Find a queue family that supports graphics.
            let mut qcount: u32 = 0;
            vkGetPhysicalDeviceQueueFamilyProperties(phys, &mut qcount, core::ptr::null_mut());
            let mut qbuf = vec![0u8; qcount as usize * QUEUE_FAMILY_PROPS_SIZE];
            vkGetPhysicalDeviceQueueFamilyProperties(
                phys,
                &mut qcount,
                qbuf.as_mut_ptr() as *mut c_void,
            );
            let mut family: Option<u32> = None;
            for i in 0..qcount as usize {
                let off = i * QUEUE_FAMILY_PROPS_SIZE;
                let flags =
                    u32::from_ne_bytes([qbuf[off], qbuf[off + 1], qbuf[off + 2], qbuf[off + 3]]);
                if flags & VK_QUEUE_GRAPHICS_BIT != 0 {
                    family = Some(i as u32);
                    break;
                }
            }
            let Some(family) = family else {
                vkDestroyInstance(instance, core::ptr::null());
                return Err("no graphics queue family".into());
            };

            // Create a logical device with one queue from that family.
            let priority: f32 = 1.0;
            let qci = VkDeviceQueueCreateInfo {
                sType: VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                queueFamilyIndex: family,
                queueCount: 1,
                pQueuePriorities: &priority,
            };
            let dci = VkDeviceCreateInfo {
                sType: VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                queueCreateInfoCount: 1,
                pQueueCreateInfos: &qci,
                enabledLayerCount: 0,
                ppEnabledLayerNames: core::ptr::null(),
                enabledExtensionCount: 0,
                ppEnabledExtensionNames: core::ptr::null(),
                pEnabledFeatures: core::ptr::null(),
            };
            let mut device: VkDevice = core::ptr::null_mut();
            if vkCreateDevice(phys, &dci, core::ptr::null(), &mut device) != VK_SUCCESS {
                vkDestroyInstance(instance, core::ptr::null());
                return Err("vkCreateDevice failed".into());
            }
            Ok(Gpu {
                instance,
                phys,
                device,
                family,
            })
        }
    }

    /// Create a `width`×`height` `R8G8B8A8_UNORM` color-attachment image and back
    /// it with a `DEVICE_LOCAL` memory allocation. Returns `(image, memory,
    /// size)`; the caller frees both with `vkDestroyImage` + `vkFreeMemory`.
    unsafe fn create_color_image(
        &self,
        width: u32,
        height: u32,
    ) -> Result<(VkImage, VkDeviceMemory, u64), String> {
        unsafe {
            let ici = VkImageCreateInfo {
                sType: VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                imageType: VK_IMAGE_TYPE_2D,
                format: VK_FORMAT_R8G8B8A8_UNORM,
                extent: VkExtent3D {
                    width,
                    height,
                    depth: 1,
                },
                mipLevels: 1,
                arrayLayers: 1,
                samples: VK_SAMPLE_COUNT_1_BIT,
                tiling: VK_IMAGE_TILING_OPTIMAL,
                usage: VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
                sharingMode: VK_SHARING_MODE_EXCLUSIVE,
                queueFamilyIndexCount: 0,
                pQueueFamilyIndices: core::ptr::null(),
                initialLayout: VK_IMAGE_LAYOUT_UNDEFINED,
            };
            let mut image: VkImage = 0;
            if vkCreateImage(self.device, &ici, core::ptr::null(), &mut image) != VK_SUCCESS {
                return Err("vkCreateImage failed".into());
            }

            let mut req = VkMemoryRequirements {
                size: 0,
                alignment: 0,
                memoryTypeBits: 0,
            };
            vkGetImageMemoryRequirements(self.device, image, &mut req);

            // Read the device's memory types and pick the first DEVICE_LOCAL one
            // permitted by the image's memoryTypeBits mask.
            let mut memprops = vec![0u8; 1024];
            vkGetPhysicalDeviceMemoryProperties(self.phys, memprops.as_mut_ptr() as *mut c_void);
            let type_count =
                u32::from_ne_bytes([memprops[0], memprops[1], memprops[2], memprops[3]]);
            let mut chosen: Option<u32> = None;
            for i in 0..type_count as usize {
                if req.memoryTypeBits & (1 << i) == 0 {
                    continue;
                }
                let off = MEM_TYPES_OFFSET + i * MEM_TYPE_STRIDE;
                let flags = u32::from_ne_bytes([
                    memprops[off],
                    memprops[off + 1],
                    memprops[off + 2],
                    memprops[off + 3],
                ]);
                if flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT != 0 {
                    chosen = Some(i as u32);
                    break;
                }
            }
            let Some(mem_type) = chosen else {
                vkDestroyImage(self.device, image, core::ptr::null());
                return Err("no DEVICE_LOCAL memory type for the image".into());
            };

            let mai = VkMemoryAllocateInfo {
                sType: VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
                pNext: core::ptr::null(),
                allocationSize: req.size,
                memoryTypeIndex: mem_type,
            };
            let mut memory: VkDeviceMemory = 0;
            if vkAllocateMemory(self.device, &mai, core::ptr::null(), &mut memory) != VK_SUCCESS {
                vkDestroyImage(self.device, image, core::ptr::null());
                return Err("vkAllocateMemory failed".into());
            }
            if vkBindImageMemory(self.device, image, memory, 0) != VK_SUCCESS {
                vkFreeMemory(self.device, memory, core::ptr::null());
                vkDestroyImage(self.device, image, core::ptr::null());
                return Err("vkBindImageMemory failed".into());
            }
            Ok((image, memory, req.size))
        }
    }

    /// Build a complete offscreen render target: a color image + memory, an
    /// image view, a single-attachment render pass (clear→store, ending
    /// transfer-readable), and a framebuffer binding them. Frees what it already
    /// created on any failure.
    unsafe fn create_target(&self, width: u32, height: u32) -> Result<Target, String> {
        unsafe {
            let (image, memory, _bytes) = self.create_color_image(width, height)?;

            let view_ci = VkImageViewCreateInfo {
                sType: VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                image,
                viewType: VK_IMAGE_VIEW_TYPE_2D,
                format: VK_FORMAT_R8G8B8A8_UNORM,
                components: VkComponentMapping {
                    r: VK_COMPONENT_SWIZZLE_IDENTITY,
                    g: VK_COMPONENT_SWIZZLE_IDENTITY,
                    b: VK_COMPONENT_SWIZZLE_IDENTITY,
                    a: VK_COMPONENT_SWIZZLE_IDENTITY,
                },
                subresourceRange: VkImageSubresourceRange {
                    aspectMask: VK_IMAGE_ASPECT_COLOR_BIT,
                    baseMipLevel: 0,
                    levelCount: 1,
                    baseArrayLayer: 0,
                    layerCount: 1,
                },
            };
            let mut view: VkImageView = 0;
            if vkCreateImageView(self.device, &view_ci, core::ptr::null(), &mut view) != VK_SUCCESS
            {
                vkFreeMemory(self.device, memory, core::ptr::null());
                vkDestroyImage(self.device, image, core::ptr::null());
                return Err("vkCreateImageView failed".into());
            }

            let attachment = VkAttachmentDescription {
                flags: 0,
                format: VK_FORMAT_R8G8B8A8_UNORM,
                samples: VK_SAMPLE_COUNT_1_BIT,
                loadOp: VK_ATTACHMENT_LOAD_OP_CLEAR,
                storeOp: VK_ATTACHMENT_STORE_OP_STORE,
                stencilLoadOp: VK_ATTACHMENT_LOAD_OP_DONT_CARE,
                stencilStoreOp: VK_ATTACHMENT_STORE_OP_DONT_CARE,
                initialLayout: VK_IMAGE_LAYOUT_UNDEFINED,
                finalLayout: VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
            };
            let color_ref = VkAttachmentReference {
                attachment: 0,
                layout: VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
            };
            let subpass = VkSubpassDescription {
                flags: 0,
                pipelineBindPoint: VK_PIPELINE_BIND_POINT_GRAPHICS,
                inputAttachmentCount: 0,
                pInputAttachments: core::ptr::null(),
                colorAttachmentCount: 1,
                pColorAttachments: &color_ref,
                pResolveAttachments: core::ptr::null(),
                pDepthStencilAttachment: core::ptr::null(),
                preserveAttachmentCount: 0,
                pPreserveAttachments: core::ptr::null(),
            };
            let rp_ci = VkRenderPassCreateInfo {
                sType: VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                attachmentCount: 1,
                pAttachments: &attachment,
                subpassCount: 1,
                pSubpasses: &subpass,
                dependencyCount: 0,
                pDependencies: core::ptr::null(),
            };
            let mut render_pass: VkRenderPass = 0;
            if vkCreateRenderPass(self.device, &rp_ci, core::ptr::null(), &mut render_pass)
                != VK_SUCCESS
            {
                vkDestroyImageView(self.device, view, core::ptr::null());
                vkFreeMemory(self.device, memory, core::ptr::null());
                vkDestroyImage(self.device, image, core::ptr::null());
                return Err("vkCreateRenderPass failed".into());
            }

            let fb_ci = VkFramebufferCreateInfo {
                sType: VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                renderPass: render_pass,
                attachmentCount: 1,
                pAttachments: &view,
                width,
                height,
                layers: 1,
            };
            let mut framebuffer: VkFramebuffer = 0;
            if vkCreateFramebuffer(self.device, &fb_ci, core::ptr::null(), &mut framebuffer)
                != VK_SUCCESS
            {
                vkDestroyRenderPass(self.device, render_pass, core::ptr::null());
                vkDestroyImageView(self.device, view, core::ptr::null());
                vkFreeMemory(self.device, memory, core::ptr::null());
                vkDestroyImage(self.device, image, core::ptr::null());
                return Err("vkCreateFramebuffer failed".into());
            }

            Ok(Target {
                image,
                memory,
                view,
                render_pass,
                framebuffer,
                width,
                height,
            })
        }
    }

    /// Create a `size`-byte buffer usable as a transfer destination, backed by
    /// `HOST_VISIBLE | HOST_COHERENT` memory so the CPU can map and read it.
    /// Returns `(buffer, memory)`; the caller frees both.
    unsafe fn create_host_buffer(&self, size: u64) -> Result<(VkBuffer, VkDeviceMemory), String> {
        unsafe {
            let bci = VkBufferCreateInfo {
                sType: VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                size,
                usage: VK_BUFFER_USAGE_TRANSFER_DST_BIT,
                sharingMode: VK_SHARING_MODE_EXCLUSIVE,
                queueFamilyIndexCount: 0,
                pQueueFamilyIndices: core::ptr::null(),
            };
            let mut buffer: VkBuffer = 0;
            if vkCreateBuffer(self.device, &bci, core::ptr::null(), &mut buffer) != VK_SUCCESS {
                return Err("vkCreateBuffer failed".into());
            }

            let mut req = VkMemoryRequirements {
                size: 0,
                alignment: 0,
                memoryTypeBits: 0,
            };
            vkGetBufferMemoryRequirements(self.device, buffer, &mut req);

            let want = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
            let mut memprops = vec![0u8; 1024];
            vkGetPhysicalDeviceMemoryProperties(self.phys, memprops.as_mut_ptr() as *mut c_void);
            let type_count =
                u32::from_ne_bytes([memprops[0], memprops[1], memprops[2], memprops[3]]);
            let mut chosen: Option<u32> = None;
            for i in 0..type_count as usize {
                if req.memoryTypeBits & (1 << i) == 0 {
                    continue;
                }
                let off = MEM_TYPES_OFFSET + i * MEM_TYPE_STRIDE;
                let flags = u32::from_ne_bytes([
                    memprops[off],
                    memprops[off + 1],
                    memprops[off + 2],
                    memprops[off + 3],
                ]);
                if flags & want == want {
                    chosen = Some(i as u32);
                    break;
                }
            }
            let Some(mem_type) = chosen else {
                vkDestroyBuffer(self.device, buffer, core::ptr::null());
                return Err("no HOST_VISIBLE|COHERENT memory type for the buffer".into());
            };

            let mai = VkMemoryAllocateInfo {
                sType: VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
                pNext: core::ptr::null(),
                allocationSize: req.size,
                memoryTypeIndex: mem_type,
            };
            let mut memory: VkDeviceMemory = 0;
            if vkAllocateMemory(self.device, &mai, core::ptr::null(), &mut memory) != VK_SUCCESS {
                vkDestroyBuffer(self.device, buffer, core::ptr::null());
                return Err("vkAllocateMemory (host buffer) failed".into());
            }
            if vkBindBufferMemory(self.device, buffer, memory, 0) != VK_SUCCESS {
                vkFreeMemory(self.device, memory, core::ptr::null());
                vkDestroyBuffer(self.device, buffer, core::ptr::null());
                return Err("vkBindBufferMemory failed".into());
            }
            Ok((buffer, memory))
        }
    }

    /// Create a shader module from a SPIR-V byte blob. SPIR-V is a stream of
    /// 32-bit words; `include_bytes!` yields byte alignment 1, so we realign into
    /// a `Vec<u32>` before handing Vulkan `pCode`.
    unsafe fn shader_module(&self, spv: &[u8]) -> Result<VkShaderModule, String> {
        unsafe {
            if !spv.len().is_multiple_of(4) {
                return Err("SPIR-V length is not a multiple of 4".into());
            }
            let words: Vec<u32> = spv
                .chunks_exact(4)
                .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
                .collect();
            let ci = VkShaderModuleCreateInfo {
                sType: VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                codeSize: spv.len(),
                pCode: words.as_ptr(),
            };
            let mut module: VkShaderModule = 0;
            if vkCreateShaderModule(self.device, &ci, core::ptr::null(), &mut module) != VK_SUCCESS
            {
                return Err("vkCreateShaderModule failed".into());
            }
            Ok(module)
        }
    }

    /// Run one render pass on `target` — clearing to `clear`, then executing
    /// `record` (which adds draw commands inside the pass) — copy the result to a
    /// host buffer, and return the read-back RGBA pixels. The shared
    /// record→submit→copy→map path behind both the plain clear and the triangle
    /// draw. Cleans up everything it allocates (buffer, pool, fence); the caller
    /// still owns `target` and `self`.
    unsafe fn draw_to_pixels(
        &self,
        target: &Target,
        clear: [f32; 4],
        record: impl FnOnce(VkCommandBuffer),
    ) -> Result<Vec<u8>, String> {
        unsafe {
            let size = target.width as u64 * target.height as u64 * 4;
            let (buffer, buf_mem) = self.create_host_buffer(size)?;

            // Tears down everything this function allocates.
            let cleanup = |dev: VkDevice,
                           buffer: VkBuffer,
                           buf_mem: VkDeviceMemory,
                           pool: VkCommandPool,
                           fence: VkFence| {
                if fence != 0 {
                    vkDestroyFence(dev, fence, core::ptr::null());
                }
                if pool != 0 {
                    vkDestroyCommandPool(dev, pool, core::ptr::null());
                }
                vkFreeMemory(dev, buf_mem, core::ptr::null());
                vkDestroyBuffer(dev, buffer, core::ptr::null());
            };

            let pool_ci = VkCommandPoolCreateInfo {
                sType: VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                queueFamilyIndex: self.family,
            };
            let mut pool: VkCommandPool = 0;
            if vkCreateCommandPool(self.device, &pool_ci, core::ptr::null(), &mut pool)
                != VK_SUCCESS
            {
                cleanup(self.device, buffer, buf_mem, 0, 0);
                return Err("vkCreateCommandPool failed".into());
            }
            let alloc = VkCommandBufferAllocateInfo {
                sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
                pNext: core::ptr::null(),
                commandPool: pool,
                level: VK_COMMAND_BUFFER_LEVEL_PRIMARY,
                commandBufferCount: 1,
            };
            let mut cmd: VkCommandBuffer = core::ptr::null_mut();
            if vkAllocateCommandBuffers(self.device, &alloc, &mut cmd) != VK_SUCCESS {
                cleanup(self.device, buffer, buf_mem, pool, 0);
                return Err("vkAllocateCommandBuffers failed".into());
            }

            let begin = VkCommandBufferBeginInfo {
                sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
                pNext: core::ptr::null(),
                flags: VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
                pInheritanceInfo: core::ptr::null(),
            };
            if vkBeginCommandBuffer(cmd, &begin) != VK_SUCCESS {
                cleanup(self.device, buffer, buf_mem, pool, 0);
                return Err("vkBeginCommandBuffer failed".into());
            }
            let clear_value = VkClearValue { float32: clear };
            let rp_begin = VkRenderPassBeginInfo {
                sType: VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
                pNext: core::ptr::null(),
                renderPass: target.render_pass,
                framebuffer: target.framebuffer,
                renderArea: VkRect2D {
                    offset: VkOffset2D { x: 0, y: 0 },
                    extent: VkExtent2D {
                        width: target.width,
                        height: target.height,
                    },
                },
                clearValueCount: 1,
                pClearValues: &clear_value,
            };
            vkCmdBeginRenderPass(cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
            record(cmd);
            vkCmdEndRenderPass(cmd);

            // The render pass left the image in TRANSFER_SRC_OPTIMAL — copy it,
            // tightly packed, into the host buffer.
            let region = VkBufferImageCopy {
                bufferOffset: 0,
                bufferRowLength: 0,
                bufferImageHeight: 0,
                imageSubresource: VkImageSubresourceLayers {
                    aspectMask: VK_IMAGE_ASPECT_COLOR_BIT,
                    mipLevel: 0,
                    baseArrayLayer: 0,
                    layerCount: 1,
                },
                imageOffset: VkOffset3D { x: 0, y: 0, z: 0 },
                imageExtent: VkExtent3D {
                    width: target.width,
                    height: target.height,
                    depth: 1,
                },
            };
            vkCmdCopyImageToBuffer(
                cmd,
                target.image,
                VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
                buffer,
                1,
                &region,
            );
            if vkEndCommandBuffer(cmd) != VK_SUCCESS {
                cleanup(self.device, buffer, buf_mem, pool, 0);
                return Err("vkEndCommandBuffer failed".into());
            }

            let mut queue: VkQueue = core::ptr::null_mut();
            vkGetDeviceQueue(self.device, self.family, 0, &mut queue);
            let fence_ci = VkFenceCreateInfo {
                sType: VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
            };
            let mut fence: VkFence = 0;
            if vkCreateFence(self.device, &fence_ci, core::ptr::null(), &mut fence) != VK_SUCCESS {
                cleanup(self.device, buffer, buf_mem, pool, 0);
                return Err("vkCreateFence failed".into());
            }
            let submit = VkSubmitInfo {
                sType: VK_STRUCTURE_TYPE_SUBMIT_INFO,
                pNext: core::ptr::null(),
                waitSemaphoreCount: 0,
                pWaitSemaphores: core::ptr::null(),
                pWaitDstStageMask: core::ptr::null(),
                commandBufferCount: 1,
                pCommandBuffers: &cmd,
                signalSemaphoreCount: 0,
                pSignalSemaphores: core::ptr::null(),
            };
            if vkQueueSubmit(queue, 1, &submit, fence) != VK_SUCCESS {
                cleanup(self.device, buffer, buf_mem, pool, fence);
                return Err("vkQueueSubmit failed".into());
            }
            if vkWaitForFences(self.device, 1, &fence, VK_TRUE, u64::MAX) != VK_SUCCESS {
                cleanup(self.device, buffer, buf_mem, pool, fence);
                return Err("vkWaitForFences failed".into());
            }

            let mut ptr: *mut c_void = core::ptr::null_mut();
            if vkMapMemory(self.device, buf_mem, 0, size, 0, &mut ptr) != VK_SUCCESS
                || ptr.is_null()
            {
                cleanup(self.device, buffer, buf_mem, pool, fence);
                return Err("vkMapMemory failed".into());
            }
            let mut pixels = vec![0u8; size as usize];
            core::ptr::copy_nonoverlapping(ptr as *const u8, pixels.as_mut_ptr(), size as usize);
            vkUnmapMemory(self.device, buf_mem);

            cleanup(self.device, buffer, buf_mem, pool, fence);
            Ok(pixels)
        }
    }

    unsafe fn destroy(self) {
        unsafe {
            vkDestroyDevice(self.device, core::ptr::null());
            vkDestroyInstance(self.instance, core::ptr::null());
        }
    }
}

/// A complete offscreen render target owned alongside a [`Gpu`]: the color image
/// and its backing memory, a view, a render pass, and a framebuffer. Destroyed
/// explicitly via [`Target::destroy`] (passing the owning device).
struct Target {
    image: VkImage,
    memory: VkDeviceMemory,
    view: VkImageView,
    render_pass: VkRenderPass,
    framebuffer: VkFramebuffer,
    width: u32,
    height: u32,
}

impl Target {
    unsafe fn destroy(self, device: VkDevice) {
        unsafe {
            vkDestroyFramebuffer(device, self.framebuffer, core::ptr::null());
            vkDestroyRenderPass(device, self.render_pass, core::ptr::null());
            vkDestroyImageView(device, self.view, core::ptr::null());
            vkFreeMemory(device, self.memory, core::ptr::null());
            vkDestroyImage(device, self.image, core::ptr::null());
        }
    }
}

/// Create an instance, pick the first physical device, select a graphics queue
/// family, and create a logical device with that queue — the core a Vulkan
/// render backend builds on. Returns a one-line summary. Errors if any step
/// fails or no graphics-capable device exists.
pub fn init_device() -> Result<String, String> {
    unsafe {
        let gpu = Gpu::create()?;
        let mut queue: VkQueue = core::ptr::null_mut();
        vkGetDeviceQueue(gpu.device, gpu.family, 0, &mut queue);
        let ok = !queue.is_null();
        let family = gpu.family;
        gpu.destroy();
        if ok {
            Ok(format!(
                "logical device + graphics queue (family {family}) created"
            ))
        } else {
            Err("vkGetDeviceQueue returned null".into())
        }
    }
}

/// Allocate a GPU-resident render target: create a `width`×`height`
/// `R8G8B8A8_UNORM` color-attachment [`VkImage`], query its memory
/// requirements, choose a `DEVICE_LOCAL` memory type, and back it with a
/// [`VkDeviceMemory`] allocation — the offscreen target a Vulkan render pass
/// draws into. Returns a one-line summary (size + chosen memory type). Errors if
/// any step fails.
pub fn init_image(width: u32, height: u32) -> Result<String, String> {
    unsafe {
        let gpu = Gpu::create()?;
        let r = gpu.create_color_image(width, height);
        match r {
            Ok((image, memory, bytes)) => {
                vkFreeMemory(gpu.device, memory, core::ptr::null());
                vkDestroyImage(gpu.device, image, core::ptr::null());
                gpu.destroy();
                Ok(format!(
                    "{width}x{height} color image bound to {bytes}B of DEVICE_LOCAL memory"
                ))
            }
            Err(e) => {
                gpu.destroy();
                Err(e)
            }
        }
    }
}

/// Build the render-target objects a Vulkan render pass needs: a [`VkImageView`]
/// over a freshly-allocated color image, a single-attachment [`VkRenderPass`]
/// (clear on load, store on done, ending in `TRANSFER_SRC_OPTIMAL` ready for
/// readback), and a [`VkFramebuffer`] binding the view to the pass. Returns a
/// one-line summary. Errors if any step fails.
pub fn init_framebuffer(width: u32, height: u32) -> Result<String, String> {
    unsafe {
        let gpu = Gpu::create()?;
        match gpu.create_target(width, height) {
            Ok(target) => {
                target.destroy(gpu.device);
                gpu.destroy();
                Ok(format!(
                    "{width}x{height} framebuffer + render pass + image view created"
                ))
            }
            Err(e) => {
                gpu.destroy();
                Err(e)
            }
        }
    }
}

/// Execute real GPU work: record a primary command buffer that runs the
/// single-attachment render pass — whose load-op **clears** the color image to a
/// fixed color — submit it to the graphics queue, and block on a fence until the
/// GPU signals completion. This is the first command-buffer round-trip the
/// eventual draw pipeline (pipeline + draw calls) slots into. Returns a one-line
/// summary. Errors if any step fails.
pub fn init_clear(width: u32, height: u32) -> Result<String, String> {
    unsafe {
        let gpu = Gpu::create()?;
        let target = match gpu.create_target(width, height) {
            Ok(t) => t,
            Err(e) => {
                gpu.destroy();
                return Err(e);
            }
        };

        // Tear down everything created so far, on failure or success.
        let finish = |gpu: Gpu, target: Target, pool: VkCommandPool, fence: VkFence| {
            if fence != 0 {
                vkDestroyFence(gpu.device, fence, core::ptr::null());
            }
            if pool != 0 {
                // Frees the command buffers allocated from it too.
                vkDestroyCommandPool(gpu.device, pool, core::ptr::null());
            }
            target.destroy(gpu.device);
            gpu.destroy();
        };

        // A command pool on the graphics family, and one primary command buffer.
        let pool_ci = VkCommandPoolCreateInfo {
            sType: VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            queueFamilyIndex: gpu.family,
        };
        let mut pool: VkCommandPool = 0;
        if vkCreateCommandPool(gpu.device, &pool_ci, core::ptr::null(), &mut pool) != VK_SUCCESS {
            finish(gpu, target, 0, 0);
            return Err("vkCreateCommandPool failed".into());
        }
        let alloc = VkCommandBufferAllocateInfo {
            sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
            pNext: core::ptr::null(),
            commandPool: pool,
            level: VK_COMMAND_BUFFER_LEVEL_PRIMARY,
            commandBufferCount: 1,
        };
        let mut cmd: VkCommandBuffer = core::ptr::null_mut();
        if vkAllocateCommandBuffers(gpu.device, &alloc, &mut cmd) != VK_SUCCESS {
            finish(gpu, target, pool, 0);
            return Err("vkAllocateCommandBuffers failed".into());
        }

        // Record: begin → run the clearing render pass → end.
        let begin = VkCommandBufferBeginInfo {
            sType: VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
            pNext: core::ptr::null(),
            flags: VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
            pInheritanceInfo: core::ptr::null(),
        };
        if vkBeginCommandBuffer(cmd, &begin) != VK_SUCCESS {
            finish(gpu, target, pool, 0);
            return Err("vkBeginCommandBuffer failed".into());
        }
        // A recognizable stipple blue (0x60, 0x9c, 0xff) so a later readback can
        // confirm the clear actually ran.
        let clear = VkClearValue {
            float32: [0x60 as f32 / 255.0, 0x9c as f32 / 255.0, 1.0, 1.0],
        };
        let rp_begin = VkRenderPassBeginInfo {
            sType: VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
            pNext: core::ptr::null(),
            renderPass: target.render_pass,
            framebuffer: target.framebuffer,
            renderArea: VkRect2D {
                offset: VkOffset2D { x: 0, y: 0 },
                extent: VkExtent2D {
                    width: target.width,
                    height: target.height,
                },
            },
            clearValueCount: 1,
            pClearValues: &clear,
        };
        vkCmdBeginRenderPass(cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
        vkCmdEndRenderPass(cmd);
        if vkEndCommandBuffer(cmd) != VK_SUCCESS {
            finish(gpu, target, pool, 0);
            return Err("vkEndCommandBuffer failed".into());
        }

        // Submit to the graphics queue, fenced, and wait for the GPU.
        let mut queue: VkQueue = core::ptr::null_mut();
        vkGetDeviceQueue(gpu.device, gpu.family, 0, &mut queue);

        let fence_ci = VkFenceCreateInfo {
            sType: VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
        };
        let mut fence: VkFence = 0;
        if vkCreateFence(gpu.device, &fence_ci, core::ptr::null(), &mut fence) != VK_SUCCESS {
            finish(gpu, target, pool, 0);
            return Err("vkCreateFence failed".into());
        }
        let submit = VkSubmitInfo {
            sType: VK_STRUCTURE_TYPE_SUBMIT_INFO,
            pNext: core::ptr::null(),
            waitSemaphoreCount: 0,
            pWaitSemaphores: core::ptr::null(),
            pWaitDstStageMask: core::ptr::null(),
            commandBufferCount: 1,
            pCommandBuffers: &cmd,
            signalSemaphoreCount: 0,
            pSignalSemaphores: core::ptr::null(),
        };
        if vkQueueSubmit(queue, 1, &submit, fence) != VK_SUCCESS {
            finish(gpu, target, pool, fence);
            return Err("vkQueueSubmit failed".into());
        }
        let waited = vkWaitForFences(gpu.device, 1, &fence, VK_TRUE, u64::MAX) == VK_SUCCESS;

        finish(gpu, target, pool, fence);
        if waited {
            Ok(format!(
                "{width}x{height} render pass submitted and cleared (fence signaled)"
            ))
        } else {
            Err("vkWaitForFences failed".into())
        }
    }
}

/// The Vulkan offscreen capstone: run the clearing render pass on the GPU, then
/// `vkCmdCopyImageToBuffer` the result into a host-visible buffer, fence-wait,
/// map it, and return the `width`×`height` RGBA pixels — an actual GPU-rendered
/// frame read back to the CPU (so CI can turn it into a screenshot). The eventual
/// draw pipeline replaces only the "clear" with real draw calls; this readback
/// path stays. Errors if any step fails.
pub fn render_clear(width: u32, height: u32) -> Result<Vec<u8>, String> {
    unsafe {
        let gpu = Gpu::create()?;
        let target = match gpu.create_target(width, height) {
            Ok(t) => t,
            Err(e) => {
                gpu.destroy();
                return Err(e);
            }
        };
        // stipple blue (0x60, 0x9c, 0xff) — the readback pixels should be this.
        let clear = [0x60 as f32 / 255.0, 0x9c as f32 / 255.0, 1.0, 1.0];
        let result = gpu.draw_to_pixels(&target, clear, |_cmd| {});
        target.destroy(gpu.device);
        gpu.destroy();
        result
    }
}

// Precompiled SPIR-V (committed; built once from shaders/*.{vert,frag} with
// glslangValidator) so the crate has no build-time shader-compiler dependency.
const TRIANGLE_VERT_SPV: &[u8] = include_bytes!("shaders/triangle.vert.spv");
const TRIANGLE_FRAG_SPV: &[u8] = include_bytes!("shaders/triangle.frag.spv");

/// The full Vulkan render pipeline: compile two SPIR-V shader modules, build a
/// graphics pipeline (no vertex buffers — the vertex shader emits a triangle
/// from `gl_VertexIndex`), then **draw** it over a dark-cleared `width`×`height`
/// target and read the frame back to the CPU. Unlike [`render_clear`] this runs
/// real shaders through `vkCmdDraw`, so the center pixel comes out stipple green.
/// Returns the RGBA pixels. Errors if any step fails.
pub fn render_triangle(width: u32, height: u32) -> Result<Vec<u8>, String> {
    unsafe {
        let gpu = Gpu::create()?;
        let target = match gpu.create_target(width, height) {
            Ok(t) => t,
            Err(e) => {
                gpu.destroy();
                return Err(e);
            }
        };

        // Shader modules from the committed SPIR-V.
        let vert = match gpu.shader_module(TRIANGLE_VERT_SPV) {
            Ok(m) => m,
            Err(e) => {
                target.destroy(gpu.device);
                gpu.destroy();
                return Err(e);
            }
        };
        let frag = match gpu.shader_module(TRIANGLE_FRAG_SPV) {
            Ok(m) => m,
            Err(e) => {
                vkDestroyShaderModule(gpu.device, vert, core::ptr::null());
                target.destroy(gpu.device);
                gpu.destroy();
                return Err(e);
            }
        };

        // Cleans up the pipeline-related objects (and target + gpu) on exit.
        let teardown =
            |gpu: Gpu, target: Target, pipeline: VkPipeline, layout: VkPipelineLayout| {
                if pipeline != 0 {
                    vkDestroyPipeline(gpu.device, pipeline, core::ptr::null());
                }
                if layout != 0 {
                    vkDestroyPipelineLayout(gpu.device, layout, core::ptr::null());
                }
                vkDestroyShaderModule(gpu.device, frag, core::ptr::null());
                vkDestroyShaderModule(gpu.device, vert, core::ptr::null());
                target.destroy(gpu.device);
                gpu.destroy();
            };

        // An empty pipeline layout (no descriptors, no push constants).
        let pl_ci = VkPipelineLayoutCreateInfo {
            sType: VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            setLayoutCount: 0,
            pSetLayouts: core::ptr::null(),
            pushConstantRangeCount: 0,
            pPushConstantRanges: core::ptr::null(),
        };
        let mut layout: VkPipelineLayout = 0;
        if vkCreatePipelineLayout(gpu.device, &pl_ci, core::ptr::null(), &mut layout) != VK_SUCCESS
        {
            teardown(gpu, target, 0, 0);
            return Err("vkCreatePipelineLayout failed".into());
        }

        let stages = [
            VkPipelineShaderStageCreateInfo {
                sType: VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                stage: VK_SHADER_STAGE_VERTEX_BIT,
                module: vert,
                pName: c"main".as_ptr(),
                pSpecializationInfo: core::ptr::null(),
            },
            VkPipelineShaderStageCreateInfo {
                sType: VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                pNext: core::ptr::null(),
                flags: 0,
                stage: VK_SHADER_STAGE_FRAGMENT_BIT,
                module: frag,
                pName: c"main".as_ptr(),
                pSpecializationInfo: core::ptr::null(),
            },
        ];
        // No vertex buffers — the vertex shader generates positions.
        let vertex_input = VkPipelineVertexInputStateCreateInfo {
            sType: VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            vertexBindingDescriptionCount: 0,
            pVertexBindingDescriptions: core::ptr::null(),
            vertexAttributeDescriptionCount: 0,
            pVertexAttributeDescriptions: core::ptr::null(),
        };
        let input_assembly = VkPipelineInputAssemblyStateCreateInfo {
            sType: VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            topology: VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
            primitiveRestartEnable: 0,
        };
        let viewport = VkViewport {
            x: 0.0,
            y: 0.0,
            width: width as f32,
            height: height as f32,
            minDepth: 0.0,
            maxDepth: 1.0,
        };
        let scissor = VkRect2D {
            offset: VkOffset2D { x: 0, y: 0 },
            extent: VkExtent2D { width, height },
        };
        let viewport_state = VkPipelineViewportStateCreateInfo {
            sType: VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            viewportCount: 1,
            pViewports: &viewport,
            scissorCount: 1,
            pScissors: &scissor,
        };
        let raster = VkPipelineRasterizationStateCreateInfo {
            sType: VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            depthClampEnable: 0,
            rasterizerDiscardEnable: 0,
            polygonMode: VK_POLYGON_MODE_FILL,
            cullMode: VK_CULL_MODE_NONE,
            frontFace: VK_FRONT_FACE_COUNTER_CLOCKWISE,
            depthBiasEnable: 0,
            depthBiasConstantFactor: 0.0,
            depthBiasClamp: 0.0,
            depthBiasSlopeFactor: 0.0,
            lineWidth: 1.0,
        };
        let multisample = VkPipelineMultisampleStateCreateInfo {
            sType: VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            rasterizationSamples: VK_SAMPLE_COUNT_1_BIT,
            sampleShadingEnable: 0,
            minSampleShading: 0.0,
            pSampleMask: core::ptr::null(),
            alphaToCoverageEnable: 0,
            alphaToOneEnable: 0,
        };
        let blend_attachment = VkPipelineColorBlendAttachmentState {
            blendEnable: 0,
            srcColorBlendFactor: 0,
            dstColorBlendFactor: 0,
            colorBlendOp: 0,
            srcAlphaBlendFactor: 0,
            dstAlphaBlendFactor: 0,
            alphaBlendOp: 0,
            colorWriteMask: VK_COLOR_COMPONENT_RGBA,
        };
        let color_blend = VkPipelineColorBlendStateCreateInfo {
            sType: VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            logicOpEnable: 0,
            logicOp: 0,
            attachmentCount: 1,
            pAttachments: &blend_attachment,
            blendConstants: [0.0; 4],
        };
        let gp_ci = VkGraphicsPipelineCreateInfo {
            sType: VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
            pNext: core::ptr::null(),
            flags: 0,
            stageCount: 2,
            pStages: stages.as_ptr(),
            pVertexInputState: &vertex_input,
            pInputAssemblyState: &input_assembly,
            pTessellationState: core::ptr::null(),
            pViewportState: &viewport_state,
            pRasterizationState: &raster,
            pMultisampleState: &multisample,
            pDepthStencilState: core::ptr::null(),
            pColorBlendState: &color_blend,
            pDynamicState: core::ptr::null(),
            layout,
            renderPass: target.render_pass,
            subpass: 0,
            basePipelineHandle: 0,
            basePipelineIndex: -1,
        };
        let mut pipeline: VkPipeline = 0;
        if vkCreateGraphicsPipelines(gpu.device, 0, 1, &gp_ci, core::ptr::null(), &mut pipeline)
            != VK_SUCCESS
        {
            teardown(gpu, target, 0, layout);
            return Err("vkCreateGraphicsPipelines failed".into());
        }

        // Dark background; the triangle is drawn stipple green over it.
        let clear = [
            0x14 as f32 / 255.0,
            0x15 as f32 / 255.0,
            0x18 as f32 / 255.0,
            1.0,
        ];
        let result = gpu.draw_to_pixels(&target, clear, |cmd| {
            vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
            vkCmdDraw(cmd, 3, 1, 0, 0);
        });
        teardown(gpu, target, pipeline, layout);
        result
    }
}