aboutsummaryrefslogtreecommitdiff
path: root/src/engine.cpp
blob: fa5814f6ae6f2996ce9371cf85b1c06cf0a4d2cb (plain) (blame)
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
#include "config.h"
#include <iostream>

#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <functional>
#include <utility>
#include <iterator>
#include <memory>
#include <numbers>
#include <optional>
#include <algorithm>
#include <tuple>
#include <limits>
#include <array>
#include <ios>
#include <fstream>

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <vulkan/vk_enum_string_helper.h>

#ifdef HAVE_NCURSES
#include <ncurses.h>
#endif

#include "fb/chfb.hpp"
#include "fb/pixfb.hpp"
#include "o3d/scene.hpp"
#include "o3d/mesh.hpp"
#include "o3d/obj3d.hpp"
#include "o3d/vertex_data.hpp"
#include "o3d/tri.hpp"
#include "o3d/camera.hpp"
#include "math/vector.hpp"
#include "math/mat4.hpp"
#include "math/quat.hpp"
#include "math/tform.hpp"
#include "ctrl/keyboard.hpp"
#include "ctrl/mouse.hpp"
#include "renderer.hpp"
#include "obj_parser.hpp"
#include "vulkan_utils.hpp"

using
    engine::Renderer,
    engine::fb::CharacterFrameBuffer,
    engine::fb::PixelFrameBuffer,
    engine::o3d::Scene,
    engine::o3d::Mesh,
    engine::o3d::Triangle,
    engine::o3d::Camera,
    engine::o3d::VertexData,
    engine::math::Vector2,
    engine::math::Vector3,
    engine::math::Vector4,
    engine::math::Matrix4,
    engine::math::Quaternion,
    engine::controllers::Keyboard,
    engine::controllers::KeyboardKey,
    engine::controllers::Mouse;

#define FPS 60

#define PI 3.1415926535f

#define MODE_HELP      0
#define MODE_TERM      1
#define MODE_GRAPHICAL 2

#define GAME_PLANE   0
#define GAME_SUZANNE 1
#define GAME_PHYSICS 2

#define GAME GAME_PHYSICS

static void print_usage(std::ostream& output_stream) {
    output_stream << "Usage: ./engine [-htg] [--help] [--term] [--graphical]\n"
                  << "  -h, --help        show usage (this)\n"
                  << "  -t, --term        terminal mode\n"
                  << "  -g, --graphical   graphical mode (default)\n"
                  << std::flush;
}

[[noreturn]]
static void usage_error_exit() {
    print_usage(std::cerr);
    std::exit(EXIT_FAILURE);
}

extern Camera* camera;
Camera* camera;

template<typename FrameBuffer, typename UpdateFrameFn>
static void scene_main(Renderer<FrameBuffer>& renderer, const Matrix4& final_transform_mat, UpdateFrameFn update_frame) {
    bool cont = true;
    Scene scene{
        {90.f * PI / 180.f, {{0.f, 1.8f, 7.f}, Quaternion::one(), {1.f, 1.f, 1.f}}},
        {
#if GAME == GAME_PLANE
            {
                Mesh::plane(2.f, 2.f),
                {
                    Vector3(0.f, 0.f, 0.f),
                    Quaternion::one(),
                    Vector3(1.f, 1.f, 1.f),
                }
            },
#elif GAME == GAME_SUZANNE
            {
                engine::parse_object(DATADIR "/assets/suzanne.obj"),
                {
                    Vector3(0.f, 0.f, 0.f),
                    Quaternion::one(),
                    Vector3(1.f, 1.f, 1.f),
                }
            },
#elif GAME == GAME_PHYSICS
            {
                Mesh::plane(10.f, 10.f),
                {
                    Vector3(0.f, 0.f, 0.f),
                    Quaternion::one(),
                    Vector3(1.f, 1.f, 1.f),
                }
            },
            {
                engine::parse_object(DATADIR "/assets/suzanne.obj"),
                {
                    Vector3(0.f, 1.f, 0.f),
                    Quaternion::one(),
                    Vector3(1.f, 1.f, 1.f),
                }
            },
#endif
        }
    };

    float rx = 0.f, ry = 0.f;
    Keyboard kb{[&](KeyboardKey key) {
        (void) key;
    }, [&](KeyboardKey key) {
        (void) key;
    }};
    Mouse mouse{[&](Vector2 rel) {
        rx += -rel.y;
        ry += -rel.x;
        if (rx < -PI / 2.f) rx = -PI / 2.f;
        if (rx >  PI / 2.f) rx =  PI / 2.f;
        scene.camera.transform.rot = Quaternion::euler_zxy(rx, ry, 0.f);
    }};

    camera = &scene.camera;

    while (cont) {
        renderer.clear();
        auto pre_final_mat = final_transform_mat
            * scene.camera.to_mat4(static_cast<float>(renderer.height()) / static_cast<float>(renderer.width()), .5f, 12.f);
        for (const auto& obj : scene.objs) {
            auto obj_mat = obj.transform.to_mat4();
            auto final_mat = pre_final_mat * obj_mat;
            const auto& mesh = obj.mesh;
            std::vector<Vector4> vertices;
            std::vector<VertexData> vertices_data;
            for (const auto& vertex : mesh.vertices) {
                vertices.push_back(final_mat * vertex);
                vertices_data.push_back(VertexData((obj_mat * vertex).xyz()));
            }
            for (const auto& triangle_indices : mesh.indices) {
                [&]<std::size_t... j>(std::integer_sequence<std::size_t, j...>) {
                    renderer.draw_triangle({{vertices[triangle_indices[j][0]], mesh.normals[triangle_indices[j][1]], vertices_data[triangle_indices[j][0]]}...});
                }(std::make_integer_sequence<std::size_t, 3>());
            }
        }
        cont = update_frame(scene, kb, mouse);

        Vector3 movement(0.f, 0.f, 0.f);
        if (kb.is_down(KeyboardKey::fw))        movement.z += -1.f;
        if (kb.is_down(KeyboardKey::key_left))  movement.x += -1.f;
        if (kb.is_down(KeyboardKey::bw))        movement.z += +1.f;
        if (kb.is_down(KeyboardKey::key_right)) movement.x += +1.f;
        if (kb.is_down(KeyboardKey::fw) || kb.is_down(KeyboardKey::key_left)
            || kb.is_down(KeyboardKey::bw) || kb.is_down(KeyboardKey::key_right)) movement.normalize();
        scene.camera.transform.loc += movement.rot(Quaternion::rot_y(ry)) * .05f;
        scene.camera.fov = (kb.is_down(KeyboardKey::zoom) ? 40.f : 80.f) * PI / 180.f;
    }
}

