summaryrefslogtreecommitdiff
path: root/vk-cube/vk-cube.c
blob: b33a0483f540295790099eb1e48aa80991bde60f (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
// ================================================================================================
// This is a basic spinning cube that I wrote to learn Vulkan.
//
// This program could be structured better. I intentionally kept all the Vulkan API calls in the
// main function so they can be read sequentially. It would be better to create helper functions
// for swapchain creation, memory allocation, etc.
//
// ref: https://docs.vulkan.org
// ref: https://github.com/KhronosGroup/Vulkan-Samples
//
// Changelog:
//     ??/??/????: Initial release
//
// License:
//     Copyright (c) 2026 Hunter Kvalevog
//
//     Permission to use, copy, modify, and/or distribute this software for any
//     purpose with or without fee is hereby granted.
//
//     THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
//     WITH REGARD TO THIS SOFTWARE.
// ================================================================================================

#include <SDL3/SDL.h>
#include <SDL3/SDL_vulkan.h>
#include <vulkan/vulkan.h>

#include <assert.h>
#include <stdlib.h>

#if defined(__APPLE__) || defined(__linux__)
#   include <unistd.h>
#endif

#ifdef __APPLE__
#   include <vulkan/vulkan_metal.h>
#endif

// ================================================================================================
// Utility code
// ================================================================================================

#define ASSERT(X)    assert(X)
#define COUNTOF(ARR) (sizeof(ARR) / sizeof((ARR)[0]))
#define MAX(A, B)    ((A) > (B) ? (A) : (B))
#define MIN(A, B)    ((A) < (B) ? (A) : (B))
#define UNUSED(X)    ((void)(X))

// Find the index of the appropriate memory type
static uint32_t find_mem_type(VkPhysicalDevice pdev, uint32_t filter, VkMemoryPropertyFlags flags)
{
    VkPhysicalDeviceMemoryProperties mem;
    vkGetPhysicalDeviceMemoryProperties(pdev, &mem);
    for (uint32_t i = 0; i < mem.memoryTypeCount; i++) {
        if ((filter & (1 << i)) && (mem.memoryTypes[i].propertyFlags & flags) == flags) {
            return i;
        }
    }
    assert(0 && "failed to find memory type");
    return 0;
}

// 4x4 identity matrix
static inline void mat4ident(float dst[16])
{
    dst[ 0] = 1.0f; dst[ 1] = 0.0f; dst[ 2] = 0.0f; dst[ 3] = 0.0f;
    dst[ 4] = 0.0f; dst[ 5] = 1.0f; dst[ 6] = 0.0f; dst[ 7] = 0.0f;
    dst[ 8] = 0.0f; dst[ 9] = 0.0f; dst[10] = 1.0f; dst[11] = 0.0f;
    dst[12] = 0.0f; dst[13] = 0.0f; dst[14] = 0.0f; dst[15] = 1.0f;
}

// 4x4 matrix multiplication
static inline void mat4mul(float dst[16], const float left[16], const float right[16])
{
    for (size_t col = 0; col < 4; ++col) {
    for (size_t row = 0; row < 4; ++row) {
        dst[col * 4 + row] =
            left[0 * 4 + row] * right[col * 4 + 0] +
            left[1 * 4 + row] * right[col * 4 + 1] +
            left[2 * 4 + row] * right[col * 4 + 2] +
            left[3 * 4 + row] * right[col * 4 + 3];
    }
    }
}

// ================================================================================================
// Application code
// ================================================================================================

int main(int argc, const char **argv)
{
    UNUSED(argc); UNUSED(argv);

    if (!SDL_Init(SDL_INIT_VIDEO)) {
        printf("Failed to initialize SDL: %s", SDL_GetError());
        return 0;
    }

    // Shader binaries should be in the same directory as the demo executable. Reset the working
    // directory to make things reliable.
    {
        const char *exe_dir = SDL_GetBasePath();
        printf("Setting working directory: %s\n", exe_dir);
        // I wish the SDL devs were pragmatic enough to add SDL_SetCurrentDirectory():
        // https://github.com/libsdl-org/SDL/issues/9110
#if defined(__APPLE__) || defined(__linux__)
        chdir(exe_dir);
#endif
    }

    // Create VkInstance
    VkInstance vki = 0;
    {
        // Instance extensions are essentially just extensions to the Vulkan spec. Without any
        // extensions, Vulkan can't actually render anything because it doesn't know how to interop
        // with the native OS window.
        uint32_t    num_exts = 0;
        const char *exts[32] = { 0 };
        #define REQUIRE_EXTENSION(NAME) ASSERT(num_exts < COUNTOF(exts)); exts[num_exts++] = NAME;
        
        // SDL has a nice function that tells us what extensions are required for the given video
        // backend.
        uint32_t num_sdl_exts = 0;
        const char *const *sdl_exts = SDL_Vulkan_GetInstanceExtensions(&num_sdl_exts);
        for (uint32_t i = 0; i < num_sdl_exts; ++i) {
            REQUIRE_EXTENSION(sdl_exts[i]);
        }

        // On macOS, we also need to activate the portability extension in order to use MoltenVK.
        // This is currently the only extension we need that isn't mentioned by SDL.
#ifdef __APPLE__
        REQUIRE_EXTENSION(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
#endif

        // Tell the driver about this app. The only thing that relly matters is the API version.
        VkApplicationInfo app_info = {
            .sType      = VK_STRUCTURE_TYPE_APPLICATION_INFO,
            .apiVersion = VK_API_VERSION_1_3,
        };

        // Bitwise flags that change the behavior of the VkInstance. It's basically pointless. The
        // only accepted value in the spec is  VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR.
        VkInstanceCreateFlags flags = 0;

        // ...which we need on macOS
#ifdef __APPLE__
        flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
#endif

        printf("Requested instance extensions:\n");
        for (uint32_t i = 0; i < num_exts; ++i) {
            printf("    %s\n", exts[i]);
        }

        // The VK_LAYER_KHRONOS_validation validation layer helps detect incorrect API usage. It's
        // extremely helpful in development, but not supported on every system. Enable it if it's
        // available.

        const char *validation_layer     = "VK_LAYER_KHRONOS_validation";
        bool        has_validation_layer = false;
        {
            uint32_t num_layers = 0;
            vkEnumerateInstanceLayerProperties(&num_layers, 0);

            VkLayerProperties *layers = calloc(num_layers, sizeof(VkLayerProperties));
            vkEnumerateInstanceLayerProperties(&num_layers, layers);

            for (uint32_t i = 0; i < num_layers; ++i) {
                if (!strcmp(layers[i].layerName, validation_layer)) {
                    has_validation_layer = true;
                    break;
                }
            }

            free(layers);
        }

        // This function just passes info the vkCreateInstance. Specify required instance
        // extensions and validation layers here.
        VkInstanceCreateInfo create_info = {
            .sType                   = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
            .flags                   = flags,
            .pApplicationInfo        = &app_info,
            .enabledExtensionCount   = num_exts,
            .ppEnabledExtensionNames = exts,
            .enabledLayerCount       = has_validation_layer ? 1 : 0,
            .ppEnabledLayerNames     = &validation_layer,
        };
        VkResult vkr = vkCreateInstance(&create_info, 0, &vki);
        if (vkr != VK_SUCCESS) {
            printf("vkCreateInstance failed: %d", vkr);
            return 0;
        }

        #undef REQUIRE_EXTENSION
    }

    // Create the window
    const uint32_t wndflags = SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE;
    SDL_Window *wnd = SDL_CreateWindow("vk-cube", 1024, 768, wndflags);
    if (!wnd) {
        printf("Failed to create window: %s\n", SDL_GetError());
        return 0;
    }

    // Create the surface now so we can check if the physical device and queue families support
    // drawing to it.
    VkSurfaceKHR vksurf = 0;
    if (!SDL_Vulkan_CreateSurface(wnd, vki, 0, &vksurf)) {
        printf("Failed to create Vulkan surface: %s\n", SDL_GetError());
        return 0;
    }

    // Image formats
    VkFormat swapchain_format = VK_FORMAT_B8G8R8A8_SRGB;
    VkFormat depth_format     = VK_FORMAT_D32_SFLOAT;

    // Select physical device and queue family
    //
    // The physical device is the literal GPU hardware unit that support Vulkan. I'm just selecting
    // the first one with dynamic rendering support. In a real app, you might want to make it more
    // complex and try to select the best GPU. Or better yet, allow the user to select the GPU and
    // match the device UUID in VkPhysicalDeviceProperties.
    //
    // Queue families essentially just describe what operations a given device supports. This is
    // important for nuanced things like compute or video, but this isn't really critical when we
    // just want to draw basic 3D graphics. Like the device, just support the first queue family
    // with VK_QUEUE_GRAPHICS_BIT support.
    VkPhysicalDevice vkpdev = 0;
    uint32_t         vkqfi  = UINT32_MAX;
    {
        // Enumerate physical devices
        uint32_t num_devs = 0;
        vkEnumeratePhysicalDevices(vki, &num_devs, 0);

        VkPhysicalDevice *devs = calloc(num_devs, sizeof(VkPhysicalDevice));
        vkEnumeratePhysicalDevices(vki, &num_devs, devs);

        printf("Available GPUs:\n");
        for (uint32_t i = 0; i < num_devs; ++i) {
            // Get basic device properties (name)
            VkPhysicalDeviceProperties2 properties = {
                .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,
            };
            vkGetPhysicalDeviceProperties2(devs[i], &properties);

            // Get dynamic rendering support
            VkPhysicalDeviceDynamicRenderingFeatures dynamic_rendering_features = {
                .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES,
            };
            // and Synchronization2 support
            VkPhysicalDeviceSynchronization2Features sync2_features = {
                .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES,
                .pNext = &dynamic_rendering_features,
            };
            VkPhysicalDeviceFeatures2 features = {
                .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
                .pNext = &sync2_features,
            };
            vkGetPhysicalDeviceFeatures2(devs[i], &features);

            // Get device queue families
            uint32_t num_qfams = 0;
            vkGetPhysicalDeviceQueueFamilyProperties(devs[i], &num_qfams, 0);

            VkQueueFamilyProperties *qfams = calloc(num_qfams, sizeof(VkQueueFamilyProperties));
            vkGetPhysicalDeviceQueueFamilyProperties(devs[i], &num_qfams, qfams);

            uint32_t dev_qfi = UINT32_MAX;
            for (uint32_t j = 0; j < num_qfams; ++j) {
                if (!(qfams[j].queueFlags & VK_QUEUE_GRAPHICS_BIT)) {
                    continue;
                }

                if (SDL_Vulkan_GetPresentationSupport(vki, devs[i], j)) {
                    dev_qfi = j;
                }
            }

            free(qfams);

            bool selected = !vkpdev && dev_qfi != UINT32_MAX &&
                            dynamic_rendering_features.dynamicRendering &&
                            sync2_features.synchronization2;

            printf("    %s%s\n", properties.properties.deviceName, selected ? " (selected)" : "");

            if (selected) {
                vkpdev = devs[i];
                vkqfi  = dev_qfi;
            }
        }
        free(devs);
    }

    // At this point our validation layers are loaded and I'm not going to check VkResult

    // Create the device instance
    VkDevice vkdev = 0;
    {
        const char *exts[] = {
            "VK_KHR_swapchain",          // required to present stuff to the screen
#ifdef __APPLE__
            "VK_KHR_portability_subset", // required for MoltenVK
#endif
        };
        printf("Requested device extensions:\n");
        for (uint32_t i = 0; i < COUNTOF(exts); ++i) {
            printf("    %s\n", exts[i]);
        }

        // Ask for dynamic rendering support
        VkPhysicalDeviceDynamicRenderingFeatures dynamic_rendering_features = {
            .sType            = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES,
            .dynamicRendering = VK_TRUE,
        };
        // Ask for Synchronization2 support
        VkPhysicalDeviceSynchronization2Features sync2_features = {
            .sType            = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES,
            .synchronization2 = VK_TRUE,
            .pNext            = &dynamic_rendering_features,
        };

        float queue_priority = 1.0f;
        VkDeviceQueueCreateInfo queue_create_info = {
            .sType            = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
            .queueFamilyIndex = vkqfi,
            .queueCount       = 1,
            .pQueuePriorities = &queue_priority,
        };
        VkDeviceCreateInfo create_info = {
            .sType                   = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
            .queueCreateInfoCount    = 1,
            .pQueueCreateInfos       = &queue_create_info,
            .pNext                   = &sync2_features,
            .enabledExtensionCount   = COUNTOF(exts),
            .ppEnabledExtensionNames = exts,
        };
        vkCreateDevice(vkpdev, &create_info, 0, &vkdev);

        printf("Logical device created\n");
    }

    // Get handle to graphics queue for the logical device
    VkQueue vkq = 0;
    vkGetDeviceQueue(vkdev, vkqfi, 0, &vkq);

    // Allow two frames in flight. This means we can start preparing the next CPU-side while
    // waiting for the GPU to render the last frame;
    const uint32_t max_frames_in_flight = 2;

    // Create command pool and buffers.
    //
    // The command pool is simply a memory allocator for GPU commands.
    //
    // The command buffer is the actual list of commands that will later be queued for execution on
    // the GPU. With max_frames_in_flight = 2, we will need 2 command buffers since we will be
    // rendering two frames at the same time.
    VkCommandPool    vkcmdpool = 0;
    VkCommandBuffer *vkcmdbufs = calloc(max_frames_in_flight, sizeof(VkCommandBuffer));
    {
        VkCommandPoolCreateInfo create_pool = {
            .sType            = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
            .flags            = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
            .queueFamilyIndex = vkqfi,
        };
        vkCreateCommandPool(vkdev, &create_pool, 0, &vkcmdpool);

        VkCommandBufferAllocateInfo allocate_buffer = {
            .sType              = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
            .commandPool        = vkcmdpool,
            .level              = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
            .commandBufferCount = max_frames_in_flight,
        };
        vkAllocateCommandBuffers(vkdev, &allocate_buffer, vkcmdbufs);

        printf("Command buffers created\n");
    }

    // Model data for a unit cube
    const float vdata[] = {
        -0.5f, -0.5f,  0.5f, // f tl
         0.5f, -0.5f,  0.5f, // f tr
         0.5f,  0.5f,  0.5f, // f br
        -0.5f,  0.5f,  0.5f, // f bl
         0.5f, -0.5f, -0.5f, // b tl
        -0.5f, -0.5f, -0.5f, // b tr
        -0.5f,  0.5f, -0.5f, // b br
         0.5f,  0.5f, -0.5f, // b bl
    };
    const uint16_t idata[] = {
        0, 1, 2,
        0, 2, 3,
    };

    // Uniform data
    typedef struct Uniforms Uniforms;
    struct Uniforms
    {
        float mvp[4 * 4];
    };

    // Alllocate memory for vertex, index, and uniform data
    //
    // Note: vkAllocateMemory is very expensive, and there's a hard limit to how many times it can
    // be called. In a real app, it's better to do bulk allocations and sub-allocate as needed.
    // Theres'a a library called "vulkan memory allocator" that people really like. For this demo,
    // allocating per buffer is fine.
    
    VkBuffer       vkvbuf = 0; // cube vertex buffer
    VkDeviceMemory vkvmem = 0;
    VkBuffer       vkibuf = 0; // cube index buffer
    VkDeviceMemory vkimem = 0;

    VkBuffer       *vkubufs = calloc(max_frames_in_flight, sizeof(VkBuffer));
    VkDeviceMemory *vkumems = calloc(max_frames_in_flight, sizeof(VkDeviceMemory));

    {
        VkPhysicalDeviceMemoryProperties memprops = { 0 };
        vkGetPhysicalDeviceMemoryProperties(vkpdev, &memprops);

        // This code is super long for what it does, so make it data-driven. It would be cleaner
        // as a function, but I want this demo to read sequentually.

        typedef struct Alloc Alloc;
        struct Alloc
        {
            VkBuffer           *buf;
            VkDeviceMemory     *mem;
            VkDeviceSize       size;
            VkBufferUsageFlags usage;
        };

        uint32_t num_allocs = 0;
        Alloc    allocs[32] = { 0 };

        #define ALLOC(BUF, MEM, SIZE, USAGE)                         \
            ASSERT(num_allocs< COUNTOF(allocs));                     \
            allocs[num_allocs++] = (Alloc){ BUF, MEM, SIZE, USAGE };

        ALLOC(&vkvbuf, &vkvmem, sizeof(vdata), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
        ALLOC(&vkibuf, &vkimem, sizeof(idata), VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
        for (uint32_t i = 0; i < max_frames_in_flight; ++i) {
            ALLOC(&vkubufs[i], &vkumems[i], sizeof(Uniforms), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
        }

        for (uint32_t i = 0; i < num_allocs; ++i) {
            VkBufferCreateInfo create = {
                .sType       = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
                .size        = allocs[i].size,
                .usage       = allocs[i].usage,
                .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
            };
            vkCreateBuffer(vkdev, &create, 0, allocs[i].buf);

            // Actual allocation size including padding and alignment
            VkMemoryRequirements memreq = { 0 };
            vkGetBufferMemoryRequirements(vkdev, *allocs[i].buf, &memreq);

            // Find the appropriate device memory type for this allocation
            VkMemoryPropertyFlagBits required_props = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
                                                      VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
            uint32_t mem_type_idx = find_mem_type(vkpdev, memreq.memoryTypeBits, required_props);

            VkMemoryAllocateInfo alloc = {
                .sType           = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
                .allocationSize  = memreq.size,
                .memoryTypeIndex = mem_type_idx,
            };
            vkAllocateMemory(vkdev, &alloc, 0, allocs[i].mem);
            vkBindBufferMemory(vkdev, *allocs[i].buf, *allocs[i].mem, 0);
        }

        #undef ALLOC

        printf("Geometry buffers created\n");
    }

    // Upload vertex data
    {
        void *map = 0;
        vkMapMemory(vkdev, vkvmem, 0, sizeof(vdata), 0, &map);
        memcpy(map, vdata, sizeof(vdata));
        vkUnmapMemory(vkdev, vkvmem);
    }
    
    // Upload index data
    {
        void *map = 0;
        vkMapMemory(vkdev, vkimem, 0, sizeof(idata), 0, &map);
        memcpy(map, idata, sizeof(idata));
        vkUnmapMemory(vkdev, vkimem);
    }

    // Map uniform buffers
    Uniforms **ubufs = calloc(max_frames_in_flight, sizeof(Uniforms *));
    for (uint32_t i = 0; i < max_frames_in_flight; ++i) {
        vkMapMemory(vkdev, vkumems[i], 0, sizeof(Uniforms), 0, (void **)&ubufs[i]);
    }

    // Create descriptors
    //
    // Descriptors specify how a shader can access a resource. In this case, it only needs to
    // know how to read uniforms in the vertex stage.
    //
    // VkDescriptorSetLayout defines how the binding is used
    // VkDescriptorPool is an allocator for descriptor sets
    // VkDescriptorSet defines the pointer to the actual block of GPU device memory is used
    VkDescriptorSetLayout vksetlayout = 0;
    VkDescriptorPool      vkdescpool  = 0;
    VkDescriptorSet      *vksets      = calloc(max_frames_in_flight, sizeof(VkDescriptorSet));
    {
        VkDescriptorSetLayoutBinding descriptor_set_layout_binding = {
            .binding         = 0,
            .descriptorType  = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
            .descriptorCount = 1,
            .stageFlags      = VK_SHADER_STAGE_VERTEX_BIT
        };
        VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create = {
            .sType        = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
            .bindingCount = 1,
            .pBindings    = &descriptor_set_layout_binding
        };
        vkCreateDescriptorSetLayout(vkdev, &descriptor_set_layout_create, 0, &vksetlayout);

        // Allocator for descriptor sets
        VkDescriptorPoolSize pool_size = {
            .type            = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
            .descriptorCount = max_frames_in_flight
        };
        VkDescriptorPoolCreateInfo pool_create = {
            .sType         = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
            .maxSets       = max_frames_in_flight,
            .poolSizeCount = 1,
            .pPoolSizes    = &pool_size
        };
        vkCreateDescriptorPool(vkdev, &pool_create, 0, &vkdescpool);

        VkDescriptorSetLayout *layouts = calloc(max_frames_in_flight,
                                                sizeof(VkDescriptorSetLayout));
        for (uint32_t i = 0; i < max_frames_in_flight; ++i) {
            layouts[i] = vksetlayout;
        }

        VkDescriptorSetAllocateInfo set_alloc_info = {
            .sType              = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
            .descriptorPool     = vkdescpool,
            .descriptorSetCount = max_frames_in_flight,
            .pSetLayouts        = layouts
        };
        vkAllocateDescriptorSets(vkdev, &set_alloc_info, vksets);

        // Point each descriptor set to its respective uniform buffer
        for (uint32_t i = 0; i < max_frames_in_flight; ++i) {
            VkDescriptorBufferInfo buffer_info = {
                .buffer = vkubufs[i],
                .offset = 0,
                .range  = sizeof(Uniforms)
            };
            VkWriteDescriptorSet write = {
                .sType           = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
                .dstSet          = vksets[i],
                .dstBinding      = 0,
                .descriptorType  = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
                .descriptorCount = 1,
                .pBufferInfo     = &buffer_info
            };
            vkUpdateDescriptorSets(vkdev, 1, &write, 0, 0);
        }
        printf("Descriptor sets created\n");
    }

    // Create pipeline
    VkPipelineLayout vklayout = 0;
    VkPipeline       vkpl     = 0;
    {
        // Vertex shader module
        VkShaderModule vs_mod = 0;
        VkShaderModuleCreateInfo vs_create = {
            .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO
        };
        vs_create.pCode = SDL_LoadFile("vk-cube-vs.spv", &vs_create.codeSize);
        if (!vs_create.pCode) {
            printf("Failed to load vertex shader: %s\n", SDL_GetError());
            return 0;
        }
        vkCreateShaderModule(vkdev, &vs_create, 0, &vs_mod);

        VkPipelineShaderStageCreateInfo vs_stage = {
            .sType  = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
            .stage  = VK_SHADER_STAGE_VERTEX_BIT,
            .module = vs_mod,
            .pName  = "main"
        };

        // Fragment shader module
        VkShaderModule fs_mod = 0;
        VkShaderModuleCreateInfo fs_create = {
            .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
        };
        fs_create.pCode = SDL_LoadFile("vk-cube-fs.spv", &fs_create.codeSize);
        if (!fs_create.pCode) {
            printf("Failed to load fragment shader: %s\n", SDL_GetError());
            return 0;
        }
        vkCreateShaderModule(vkdev, &fs_create, 0, &fs_mod);

        VkPipelineShaderStageCreateInfo fs_stage = {
            .sType  = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
            .stage  = VK_SHADER_STAGE_FRAGMENT_BIT,
            .module = fs_mod,
            .pName  = "main"
        };

        VkPipelineShaderStageCreateInfo stages[] = { vs_stage, fs_stage };

        // Define vertex input
        VkVertexInputBindingDescription vert_bind_desc = {
            .binding   = 0,
            .stride    = sizeof(float) * 3,
            .inputRate = VK_VERTEX_INPUT_RATE_VERTEX
        };

        // Only one attribute - position
        VkVertexInputAttributeDescription vert_attr_p = {
            .binding  = 0,
            .location = 0,
            .format   = VK_FORMAT_R32G32B32_SFLOAT,
            .offset   = 0
        };
        VkVertexInputAttributeDescription vert_attrs[] = { vert_attr_p };

        VkPipelineVertexInputStateCreateInfo vert_create = {
            .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
            .vertexBindingDescriptionCount   = 1,
            .pVertexBindingDescriptions      = &vert_bind_desc,
            .vertexAttributeDescriptionCount = COUNTOF(vert_attrs),
            .pVertexAttributeDescriptions    = vert_attrs
        };

        // Input geometry layout
        VkPipelineInputAssemblyStateCreateInfo input_assembly_create = {
            .sType    = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
            .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST
        };

        // Dynamic viewport and scissor state
        VkDynamicState dynamic_states[] = {
            VK_DYNAMIC_STATE_VIEWPORT,
            VK_DYNAMIC_STATE_SCISSOR
        };
        VkPipelineDynamicStateCreateInfo dynamic_state_create = {
            .sType             = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
            .dynamicStateCount = COUNTOF(dynamic_states),
            .pDynamicStates    = dynamic_states
        };
        VkPipelineViewportStateCreateInfo viewport_state_create = {
            .sType         = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
            .viewportCount = 1,
            .scissorCount  = 1
        };

        // Rasterizer state
        VkPipelineRasterizationStateCreateInfo rasterizer_state_create = {
            .sType       = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
            .polygonMode = VK_POLYGON_MODE_FILL,
            .cullMode    = VK_CULL_MODE_BACK_BIT,
            .frontFace   = VK_FRONT_FACE_COUNTER_CLOCKWISE,
            .lineWidth   = 1.0f
        };

        // Multisample state
        VkPipelineMultisampleStateCreateInfo multisample_state_create = {
            .sType                = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
            .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT // disabled
        };

        // Depth stencil state
        VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create = {
            .sType            = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
            .depthTestEnable  = VK_TRUE,
            .depthWriteEnable = VK_TRUE,
            .depthCompareOp   = VK_COMPARE_OP_LESS
        };

        // Color blending state
        VkPipelineColorBlendAttachmentState color_blend_attachment_state = {
            .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
                              VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT,
        };
        VkPipelineColorBlendStateCreateInfo color_blend_state_create = {
            .sType           = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
            .attachmentCount = 1,
            .pAttachments    = &color_blend_attachment_state
        };

        // Pipeline layout - basically just specifies descriptor set layout
        VkPipelineLayoutCreateInfo layout_create = {
            .sType          = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
            .setLayoutCount = 1,
            .pSetLayouts    = &vksetlayout
        };
        vkCreatePipelineLayout(vkdev, &layout_create, 0, &vklayout);

        // Rendering state
        VkPipelineRenderingCreateInfo rendering_create = {
            .sType                   = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO,
            .colorAttachmentCount    = 1,
            .pColorAttachmentFormats = &swapchain_format,
            .depthAttachmentFormat   = depth_format
        };

        // Assemble everything
        VkGraphicsPipelineCreateInfo pipeline_create = {
            .sType               = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
            .pNext               = &rendering_create,
            .stageCount          = COUNTOF(stages),
            .pStages             = stages,
            .pVertexInputState   = &vert_create,
            .pInputAssemblyState = &input_assembly_create,
            .pViewportState      = &viewport_state_create,
            .pRasterizationState = &rasterizer_state_create,
            .pMultisampleState   = &multisample_state_create,
            .pDepthStencilState  = &depth_stencil_state_create,
            .pColorBlendState    = &color_blend_state_create,
            .pDynamicState       = &dynamic_state_create,
            .layout              = vklayout
        };
        vkCreateGraphicsPipelines(vkdev, 0, 1, &pipeline_create, 0, &vkpl);

        printf("Pipeline created\n");
    }

    // The swapchain needs to be recreated any time the window is resized
    bool           swapchain_dirty      = true;
    VkSwapchainKHR vkswapchain          = 0;
    uint32_t       num_swapchain_images = 0;
    VkImage       *swapchain_images     = 0;
    VkImageView   *swapchain_views      = 0;
    VkImage        depth_image          = 0;
    VkDeviceMemory depth_mem            = 0;
    VkImageView    depth_view           = 0;
    VkExtent2D     extent2              = { 0 };
    VkExtent3D     extent3              = { 0 };

    // Signaled when the swapchain has fresh image to render to
    VkSemaphore *vk_image_available_sems = 0;

    // Signaled when we are done drawing to an image and it should be presented to the user
    VkSemaphore *vk_render_finished_sems = 0;

    // Signaled when the command buffer is done executing. Signaled by default to avoid deadlock
    // on first frame.
    VkFence *vk_in_flight_fences = calloc(max_frames_in_flight, sizeof(VkFence));
    for (uint32_t i = 0; i < max_frames_in_flight; ++i) {
        VkFenceCreateInfo fci = {
            .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
            .flags = VK_FENCE_CREATE_SIGNALED_BIT,
        };
        vkCreateFence(vkdev, &fci, 0, &vk_in_flight_fences[i]);
    }

    bool running = true;
    while (running) {
        SDL_Event evt;
        while (SDL_PollEvent(&evt)) {
            switch (evt.type) {
                case SDL_EVENT_WINDOW_RESIZED:
                    swapchain_dirty = true;
                    break;
                case SDL_EVENT_QUIT:
                    running = false;
                    break;
            };
        }

        int wnd_w = 0;
        int wnd_h = 0;
        SDL_GetWindowSizeInPixels(wnd, &wnd_w, &wnd_h);
        
        if (wnd_w <= 0 || wnd_h <= 0) {
            SDL_Delay(10); // 10ms, idk
            continue;
        }

        // Create swapchain if needed
        if (swapchain_dirty) {
            vkDeviceWaitIdle(vkdev);

            VkSurfaceCapabilitiesKHR scaps;
            vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vkpdev, vksurf, &scaps);

            assert(scaps.currentExtent.width  > 0);
            assert(scaps.currentExtent.height > 0);

            if (vkswapchain) {
                vkDestroyImageView(vkdev, depth_view, 0); depth_view = 0;
                vkDestroyImage(vkdev, depth_image, 0); depth_image = 0;
                vkFreeMemory(vkdev, depth_mem, 0); depth_mem = 0;
                for (uint32_t i = 0; i < num_swapchain_images; ++i) {
                    vkDestroyImageView(vkdev, swapchain_views[i], 0);
                    swapchain_views[i] = 0;
                }
                free(swapchain_images); swapchain_images = 0;
                free(swapchain_views);  swapchain_views  = 0;
                vkDestroySwapchainKHR(vkdev, vkswapchain, 0); vkswapchain = 0;
            }

            // minImageCount is almost always 2
            uint32_t image_count = scaps.minImageCount + 1;
            if (scaps.maxImageCount > 0) {
                image_count = MIN(image_count, scaps.maxImageCount);
            }
            assert(max_frames_in_flight <= image_count);

            extent2.width  = wnd_w;
            extent2.height = wnd_h;
            extent3.width  = extent2.width;
            extent3.height = extent2.height;
            extent3.depth  = 1;

            VkSwapchainCreateInfoKHR swapchain_create = {
                .sType            = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
                .surface          = vksurf,
                .minImageCount    = image_count,
                .imageFormat      = swapchain_format,
                .imageColorSpace  = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR,
                .imageExtent      = extent2,
                .imageArrayLayers = 1,
                .imageUsage       = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
                .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, // gfx and present queues are same
                .preTransform     = scaps.currentTransform,
                .compositeAlpha   = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
                .presentMode      = VK_PRESENT_MODE_FIFO_KHR, // vsync
                .clipped          = VK_TRUE
            };
            vkCreateSwapchainKHR(vkdev, &swapchain_create, 0, &vkswapchain);

            // Get swapchain image handles
            vkGetSwapchainImagesKHR(vkdev, vkswapchain, &num_swapchain_images, 0);
            swapchain_images = calloc(num_swapchain_images, sizeof(VkImage));
            vkGetSwapchainImagesKHR(vkdev, vkswapchain, &num_swapchain_images, swapchain_images);

            // Create swapchain image views
            swapchain_views = calloc(num_swapchain_images, sizeof(VkImageView));
            for (uint32_t i = 0; i < num_swapchain_images; ++i) {
                VkImageViewCreateInfo view_create = {
                    .sType            = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
                    .image            = swapchain_images[i],
                    .viewType         = VK_IMAGE_VIEW_TYPE_2D,
                    .format           = swapchain_format,
                    .subresourceRange = (VkImageSubresourceRange){
                        .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
                        .levelCount = 1,
                        .layerCount = 1
                    }
                };
                vkCreateImageView(vkdev, &view_create, 0, &swapchain_views[i]);
            }

            // Create depth image
            VkImageCreateInfo depth_create = {
                .sType       = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
                .imageType   = VK_IMAGE_TYPE_2D,
                .format      = depth_format,
                .extent      = extent3,
                .mipLevels   = 1,
                .arrayLayers = 1,
                .samples     = VK_SAMPLE_COUNT_1_BIT,
                .tiling      = VK_IMAGE_TILING_OPTIMAL,
                .usage       = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT
            };
            vkCreateImage(vkdev, &depth_create, 0, &depth_image);

            // Allocate depth image memory
            VkMemoryRequirements memreq = { 0 };
            vkGetImageMemoryRequirements(vkdev, depth_image, &memreq);
            VkMemoryAllocateInfo alloc = {
                .sType          = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
                .allocationSize = memreq.size
            };
            alloc.memoryTypeIndex = find_mem_type(vkpdev, memreq.memoryTypeBits,
                                                  VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
            vkAllocateMemory(vkdev, &alloc, 0, &depth_mem);
            vkBindImageMemory(vkdev, depth_image, depth_mem, 0);

            // Create depth image view
            VkImageViewCreateInfo view_create = {
                .sType            = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
                .image            = depth_image,
                .viewType         = VK_IMAGE_VIEW_TYPE_2D,
                .format           = depth_format,
                .subresourceRange = (VkImageSubresourceRange){
                    .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT,
                    .levelCount = 1,
                    .layerCount = 1
                }
            };
            vkCreateImageView(vkdev, &view_create, 0, &depth_view);

            // Create synchronization objects
            //
            // Semaphores are for GPU-GPU synchronization and fences are for CPU-GPU sync.
            {
                if (vk_image_available_sems) {
                    for (uint32_t i = 0; i < num_swapchain_images; ++i) {
                        vkDestroySemaphore(vkdev, vk_image_available_sems[i], 0);
                        vkDestroySemaphore(vkdev, vk_render_finished_sems[i], 0);
                    }
                    free(vk_image_available_sems);
                    free(vk_render_finished_sems);
                }
                vk_image_available_sems = calloc(num_swapchain_images, sizeof(VkSemaphore));
                vk_render_finished_sems = calloc(num_swapchain_images, sizeof(VkSemaphore));
                VkSemaphoreCreateInfo sci = {
                    .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
                };
                for (uint32_t i = 0; i < num_swapchain_images; ++i) {
                    vkCreateSemaphore(vkdev, &sci, 0, &vk_image_available_sems[i]);
                    vkCreateSemaphore(vkdev, &sci, 0, &vk_render_finished_sems[i]);
                }
            }

            printf("Swapchain created\n");

            swapchain_dirty = false;
        }

        static int f = 0; // frame cycler, [0, max_frames_in_flight)

        vkWaitForFences(vkdev, 1, &vk_in_flight_fences[f], VK_TRUE, UINT64_MAX);

        uint32_t img_idx = 0;
        VkResult vkr = vkAcquireNextImageKHR(vkdev, vkswapchain, UINT64_MAX,
                                             vk_image_available_sems[f], VK_NULL_HANDLE, &img_idx);
        if (vkr == VK_ERROR_OUT_OF_DATE_KHR) {
            swapchain_dirty = true;
            continue;
        }

        vkResetFences(vkdev, 1, &vk_in_flight_fences[f]);

        // Update MVP
        float *mvp = ubufs[f]->mvp;
        mvp[ 0] = 1.0f; mvp[ 1] = 0.0f; mvp[ 2] = 0.0f; mvp[ 3] = 0.0f;
        mvp[ 4] = 0.0f; mvp[ 5] = 1.0f; mvp[ 6] = 0.0f; mvp[ 7] = 0.0f;
        mvp[ 8] = 0.0f; mvp[ 9] = 0.0f; mvp[10] = 1.0f; mvp[11] = 0.0f;
        mvp[12] = 0.0f; mvp[13] = 0.0f; mvp[14] = 0.0f; mvp[15] = 1.0f;

        VkCommandBuffer cmd = vkcmdbufs[f];
        vkResetCommandBuffer(cmd, 0);

        VkCommandBufferBeginInfo cmd_begin = {
            .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO
        };
        vkBeginCommandBuffer(cmd, &cmd_begin);

        // Transition swapchain image: unknown -> color attachment
        {
            VkImageMemoryBarrier2 barrier = {
                .sType               = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
                .srcStageMask        = VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT,
                .srcAccessMask       = 0,
                .dstStageMask        = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
                .dstAccessMask       = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT,
                .oldLayout           = VK_IMAGE_LAYOUT_UNDEFINED,
                .newLayout           = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
                .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
                .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
                .image               = swapchain_images[img_idx],
                .subresourceRange    = (VkImageSubresourceRange){
                    .aspectMask     = VK_IMAGE_ASPECT_COLOR_BIT,
                    .baseMipLevel   = 0,
                    .levelCount     = 1,
                    .baseArrayLayer = 0,
                    .layerCount     = 1
                }
            };

            VkDependencyInfo dep_info = {
                .sType                   = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
                .imageMemoryBarrierCount = 1,
                .pImageMemoryBarriers    = &barrier
            };
            vkCmdPipelineBarrier2(cmd, &dep_info);
        }

        // Transition depth image: unknown -> depth attachment
        {
            VkImageMemoryBarrier2 barrier = {
                .sType               = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
                .srcStageMask        = VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT,
                .srcAccessMask       = 0,
                .dstStageMask        = VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT,
                .dstAccessMask       = VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
                .oldLayout           = VK_IMAGE_LAYOUT_UNDEFINED,
                .newLayout           = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
                .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
                .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
                .image               = depth_image,
                .subresourceRange    = (VkImageSubresourceRange){
                    .aspectMask     = VK_IMAGE_ASPECT_DEPTH_BIT,
                    .baseMipLevel   = 0,
                    .levelCount     = 1,
                    .baseArrayLayer = 0,
                    .layerCount     = 1
                }
            };

            VkDependencyInfo dep_info = {
                .sType                   = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
                .imageMemoryBarrierCount = 1,
                .pImageMemoryBarriers    = &barrier
            };
            vkCmdPipelineBarrier2(cmd, &dep_info);
        }

        // Begin dynamic rendering
        {
            VkRenderingAttachmentInfo color_attachment = {
                .sType            = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
                .imageView        = swapchain_views[img_idx],
                .imageLayout      = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
                .loadOp           = VK_ATTACHMENT_LOAD_OP_CLEAR,
                .storeOp          = VK_ATTACHMENT_STORE_OP_STORE,
                .clearValue.color = { { 0.1f, 0.1f, 0.12f, 1.0f } }
            };

            VkRenderingAttachmentInfo depth_attachment = {
                .sType                   = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
                .imageView               = depth_view,
                .imageLayout             = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
                .loadOp                  = VK_ATTACHMENT_LOAD_OP_CLEAR,
                .storeOp                 = VK_ATTACHMENT_STORE_OP_DONT_CARE,
                .clearValue.depthStencil = { 1.0f, 0 }
            };

            VkRenderingInfo render_info = {
                .sType      = VK_STRUCTURE_TYPE_RENDERING_INFO,
                .renderArea = { { 0, 0 }, extent2 },
                .layerCount = 1,
                .colorAttachmentCount = 1,
                .pColorAttachments = &color_attachment,
                .pDepthAttachment = &depth_attachment
            };

            vkCmdBeginRendering(cmd, &render_info);
        }

        // Set dynamic viewport and scissor
        {
            VkViewport viewport = {
                .width    = extent2.width,
                .height   = extent2.height,
                .minDepth = 0.0f,
                .maxDepth = 1.0f,
            };
            vkCmdSetViewport(cmd, 0, 1, &viewport);

            VkRect2D scissor = {
                .extent = extent2,
            };
            vkCmdSetScissor(cmd, 0, 1, &scissor);
        }

        // Draw the cube
        {
            vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, vkpl);
            vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, vklayout, 0, 1,
                                    &vksets[f], 0, 0);
            VkDeviceSize offset = 0;
            vkCmdBindVertexBuffers(cmd, 0, 1, &vkvbuf, &offset);
            vkCmdBindIndexBuffer(cmd, vkibuf, 0, VK_INDEX_TYPE_UINT16);
            vkCmdDrawIndexed(cmd, COUNTOF(idata), 1, 0, 0, 0);
        }

        // End dynamic rendering
        vkCmdEndRendering(cmd);

        // Transition swapchain image: color attachment -> present
        {
            VkImageMemoryBarrier2 barrier = {
                .sType               = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
                .srcStageMask        = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
                .srcAccessMask       = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT,
                .dstStageMask        = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT,
                .dstAccessMask       = 0,
                .oldLayout           = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
                .newLayout           = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
                .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
                .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
                .image               = swapchain_images[img_idx],
                .subresourceRange    = (VkImageSubresourceRange){
                    .aspectMask     = VK_IMAGE_ASPECT_COLOR_BIT,
                    .baseMipLevel   = 0,
                    .levelCount     = 1,
                    .baseArrayLayer = 0,
                    .layerCount     = 1
                }
            };

            VkDependencyInfo dep_info = {
                .sType                   = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
                .imageMemoryBarrierCount = 1,
                .pImageMemoryBarriers    = &barrier
            };
            vkCmdPipelineBarrier2(cmd, &dep_info);
        }

        // Done recording commands
        vkEndCommandBuffer(cmd);

        // Wait for these semaphores before swapping
        VkSemaphore wait_sems[]   = { vk_image_available_sems[f] };

        // Signal these semaphores after swapping
        VkSemaphore signal_sems[] = { vk_render_finished_sems[img_idx] };

        // Where to wait for wait_sems
        VkPipelineStageFlags wait_stages[] = {
            VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT
        };

        // Submit
        {
            VkSubmitInfo submit_info = {
                .sType                = VK_STRUCTURE_TYPE_SUBMIT_INFO,
                .waitSemaphoreCount   = COUNTOF(wait_sems),
                .pWaitSemaphores      = wait_sems,
                .pWaitDstStageMask    = wait_stages,
                .commandBufferCount   = 1,
                .pCommandBuffers      = &cmd,
                .signalSemaphoreCount = COUNTOF(signal_sems),
                .pSignalSemaphores    = signal_sems
            };
            vkQueueSubmit(vkq, 1, &submit_info, vk_in_flight_fences[f]);
        }

        // Present
        {
            VkPresentInfoKHR present_info = {
                .sType              = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
                .waitSemaphoreCount = COUNTOF(signal_sems),
                .pWaitSemaphores    = signal_sems,
                .swapchainCount     = 1,
                .pSwapchains        = &vkswapchain,
                .pImageIndices      = &img_idx
            };
            VkResult vkr = vkQueuePresentKHR(vkq, &present_info);
            if (vkr == VK_ERROR_OUT_OF_DATE_KHR || vkr == VK_SUBOPTIMAL_KHR) {
                swapchain_dirty = true;
            }
        }

        printf("frame\n");
        f = (f + 1) % max_frames_in_flight;
    }

    return 0;
}