summaryrefslogtreecommitdiff
path: root/main.c
blob: 2a7f242f99671628276c1677433f2ddef313c612 (plain)
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
/*
Copyright (c) 2019, Jordan Halase <jordan@halase.me>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/

/* Note: Due to the length of many function and variable names in the
 *       Vulkan API, the line width of any Vulkan-related code here may be
 *       extended from 80 columns to 120 colums to improve readability.
 */

/* The goal of this project is to create an entirely self-contained, embeddable
 * Vulkan renderer. While dynamic linking directly against the system Vulkan
 * loader is safe, it will crash if attempting to run on a system without it
 * installed. By loading the Vulkan library dynamically, the application may
 * gracefully close or even fall back to a different rendering API.
 * Furthermore, Vulkan specifies that using functions retrieved via
 * `vkGetDeviceProcAddr` may actually run faster than if the application were
 * using the Vulkan loader directly due to bypassing the loader terminator.
 *
 * https://vulkan.lunarg.com/doc/sdk/1.0.61.1/windows/LoaderAndLayerInterface.html
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include <vulkan/vulkan.h>

#if defined(_WIN32)
#include <windows.h>
#include <vulkan/vulkan_win32.h>	// XXX Pugl: to implement puglCreateVulkanSurface() on Win32
#else
#include <X11/Xlib.h>		// XXX Pugl: to implement puglCreateVulkanSurface() on X11
#include <vulkan/vulkan_xlib.h>	// XXX Pugl: to implement puglCreateVulkanSurface() on X11
#endif

#include "test/test_utils.h"	// for printEvent()

#include "pugl/pugl.h"
#include "pugl/pugl_stub_backend.h"

#define STB_SPRINTF_IMPLEMENTATION
#include "stb_sprintf.h"	// a better, cross-platform sprintf() for error formatting

/* Thread-local storage for ad-hoc dlerr() on Windows */
#if defined(__GNUC__)
#define APP_THREAD_LOCAL	__thread
#else
#define APP_THREAD_LOCAL	__declspec(thread)
#endif

struct Arguments {
	bool validation;
	bool verbose;
	bool continuous;
};

static void printUsage(const char *cmd, const struct Arguments *args, const bool error)
{
	FILE *fp = error ? stderr : stdout;
	const char *const defaultStr = "\t[default]\n";
	const char *const newline = "\n";
	fprintf(fp, "Usage: %s [OPTION...]\n", cmd);
	fprintf(fp, "  -h, --help\t\tShow this help message\n");
	fprintf(fp, "  --validation\t\tRun with Vulkan validation layers and debug callback%s",
			args->validation ? defaultStr : newline);
	fprintf(fp, "  --no-validation\tRun without Vulkan validation layers or debug callback%s",
			!args->validation ? defaultStr : newline);
	fprintf(fp, "  -c, --continuous\tDraw continuously as fast as possible%s",
			args->continuous ? defaultStr : newline);
	fprintf(fp, "  -v, --verbose\t\tPrint verbose window system events%s",
			args->verbose ? defaultStr : newline);
	exit(error);
}

static void parseArgs(const int argc, char *const *const argv, struct Arguments *const args)
{
	if (argc < 2) {
		return;
	}
	const struct Arguments immutable = *args;
	int i;
	for (i = 1; i < argc; ++i) {
		if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
			printUsage(argv[0], &immutable, false);
		} else if (!strcmp(argv[i], "--validation")) {
			args->validation = true;
		} else if (!strcmp(argv[i], "--no-validation")) {
			args->validation = false;
		} else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--continuous")) {
			args->continuous = true;
		} else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")) {
			args->verbose = true;
		} else {
			fprintf(stderr, "Unknown option `%s`\n", argv[1]);
			printUsage(argv[0], &immutable, true);
		}
	}
}

static void printArgs(int argc, char **argv)
{
	int i;
	for (i = 0; i < argc-1; ++i) {
		printf("%s ", argv[i]);
	}
	printf("%s\n", argv[i]);
}

/** Vulkan allocation callbacks if we ever decide to use them when debugging.
 *
 * This is put in a macro so we don't have to look for every Vulkan function
 * that uses it.
 */
#define ALLOC_VK	NULL

/** Instance-level Vulkan functions and handle */
struct VulkanAPI {
	void						*handle;
	PFN_vkGetInstanceProcAddr			vkGetInstanceProcAddr;
	PFN_vkEnumerateInstanceVersion			vkEnumerateInstanceVersion;
	PFN_vkEnumerateInstanceExtensionProperties	vkEnumerateInstanceExtensionProperties;
	PFN_vkEnumerateInstanceLayerProperties		vkEnumerateInstanceLayerProperties;
	PFN_vkCreateInstance				vkCreateInstance;
	PFN_vkDestroyInstance				vkDestroyInstance;
	PFN_vkCreateDebugReportCallbackEXT		vkCreateDebugReportCallbackEXT;
	PFN_vkDestroyDebugReportCallbackEXT		vkDestroyDebugReportCallbackEXT;
	PFN_vkDestroySurfaceKHR				vkDestroySurfaceKHR;
	PFN_vkEnumeratePhysicalDevices			vkEnumeratePhysicalDevices;
	PFN_vkGetPhysicalDeviceProperties		vkGetPhysicalDeviceProperties;
	PFN_vkGetPhysicalDeviceQueueFamilyProperties	vkGetPhysicalDeviceQueueFamilyProperties;
	PFN_vkGetPhysicalDeviceSurfaceSupportKHR	vkGetPhysicalDeviceSurfaceSupportKHR;
	PFN_vkGetPhysicalDeviceMemoryProperties		vkGetPhysicalDeviceMemoryProperties;
	PFN_vkEnumerateDeviceExtensionProperties	vkEnumerateDeviceExtensionProperties;
	PFN_vkCreateDevice				vkCreateDevice;
	PFN_vkGetDeviceProcAddr				vkGetDeviceProcAddr;
	PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR	vkGetPhysicalDeviceSurfaceCapabilitiesKHR;
	PFN_vkGetPhysicalDeviceSurfaceFormatsKHR	vkGetPhysicalDeviceSurfaceFormatsKHR;
	PFN_vkGetPhysicalDeviceSurfacePresentModesKHR	vkGetPhysicalDeviceSurfacePresentModesKHR;
};

/** Device-level Vulkan functions */
struct VulkanDev {
	PFN_vkDestroyDevice		vkDestroyDevice;
	PFN_vkDeviceWaitIdle		vkDeviceWaitIdle;
	PFN_vkGetDeviceQueue		vkGetDeviceQueue;
	PFN_vkQueueWaitIdle		vkQueueWaitIdle;
	PFN_vkCreateCommandPool		vkCreateCommandPool;
	PFN_vkDestroyCommandPool	vkDestroyCommandPool;
	PFN_vkCreateSwapchainKHR	vkCreateSwapchainKHR;
	PFN_vkDestroySwapchainKHR	vkDestroySwapchainKHR;
	PFN_vkGetSwapchainImagesKHR	vkGetSwapchainImagesKHR;
	PFN_vkCreateImageView		vkCreateImageView;
	PFN_vkDestroyImageView		vkDestroyImageView;
	PFN_vkAllocateCommandBuffers	vkAllocateCommandBuffers;
	PFN_vkFreeCommandBuffers	vkFreeCommandBuffers;
	PFN_vkBeginCommandBuffer	vkBeginCommandBuffer;
	PFN_vkEndCommandBuffer		vkEndCommandBuffer;
	PFN_vkCmdPipelineBarrier	vkCmdPipelineBarrier;
	PFN_vkCmdClearColorImage	vkCmdClearColorImage;
	PFN_vkCreateSemaphore		vkCreateSemaphore;
	PFN_vkDestroySemaphore		vkDestroySemaphore;
	PFN_vkCreateFence		vkCreateFence;
	PFN_vkDestroyFence		vkDestroyFence;
	PFN_vkGetFenceStatus		vkGetFenceStatus;
	PFN_vkAcquireNextImageKHR	vkAcquireNextImageKHR;
	PFN_vkWaitForFences		vkWaitForFences;
	PFN_vkResetFences		vkResetFences;
	PFN_vkQueueSubmit		vkQueueSubmit;
	PFN_vkQueuePresentKHR		vkQueuePresentKHR;
};

/** Application-specific swapchain behavior */
struct SwapchainVulkan {
	struct SwapchainVulkan	*pNext;	// Linked list of retired swapchains
	VkSwapchainKHR		rawSwapchain;
	uint32_t		nImages;
	VkExtent2D		extent;
	VkImage			*images;
	VkImageView		*imageViews;
	VkFence			*fences;
};

struct SemaphoreVulkan {
	VkSemaphore presentComplete;
	VkSemaphore renderFinished;
};

struct FenceVulkan {
	VkFence *swapchain;	// Fences for each swapchain image
};

struct SyncVulkan {
	struct SemaphoreVulkan	semaphore;
};

/** Vulkan application that uses Pugl for windows and events
 *
 * TODO: Separate Instance from rest of application.
 */