#ifdef HAVE_NCURSES
#define MKEY_ESC 27

static int main_term() {
    // init
    std::setlocale(LC_ALL, "");
    initscr();
    cbreak();
    noecho();
    intrflush(stdscr, FALSE);
    keypad(stdscr, TRUE);
    set_escdelay(0);
    curs_set(0);

    int w, h;
    getmaxyx(stdscr, h, w);
    Renderer<CharacterFrameBuffer> renderer{CharacterFrameBuffer{static_cast<unsigned int>(w), static_cast<unsigned int>(h)}};

    scene_main(renderer, Matrix4::scale(Vector3(2.f, 1.f, 1.f)),
        [&](Scene& scene, auto& kb, auto& mouse) {
            (void) scene;
            mvaddnstr(0, 0, renderer.fb.chars(), renderer.width() * renderer.height());

            bool cont = true;
            std::optional<KeyboardKey> key;
            std::optional<Vector2> rel;
            //timeout(1000 / FPS);
            timeout(10);
            int c = getch();

            switch (c) {
            case 'z':
                key = KeyboardKey::fw;
                break;
            case 'q':
                key = KeyboardKey::key_left;
                break;
            case 's':
                key = KeyboardKey::bw;
                break;
            case 'd':
                key = KeyboardKey::key_right;
                break;
            case 'p':
                key = KeyboardKey::zoom;
                break;
            case KEY_UP:
                rel = Vector2(0.f, -.1f);
                break;
            case KEY_LEFT:
                rel = Vector2(-.1f, 0.f);
                break;
            case KEY_DOWN:
                rel = Vector2(0.f, +.1f);
                break;
            case KEY_RIGHT:
                rel = Vector2(+.1f, 0.f);
                break;
            case MKEY_ESC:
                return false;
            }

            if (key && *key == KeyboardKey::fw) {
                if (!kb.is_down(KeyboardKey::fw)) kb.key_down_event(KeyboardKey::fw);
            } else {
                if (kb.is_down(KeyboardKey::fw)) kb.key_up_event(KeyboardKey::fw);
            }
            if (key && *key == KeyboardKey::key_left) {
                if (!kb.is_down(KeyboardKey::key_left)) kb.key_down_event(KeyboardKey::key_left);
            } else {
                if (kb.is_down(KeyboardKey::key_left)) kb.key_up_event(KeyboardKey::key_left);
            }
            if (key && *key == KeyboardKey::bw) {
                if (!kb.is_down(KeyboardKey::bw)) kb.key_down_event(KeyboardKey::bw);
            } else {
                if (kb.is_down(KeyboardKey::bw)) kb.key_up_event(KeyboardKey::bw);
            }
            if (key && *key == KeyboardKey::key_right) {
                if (!kb.is_down(KeyboardKey::key_right)) kb.key_down_event(KeyboardKey::key_right);
            } else {
                if (kb.is_down(KeyboardKey::key_right)) kb.key_up_event(KeyboardKey::key_right);
            }

            if (key && *key == KeyboardKey::zoom) {
                if (kb.is_down(KeyboardKey::zoom)) kb.key_up_event(KeyboardKey::zoom);
                else kb.key_down_event(KeyboardKey::zoom);
            }

            if (rel)
                mouse.mouse_motion_event(*rel);

            getmaxyx(stdscr, h, w);
            renderer.resize(static_cast<unsigned int>(w), static_cast<unsigned int>(h));

            return cont;
        }
    );

    // terminate
    endwin();

    return EXIT_SUCCESS;
}
#endif

#define SCREEN_WIDTH  640
#define SCREEN_HEIGHT 480

static const std::vector<const char*> validation_layers = {
    "VK_LAYER_KHRONOS_validation",
};

static const std::vector<const char*> device_exts = {
    VK_KHR_SWAPCHAIN_EXTENSION_NAME,
    VK_KHR_SPIRV_1_4_EXTENSION_NAME,
    VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME,
    VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME,
};

#ifdef NDEBUG
const bool enable_validation_layers = false;
#else
const bool enable_validation_layers = true;
#endif

static bool check_validation_layer_support() {
    uint32_t layer_count;
    if (VkResult res = vkEnumerateInstanceLayerProperties(&layer_count, nullptr); res != VK_SUCCESS) {
        std::cerr << "failed to enumerate instance layer properties, error code: " << string_VkResult(res) << std::endl;
        std::exit(EXIT_FAILURE);
    }
    std::vector<VkLayerProperties> available_layers(layer_count);
    if (VkResult res = vkEnumerateInstanceLayerProperties(&layer_count, available_layers.data()); res != VK_SUCCESS) {
        std::cerr << "failed to enumerate instance layer properties, error code: " << string_VkResult(res) << std::endl;
        std::exit(EXIT_FAILURE);
    }

    for (const char* layer_name : validation_layers) {
        bool layer_found = false;

        for (const auto& layer_properties : available_layers) {
            if (strcmp(layer_name, layer_properties.layerName) == 0) {
                layer_found = true;
                break;
            }
        }

        if (!layer_found) {
            return false;
        }
    }

    return true;
}

static std::string severity_to_str(VkDebugUtilsMessageSeverityFlagBitsEXT severity) {
    switch (severity) {
    case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
        return "VERBOSE";
    case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
        return "INFO";
    case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
        return "WARNING";
    case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
        return "ERROR";
    default:
        std::unreachable();
    }
}

// TODO: remove [[maybe_unused]]
static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(
        VkDebugUtilsMessageSeverityFlagBitsEXT message_severity,
        [[maybe_unused]] VkDebugUtilsMessageTypeFlagsEXT message_type,
        const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
        [[maybe_unused]] void* user_data) {
    std::cerr << "validation layer: [" << severity_to_str(message_severity) << "] " << callback_data->pMessage << std::endl;
    return VK_FALSE;
}

static void populate_msger_ci(VkDebugUtilsMessengerCreateInfoEXT& msger_ci) {
    msger_ci.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
    msger_ci.messageSeverity =
          VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT
        | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
    msger_ci.messageType =
          VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT
        | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT
        | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
    msger_ci.pfnUserCallback = debug_callback;
    msger_ci.pUserData = nullptr;
}