struct RenderVulkan {
	struct VulkanAPI		*api;
	struct VulkanDev		*dev;
	char				*errMsg;
	PuglWorld			*world;
	PuglView			*view;
	VkInstance			instance;
	VkDebugReportCallbackEXT	debugCallback;
	VkSurfaceKHR			surface;
	VkSurfaceCapabilitiesKHR	surfaceCapabilities;
	VkSurfaceFormatKHR		surfaceFormat;
	VkPresentModeKHR		presentMode;
	VkPhysicalDeviceProperties	deviceProperties;	// TODO: Make this a pointer. It's really big.
	VkPhysicalDevice		physicalDevice;
	uint32_t			graphicsIndex;
	VkDevice			device;
	VkQueue				graphicsQueue;
	VkCommandPool			commandPool;
	struct SwapchainVulkan		*swapchain;
	VkCommandBuffer			*commandBuffers;
	struct SyncVulkan		sync;
};

#define RVK_ERRMSG_LEN	4096

void rvkSetErrMsg(struct RenderVulkan *vk, const char *fmt, ...)
{
	vk->errMsg = realloc(vk->errMsg, RVK_ERRMSG_LEN);
	va_list args;
	va_start(args, fmt);
	stbsp_vsnprintf(vk->errMsg, RVK_ERRMSG_LEN, fmt, args);
	va_end(args);
}

void rvkClearErrMsg(struct RenderVulkan *vk)
{
	if (vk->errMsg) {
		free(vk->errMsg);
		vk->errMsg = NULL;
	}
}

const char *rvkGetErrMsg(struct RenderVulkan *vk)
{
	return vk->errMsg;
}

#if defined(_WIN32)
#define VULKAN_SONAME_LATEST	"vulkan-1.dll"
static inline void *appDlopen(const char *soname)
{
	return LoadLibraryA(soname);
}

static inline char *appDlerror()
{
	// TODO: Print a more informative string. Error codes are annoying.
	DWORD errCode = GetLastError();
	static APP_THREAD_LOCAL char errStr[64];
	stbsp_snprintf(errStr, sizeof(errStr),
			"Dynamic Library Error: %d", errCode);
	return errStr;
}

static inline void *appDlsym(void *handle, const char *symbol)
{
	const uintptr_t ulAddr = (uintptr_t)GetProcAddress(handle, symbol);
	return (void*)ulAddr;
}

static inline int appDlclose(void *handle)
{
	return FreeLibrary(handle);
}

/* XXX:  puglGetRequiredInstanceExtensions() implementation for Win32
 *       "Get the platform-specific names of the required instance-level
 *        extensions if you want to display your images to the screen."
 *       Reminder that Vulkan is off-screen by default.
 */
void getRequiredInstanceExtensions(
		uint32_t *pExtensionCount,
		const char **const ppExtensionNames)
{
	static const char *const required[] = {
		VK_KHR_SURFACE_EXTENSION_NAME,
		VK_KHR_WIN32_SURFACE_EXTENSION_NAME
	};
	static const uint32_t num = sizeof(required) / sizeof(required[0]);
	if (ppExtensionNames) {
		for (uint32_t i = 0; i < num; ++i) {
			ppExtensionNames[i] = required[i];
		}
	} else {
		*pExtensionCount = num;
	}
}

/* XXX: puglCreateVulkanSurface() implementation for Win32
 *
 *      Creating a surface is platform-specific and should be handled by Pugl
 *      with this function exposed publicly.
 *
 *      No need to wrap vkFreeSurfaceKHR(). Creating a surface is platform
 *      specific, but freeing it is not.
 */
VkResult createVulkanSurface(PuglView *view,
		VkInstance instance,
		PFN_vkGetInstanceProcAddr getInstanceProcAddrFunc,
		const VkAllocationCallbacks *pAllocator,
		VkSurfaceKHR *pSurface)
{
	VkWin32SurfaceCreateInfoKHR createInfo = { 0 };
	createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
	//createInfo.hinstance = GetModuleHandle(0);	// FIXME (?)
	createInfo.hinstance = puglGetNativeWorld(puglGetWorld(view));
	createInfo.hwnd = puglGetNativeWindow(view);

	PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR =
		(PFN_vkCreateWin32SurfaceKHR)getInstanceProcAddrFunc(
				instance, "vkCreateWin32SurfaceKHR");

	return vkCreateWin32SurfaceKHR(instance,
				       &createInfo,
				       pAllocator,
				       pSurface);
}
#else
#define VULKAN_SONAME_LATEST	"libvulkan.so.1"
#include <dlfcn.h>
static inline void *appDlopen(const char *soname)
{
	return dlopen(soname, RTLD_NOW);
}

static inline char *appDlerror()
{
	return dlerror();
}

static inline void *appDlsym(void *handle, const char *symbol)
{
	return dlsym(handle, symbol);
}

static inline int appDlclose(void *handle)
{
	return dlclose(handle);
}

/* XXX:  puglGetRequiredInstanceExtensions() implementation for Xlib
 *       "Get the platform-specific names of the required instance-level
 *        extensions if you want to display your images to the screen."
 *       Reminder that Vulkan is off-screen by default.
 */
void getRequiredInstanceExtensions(
		uint32_t *pExtensionCount,
		const char **const ppExtensionNames)
{
	static const char *const required[] = {
		VK_KHR_SURFACE_EXTENSION_NAME,
		VK_KHR_XLIB_SURFACE_EXTENSION_NAME
	};
	static const uint32_t num = sizeof(required) / sizeof(required[0]);
	if (ppExtensionNames) {
		for (uint32_t i = 0; i < num; ++i) {
			ppExtensionNames[i] = required[i];
		}
	} else {
		*pExtensionCount = num;
	}
}

/* XXX: puglCreateVulkanSurface() implementation for Xlib
 *
 *      Creating a surface is platform-specific and should be handled by Pugl
 *      with this function exposed publicly.
 *
 *      No need to wrap vkFreeSurfaceKHR(). Creating a surface is platform
 *      specific, but freeing it is not.
 */
VkResult createVulkanSurface(PuglView *view,
		VkInstance instance,
		PFN_vkGetInstanceProcAddr getInstanceProcAddrFunc,
		const VkAllocationCallbacks *pAllocator,
		VkSurfaceKHR *pSurface)
{
	VkXlibSurfaceCreateInfoKHR createInfo = { 0 };
	createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
	//createInfo.dpy = ((struct PuglWorldImpl*)world)->impl->display;
	createInfo.dpy = puglGetNativeWorld(puglGetWorld(view));
	createInfo.window = puglGetNativeWindow(view);

	PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR =
		(PFN_vkCreateXlibSurfaceKHR)getInstanceProcAddrFunc(
				instance, "vkCreateXlibSurfaceKHR");

	return vkCreateXlibSurfaceKHR(instance,
				      &createInfo,
				      pAllocator,
				      pSurface);
}
#endif

static void *loadVulkanLibrary()
{
	void *handle = appDlopen(VULKAN_SONAME_LATEST);
	return handle;
}

static void loadVulkanGetInstanceProcAddrFunc(void *handle,
		PFN_vkGetInstanceProcAddr *getInstanceProcAddrFunc)
{
	*getInstanceProcAddrFunc = (PFN_vkGetInstanceProcAddr)appDlsym(
			handle,
			"vkGetInstanceProcAddr");
}

static int unloadVulkanLibrary(void *handle)
{
	if (handle) {
		return appDlclose(handle);
	}
	return 0;
}

static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
		VkDebugReportFlagsEXT flags,
		VkDebugReportObjectTypeEXT objType,
		uint64_t obj,
		size_t location,
		int32_t code,
		const char *layerPrefix,
		const char *msg,
		void *userData
		)
{
	fprintf(stderr, "\nValidation layer:\n%s\n\n", msg);
	return VK_FALSE;
}

static VkResult rvkCreateInternalInstance(
		struct RenderVulkan *vk,
		const uint32_t nLayers,
		const char *const *const layers,
		const uint32_t nAdditional,
		const char *const *const additionalExtensions)
{
	VkApplicationInfo appInfo = { 0 };
	appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
	appInfo.pApplicationName = "Pugl Vulkan Test";
	appInfo.applicationVersion = VK_MAKE_VERSION(0, 1, 0);
	appInfo.pEngineName = "Pugl Vulkan Test Engine";
	appInfo.engineVersion = VK_MAKE_VERSION(0, 1, 0);
	/* MoltenVK for macOS currently only supports Vulkan 1.0 */
	appInfo.apiVersion = VK_MAKE_VERSION(1, 0, 0);

	uint32_t i, j, nRequired;
	getRequiredInstanceExtensions(&nRequired, NULL);

	const uint32_t nExtensions = nRequired + nAdditional;
	const char **const extensions = malloc(sizeof(const char*) * nExtensions);

	getRequiredInstanceExtensions(NULL, extensions);
	for (i = nRequired, j = 0; i < nExtensions; ++i, ++j) {
		extensions[i] = additionalExtensions[j];
	}

	for (i = 0; i < nExtensions; ++i) {
		printf("Using instance extension:\t%s\n", extensions[i]);
	}

	for (i = 0; i < nLayers; ++i) {
		printf("Using instance layer:\t\t%s\n", layers[i]);
	}

	VkInstanceCreateInfo createInfo = { 0 };
	createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
	createInfo.pApplicationInfo = &appInfo;
	createInfo.enabledLayerCount = nLayers;
	createInfo.ppEnabledLayerNames = layers;
	createInfo.enabledExtensionCount = nExtensions;
	createInfo.ppEnabledExtensionNames = extensions;

	VkResult result = VK_SUCCESS;
	if ((result = vk->api->vkCreateInstance(&createInfo, ALLOC_VK, &vk->instance))) {
		rvkSetErrMsg(vk, "Could not create Vulkan Instance: %d\n", result);
	}
	free(extensions);
	return result;
}

static void rvkDestroyInternalInstance(struct RenderVulkan *vk)
{
	vk->api->vkDestroyInstance(vk->instance, ALLOC_VK);
	vk->instance = VK_NULL_HANDLE;
}

/** Create a self-contained Vulkan instance and set up a debug reporter
 *
 * If errors occurred, the struct will be returned in an unusable state.
 * It MUST then be destroyed via `rvkDestroyWorld`.
 * */
int rvkCreateWorld(struct RenderVulkan **vkOut, bool validation)
{
	struct RenderVulkan *vk = calloc(1, sizeof(*vk));
	*vkOut = vk;
	vk->world = puglNewWorld();
	if (!vk->world) {
		rvkSetErrMsg(vk, "Could not create Pugl world");
		return -1;
	}

	vk->api = calloc(1, sizeof(*vk->api));
	vk->api->handle = loadVulkanLibrary();
	if (!vk->api->handle) {
		rvkSetErrMsg(vk, "Error loading Vulkan shared library:\n%s\n", appDlerror());
		return -1;
	}

	loadVulkanGetInstanceProcAddrFunc(vk->api->handle, &vk->api->vkGetInstanceProcAddr);
	if (!vk->api->vkGetInstanceProcAddr) {
		rvkSetErrMsg(vk, "Error loading `vkGetInstanceProcAddr`:\n%s", appDlerror());
		return -1;
	}

	vk->api->vkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion)vk->api->vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceVersion");
	if (!vk->api->vkEnumerateInstanceVersion) {
		rvkSetErrMsg(vk, "Error loading `vkEnumerateInstanceVersion`");
		return -1;
	}

	vk->api->vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)vk->api->vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceExtensionProperties");
	if (!vk->api->vkEnumerateInstanceExtensionProperties) {
		rvkSetErrMsg(vk, "Error loading `vkEnumerateInstanceExtensionProperties`");
		return -1;
	}

	vk->api->vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)vk->api->vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceLayerProperties");
	if (!vk->api->vkEnumerateInstanceLayerProperties) {
		rvkSetErrMsg(vk, "Error loading `vkEnumerateInstanceLayerProperties`");
		return -1;
	}

	vk->api->vkCreateInstance = (PFN_vkCreateInstance)vk->api->vkGetInstanceProcAddr(NULL, "vkCreateInstance");
	if (!vk->api->vkCreateInstance) {
		rvkSetErrMsg(vk, "Error loading `vkCreateInstance`");
		return -1;
	}

	VkResult result;
	// FIXME: Use `vkEnumerateInstanceExtensionProperties` to query for
	// debug & validation support or it will fail if not found.
	if (validation) {
		static const char *const instanceLayers[] = {
			"VK_LAYER_KHRONOS_validation"
		};
		const uint32_t nInstanceLayers = sizeof(instanceLayers) / sizeof(instanceLayers[0]);
		static const char *const instanceExtensions[] = {
			VK_EXT_DEBUG_REPORT_EXTENSION_NAME
		};
		const uint32_t nInstanceExtensions = sizeof(instanceExtensions) / sizeof(instanceExtensions[0]);
		if ((result = rvkCreateInternalInstance(vk,
						nInstanceLayers,
						instanceLayers,
						nInstanceExtensions,
						instanceExtensions))) {
			return -1;
		}
	} else {
		if ((result = rvkCreateInternalInstance(vk, 0, NULL, 0, NULL))) {
			return -1;
		}
	}

	static const char *const strErrLd = "Error loading instance function %s";

	static const char *const _vkDestroyInstance = "vkDestroyInstance";
	vk->api->vkDestroyInstance = (PFN_vkDestroyInstance)vk->api->vkGetInstanceProcAddr(vk->instance, _vkDestroyInstance);
	if (!vk->api->vkDestroyInstance) {
		rvkSetErrMsg(vk, strErrLd, _vkDestroyInstance);
		return -1;
	}

	/* It is okay if debug reporter functions are not resolved (for now) */
	vk->api->vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vk->api->vkGetInstanceProcAddr(vk->instance, "vkCreateDebugReportCallbackEXT");
	vk->api->vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vk->api->vkGetInstanceProcAddr(vk->instance, "vkDestroyDebugReportCallbackEXT");

	/* But not if we are unable to destroy a created debug reporter */
	if (vk->api->vkCreateDebugReportCallbackEXT && !vk->api->vkDestroyDebugReportCallbackEXT) {
		rvkSetErrMsg(vk, "No debug reporter destroy function loaded for corresponding create function\n");
		return -1;
	}

	/* Dynamically load instance-level Vulkan function pointers via `vkGetInstanceProcAddr`
	 *
	 * TODO: This could perhaps be generated by a script and put into a separate "loader" file
	 */
	static const char *const _vkDestroySurfaceKHR = "vkDestroySurfaceKHR";
	vk->api->vkDestroySurfaceKHR = (PFN_vkDestroySurfaceKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkDestroySurfaceKHR);
	if (!vk->api->vkDestroySurfaceKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkDestroySurfaceKHR);
		return -1;
	}

	static const char *const _vkEnumeratePhysicalDevices = "vkEnumeratePhysicalDevices";
	vk->api->vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices)vk->api->vkGetInstanceProcAddr(vk->instance, _vkEnumeratePhysicalDevices);
	if (!vk->api->vkEnumeratePhysicalDevices) {
		rvkSetErrMsg(vk, strErrLd, _vkEnumeratePhysicalDevices);
		return -1;
	}

	static const char *const _vkGetPhysicalDeviceProperties = "vkGetPhysicalDeviceProperties";
	vk->api->vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceProperties);
	if (!vk->api->vkGetPhysicalDeviceProperties) {
		rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceProperties);
		return -1;
	}

	static const char *const _vkGetPhysicalDeviceQueueFamilyProperties = "vkGetPhysicalDeviceQueueFamilyProperties";
	vk->api->vkGetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceQueueFamilyProperties);
	if (!vk->api->vkGetPhysicalDeviceQueueFamilyProperties) {
		rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceQueueFamilyProperties);
		return -1;
	}

	static const char *const _vkGetPhysicalDeviceSurfaceSupportKHR = "vkGetPhysicalDeviceSurfaceSupportKHR";
	vk->api->vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceSurfaceSupportKHR);
	if (!vk->api->vkGetPhysicalDeviceSurfaceSupportKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceSurfaceSupportKHR);
		return -1;
	}

	static const char *const _vkGetPhysicalDeviceMemoryProperties = "vkGetPhysicalDeviceMemoryProperties";
	vk->api->vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceMemoryProperties);
	if (!vk->api->vkGetPhysicalDeviceMemoryProperties) {
		rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceMemoryProperties);
		return -1;
	}

	static const char *const _vkEnumerateDeviceExtensionProperties = "vkEnumerateDeviceExtensionProperties";
	vk->api->vkEnumerateDeviceExtensionProperties = (PFN_vkEnumerateDeviceExtensionProperties)vk->api->vkGetInstanceProcAddr(vk->instance, _vkEnumerateDeviceExtensionProperties);
	if (!vk->api->vkEnumerateDeviceExtensionProperties) {
		rvkSetErrMsg(vk, strErrLd, _vkEnumerateDeviceExtensionProperties);
		return -1;
	}

	static const char *const _vkCreateDevice = "vkCreateDevice";
	vk->api->vkCreateDevice = (PFN_vkCreateDevice)vk->api->vkGetInstanceProcAddr(vk->instance, _vkCreateDevice);
	if (!vk->api->vkCreateDevice) {
		rvkSetErrMsg(vk, strErrLd, _vkCreateDevice);
		return -1;
	}

	static const char *const _vkGetDeviceProcAddr = "vkGetDeviceProcAddr";
	vk->api->vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetDeviceProcAddr);
	if (!vk->api->vkGetDeviceProcAddr) {
		rvkSetErrMsg(vk, strErrLd, _vkGetDeviceProcAddr);
		return -1;
	}

	static const char *const _vkGetPhysicalDeviceSurfaceCapabilitiesKHR = "vkGetPhysicalDeviceSurfaceCapabilitiesKHR";
	vk->api->vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceSurfaceCapabilitiesKHR);
	if (!vk->api->vkGetPhysicalDeviceSurfaceCapabilitiesKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceSurfaceCapabilitiesKHR);
		return -1;
	}

	static const char *const _vkGetPhysicalDeviceSurfaceFormatsKHR = "vkGetPhysicalDeviceSurfaceFormatsKHR";
	vk->api->vkGetPhysicalDeviceSurfaceFormatsKHR = (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceSurfaceFormatsKHR);
	if (!vk->api->vkGetPhysicalDeviceSurfaceFormatsKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceSurfaceFormatsKHR);
		return -1;
	}

	static const char *const _vkGetPhysicalDeviceSurfacePresentModesKHR = "vkGetPhysicalDeviceSurfacePresentModesKHR";
	vk->api->vkGetPhysicalDeviceSurfacePresentModesKHR = (PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceSurfacePresentModesKHR);
	if (!vk->api->vkGetPhysicalDeviceSurfacePresentModesKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceSurfacePresentModesKHR);
		return -1;
	}

	/* End loading function pointers */

	if (vk->api->vkCreateDebugReportCallbackEXT) {
		printf("Creating debug reporter\n");
		VkDebugReportCallbackCreateInfoEXT debugInfo = { 0 };
		debugInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
		debugInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
		debugInfo.pfnCallback = debugCallback;
		if ((result = vk->api->vkCreateDebugReportCallbackEXT(vk->instance,
						&debugInfo, ALLOC_VK, &vk->debugCallback))) {
			rvkSetErrMsg(vk, "Could not create debug reporter: %d", result);
			return -1;
		}
	}

	return 0;
}