static std::tuple<std::optional<uint32_t>, std::optional<uint32_t>> find_queue_family_indices(
        VkPhysicalDevice physical_device, const std::vector<VkQueueFamilyProperties2>& queue_family_properties, VkSurfaceKHR surface) {
    std::optional<uint32_t> graphics_queue_family_index, present_queue_family_index;
    for (uint32_t i = 0; i < queue_family_properties.size(); i++) {
        const auto& prop = queue_family_properties[i];
        bool is_graphics_queue = (prop.queueFamilyProperties.queueFlags & VK_QUEUE_GRAPHICS_BIT) != static_cast<VkQueueFlags>(0);
        VkBool32 is_presentation_queue;
        if (VkResult res = vkGetPhysicalDeviceSurfaceSupportKHR(physical_device, i, surface, &is_presentation_queue); res != VK_SUCCESS) {
            std::cerr << "failed to check if queue family supports surface, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        if (is_graphics_queue && is_presentation_queue) {
            graphics_queue_family_index = i;
            present_queue_family_index = i;
            break;
        } else if (is_graphics_queue && !graphics_queue_family_index) {
            graphics_queue_family_index = i;
        } else if (is_presentation_queue && !present_queue_family_index) {
            present_queue_family_index = i;
        }
    }
    return { graphics_queue_family_index, present_queue_family_index };
}

static void transition_image_layout(VkCommandBuffer cmd_buf, VkImage img,
        VkImageLayout old_layout, VkImageLayout new_layout,
        VkAccessFlags2 src_access_mask, VkAccessFlags2 dst_access_mask,
        VkPipelineStageFlags2 src_stage_mask, VkPipelineStageFlags2 dst_stage_mask) {
    VkImageMemoryBarrier2 img_mem_barrier {
        .sType               = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
        .pNext               = nullptr,
        .srcStageMask        = src_stage_mask,
        .srcAccessMask       = src_access_mask,
        .dstStageMask        = dst_stage_mask,
        .dstAccessMask       = dst_access_mask,
        .oldLayout           = old_layout,
        .newLayout           = new_layout,
        .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
        .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
        .image               = img,
        .subresourceRange    = {
            .aspectMask     = VK_IMAGE_ASPECT_COLOR_BIT,
            .baseMipLevel   = 0,
            .levelCount     = 1,
            .baseArrayLayer = 0,
            .layerCount     = 1,
        },
    };
    VkDependencyInfo dependency_info {
        .sType                    = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
        .pNext                    = nullptr,
        .dependencyFlags          = {},
        .memoryBarrierCount       = 0,
        .pMemoryBarriers          = {},
        .bufferMemoryBarrierCount = 0,
        .pBufferMemoryBarriers    = {},
        .imageMemoryBarrierCount  = 1,
        .pImageMemoryBarriers     = &img_mem_barrier,
    };
    vkCmdPipelineBarrier2(cmd_buf, &dependency_info);
}