/** Create the view, window, and surface for this application */
int rvkCreateSurface(struct RenderVulkan *vk, const PuglRect frame)
{
	vk->view = puglNewView(vk->world);
	if (!vk->view) {
		rvkSetErrMsg(vk, "Could not create Pugl view");
		return -1;
	}
	puglSetFrame(vk->view, frame);
	puglSetHandle(vk->view, vk);
	puglSetBackend(vk->view, puglStubBackend());

	PuglStatus status;
	if ((status = puglCreateWindow(vk->view, "Vulkan Application Using Pugl"))) {
		rvkSetErrMsg(vk, "Could not create window: %s\n", puglStrerror(status));
		return -1;
	}

	VkResult result;
	if ((result = createVulkanSurface(vk->view, vk->instance, vk->api->vkGetInstanceProcAddr, ALLOC_VK, &vk->surface))) {
		rvkSetErrMsg(vk, "Could not create window surface: %d\n", result);
		return -1;
	}
	return 0;
}

static void printQueueFamilyCapabilities(const VkQueueFlagBits queueFlags)
{
	const char *maybeOr = "";
	const char *const or = " | ";
	if (queueFlags & VK_QUEUE_GRAPHICS_BIT) {
		printf("%sGRAPHICS", maybeOr);
		maybeOr = or;
	}
	if (queueFlags & VK_QUEUE_COMPUTE_BIT) {
		printf("%sCOMPUTE", maybeOr);
		maybeOr = or;
	}
	if (queueFlags & VK_QUEUE_TRANSFER_BIT) {
		printf("%sTRANSFER", maybeOr);
		maybeOr = or;
	}
	if (queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) {
		printf("%sSPARSE_BINDING", maybeOr);
		maybeOr = or;
	}
	if (queueFlags & VK_QUEUE_PROTECTED_BIT) {
		printf("%sPROTECTED", maybeOr);
		maybeOr = or;
	}
	printf("\n");
}

/** Checks if a particular physical device is suitable for this application.
 *
 * This function is referentially transparent (aside from printing to stdout).
 *
 * Choosing a physical device is an *extremely* application-specific procedure.
 *
 * All rendering in Vulkan is done off-screen by default. To get rendered
 * results on-screen they must be "presented" to a surface.
 * The Vulkan spec allows devices to have presentation done on a separate queue
 * family than GRAPHICS, or no present support at all. However, every graphics
 * card today that is capable of connecting to a display has at least one queue
 * family capable of both GRAPHICS and present.
 *
 * This single-threaded application will use only one queue for all operations.
 * More specifically, it will make use of GRAPHICS and TRANSFER operations on
 * a single queue retrieved from a GRAPHICS queue family that supports present.
 *
 * In my experience, most cards follow this format:
 *
 * INTEGRATED: Typically have one queue family for all operations.
 *             May retrieve only one queue from this single queue family.
 * DEDICATED:  Older cards typically have one queue family for GRAPHICS and one
 *             for TRANSFER. Newer cards typically have a separate queue family
 *             for COMPUTE. Remember that all GRAPHICS queue families
 *             implicitly allow both COMPUTE and TRANSFER operations on it as
 *             well. Programmers making use of separate queue families may allow
 *             devices to work more efficiently.
 *
 *             May typically retrieve up to a few queues from either queue
 *             family. The maximum number of available queues is specific to
 *             that device's queue families. Programmers making use of separate
 *             queues for highly independent workloads may allow devices to work
 *             more efficiently. Queues must be submitted to from a single
 *             thread at a time, so programmers wanting to make use of
 *             multithreaded queue submission must retrieve queues per-thread.
 *
 *             GOTCHA: Some devices may have multiple GRAPHICS queue families
 *                     with only one of them able to present. Do not assume a
 *                     device is unsuitable until ALL queue families have been
 *                     checked.
 *
 * Because this application will load all resources before any rendering begins,
 * and the amount of resources are small enough to be loaded almost instantly,
 * it will not make use of a separate TRANSFER queue family.
 *
 * Information for many devices is available online at
 * https://vulkan.gpuinfo.org/
 */
static bool rvkIsDeviceSuitable(const struct RenderVulkan *const vk,
		const VkPhysicalDevice physicalDevice,
		uint32_t *const graphicsIndex)
{
	uint32_t nQueueFamilies;
	vk->api->vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &nQueueFamilies, NULL);
	VkQueueFamilyProperties *queueProperties = malloc(nQueueFamilies * sizeof(*queueProperties));
	vk->api->vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &nQueueFamilies, queueProperties);
	for (uint32_t i = 0; i < nQueueFamilies; ++i) {
		printf("Queue family %d queueCount:\t%d\n", i, queueProperties[i].queueCount);
	}
	for (uint32_t i = 0; i < nQueueFamilies; ++i) {
		printf("Queue family %d queueFlags:\t", i);
		printQueueFamilyCapabilities(queueProperties[i].queueFlags);
	}
	uint32_t g;
	for (g = 0; g < nQueueFamilies; ++g) {
		if (queueProperties[g].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
			VkBool32 canSurface;
			vk->api->vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, g, vk->surface, &canSurface);
			if (canSurface) break;
		}
	}
	free(queueProperties);
	if (g >= nQueueFamilies) {
		/* We only support graphics and present on the same queue family. */
		printf("No graphics+support queue families found on this device\n");
		return false;
	}
	VkBool32 canSwapchain = VK_FALSE;
	uint32_t nExtensions;
	vk->api->vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &nExtensions, NULL);
	VkExtensionProperties *availableExtensions = malloc(nExtensions * sizeof(*availableExtensions));
	vk->api->vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &nExtensions, availableExtensions);
	for (uint32_t i = 0; i < nExtensions; ++i) {
		if (!strcmp(availableExtensions[i].extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) {
			canSwapchain = VK_TRUE;
			break;
		}
	}
	free(availableExtensions);
	if (!canSwapchain) {
		printf("Cannot use a swapchain on this device\n");
		return false;
	}
	*graphicsIndex = g;
	return true;
}

const char *strDeviceType(const VkPhysicalDeviceType deviceType)
{
	switch (deviceType) {
		case VK_PHYSICAL_DEVICE_TYPE_OTHER:
			return "Other";
		case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
			return "Integrated GPU";
		case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
			return "Discrete GPU";
		case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
			return "Virtual GPU";
		case VK_PHYSICAL_DEVICE_TYPE_CPU:
			return "CPU";
		default:
			return "Unknown";
	}
}

/** Selects a physical device
 *
 * This application will not attempt to find the "most powerful" device on the
 * system, and will choose the first suitable device it finds.
 */
int rvkSelectPhysicalDevice(struct RenderVulkan *vk)
{
	int ret = 0;
	if (!vk->surface) {
		rvkSetErrMsg(vk, "Cannot select a physical device without a surface");
		return -1;
	}
	static const char *const strErrEnum = "Could not enumerate physical devices: %s";
	static const char *const strWarnEnum = "Warn: Incomplete enumeration of physical devices";
	uint32_t nDevices;
	VkResult result;
	if ((result = vk->api->vkEnumeratePhysicalDevices(vk->instance, &nDevices, NULL))) {
		if (result != VK_INCOMPLETE) {
			rvkSetErrMsg(vk, strErrEnum, result);
			return -1;
		} else {
			fprintf(stderr, "%s\n", strWarnEnum);
		}
	}
	if (!nDevices) {
		rvkSetErrMsg(vk, "No physical devices found");
		return -1;
	}
	VkPhysicalDevice *devices = malloc(nDevices * sizeof(*devices));
	VkPhysicalDeviceProperties *deviceProperties = malloc(nDevices * sizeof(*deviceProperties));
	if ((result = vk->api->vkEnumeratePhysicalDevices(vk->instance, &nDevices, devices))) {
		if (result != VK_INCOMPLETE) {
			rvkSetErrMsg(vk, strErrEnum, result);
			ret = -1;
			goto done;
		} else {
			fprintf(stderr, "%s\n", strWarnEnum);
		}
	}

	const char *strType;
	uint32_t i;
	for (i = 0; i < nDevices; ++i) {
		vk->api->vkGetPhysicalDeviceProperties(devices[i], &deviceProperties[i]);
		strType = strDeviceType(deviceProperties[i].deviceType);
		printf("Found physical device %d/%d:\t`%s`\t(%s)\n",
				i+1, nDevices, deviceProperties[i].deviceName, strType);
	}
	for (i = 0; i < nDevices; ++i) {
		strType = strDeviceType(deviceProperties[i].deviceType);
		printf("Checking suitability for\t`%s`...\t(%s)\n", deviceProperties[i].deviceName, strType);
		uint32_t graphicsIndex;
		if (rvkIsDeviceSuitable(vk, devices[i], &graphicsIndex)) {
			printf("Using physical device:\t\t`%s`\t(%s)\n",
					deviceProperties[i].deviceName,
					strDeviceType(deviceProperties[i].deviceType));
			vk->deviceProperties = deviceProperties[i];
			vk->physicalDevice = devices[i];
			vk->graphicsIndex = graphicsIndex;
			printf("Using queue family index:\t%d\tfor\tGRAPHICS\n", vk->graphicsIndex);
			goto done;
		}
		printf("Device `%s` (%s) not suitable\n", deviceProperties[i].deviceName, strType);
	}
	if (i >= nDevices) {
		rvkSetErrMsg(vk, "No suitable devices found");
		ret = -1;
	}
done:
	free(deviceProperties);
	free(devices);
	return ret;
}

static int rvkLoadDeviceFunctions(struct RenderVulkan *vk, VkDevice device)
{
	const char *const strErrLd = "Error loading device function %s";

	static const char *const _vkDestroyDevice = "vkDestroyDevice";
	vk->dev->vkDestroyDevice = (PFN_vkDestroyDevice)vk->api->vkGetDeviceProcAddr(device, _vkDestroyDevice);
	if (!vk->dev->vkDestroyDevice) {
		rvkSetErrMsg(vk, strErrLd, _vkDestroyDevice);
		return -1;
	}

	static const char *const _vkDeviceWaitIdle = "vkDeviceWaitIdle";
	vk->dev->vkDeviceWaitIdle = (PFN_vkDeviceWaitIdle)vk->api->vkGetDeviceProcAddr(device, _vkDeviceWaitIdle);
	if (!vk->dev->vkDeviceWaitIdle) {
		rvkSetErrMsg(vk, strErrLd, _vkDeviceWaitIdle);
		return -1;
	}

	static const char *const _vkGetDeviceQueue = "vkGetDeviceQueue";
	vk->dev->vkGetDeviceQueue = (PFN_vkGetDeviceQueue)vk->api->vkGetDeviceProcAddr(device, _vkGetDeviceQueue);
	if (!vk->dev->vkGetDeviceQueue) {
		rvkSetErrMsg(vk, strErrLd, _vkGetDeviceQueue);
		return -1;
	}

	static const char *const _vkQueueWaitIdle = "vkQueueWaitIdle";
	vk->dev->vkQueueWaitIdle = (PFN_vkQueueWaitIdle)vk->api->vkGetDeviceProcAddr(device, _vkQueueWaitIdle);
	if (!vk->dev->vkQueueWaitIdle) {
		rvkSetErrMsg(vk, strErrLd, _vkQueueWaitIdle);
		return -1;
	}

	static const char *const _vkCreateCommandPool = "vkCreateCommandPool";
	vk->dev->vkCreateCommandPool = (PFN_vkCreateCommandPool)vk->api->vkGetDeviceProcAddr(device, _vkCreateCommandPool);
	if (!vk->dev->vkCreateCommandPool) {
		rvkSetErrMsg(vk, strErrLd, _vkCreateCommandPool);
		return -1;
	}

	static const char *const _vkDestroyCommandPool = "vkDestroyCommandPool";
	vk->dev->vkDestroyCommandPool = (PFN_vkDestroyCommandPool)vk->api->vkGetDeviceProcAddr(device, _vkDestroyCommandPool);
	if (!vk->dev->vkDestroyCommandPool) {
		rvkSetErrMsg(vk, strErrLd, _vkDestroyCommandPool);
		return -1;
	}

	static const char *const _vkCreateSwapchainKHR = "vkCreateSwapchainKHR";
	vk->dev->vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)vk->api->vkGetDeviceProcAddr(device, _vkCreateSwapchainKHR);
	if (!vk->dev->vkCreateSwapchainKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkCreateSwapchainKHR);
		return -1;
	}

	static const char *const _vkDestroySwapchainKHR = "vkDestroySwapchainKHR";
	vk->dev->vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)vk->api->vkGetDeviceProcAddr(device, _vkDestroySwapchainKHR);
	if (!vk->dev->vkDestroySwapchainKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkDestroySwapchainKHR);
		return -1;
	}

	static const char *const _vkGetSwapchainImagesKHR = "vkGetSwapchainImagesKHR";
	vk->dev->vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)vk->api->vkGetDeviceProcAddr(device, _vkGetSwapchainImagesKHR);
	if (!vk->dev->vkGetSwapchainImagesKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkGetSwapchainImagesKHR);
		return -1;
	}

	static const char *const _vkCreateImageView = "vkCreateImageView";
	vk->dev->vkCreateImageView = (PFN_vkCreateImageView)vk->api->vkGetDeviceProcAddr(device, _vkCreateImageView);
	if (!vk->dev->vkCreateImageView) {
		rvkSetErrMsg(vk, strErrLd, _vkCreateImageView);
		return -1;
	}

	static const char *const _vkDestroyImageView = "vkDestroyImageView";
	vk->dev->vkDestroyImageView = (PFN_vkDestroyImageView)vk->api->vkGetDeviceProcAddr(device, _vkDestroyImageView);
	if (!vk->dev->vkDestroyImageView) {
		rvkSetErrMsg(vk, strErrLd, _vkDestroyImageView);
		return -1;
	}

	static const char *const _vkAllocateCommandBuffers = "vkAllocateCommandBuffers";
	vk->dev->vkAllocateCommandBuffers = (PFN_vkAllocateCommandBuffers)vk->api->vkGetDeviceProcAddr(device, _vkAllocateCommandBuffers);
	if (!vk->dev->vkAllocateCommandBuffers) {
		rvkSetErrMsg(vk, strErrLd, _vkAllocateCommandBuffers);
		return -1;
	}

	static const char *const _vkFreeCommandBuffers = "vkFreeCommandBuffers";
	vk->dev->vkFreeCommandBuffers = (PFN_vkFreeCommandBuffers)vk->api->vkGetDeviceProcAddr(device, _vkFreeCommandBuffers);
	if (!vk->dev->vkFreeCommandBuffers) {
		rvkSetErrMsg(vk, strErrLd, _vkFreeCommandBuffers);
		return -1;
	}

	static const char *const _vkBeginCommandBuffer = "vkBeginCommandBuffer";
	vk->dev->vkBeginCommandBuffer = (PFN_vkBeginCommandBuffer)vk->api->vkGetDeviceProcAddr(device, _vkBeginCommandBuffer);
	if (!vk->dev->vkBeginCommandBuffer) {
		rvkSetErrMsg(vk, strErrLd, _vkBeginCommandBuffer);
		return -1;
	}

	static const char *const _vkEndCommandBuffer = "vkEndCommandBuffer";
	vk->dev->vkEndCommandBuffer = (PFN_vkEndCommandBuffer)vk->api->vkGetDeviceProcAddr(device, _vkEndCommandBuffer);
	if (!vk->dev->vkEndCommandBuffer) {
		rvkSetErrMsg(vk, strErrLd, _vkEndCommandBuffer);
		return -1;
	}

	static const char *const _vkCmdPipelineBarrier = "vkCmdPipelineBarrier";
	vk->dev->vkCmdPipelineBarrier = (PFN_vkCmdPipelineBarrier)vk->api->vkGetDeviceProcAddr(device, _vkCmdPipelineBarrier);
	if (!vk->dev->vkCmdPipelineBarrier) {
		rvkSetErrMsg(vk, strErrLd, _vkCmdPipelineBarrier);
		return -1;
	}

	static const char *const _vkCmdClearColorImage = "vkCmdClearColorImage";
	vk->dev->vkCmdClearColorImage = (PFN_vkCmdClearColorImage)vk->api->vkGetDeviceProcAddr(device, _vkCmdClearColorImage);
	if (!vk->dev->vkCmdClearColorImage) {
		rvkSetErrMsg(vk, strErrLd, _vkCmdClearColorImage);
		return -1;
	}

	static const char *const _vkCreateSemaphore = "vkCreateSemaphore";
	vk->dev->vkCreateSemaphore = (PFN_vkCreateSemaphore)vk->api->vkGetDeviceProcAddr(device, _vkCreateSemaphore);
	if (!vk->dev->vkCreateSemaphore) {
		rvkSetErrMsg(vk, strErrLd, _vkCreateSemaphore);
		return -1;
	}

	static const char *const _vkCreateFence = "vkCreateFence";
	vk->dev->vkCreateFence = (PFN_vkCreateFence)vk->api->vkGetDeviceProcAddr(device, _vkCreateFence);
	if (!vk->dev->vkCreateFence) {
		rvkSetErrMsg(vk, strErrLd, _vkCreateFence);
		return -1;
	}

	static const char *const _vkDestroyFence = "vkDestroyFence";
	vk->dev->vkDestroyFence = (PFN_vkDestroyFence)vk->api->vkGetDeviceProcAddr(device, _vkDestroyFence);
	if (!vk->dev->vkDestroyFence) {
		rvkSetErrMsg(vk, strErrLd, _vkDestroyFence);
		return -1;
	}

	static const char *const _vkGetFenceStatus = "vkGetFenceStatus";
	vk->dev->vkGetFenceStatus = (PFN_vkGetFenceStatus)vk->api->vkGetDeviceProcAddr(device, _vkGetFenceStatus);
	if (!vk->dev->vkGetFenceStatus) {
		rvkSetErrMsg(vk, strErrLd, _vkGetFenceStatus);
		return -1;
	}

	static const char *const _vkDestroySemaphore = "vkDestroySemaphore";
	vk->dev->vkDestroySemaphore = (PFN_vkDestroySemaphore)vk->api->vkGetDeviceProcAddr(device, _vkDestroySemaphore);
	if (!vk->dev->vkDestroySemaphore) {
		rvkSetErrMsg(vk, strErrLd, _vkDestroySemaphore);
		return -1;
	}

	static const char *const _vkAcquireNextImageKHR = "vkAcquireNextImageKHR";
	vk->dev->vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)vk->api->vkGetDeviceProcAddr(device, _vkAcquireNextImageKHR);
	if (!vk->dev->vkAcquireNextImageKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkAcquireNextImageKHR);
		return -1;
	}

	static const char *const _vkWaitForFences = "vkWaitForFences";
	vk->dev->vkWaitForFences = (PFN_vkWaitForFences)vk->api->vkGetDeviceProcAddr(device, _vkWaitForFences);
	if (!vk->dev->vkWaitForFences) {
		rvkSetErrMsg(vk, strErrLd, _vkWaitForFences);
		return -1;
	}

	static const char *const _vkResetFences = "vkResetFences";
	vk->dev->vkResetFences = (PFN_vkResetFences)vk->api->vkGetDeviceProcAddr(device, _vkResetFences);
	if (!vk->dev->vkResetFences) {
		rvkSetErrMsg(vk, strErrLd, _vkResetFences);
		return -1;
	}

	static const char *const _vkQueueSubmit = "vkQueueSubmit";
	vk->dev->vkQueueSubmit = (PFN_vkQueueSubmit)vk->api->vkGetDeviceProcAddr(device, _vkQueueSubmit);
	if (!vk->dev->vkQueueSubmit) {
		rvkSetErrMsg(vk, strErrLd, _vkQueueSubmit);
		return -1;
	}

	static const char *const _vkQueuePresentKHR = "vkQueuePresentKHR";
	vk->dev->vkQueuePresentKHR = (PFN_vkQueuePresentKHR)vk->api->vkGetDeviceProcAddr(device, _vkQueuePresentKHR);
	if (!vk->dev->vkQueuePresentKHR) {
		rvkSetErrMsg(vk, strErrLd, _vkQueuePresentKHR);
		return -1;
	}

	return 0;
}