static int main_graphical() {
    // init window
    glfwInit();
    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
    GLFWwindow* window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Engine", nullptr, nullptr);

    // init Vulkan
    std::cout << "Vulkan loader version: " << engine::myvk::api { VK_HEADER_VERSION_COMPLETE } << std::endl;

    // init Vulkan - create instance
    if (enable_validation_layers && !check_validation_layer_support()) {
        std::cerr << "validation layers requested, but not available!" << std::endl;
        std::exit(EXIT_FAILURE);
    }

    auto instance = [&]() {
        VkApplicationInfo app_info {
            .sType              = VK_STRUCTURE_TYPE_APPLICATION_INFO,
            .pNext              = nullptr,
            .pApplicationName   = "engine - test",
            .applicationVersion = VK_MAKE_VERSION(1, 0, 0),
            .pEngineName        = "engine",
            .engineVersion      = VK_MAKE_VERSION(1, 0, 0),
            .apiVersion         = VK_API_VERSION_1_4,
        };

        std::vector<const char*> extensions;

        {
            uint32_t glfw_extension_count;
            const char** glfw_extensions;
            glfw_extensions = glfwGetRequiredInstanceExtensions(&glfw_extension_count);
            extensions.insert(extensions.end(), glfw_extensions, glfw_extensions + glfw_extension_count);
        }

        if (enable_validation_layers) {
            extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
        }

        uint32_t extension_count;
        if (VkResult res = vkEnumerateInstanceExtensionProperties(nullptr, &extension_count, nullptr); res != VK_SUCCESS) {
            std::cerr << "failed to enumerate instance extension properties, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        std::vector<VkExtensionProperties> available_extensions(extension_count);
        if (VkResult res = vkEnumerateInstanceExtensionProperties(nullptr, &extension_count, available_extensions.data()); res != VK_SUCCESS) {
            std::cerr << "failed to enumerate instance extension properties, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }

        std::cout << "required instance extensions:\n";
        for (const auto& extension_name : extensions) {
            std::cout << (std::ranges::find_if(available_extensions, [&](const auto& avail_ext) {
                    return strcmp(avail_ext.extensionName, extension_name) == 0;
                }) == available_extensions.end() ? "!" : " ");
            std::cout << " " << extension_name << "\n";
        }

        VkInstanceCreateInfo instance_ci {
            .sType                   = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
            .pNext                   = nullptr,
            .flags                   = {},
            .pApplicationInfo        = &app_info,
            .enabledLayerCount       = {},
            .ppEnabledLayerNames     = {},
            .enabledExtensionCount   = static_cast<uint32_t>(extensions.size()),
            .ppEnabledExtensionNames = extensions.data(),
        };

        VkDebugUtilsMessengerCreateInfoEXT inst_msger_ci{};
        if (enable_validation_layers) {
            populate_msger_ci(inst_msger_ci);
            instance_ci.pNext = (VkDebugUtilsMessengerCreateInfoEXT*) &inst_msger_ci;
            instance_ci.enabledLayerCount = static_cast<uint32_t>(validation_layers.size());
            instance_ci.ppEnabledLayerNames = validation_layers.data();
        }

        VkInstance instance;
        if (VkResult res = vkCreateInstance(&instance_ci, nullptr, &instance); res != VK_SUCCESS) {
            std::cerr << "failed to create instance, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        return instance;
    }();

    VkDebugUtilsMessengerEXT debug_messenger;
    if (enable_validation_layers) {
        VkDebugUtilsMessengerCreateInfoEXT msger_ci{};
        populate_msger_ci(msger_ci);

        auto create_debug_messenger = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
        if (!create_debug_messenger) {
            std::cerr << "failed to set up debug messenger!" << std::endl;
            std::exit(EXIT_FAILURE);
        }
        create_debug_messenger(instance, &msger_ci, nullptr, &debug_messenger);
    }

    // create window surface
    auto surface = [&]() {
        VkSurfaceKHR surface;
        if (VkResult res = glfwCreateWindowSurface(instance, window, nullptr, &surface); res != VK_SUCCESS) {
            std::cerr << "failed to create window surface, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        return surface;
    }();

    // select physical device and queues
    auto [physical_device, graphics_queue_family_index, present_queue_family_index, device_features] = [&]() {
        std::optional<VkPhysicalDevice> physical_device;
        uint32_t res_graphics_queue_family_index, res_presentation_queue_family_index;
        VkPhysicalDeviceFeatures2 res_features;

        uint32_t physical_devices_count;
        if (VkResult res = vkEnumeratePhysicalDevices(instance, &physical_devices_count, nullptr); res != VK_SUCCESS) {
            std::cerr << "failed to enumerate physical devices, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        std::vector<VkPhysicalDevice> avail_physical_devices(physical_devices_count);
        if (VkResult res = vkEnumeratePhysicalDevices(instance, &physical_devices_count, avail_physical_devices.data()); res != VK_SUCCESS) {
            std::cerr << "failed to enumerate physical devices, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }

        if (avail_physical_devices.empty()) {
            std::cerr << "failed to find physical devices with Vulkan support" << std::endl;
            std::exit(EXIT_FAILURE);
        }

        std::cout << "devices:" << std::endl;

        for (const auto& avail_physical_device : avail_physical_devices) {
            VkPhysicalDeviceProperties2 properties{};
            properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
            vkGetPhysicalDeviceProperties2(avail_physical_device, &properties);

            std::cout << "  " << properties.properties.deviceName << ":" << std::endl;
            std::cout << "    apiVersion: " << engine::myvk::api { properties.properties.apiVersion } << std::endl;

            VkPhysicalDeviceFeatures2 features{};
            features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
            vkGetPhysicalDeviceFeatures2(avail_physical_device, &features);

            // TODO: found a better name, too confusing with device_exts
            uint32_t ext_props_count;
            if (VkResult res = vkEnumerateDeviceExtensionProperties(avail_physical_device, nullptr, &ext_props_count, nullptr); res != VK_SUCCESS) {
                std::cerr << "failed to enumerate physical device extension properties, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }
            std::vector<VkExtensionProperties> ext_props(ext_props_count);
            if (VkResult res = vkEnumerateDeviceExtensionProperties(avail_physical_device, nullptr, &ext_props_count, ext_props.data()); res != VK_SUCCESS) {
                std::cerr << "failed to enumerate physical device extension properties, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }

            std::cout << "    required physical device extensions:" << std::endl;
            for (const auto& ext : device_exts) {
                std::cout << "    " << (std::ranges::find_if(ext_props, [&](const auto& avail_ext) {
                        return strcmp(avail_ext.extensionName, ext) == 0;
                    }) == ext_props.end() ? "!" : " ");
                std::cout << " " << ext << std::endl;
            }

            uint32_t queue_family_properties_count;
            vkGetPhysicalDeviceQueueFamilyProperties2(avail_physical_device, &queue_family_properties_count, nullptr);
            std::vector<VkQueueFamilyProperties2> queue_family_properties(queue_family_properties_count);
            for (auto& elt : queue_family_properties)
                elt.sType = VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2;
            vkGetPhysicalDeviceQueueFamilyProperties2(avail_physical_device, &queue_family_properties_count, queue_family_properties.data());

            auto [graphics_queue_family_index, present_queue_family_index] = find_queue_family_indices(avail_physical_device, queue_family_properties, surface);
            std::cout << "    graphics queue family index: ";
            if (graphics_queue_family_index)
                std::cout << *graphics_queue_family_index;
            else
                std::cout << "none";
            std::cout << std::endl;
            std::cout << "    presentation queue family index: ";
            if (present_queue_family_index)
                std::cout << *present_queue_family_index;
            else
                std::cout << "none";
            std::cout << std::endl;

            bool is_suitable = [&]() {
                if (VK_API_VERSION_VARIANT(properties.properties.apiVersion) != 0
                        || properties.properties.apiVersion < VK_API_VERSION_1_4)
                    return false;
                if (!graphics_queue_family_index || !present_queue_family_index)
                    return false;
                if (std::ranges::find_if_not(device_exts, [&](const auto& device_ext) {
                            return std::ranges::find_if(ext_props,
                                    [&](const auto& ext_prop) { return strcmp(ext_prop.extensionName, device_ext) == 0; })
                                != ext_props.end();
                        }) != device_exts.end())
                    return false;
                return true;
            }();
            std::cout << "    is_suitable: " << std::boolalpha << is_suitable << std::noboolalpha;
            if (!physical_device && is_suitable) {
                std::cout << " (picking this one)";
                physical_device = avail_physical_device;
                res_graphics_queue_family_index = *graphics_queue_family_index;
                res_presentation_queue_family_index = *present_queue_family_index;
                res_features = features;
            }
            std::cout << std::endl;
        }

        std::cout << std::endl;

        if (!physical_device) {
            std::cerr << "no suitable physical device found" << std::endl;
            std::exit(EXIT_FAILURE);
        }

        return std::tuple<VkPhysicalDevice, uint32_t, uint32_t, VkPhysicalDeviceFeatures2>
                { *physical_device, res_graphics_queue_family_index, res_presentation_queue_family_index, res_features };
    }();

    auto device = [&]() {
        // TODO: really weird way of making a single structure if
        //   graphics_queue_family_index == present_queue_family_index
        // here, in this cas, we create both *CreateInfo, and then tell VkDeviceCreateInfo that
        // there is only a single element
        std::array queue_priorities { .5f, .5f };
        std::array device_queue_cis {
            VkDeviceQueueCreateInfo {
                .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
                .pNext = nullptr,
                .flags = {},
                .queueFamilyIndex = graphics_queue_family_index,
                .queueCount = 1,
                .pQueuePriorities = &queue_priorities[0],
            },
            VkDeviceQueueCreateInfo {
                .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
                .pNext = nullptr,
                .flags = {},
                .queueFamilyIndex = present_queue_family_index,
                .queueCount = 1,
                .pQueuePriorities = &queue_priorities[1],
            },
        };

        VkPhysicalDeviceExtendedDynamicStateFeaturesEXT device_eds_features {
            .sType                = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT,
            .pNext                = {},
            .extendedDynamicState = VK_TRUE,
        };

        VkPhysicalDeviceVulkan13Features device_vk13_features {
            .sType                                              = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,
            .pNext                                              = &device_eds_features,
            .robustImageAccess                                  = {},
            .inlineUniformBlock                                 = {},
            .descriptorBindingInlineUniformBlockUpdateAfterBind = {},
            .pipelineCreationCacheControl                       = {},
            .privateData                                        = {},
            .shaderDemoteToHelperInvocation                     = {},
            .shaderTerminateInvocation                          = {},
            .subgroupSizeControl                                = {},
            .computeFullSubgroups                               = {},
            .synchronization2                                   = VK_TRUE,
            .textureCompressionASTC_HDR                         = {},
            .shaderZeroInitializeWorkgroupMemory                = {},
            .dynamicRendering                                   = VK_TRUE,
            .shaderIntegerDotProduct                            = {},
            .maintenance4                                       = {},
        };

        device_features.pNext = &device_vk13_features;

        VkDeviceCreateInfo device_ci {
            .sType                   = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
            .pNext                   = &device_features,
            .flags                   = {},
            .queueCreateInfoCount    =
                (graphics_queue_family_index == present_queue_family_index ? static_cast<uint32_t>(1) : static_cast<uint32_t>(2)),
            .pQueueCreateInfos       = device_queue_cis.data(),
            .enabledLayerCount       = {},
            .ppEnabledLayerNames     = {},
            .enabledExtensionCount   = static_cast<uint32_t>(device_exts.size()),
            .ppEnabledExtensionNames = device_exts.data(),
            .pEnabledFeatures        = {},
        };

        VkDevice device;
        if (VkResult res = vkCreateDevice(physical_device, &device_ci, nullptr, &device); res != VK_SUCCESS) {
            std::cerr << "failed to create device: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        return device;
    }();

    auto [graphics_queue, present_queue] = [&]() {
        const auto map_family_to_queue = [&](uint32_t queue_family_index) {
            VkQueue queue;
            vkGetDeviceQueue(device, queue_family_index, 0, &queue);
            return queue;
        };
        return std::tuple {
            map_family_to_queue(graphics_queue_family_index),
            map_family_to_queue(present_queue_family_index),
        };
    }();

    // create swap chain
    // TODO: should probably use version 2 of theses functions, but glfwCreateWindowSurface return
    // version 1, so for now we will use version 1
    auto surface_capabilities = [&]() {
        VkSurfaceCapabilitiesKHR surface_capabilities;
        if (VkResult res = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device, surface, &surface_capabilities); res != VK_SUCCESS) {
            std::cerr << "failed to get physical device surface capabilities, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        return surface_capabilities;
    }();

    auto swapchain_extent = [&]() {
        if (surface_capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max())
            return surface_capabilities.currentExtent;
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        return VkExtent2D{
            .width  = std::clamp(static_cast<uint32_t>(width),  surface_capabilities.minImageExtent.width,  surface_capabilities.maxImageExtent.width),
            .height = std::clamp(static_cast<uint32_t>(height), surface_capabilities.minImageExtent.height, surface_capabilities.maxImageExtent.height),
        };
    }();

    auto surface_format = [&]() {
        uint32_t surface_formats_count;
        if (VkResult res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &surface_formats_count, nullptr); res != VK_SUCCESS) {
            std::cerr << "failed to get physical device surface formats, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        std::vector<VkSurfaceFormatKHR> surface_formats(surface_formats_count);
        if (VkResult res = vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &surface_formats_count, surface_formats.data()); res != VK_SUCCESS) {
            std::cerr << "failed to get physical device surface formats, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }

        for (const auto& surface_format : surface_formats) {
            if (surface_format.format == VK_FORMAT_B8G8R8A8_SRGB
                    && surface_format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
                return surface_format;
        }

        // not found
        std::cerr << "surface format not found (VK_FORMAT_B8G8R8_SRGB and VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)" << std::endl;
        std::exit(EXIT_FAILURE);
    }();

    auto present_mode = [&]() {
        uint32_t present_modes_count;
        if (VkResult res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &present_modes_count, nullptr); res != VK_SUCCESS) {
            std::cerr << "failed to get physical device present modes, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        std::vector<VkPresentModeKHR> present_modes(present_modes_count);
        if (VkResult res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &present_modes_count, present_modes.data()); res != VK_SUCCESS) {
            std::cerr << "failed to get physical device present modes, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }

        for (const auto& present_mode : present_modes)
            if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR)
                return present_mode;

        return VK_PRESENT_MODE_FIFO_KHR;
    }();

    auto swapchain = [&]() {
        // TODO: remove unnecessary static_cast<uint32_t>, but at this moment I'm not sure where they
        // are necessary
        uint32_t min_image_count = std::max(static_cast<uint32_t>(3), surface_capabilities.minImageCount + static_cast<uint32_t>(1));
        if (surface_capabilities.maxImageCount > 0 && surface_capabilities.maxImageCount < min_image_count)
            min_image_count = surface_capabilities.maxImageCount;

        // might not be used, but if we do, we have to keep it in memory until the call to vkCreateSwapchainKHR()
        std::array<uint32_t, 2> queue_family_indices;
        VkSwapchainCreateInfoKHR swapchain_ci {
            .sType                 = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
            .pNext                 = nullptr,
            .flags                 = {},
            .surface               = surface,
            .minImageCount         = min_image_count,
            .imageFormat           = surface_format.format,
            .imageColorSpace       = surface_format.colorSpace,
            .imageExtent           = swapchain_extent,
            .imageArrayLayers      = 1,
            .imageUsage            = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
            .imageSharingMode      = {},
            .queueFamilyIndexCount = {},
            .pQueueFamilyIndices   = {},
            .preTransform          = surface_capabilities.currentTransform,
            .compositeAlpha        = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
            .presentMode           = present_mode,
            .clipped               = VK_TRUE,
            .oldSwapchain          = {},
        };
        if (graphics_queue_family_index == present_queue_family_index) {
            swapchain_ci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
        } else {
            swapchain_ci.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
            queue_family_indices[0] = graphics_queue_family_index;
            queue_family_indices[1] = present_queue_family_index;
            swapchain_ci.queueFamilyIndexCount = 2;
            swapchain_ci.pQueueFamilyIndices = queue_family_indices.data();
        }

        VkSwapchainKHR swapchain;
        if (VkResult res = vkCreateSwapchainKHR(device, &swapchain_ci, nullptr, &swapchain); res != VK_SUCCESS) {
            std::cerr << "failed create swapchain, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        return swapchain;
    }();

    auto swapchain_imgs = [&]() {
        uint32_t swapchain_imgs_count;
        if (VkResult res = vkGetSwapchainImagesKHR(device, swapchain, &swapchain_imgs_count, nullptr); res != VK_SUCCESS) {
            std::cerr << "failed to get swapchain images, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        std::vector<VkImage> swapchain_imgs(swapchain_imgs_count);
        if (VkResult res = vkGetSwapchainImagesKHR(device, swapchain, &swapchain_imgs_count, swapchain_imgs.data()); res != VK_SUCCESS) {
            std::cerr << "failed to get swapchain images, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        return swapchain_imgs;
    }();

    auto swapchain_img_views = [&]() {
        std::vector<VkImageView> swapchain_img_views(swapchain_imgs.size());
        for (uint32_t i = 0; i < swapchain_imgs.size(); i++) {
            VkImageViewCreateInfo img_view_ci {
                .sType            = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
                .pNext            = {},
                .flags            = {},
                .image            = swapchain_imgs[i],
                .viewType         = VK_IMAGE_VIEW_TYPE_2D,
                .format           = surface_format.format,
                .components       = {},
                .subresourceRange = { // VkImageSubresourceRange
                    .aspectMask     = VK_IMAGE_ASPECT_COLOR_BIT,
                    .baseMipLevel   = 0,
                    .levelCount     = 1,
                    .baseArrayLayer = 0,
                    .layerCount     = 1,
                },
            };
            if (VkResult res = vkCreateImageView(device, &img_view_ci, nullptr, &swapchain_img_views[i]); res != VK_SUCCESS) {
                std::cerr << "failed to create image view, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }
        }
        return swapchain_img_views;
    }();

    auto [pl_layout, graphics_pl] = [&]() {
        // reading shader file
        auto shader_module = [&]() {
            // shader code has to be 32-bits aligned, which is the case with the default allocator
            std::vector<char> shader_code;
            {
                const char* shader_file_name = SHADERSDIR "/shader.spv";
                std::ifstream shader_file(shader_file_name, std::ios::ate | std::ios::binary);
                if (!shader_file.is_open()) {
                    std::cerr << "file `" << shader_file_name << "'not found" << std::endl; // TODO: improve
                    std::exit(EXIT_SUCCESS);
                }
                shader_code.resize(shader_file.tellg());
                shader_file.seekg(0, std::ios::beg);
                shader_file.read(shader_code.data(), static_cast<std::streamsize>(shader_code.size()));
            }

            VkShaderModuleCreateInfo shader_module_ci {
                .sType    = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
                .pNext    = nullptr,
                .flags    = {},
                .codeSize = shader_code.size(),
                .pCode    = reinterpret_cast<const uint32_t*>(shader_code.data()),
            };
            VkShaderModule shader_module;
            if (VkResult res = vkCreateShaderModule(device, &shader_module_ci, nullptr, &shader_module); res != VK_SUCCESS) {
                std::cerr << "failed to create shader module, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }
            return shader_module;
        }();

        auto [pl_layout, graphics_pl] = [&]() {
            std::array pl_shader_stage_create_infos {
                VkPipelineShaderStageCreateInfo {
                    .sType               = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                    .pNext               = nullptr,
                    .flags               = {},
                    .stage               = VK_SHADER_STAGE_VERTEX_BIT,
                    .module              = shader_module,
                    .pName               = "vert_main",
                    .pSpecializationInfo = nullptr,
                },
                VkPipelineShaderStageCreateInfo {
                    .sType               = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                    .pNext               = nullptr,
                    .flags               = {},
                    .stage               = VK_SHADER_STAGE_FRAGMENT_BIT,
                    .module              = shader_module,
                    .pName               = "frag_main",
                    .pSpecializationInfo = nullptr,
                },
            };

            std::array dynamic_states {
                VkDynamicState { VK_DYNAMIC_STATE_VIEWPORT },
                VkDynamicState { VK_DYNAMIC_STATE_SCISSOR },
            };
            VkPipelineDynamicStateCreateInfo pl_dyn_state_ci {
                .sType             = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
                .pNext             = nullptr,
                .flags             = {},
                .dynamicStateCount = static_cast<uint32_t>(dynamic_states.size()),
                .pDynamicStates     = dynamic_states.data(),
            };

            VkPipelineVertexInputStateCreateInfo pl_vert_in_state_ci {
                .sType                           = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
                .pNext                           = nullptr,
                .flags                           = {},
                .vertexBindingDescriptionCount   = 0,
                .pVertexBindingDescriptions      = nullptr,
                .vertexAttributeDescriptionCount = 0,
                .pVertexAttributeDescriptions    = nullptr,
            };

            VkPipelineInputAssemblyStateCreateInfo pl_in_asm_state_ci {
                .sType                  = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
                .pNext                  = nullptr,
                .flags                  = {},
                .topology               = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
                .primitiveRestartEnable = VK_FALSE,
            };

            VkPipelineViewportStateCreateInfo pl_viewport_state_ci {
                .sType         = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
                .pNext         = nullptr,
                .flags         = {},
                .viewportCount = 1,
                .pViewports    = {},
                .scissorCount  = 1,
                .pScissors     = {},
            };

            VkPipelineRasterizationStateCreateInfo pl_raster_state_ci {
                .sType                   = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
                .pNext                   = nullptr,
                .flags                   = {},
                .depthClampEnable        = VK_FALSE,
                .rasterizerDiscardEnable = VK_FALSE,
                .polygonMode             = VK_POLYGON_MODE_FILL,
                .cullMode                = VK_CULL_MODE_BACK_BIT,
                .frontFace               = VK_FRONT_FACE_CLOCKWISE,
                .depthBiasEnable         = VK_FALSE,
                .depthBiasConstantFactor = {},
                .depthBiasClamp          = {},
                .depthBiasSlopeFactor    = {},
                .lineWidth               = 1.f,
            };

            VkPipelineMultisampleStateCreateInfo pl_ms_state_ci {
                .sType                 = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
                .pNext                 = nullptr,
                .flags                 = {},
                .rasterizationSamples  = VK_SAMPLE_COUNT_1_BIT,
                .sampleShadingEnable   = VK_FALSE,
                .minSampleShading      = {},
                .pSampleMask           = {},
                .alphaToCoverageEnable = VK_FALSE,
                .alphaToOneEnable      = VK_FALSE,
            };

            VkPipelineColorBlendAttachmentState pl_col_blend_attachment_state {
                .blendEnable         = VK_FALSE,
                .srcColorBlendFactor = {},
                .dstColorBlendFactor = {},
                .colorBlendOp        = {},
                .srcAlphaBlendFactor = {},
                .dstAlphaBlendFactor = {},
                .alphaBlendOp        = {},
                .colorWriteMask      =
                      VK_COLOR_COMPONENT_R_BIT
                    | VK_COLOR_COMPONENT_G_BIT
                    | VK_COLOR_COMPONENT_B_BIT
                    | VK_COLOR_COMPONENT_A_BIT,
            };

            VkPipelineColorBlendStateCreateInfo pl_col_blend_state_ci {
                .sType           = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
                .pNext           = nullptr,
                .flags           = {},
                .logicOpEnable   = VK_FALSE,
                .logicOp         = {},
                .attachmentCount = 1,
                .pAttachments    = &pl_col_blend_attachment_state,
                .blendConstants  = { 0.f, 0.f, 0.f, 0.f },
            };

            auto pl_layout = [&]() {
                VkPipelineLayoutCreateInfo pl_layout_ci {
                    .sType                  = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
                    .pNext                  = nullptr,
                    .flags                  = {},
                    .setLayoutCount         = 0,
                    .pSetLayouts            = {},
                    .pushConstantRangeCount = 0,
                    .pPushConstantRanges    = {},
                };

                VkPipelineLayout pl_layout;
                if (VkResult res = vkCreatePipelineLayout(device, &pl_layout_ci, nullptr, &pl_layout); res != VK_SUCCESS) {
                    std::cerr << "failed to create pipeline layout, error code: " << string_VkResult(res) << std::endl;
                    std::exit(EXIT_FAILURE);
                }
                return pl_layout;
            }();

            VkPipelineRenderingCreateInfo pl_render_ci {
                .sType                   = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO,
                .pNext                   = nullptr,
                .viewMask                = {},
                .colorAttachmentCount    = 1,
                .pColorAttachmentFormats = &surface_format.format,
                .depthAttachmentFormat   = {},
                .stencilAttachmentFormat = {},
            };

            VkGraphicsPipelineCreateInfo graphics_pl_ci {
                .sType               = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
                .pNext               = &pl_render_ci,
                .flags               = {},
                .stageCount          = 2,
                .pStages             = pl_shader_stage_create_infos.data(),
                .pVertexInputState   = &pl_vert_in_state_ci,
                .pInputAssemblyState = &pl_in_asm_state_ci,
                .pTessellationState  = {},
                .pViewportState      = &pl_viewport_state_ci,
                .pRasterizationState = &pl_raster_state_ci,
                .pMultisampleState   = &pl_ms_state_ci,
                .pDepthStencilState  = {},
                .pColorBlendState    = &pl_col_blend_state_ci,
                .pDynamicState       = &pl_dyn_state_ci,
                .layout              = pl_layout,
                .renderPass          = nullptr,
                .subpass             = {},
                .basePipelineHandle  = {},
                .basePipelineIndex   = {},
            };

            VkPipeline graphics_pl;
            if (VkResult res = vkCreateGraphicsPipelines(device, nullptr, 1, &graphics_pl_ci, nullptr, &graphics_pl); res != VK_SUCCESS) {
                std::cerr << "failed to pipeline, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }
            return std::tuple { pl_layout, graphics_pl };
        }();

        vkDestroyShaderModule(device, shader_module, nullptr);

        return std::tuple { pl_layout, graphics_pl };
    }();

    auto cmd_pool = [&]() {
        VkCommandPoolCreateInfo cmd_pool_ci {
            .sType            = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
            .pNext            = nullptr,
            .flags            = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
            .queueFamilyIndex = graphics_queue_family_index,
        };
        VkCommandPool cmd_pool;
        if (VkResult res = vkCreateCommandPool(device, &cmd_pool_ci, nullptr, &cmd_pool); res != VK_SUCCESS) {
            std::cerr << "failed to create command pool, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        return cmd_pool;
    }();

    auto cmd_buf = [&]() {
        VkCommandBufferAllocateInfo cmd_buf_ai {
            .sType              = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
            .pNext              = nullptr,
            .commandPool        = cmd_pool,
            .level              = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
            .commandBufferCount = 1,
        };
        VkCommandBuffer cmd_buf;
        if (VkResult res = vkAllocateCommandBuffers(device, &cmd_buf_ai, &cmd_buf); res != VK_SUCCESS) {
            std::cerr << "failed to allocate command buffer, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        return cmd_buf;
    }();

    // create sync objects
    auto [sem_present_complete, sem_render_finished] = [&]() {
        const auto create_semaphore = [&](const char* name) {
            VkSemaphoreCreateInfo sem_ci {
                .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
                .pNext = nullptr,
                .flags = {},
            };
            VkSemaphore sem;
            if (VkResult res = vkCreateSemaphore(device, &sem_ci, nullptr, &sem); res != VK_SUCCESS) {
                std::cerr << "failed to create " << name << " semaphore, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }
            return sem;
        };
        return std::tuple {
            create_semaphore("present complete"),
            create_semaphore("render finished"),
        };
    }();
    std::cout << "sem_present_complete: " << sem_present_complete << std::endl;
    std::cout << "sem_render_finished: " << sem_render_finished << std::endl;

    auto fence_draw = [&]() {
        VkFenceCreateInfo fence_draw_ci {
            .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
            .pNext = nullptr,
            .flags = VK_FENCE_CREATE_SIGNALED_BIT,
        };
        VkFence fence_draw;
        if (VkResult res = vkCreateFence(device, &fence_draw_ci, nullptr, &fence_draw); res != VK_SUCCESS) {
            std::cerr << "failed to create draw semaphore, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }
        return fence_draw;
    }();
    std::cout << "fence_draw: " << fence_draw << std::endl;

    // main loop
    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();

        if (VkResult res = vkQueueWaitIdle(present_queue); res != VK_SUCCESS) {
            std::cerr << "failed to wait idle for graphics queue, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }

        auto img_idx = [&]() {
            uint32_t img_idx;
            if (VkResult res = vkAcquireNextImageKHR(device, swapchain,
                        std::numeric_limits<uint64_t>::max(), sem_present_complete, nullptr, &img_idx); res != VK_SUCCESS) {
                std::cerr << "failed to acquire next image, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }
            return img_idx;
        }();

        // record command buffer
        {
            VkCommandBufferBeginInfo cmd_buf_bi {
                .sType            = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
                .pNext            = nullptr,
                .flags            = {},
                .pInheritanceInfo = {},
            };
            if (VkResult res = vkBeginCommandBuffer(cmd_buf, &cmd_buf_bi); res != VK_SUCCESS) {
                std::cerr << "failed to begin command buffer, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }
        }

        transition_image_layout(cmd_buf, swapchain_imgs[img_idx],
            VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
            {}, VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT,
            VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT);

        {
            VkClearValue clear_val { .color = { .float32 = { 0.f, 0.f, 0.f, 1.f } }, };
            VkRenderingAttachmentInfo attachment_info {
                .sType              = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
                .pNext              = nullptr,
                .imageView          = swapchain_img_views[img_idx],
                .imageLayout        = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
                .resolveMode        = {},
                .resolveImageView   = {},
                .resolveImageLayout = {},
                .loadOp             = VK_ATTACHMENT_LOAD_OP_CLEAR,
                .storeOp            = VK_ATTACHMENT_STORE_OP_STORE,
                .clearValue         = clear_val,
            };
            VkRenderingInfo render_info {
                .sType                = VK_STRUCTURE_TYPE_RENDERING_INFO,
                .pNext                = nullptr,
                .flags                = {},
                .renderArea           = { .offset { 0, 0 }, .extent = swapchain_extent },
                .layerCount           = 1,
                .viewMask             = {},
                .colorAttachmentCount = 1,
                .pColorAttachments    = &attachment_info,
                .pDepthAttachment     = {},
                .pStencilAttachment   = {},
            };
            vkCmdBeginRendering(cmd_buf, &render_info);
        }

        vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pl);

        {
            VkViewport viewport {
                .x        = 0.f,
                .y        = 0.f,
                .width    = static_cast<float>(swapchain_extent.width),
                .height   = static_cast<float>(swapchain_extent.height),
                .minDepth = 0.f,
                .maxDepth = 1.f,
            };
            vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
        }

        {
            VkRect2D scissor {
                .offset = { 0, 0 },
                .extent = swapchain_extent,
            };
            vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
        }

        vkCmdDraw(cmd_buf, 3, 1, 0, 0);

        vkCmdEndRendering(cmd_buf);

        transition_image_layout(cmd_buf, swapchain_imgs[img_idx],
            VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
            VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, {},
            VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT);

        if (VkResult res = vkEndCommandBuffer(cmd_buf); res != VK_SUCCESS) {
            std::cerr << "failed to end command buffer, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }

        if (VkResult res = vkResetFences(device, 1, &fence_draw); res != VK_SUCCESS) {
            std::cerr << "failed to reset draw fence, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }

        {
            VkPipelineStageFlags pl_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
            VkSubmitInfo submit_info {
                .sType                = VK_STRUCTURE_TYPE_SUBMIT_INFO,
                .pNext                = nullptr,
                .waitSemaphoreCount   = 1,
                .pWaitSemaphores      = &sem_present_complete,
                .pWaitDstStageMask    = &pl_stage_flags,
                .commandBufferCount   = 1,
                .pCommandBuffers      = &cmd_buf,
                .signalSemaphoreCount = 1,
                .pSignalSemaphores    = &sem_render_finished,
            };
            if (VkResult res = vkQueueSubmit(graphics_queue, 1, &submit_info, fence_draw); res != VK_SUCCESS) {
                std::cerr << "failed to submit queue, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }
        }

        if (VkResult res = vkWaitForFences(device, 1, &fence_draw, VK_TRUE, std::numeric_limits<uint64_t>::max()); res != VK_SUCCESS) {
            std::cerr << "failed to wait for draw fence, error code: " << string_VkResult(res) << std::endl;
            std::exit(EXIT_FAILURE);
        }

        {
            VkPresentInfoKHR present_info {
                .sType              = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
                .pNext              = nullptr,
                .waitSemaphoreCount = 1,
                .pWaitSemaphores    = &sem_render_finished,
                .swapchainCount     = 1,
                .pSwapchains        = &swapchain,
                .pImageIndices      = &img_idx,
                .pResults           = nullptr,
            };
            if (VkResult res = vkQueuePresentKHR(present_queue, &present_info); res != VK_SUCCESS) {
                std::cerr << "failed to present, error code: " << string_VkResult(res) << std::endl;
                std::exit(EXIT_FAILURE);
            }
        }
    }

    if (VkResult res = vkDeviceWaitIdle(device); res != VK_SUCCESS) {
        std::cerr << "failed to wait idle for device, error code: " << string_VkResult(res) << std::endl;
        std::exit(EXIT_FAILURE);
    }

    // cleanup
    vkDestroyFence(device, fence_draw, nullptr);
    vkDestroySemaphore(device, sem_render_finished, nullptr);
    vkDestroySemaphore(device, sem_present_complete, nullptr);
    vkDestroyCommandPool(device, cmd_pool, nullptr);
    vkDestroyPipeline(device, graphics_pl, nullptr);
    vkDestroyPipelineLayout(device, pl_layout, nullptr);
    for (const auto img_view : swapchain_img_views)
        vkDestroyImageView(device, img_view, nullptr);
    vkDestroySwapchainKHR(device, swapchain, nullptr);
    vkDestroySurfaceKHR(instance, surface, nullptr);
    vkDestroyDevice(device, nullptr);

    if (enable_validation_layers) {
        auto destroy_debug_messenger = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
        if (!destroy_debug_messenger) {
            std::cerr << "failed to destroy debug messenger!" << std::endl;
            std::exit(EXIT_FAILURE);
        }
        destroy_debug_messenger(instance, debug_messenger, nullptr);
    }

    vkDestroyInstance(instance, nullptr);
    glfwDestroyWindow(window);
    glfwTerminate();

    return EXIT_SUCCESS;
}

static std::vector<std::string_view> convert_args(int argc, char *argv[]) {
    std::vector<std::string_view> args(argc);
    for (int i = 0; i < argc; i++)
        args[i] = argv[i];
    return args;
}

static void parse_args(const std::vector<std::string_view>& args, int& mode) {
    for (auto args_iter = std::next(args.begin()); args_iter != args.end(); args_iter++) {
        const auto& arg = *args_iter;
        if (arg.size() >= 1 && arg[0] == '-') {
            if (arg.size() >= 2 && arg[1] == '-') {
                auto long_opt = arg.substr(2);
                if (long_opt == "help") {
                    mode = MODE_HELP;
                } else if (long_opt == "term") {
                    mode = MODE_TERM;
                } else if (long_opt == "graphical") {
                    mode = MODE_GRAPHICAL;
                } else {
                    std::cerr << "Error: Unexpected option `--" << long_opt << "'." << std::endl;
                    usage_error_exit();
                }
            } else {
                std::size_t arg_len = arg.size();
                if (arg_len == 1) {
                    std::cerr << "Error: Unexpected argument `-'." << std::endl;
                    usage_error_exit();
                }
                for (auto arg_iter = std::next(arg.begin()); arg_iter != arg.end(); arg_iter++) {
                    const auto& opt = *arg_iter;
                    switch (opt) {
                    case 'h':
                        mode = MODE_HELP;
                        break;
                    case 't':
                        mode = MODE_TERM;
                        break;
                    case 'g':
                        mode = MODE_GRAPHICAL;
                        break;
                    default:
                        std::cerr << "Error: Unexpected option `-" << opt << "'." << std::endl;
                        usage_error_exit();
                    }
                }
            }
        } else {
            std::cerr << "Error: Unexpected argument `" << arg << "'." << std::endl;
            usage_error_exit();
        }
    }
}

int main(int argc, char *argv[]) {
    int mode = MODE_GRAPHICAL;
    parse_args(convert_args(argc, argv), mode);
    switch (mode) {
    case MODE_HELP:
        print_usage(std::cout);
        return EXIT_SUCCESS;
    case MODE_TERM:
#ifdef HAVE_NCURSES
        return main_term();
#else
        std::cerr << "Error: ncurses was not enabled during compilation." << std::endl;
        return EXIT_FAILURE;
#endif
    case MODE_GRAPHICAL:
        return main_graphical();
    default:
        std::unreachable();
    }
}