/** Opens the logical device, retrieves queue(s), and creates the command pool
 * for this application.
 */
int rvkOpenDevice(struct RenderVulkan *vk)
{
	if (vk->device) {
		rvkSetErrMsg(vk, "Renderer already has an opened device");
		return -1;
	}
	const float graphicsQueuePriority = 1.0f;
	const char *const swapchainName = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
	VkDeviceQueueCreateInfo queueCreateInfo = { 0 };
	queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
	queueCreateInfo.queueFamilyIndex = vk->graphicsIndex;
	queueCreateInfo.queueCount = 1;
	queueCreateInfo.pQueuePriorities = &graphicsQueuePriority;

	VkDeviceCreateInfo createInfo = { 0 };
	createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
	createInfo.queueCreateInfoCount = 1;
	createInfo.pQueueCreateInfos = &queueCreateInfo;
	/* `enabledLayerCount` and `ppEnabledLayerNames` are ignored by modern
	 * Vulkan implementations.
	 * TODO: But maybe we should support the older implementations.
	 */
	createInfo.enabledExtensionCount = 1;
	createInfo.ppEnabledExtensionNames = &swapchainName;
	/* This application uses no device features. */
	createInfo.pEnabledFeatures = NULL;

	VkDevice device;
	VkResult result;
	if ((result = vk->api->vkCreateDevice(vk->physicalDevice, &createInfo, ALLOC_VK, &device))) {
		rvkSetErrMsg(vk, "Could not open device `%s`: %d\n",
				vk->deviceProperties.deviceName, result);
		return -1;
	}
	vk->dev = calloc(1, sizeof(*vk->dev));
	vk->device = device;
	if (rvkLoadDeviceFunctions(vk, device)) {
		return -1;
	}
	vk->dev->vkGetDeviceQueue(vk->device, vk->graphicsIndex, 0, &vk->graphicsQueue);

	VkCommandPoolCreateInfo commandInfo = { 0 };
	commandInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
	commandInfo.queueFamilyIndex = vk->graphicsIndex;
	VkCommandPool commandPool;
	if ((result = vk->dev->vkCreateCommandPool(vk->device, &commandInfo, ALLOC_VK, &commandPool))) {
		rvkSetErrMsg(vk, "Could not create command pool: %d\n", result);
		return -1;
	}
	vk->commandPool = commandPool;
	return 0;
}

static char *strPresentMode(const VkPresentModeKHR presentMode)
{
	switch (presentMode) {
		case VK_PRESENT_MODE_IMMEDIATE_KHR:
			return "Immediate";
		case VK_PRESENT_MODE_MAILBOX_KHR:
			return "Mailbox";
		case VK_PRESENT_MODE_FIFO_KHR:
			return "FIFO";
		case VK_PRESENT_MODE_FIFO_RELAXED_KHR:
			return "FIFO relaxed";
		default:
			return "Other";
	}
}

static bool isPresentModeSupported(const VkPresentModeKHR *const presentModes,
		const uint32_t nPresentModes, const VkPresentModeKHR want)
{
	const char *const strWant = strPresentMode(want);
	printf("Checking for present mode:\t`%s`...\n", strWant);
	for (uint32_t i = 0; i < nPresentModes; ++i) {
		if (presentModes[i] == want) {
			return true;
		}
	}
	/* The same device on different platforms may not have the same present modes */
	printf("Present mode `%s` not available for this device or platform\n", strWant);
	return false;
}

/** Configure the surface for the currently opened device. */
int rvkConfigureSurface(struct RenderVulkan *vk)
{
	VkSurfaceCapabilitiesKHR surfaceCapabilities;
	VkSurfaceFormatKHR *surfaceFormats;
	VkPresentModeKHR *presentModes;
	VkResult result;
	if ((result = vk->api->vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
					vk->physicalDevice, vk->surface, &surfaceCapabilities))) {
		rvkSetErrMsg(vk, "Could not get surface capabilities: %d", result);
		return -1;
	}
	uint32_t nFormats;
	vk->api->vkGetPhysicalDeviceSurfaceFormatsKHR(vk->physicalDevice, vk->surface, &nFormats, NULL);
	if (!nFormats) {
		rvkSetErrMsg(vk, "No surface formats available");
		return -1;
	}
	surfaceFormats = malloc(nFormats * sizeof(*surfaceFormats));
	vk->api->vkGetPhysicalDeviceSurfaceFormatsKHR(vk->physicalDevice, vk->surface, &nFormats, surfaceFormats);

	uint32_t i;
	for (i = 0; i < nFormats; ++i) {
		const VkSurfaceFormatKHR want = {
			/* UNORM is *NOT* recommended for color blending, but is
			 * useful for getting simple "HTML" colors to the screen
			 * without manually converting to a linear color space.
			 *
			 * See:
			 * MinutePhysics (Henry Reich).
			 * "Computer Color Is Broken"
			 * YouTube video, 4:13. March 20, 2015.
			 * https://www.youtube.com/watch?v=LKnqECcg6Gw
			 */
			VK_FORMAT_B8G8R8A8_UNORM,
			VK_COLOR_SPACE_SRGB_NONLINEAR_KHR
		};
		if (surfaceFormats[i].format == VK_FORMAT_UNDEFINED) {
			vk->surfaceFormat = want;
			break;
		}
		if (surfaceFormats[i].format == want.format && surfaceFormats[i].colorSpace == want.colorSpace) {
			vk->surfaceFormat = want;
			break;
		}
	}
	free(surfaceFormats);
	if (i >= nFormats) {
		rvkSetErrMsg(vk, "Could not find a suitable surface format");
		return -1;
	}

	uint32_t nPresentModes;
	vk->api->vkGetPhysicalDeviceSurfacePresentModesKHR(vk->physicalDevice, vk->surface, &nPresentModes, NULL);
	if (!nPresentModes) {
		rvkSetErrMsg(vk, "No present modes available");
		return -1;
	}
	presentModes = malloc(nPresentModes * sizeof(*presentModes));
	vk->api->vkGetPhysicalDeviceSurfacePresentModesKHR(vk->physicalDevice,
			vk->surface, &nPresentModes, presentModes);

	VkPresentModeKHR presentMode;
	for (i = 0; i < nPresentModes; ++i) {
		presentMode = presentModes[i];
		printf("Found present mode:\t\t`%s`\t(%d)\n", strPresentMode(presentMode), presentMode);
	}

	if (isPresentModeSupported(presentModes, nPresentModes, VK_PRESENT_MODE_MAILBOX_KHR)) {
		presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
	} else if (isPresentModeSupported(presentModes, nPresentModes, VK_PRESENT_MODE_IMMEDIATE_KHR)) {
		presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
	} else {
		presentMode = VK_PRESENT_MODE_FIFO_KHR;
	}
	free(presentModes);
	vk->presentMode = presentMode;
	printf("Using present mode:\t\t`%s`\t(%d)\n", strPresentMode(presentMode), presentMode);
	vk->surfaceCapabilities = surfaceCapabilities;
	return 0;
}

static int rvkCreateRawSwapchain(struct RenderVulkan *vk, int width, int height)
{
	// TODO: Clamp
	vk->swapchain->extent.width = width;
	vk->swapchain->extent.height = height;

	vk->swapchain->nImages = vk->surfaceCapabilities.minImageCount;
	//vk->swapchain->nImages = vk->surfaceCapabilities.maxImageCount;

	printf("Using %d swapchain images\n", vk->swapchain->nImages);

	VkSwapchainCreateInfoKHR createInfo = { 0 };
	createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
	createInfo.surface = vk->surface;
	createInfo.minImageCount = vk->swapchain->nImages;
	createInfo.imageFormat = vk->surfaceFormat.format;
	createInfo.imageExtent = vk->swapchain->extent;
	createInfo.imageArrayLayers = 1;
	createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
	createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
	createInfo.preTransform = vk->surfaceCapabilities.currentTransform;
	createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
	createInfo.presentMode = vk->presentMode;
	createInfo.clipped = VK_TRUE;
	createInfo.oldSwapchain = VK_NULL_HANDLE;	// TODO
	VkResult result;
	if ((result = vk->dev->vkCreateSwapchainKHR(vk->device, &createInfo, ALLOC_VK, &vk->swapchain->rawSwapchain))) {
		rvkSetErrMsg(vk, "Could not create swapchain: %d", result);
		return -1;
	}
	return 0;
}

static void rvkDestroyRawSwapchain(struct RenderVulkan *vk)
{
	if (vk->swapchain && vk->swapchain->rawSwapchain) {
		vk->dev->vkDestroySwapchainKHR(vk->device, vk->swapchain->rawSwapchain, ALLOC_VK);
		memset(&vk->swapchain, 0, sizeof(vk->swapchain));
	}
}

static VkResult createSwapchainImageViews(VkDevice device,
		const struct VulkanDev *const dev, struct SwapchainVulkan *const swapchain)
{
	VkResult result;
	if ((result = dev->vkGetSwapchainImagesKHR(device, swapchain->rawSwapchain, &swapchain->nImages, NULL))) {
		return result;
	}
	swapchain->images = calloc(swapchain->nImages, sizeof(*swapchain->images));
	if ((result = dev->vkGetSwapchainImagesKHR(device, swapchain->rawSwapchain, &swapchain->nImages, swapchain->images))) {
		return result;
	}
#if 0
	/* We don't need this yet until we start using as a render target. */
	swapchain->imageViews = calloc(swapchain->nImages, sizeof(*swapchain->imageViews));

	for (uint32_t i = 0; i < swapchain->nImages; ++i) {
		VkImageViewCreateInfo createInfo = { 0 };
		createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
		createInfo.image = swapchain->images[i];
		createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
		createInfo.format = swapchain->surfaceFormat.format;
		createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
		createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
		createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
		createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
		createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
		createInfo.subresourceRange.baseMipLevel = 0;
		createInfo.subresourceRange.levelCount = 1;
		createInfo.subresourceRange.baseArrayLayer = 0;
		createInfo.subresourceRange.layerCount = 1;
		if ((result = dev->vkCreateImageView(device, &createInfo, ALLOC_VK, &swapchain->imageViews[i]))) {
			return result;
		}
	}
#endif
	return VK_SUCCESS;
}

static void destroySwapchainImageViews(VkDevice device,
		const struct VulkanDev *const dev,
		struct SwapchainVulkan *const swapchain)
{
	if (!swapchain) return;
	if (swapchain->imageViews) {
		for (uint32_t i = 0; i < swapchain->nImages; ++i) {
			if (swapchain->imageViews[i]) {
				dev->vkDestroyImageView(device,
						swapchain->imageViews[i],
						ALLOC_VK);
			}
		}
		free(swapchain->imageViews);
		swapchain->imageViews = NULL;
	}
	if (swapchain->images) {
		free(swapchain->images);
		swapchain->images = NULL;
		swapchain->nImages = 0;
	}
}

static VkResult allocateCommandBuffers(struct RenderVulkan *vk)
{
	VkCommandBufferAllocateInfo allocInfo = { 0 };
	allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
	allocInfo.commandPool = vk->commandPool;
	allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
	allocInfo.commandBufferCount = vk->swapchain->nImages;
	vk->commandBuffers = malloc(vk->swapchain->nImages * sizeof(vk->commandBuffers));
	return vk->dev->vkAllocateCommandBuffers(vk->device, &allocInfo, vk->commandBuffers);
}

static void freeCommandBuffers(struct RenderVulkan *vk)
{
	if (vk->commandBuffers) {
		vk->dev->vkFreeCommandBuffers(vk->device,
				vk->commandPool,
				vk->swapchain->nImages,
				vk->commandBuffers);
		free(vk->commandBuffers);
		vk->commandBuffers = NULL;
	}
}

static int recordCommandBuffers(struct RenderVulkan *vk)
{
	VkClearColorValue clearValue = { 0 };
	clearValue.float32[0] = (float)0xa4/0x100;	// R
	clearValue.float32[1] = (float)0x1e/0x100;	// G
	clearValue.float32[2] = (float)0x22/0x100;	// B
	clearValue.float32[3] = (float)0xff/0x100;	// A

	VkImageSubresourceRange range = { 0 };
	range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
	range.baseMipLevel = 0;
	range.levelCount = 1;
	range.baseArrayLayer = 0;
	range.layerCount = 1;

	VkCommandBufferBeginInfo beginInfo = { 0 };
	beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
	beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;

	for (uint32_t i = 0; i < vk->swapchain->nImages; ++i) {
		VkImageMemoryBarrier toClearBarrier = { 0 };
		toClearBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
		toClearBarrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
		toClearBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
		toClearBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
		toClearBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
		toClearBarrier.srcQueueFamilyIndex = vk->graphicsIndex;
		toClearBarrier.dstQueueFamilyIndex = vk->graphicsIndex;
		toClearBarrier.image = vk->swapchain->images[i];
		toClearBarrier.subresourceRange = range;

		VkImageMemoryBarrier toPresentBarrier = { 0 };
		toPresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
		toPresentBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
		toPresentBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
		toPresentBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
		toPresentBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
		toPresentBarrier.srcQueueFamilyIndex = vk->graphicsIndex;
		toPresentBarrier.dstQueueFamilyIndex = vk->graphicsIndex;
		toPresentBarrier.image = vk->swapchain->images[i];
		toPresentBarrier.subresourceRange = range;

		vk->dev->vkBeginCommandBuffer(vk->commandBuffers[i], &beginInfo);
		vk->dev->vkCmdPipelineBarrier(vk->commandBuffers[i],
				VK_PIPELINE_STAGE_TRANSFER_BIT,
				VK_PIPELINE_STAGE_TRANSFER_BIT,
				0,
				0, NULL,
				0, NULL,
				1, &toClearBarrier);
		vk->dev->vkCmdClearColorImage(vk->commandBuffers[i], vk->swapchain->images[i],
				VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clearValue, 1, &range);
		vk->dev->vkCmdPipelineBarrier(vk->commandBuffers[i],
				VK_PIPELINE_STAGE_TRANSFER_BIT,
				VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
				0,
				0, NULL,
				0, NULL,
				1, &toPresentBarrier);
		vk->dev->vkEndCommandBuffer(vk->commandBuffers[i]);
	}

	return 0;
}

int rvkCreateSwapchain(struct RenderVulkan *vk, const int width, const int height)
{
	vk->swapchain = calloc(1, sizeof(*vk->swapchain));
	if (rvkCreateRawSwapchain(vk, width, height)) {
		return -1;
	}
	VkResult result;
	if ((result = createSwapchainImageViews(vk->device, vk->dev, vk->swapchain))) {
		rvkSetErrMsg(vk, "Could not create swapchain image views: %d", result);
		return -1;
	}
	if ((result = allocateCommandBuffers(vk))) {
		rvkSetErrMsg(vk, "Could not allocate command buffers: %d", result);
		return -1;
	}
	VkFenceCreateInfo fenceInfo = { 0 };
	fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
	fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
	vk->swapchain->fences = calloc(vk->swapchain->nImages, sizeof(*vk->swapchain->fences));
	for (uint32_t i = 0; i < vk->swapchain->nImages; ++i) {
		if ((result = vk->dev->vkCreateFence(vk->device, &fenceInfo, ALLOC_VK, &vk->swapchain->fences[i]))) {
			rvkSetErrMsg(vk, "Could not create render finished fence: %d", result);
			return -1;
		}
	}
	if (recordCommandBuffers(vk)) {
		return -1;
	}
	return 0;
}

void rvkDestroySwapchain(struct RenderVulkan *vk)
{
	if (vk->swapchain && vk->swapchain->fences) {
		for (uint32_t i = 0; i < vk->swapchain->nImages; ++i) {
			if (vk->swapchain->fences[i]) {
				vk->dev->vkDestroyFence(vk->device,
						vk->swapchain->fences[i],
						ALLOC_VK);
			}
		}
		free(vk->swapchain->fences);
		vk->swapchain->fences = NULL;
	}
	freeCommandBuffers(vk);
	destroySwapchainImageViews(vk->device, vk->dev, vk->swapchain);
	rvkDestroyRawSwapchain(vk);
	free(vk->swapchain);
	vk->swapchain = NULL;
}

/** Creates any semaphores or fences for this application. */
int rvkCreateSyncObjects(struct RenderVulkan *vk)
{
	VkSemaphoreCreateInfo semaphoreInfo = { 0 };
	semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
	vk->dev->vkCreateSemaphore(vk->device, &semaphoreInfo, ALLOC_VK, &vk->sync.semaphore.presentComplete);
	vk->dev->vkCreateSemaphore(vk->device, &semaphoreInfo, ALLOC_VK, &vk->sync.semaphore.renderFinished);
	return 0;
}

void rvkDestroySyncObjects(struct RenderVulkan *vk)
{
	if (vk->sync.semaphore.renderFinished) {
		vk->dev->vkDestroySemaphore(vk->device, vk->sync.semaphore.renderFinished, ALLOC_VK);
		vk->sync.semaphore.renderFinished = VK_NULL_HANDLE;
	}
	if (vk->sync.semaphore.presentComplete) {
		vk->dev->vkDestroySemaphore(vk->device, vk->sync.semaphore.presentComplete, ALLOC_VK);
		vk->sync.semaphore.presentComplete = VK_NULL_HANDLE;
	}
}

static void rvkCloseDevice(struct RenderVulkan *vk)
{
	if (vk->device) {
		if (vk->dev->vkDeviceWaitIdle) vk->dev->vkDeviceWaitIdle(vk->device);
		rvkDestroySyncObjects(vk);
		rvkDestroySwapchain(vk);
		if (vk->commandPool) {
			vk->dev->vkDestroyCommandPool(vk->device, vk->commandPool, ALLOC_VK);
			vk->commandPool = VK_NULL_HANDLE;
		}
		vk->graphicsQueue = VK_NULL_HANDLE;
		/* `vk->device` implies `vk->dev` but device functions MAY not
		 * be loaded.
		 * However, all subobjects of `vk->device` imply functions loaded
		 */
		if (vk->dev->vkDestroyDevice) {
			vk->dev->vkDestroyDevice(vk->device, ALLOC_VK);
		} else {
			/* This is only theoretical, because we must load the "destroy"
			 * function AFTER we create the device
			 */
			fprintf(stderr, "Fatal: Unable to destroy logical device (missing function pointer)\n");
		}
		free(vk->dev);
		vk->dev = NULL;
		vk->device = VK_NULL_HANDLE;
	}
}

/** This must work no matter the current state of `vk` */
void rvkDestroyApplication(struct RenderVulkan *vk)
{
	if (vk) {
		rvkCloseDevice(vk);
		if (vk->surface) {
			vk->api->vkDestroySurfaceKHR(vk->instance, vk->surface, ALLOC_VK);
			vk->surface = VK_NULL_HANDLE;
		}
		if (vk->view) {
			/* PuglView must be freed AFTER surface but BEFORE instance destroy */
			puglFreeView(vk->view);
			vk->view = NULL;
		}
	}
}

/** This must be called AFTER `rvkDestroyApplication` if it was created */
void rvkDestroyWorld(struct RenderVulkan *vk)
{
	if (vk) {
		if (vk->world) {
			/* PuglWorld must be unloaded AFTER PuglView but BEFORE instance destroy */
			puglFreeWorld(vk->world);
			vk->world = NULL;
		}
		if (vk->debugCallback) {
			/* `vk->debugCallback` implies `vk->api` and all instance functions loaded */
			vk->api->vkDestroyDebugReportCallbackEXT(vk->instance, vk->debugCallback, ALLOC_VK);
			vk->debugCallback = VK_NULL_HANDLE;
		}
		if (vk->instance) {
			rvkDestroyInternalInstance(vk);
			vk->instance = VK_NULL_HANDLE;
		}
		if (vk->api) {
			if (vk->api->handle) unloadVulkanLibrary(vk->api->handle);
			free(vk->api);
			vk->api = NULL;
		}
		if (vk->errMsg) {
			free(vk->errMsg);
			vk->errMsg = NULL;
		}
		free(vk);
	}
}

/* Normally, we would NOT exit the entire process on errors when running as
 * part of a larger process, but since we own this process, there isn't anything
 * else to do. As a plugin, we would destroy the window and all memory
 * associated with it, leaving the larger process intact.
 */
static void rvkFatal(struct RenderVulkan *vk)
{
	fprintf(stderr, "%s\n", rvkGetErrMsg(vk));
	rvkDestroyApplication(vk);
	rvkDestroyWorld(vk);
	printf("Aborting gracefully\n");
	exit(1);
}

#define CHECK_RVK(rvk, expr)	do { if ((expr)) { rvkFatal(rvk); }  } while (0)

int running = 1;

struct Arguments args;

uint32_t framesDrawn;

PuglStatus onDisplay(PuglView *view)
{
	struct RenderVulkan *vk = puglGetHandle(view);
	uint32_t imageIndex;
	VkResult result;

	// TODO: Swapchain recreation when resizing, minimizing, etc.
	if ((result = vk->dev->vkAcquireNextImageKHR(
			vk->device,
			vk->swapchain->rawSwapchain,
			UINT64_MAX,
			vk->sync.semaphore.presentComplete,
			VK_NULL_HANDLE,
			&imageIndex))) {
		rvkSetErrMsg(vk, "Could not acquire swapchain image: %d", result);
		return PUGL_FAILURE;
	}

	/* If running continuously and with an asynchronous presentation engine,
	 * Vulkan can blast the queue with rendering work faster than the GPU
	 * can execute it, causing RAM usage to grow indefinitely. We use fences
	 * to limit the number of submitted frames to the number of swapchain
	 * images. These fences will be required later anyway when flushing
	 * persistently mapped uniform buffer ranges.
	 */
	vk->dev->vkWaitForFences(vk->device,
			1, &vk->swapchain->fences[imageIndex],
			VK_TRUE, UINT64_MAX);
	vk->dev->vkResetFences(vk->device, 1, &vk->swapchain->fences[imageIndex]);

	const VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_TRANSFER_BIT;

	VkSubmitInfo submitInfo = { 0 };
	submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
	submitInfo.waitSemaphoreCount = 1;
	submitInfo.pWaitSemaphores = &vk->sync.semaphore.presentComplete;
	submitInfo.pWaitDstStageMask = &waitStage;
	submitInfo.commandBufferCount = 1;
	submitInfo.pCommandBuffers = &vk->commandBuffers[imageIndex];
	submitInfo.signalSemaphoreCount = 1;
	submitInfo.pSignalSemaphores = &vk->sync.semaphore.renderFinished;

	if ((result = vk->dev->vkQueueSubmit(vk->graphicsQueue,
					1, &submitInfo,
					vk->swapchain->fences[imageIndex]
					))) {
		rvkSetErrMsg(vk, "Could not submit to queue: %d", result);
		return PUGL_FAILURE;
	}

	VkPresentInfoKHR presentInfo = { 0 };
	presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
	presentInfo.waitSemaphoreCount = 1;
	presentInfo.pWaitSemaphores = &vk->sync.semaphore.renderFinished;
	presentInfo.swapchainCount = 1;
	presentInfo.pSwapchains = &vk->swapchain->rawSwapchain;
	presentInfo.pImageIndices = &imageIndex;
	presentInfo.pResults = NULL;

	vk->dev->vkQueuePresentKHR(vk->graphicsQueue, &presentInfo);

	if (args.continuous) ++framesDrawn;
	return PUGL_SUCCESS;
}

PuglStatus onEvent(PuglView *view, const PuglEvent *e)
{
	printEvent(e, "Event:\t", args.verbose);
	switch (e->type) {
		case PUGL_EXPOSE:
			onDisplay(view);
			break;
		case PUGL_CLOSE:
			running = 0;
			break;
		case PUGL_KEY_PRESS:
			if (e->key.key == PUGL_KEY_ESCAPE) {
				running = 0;
			}
			break;
		default:
			break;
	}
	return PUGL_SUCCESS;
}

int main(int argc, char **argv)
{
#if defined(__linux__)
	/* The Mesa Vulkan drivers require this to be called */
	XInitThreads();
#endif

	args.validation = true;
	args.verbose = false;
	args.continuous = false;
	parseArgs(argc, argv, &args);
	printArgs(argc, argv);

	/* Vulkan application that uses Pugl for windows and events */
	struct RenderVulkan *vk;
	CHECK_RVK(vk, rvkCreateWorld(&vk, args.validation));

	printf("Created Vulkan Instance Successfully\n");

	const PuglRect frame = { 0, 0, 800, 600 };
	CHECK_RVK(vk, rvkCreateSurface(vk, frame));
	CHECK_RVK(vk, rvkSelectPhysicalDevice(vk));
	CHECK_RVK(vk, rvkOpenDevice(vk));
	CHECK_RVK(vk, rvkConfigureSurface(vk));
	CHECK_RVK(vk, rvkCreateSwapchain(vk, frame.width, frame.height));
	CHECK_RVK(vk, rvkCreateSyncObjects(vk));

	printf("Opened Vulkan Device Successfully\n");

	puglSetEventFunc(vk->view, onEvent);
	PuglFpsPrinter fpsPrinter = { puglGetTime(vk->world) };
	puglShowWindow(vk->view);
	while (running) {
		if (args.continuous) {
			puglPostRedisplay(vk->view);
		} else {
			puglPollEvents(vk->world, -1);
		}
		puglDispatchEvents(vk->world);
		if (args.continuous) {
			puglPrintFps(vk->world, &fpsPrinter, &framesDrawn);
		}
	}

	rvkDestroyApplication(vk);
	rvkDestroyWorld(vk);
	printf("Exiting gracefully\n");
	return 0;
}

#if 0
#if defined(_WIN32)
int WINAPI WinMain(
		HINSTANCE hInstance,
		HINSTANCE hPrevInstance,
		LPSTR lpCmdLine,
		int nCmdShow
		)
{
	(void)hInstance;
	(void)hPrevInstance;
	(void)lpCmdLine;
	(void)nCmdShow;
	return main();
}
#endif /* _WIN32 */
#endif /* 0 */