1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
|
#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>
#include <map>
#include <chrono>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <vulkan/vk_enum_string_helper.h>
#include <stb_image.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::Object3D,
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
enum class Mode {
help,
term,
graphical,
};
enum class GameType {
plane,
suzanne,
plane_and_suzanne,
test,
};
constexpr GameType game_type { GameType::test };
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);
exit(EXIT_FAILURE);
}
extern Camera* camera;
Camera* camera;
template<typename UpdateSurfaceSizeFn, typename PollEventsFn, typename RenderAndPresentFrameFn>
static void scene_main(const Matrix4& final_transform_mat, Scene& scene,
UpdateSurfaceSizeFn update_surface_size, PollEventsFn poll_events, RenderAndPresentFrameFn render_and_present_frame) {
constexpr float movement_speed = 10.f;
float rx = 0.f, ry = 0.f;
Keyboard kb { [&](KeyboardKey /* key */) {}, [&](KeyboardKey /* 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;
} };
camera = &scene.camera;
auto start_time = std::chrono::high_resolution_clock::now();
auto last_time = start_time;
for (;;) {
auto cur_time = std::chrono::high_resolution_clock::now();
float ellapsed_time = std::chrono::duration<float, std::chrono::seconds::period>(cur_time - last_time).count();
last_time = cur_time;
float time = std::chrono::duration<float, std::chrono::seconds::period>(cur_time - start_time).count();
if (!poll_events(kb, mouse))
break;
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 += Quaternion::rot_y(ry).rot(movement) * movement_speed * ellapsed_time;
scene.camera.transform.rot = Quaternion::euler_zxy(rx, ry, 0.f);
scene.camera.fov = (kb.is_down(KeyboardKey::zoom) ? 40.f : 80.f) * PI / 180.f;
auto [surface_width, surface_height] = update_surface_size();
// TODO: we no longer use Camera.to_mat4(...), I don't know if we should remove it or not.
// It multiplies projection and view matrices, but right now we do the multiplication in the
// fragment shader. The thing is, having the camera decide which projection mode to chose is
// better, because it allows us to change projection settings just by changing the camera
auto proj_mat = final_transform_mat
* Matrix4::perspective(scene.camera.fov, static_cast<float>(surface_width) / static_cast<float>(surface_height), .5f, 12.f);
render_and_present_frame(scene.camera.transform.to_inverse_mat4(), proj_mat, scene.camera.transform.to_mat4(), time, ellapsed_time);
}
}
// TODO: find better name
template<typename FrameBuffer, typename PollEventsFn, typename UpdateRendererSizeFn, typename PresentFrameFn>
static void render_software(Renderer<FrameBuffer>& renderer, const Matrix4& final_transform_mat, Scene& scene,
PollEventsFn poll_events, UpdateRendererSizeFn update_renderer_size, PresentFrameFn present_frame) {
scene_main(final_transform_mat, scene,
// update_surface_size
[&] {
update_renderer_size();
return std::tuple { renderer.width(), renderer.height() };
},
poll_events,
// render_and_present_frame
[&](const Matrix4& /* view_mat */, const Matrix4& /* proj_mat */, const Matrix4& /* inv_view_mat */, float /* time */, float /* ellapsed_time */) {
// TODO: remove
renderer.clear();
// auto proj_view_mat = proj_mat * view_mat;
// renderer.clear();
// for (const auto& obj : scene.objs) {
// auto model_mat = obj.transform.to_mat4();
// auto final_mat = proj_view_mat * model_mat;
// const auto& mesh = obj.mesh;
// std::vector<Vector4> vertices;
// std::vector<Vector3> normals;
// std::vector<VertexData> vertices_data;
// for (const auto& vertex : mesh.vertices) {
// Vector4 vertex4 { vertex, 1.f };
// vertices.push_back(final_mat * vertex4);
// vertices_data.push_back(VertexData((model_mat * vertex4).xyz()));
// }
// for (const auto& normal : mesh.normals)
// normals.push_back((model_mat * Vector4 { normal, 0.f }).xyz());
// for (const auto& triangle_indices : mesh.indices) {
// [&]<std::size_t... j>(std::index_sequence<j...>) {
// renderer.draw_triangle(
// {{vertices[triangle_indices[j][0]], normals[triangle_indices[j][1]], vertices_data[triangle_indices[j][0]]}...}
// );
// }(std::make_index_sequence<3>());
// }
// }
present_frame();
}
);
}
#ifdef HAVE_NCURSES
#define MKEY_ESC 27
static int main_term(Scene& scene) {
// init
std::setlocale(LC_ALL, "");
initscr();
cbreak();
noecho();
intrflush(stdscr, FALSE);
keypad(stdscr, TRUE);
set_escdelay(0);
curs_set(0);
auto renderer = [&] {
int w, h;
getmaxyx(stdscr, h, w);
return Renderer { CharacterFrameBuffer { static_cast<unsigned int>(w), static_cast<unsigned int>(h) } };
}();
render_software(renderer, Matrix4::scale(Vector3(2.f, 1.f, 1.f)), scene,
// poll_events
[&](auto& kb, auto& mouse) {
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);
return cont;
},
// update_renderer_size
[&] {
int w, h;
getmaxyx(stdscr, h, w);
renderer.resize(static_cast<unsigned int>(w), static_cast<unsigned int>(h));
},
// present_frame
[&] {
mvaddnstr(0, 0, renderer.fb.chars(), renderer.width() * renderer.height());
}
);
// terminate
endwin();
return EXIT_SUCCESS;
}
#endif
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
static const std::vector<const char*> validation_layers = {
"VK_LAYER_KHRONOS_validation",
};
static const std::vector<const char*> physical_device_ext_names = {
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
constexpr bool enable_validation_layers = false;
#else
constexpr bool enable_validation_layers = true;
#endif
constexpr size_t max_frames_in_flight = 2;
constexpr bool show_fps = false;
constexpr bool transparent_window = false;
struct PhysicalDeviceEntry {
uint32_t idx;
VkPhysicalDevice physical_device;
uint32_t graphics_queue_family_index, present_queue_family_index;
VkPhysicalDeviceProperties2 props;
VkPhysicalDeviceFeatures2 features;
VkFormat depth_format;
};
enum class GraphicalRendererMode {
hardware,
software,
};
static bool check_validation_layer_support() {
auto avail_layers = [&] {
uint32_t avail_layers_count;
if (VkResult res = vkEnumerateInstanceLayerProperties(&avail_layers_count, nullptr); res != VK_SUCCESS) {
std::cerr << "failed to enumerate instance layer properties, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
std::vector<VkLayerProperties> avail_layers(avail_layers_count);
if (VkResult res = vkEnumerateInstanceLayerProperties(&avail_layers_count, avail_layers.data()); res != VK_SUCCESS) {
std::cerr << "failed to enumerate instance layer properties, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return avail_layers;
}();
for (const char* layer_name : validation_layers) {
if (std::ranges::find_if(avail_layers, [&](const auto& props) { return strcmp(layer_name, props.layerName) == 0; })
== avail_layers.end())
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();
}
}
static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(
VkDebugUtilsMessageSeverityFlagBitsEXT message_severity,
VkDebugUtilsMessageTypeFlagsEXT /* message_type */,
const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
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;
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 std::optional<VkFormat> find_format(VkPhysicalDevice physical_device, const std::vector<VkFormat>& formats,
VkImageTiling tiling, VkFormatFeatureFlags flags) {
for (const auto& format : formats) {
VkFormatProperties2 format_props {};
format_props.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2;
format_props.pNext = nullptr;
vkGetPhysicalDeviceFormatProperties2(physical_device, format, &format_props);
switch (tiling) {
case VK_IMAGE_TILING_OPTIMAL:
if ((format_props.formatProperties.optimalTilingFeatures & flags) == flags)
return format;
break;
case VK_IMAGE_TILING_LINEAR:
if ((format_props.formatProperties.linearTilingFeatures & flags) == flags)
return format;
break;
default:
std::cerr << "tiling not supported: " << string_VkImageTiling(tiling) << std::endl;
exit(EXIT_FAILURE);
}
}
return {};
}
static bool has_stencil(VkFormat format) {
switch (format) {
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
return true;
default:
return false;
}
}
static uint32_t find_mem_type(VkPhysicalDevice physical_device, uint32_t type_filter, VkMemoryPropertyFlags flags) {
VkPhysicalDeviceMemoryProperties2 props {};
props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2;
vkGetPhysicalDeviceMemoryProperties2(physical_device, &props);
for (uint32_t i = 0; i < props.memoryProperties.memoryTypeCount; i++)
if (type_filter & (1 << i) && (props.memoryProperties.memoryTypes[i].propertyFlags & flags) == flags)
return i;
// not found
// TODO: improve by being explicit about what are requirements
std::cerr << "cannot find memory type matching requirements" << std::endl;
exit(EXIT_FAILURE);
}
static std::tuple<VkBuffer, VkDeviceMemory>
create_buf(VkPhysicalDevice physical_device, VkDevice device, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags mem_flags) {
auto buf = [&] {
VkBufferCreateInfo buf_ci {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = {},
.size = size,
.usage = usage,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = {},
.pQueueFamilyIndices = {},
};
VkBuffer buf;
if (VkResult res = vkCreateBuffer(device, &buf_ci, nullptr, &buf); res != VK_SUCCESS) {
std::cerr << "failed to create buffer, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return buf;
}();
VkMemoryRequirements buf_mem_requirements;
vkGetBufferMemoryRequirements(device, buf, &buf_mem_requirements);
auto buf_device_mem = [&] {
VkMemoryAllocateInfo buf_mem_ai {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = nullptr,
.allocationSize = buf_mem_requirements.size,
.memoryTypeIndex = find_mem_type(physical_device, buf_mem_requirements.memoryTypeBits, mem_flags),
};
VkDeviceMemory buf_device_mem;
if (VkResult res = vkAllocateMemory(device, &buf_mem_ai, nullptr, &buf_device_mem); res != VK_SUCCESS) {
std::cerr << "failed to allocate buffer memory, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return buf_device_mem;
}();
if (VkResult res = vkBindBufferMemory(device, buf, buf_device_mem, 0); res != VK_SUCCESS) {
std::cerr << "failed to bind buffer memory, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return { buf, buf_device_mem };
}
static VkCommandBuffer begin_single_time_cmds(VkDevice device, VkCommandPool 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;
exit(EXIT_FAILURE);
}
return cmd_buf;
}();
{
VkCommandBufferBeginInfo cmd_buf_bi {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = nullptr,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
.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;
exit(EXIT_FAILURE);
}
}
return cmd_buf;
}
static void end_single_time_cmds(VkQueue queue, VkDevice device, VkCommandPool cmd_pool, VkCommandBuffer cmd_buf) {
if (VkResult res = vkEndCommandBuffer(cmd_buf); res != VK_SUCCESS) {
std::cerr << "failed to end command buffer, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
{
VkSubmitInfo submit_info {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = nullptr,
.waitSemaphoreCount = {},
.pWaitSemaphores = {},
.pWaitDstStageMask = {},
.commandBufferCount = 1,
.pCommandBuffers = &cmd_buf,
.signalSemaphoreCount = {},
.pSignalSemaphores = {},
};
// TODO: should probably submit every command buffers in a single function call, instead of
// submitting and waiting for them to finish separatly
if (VkResult res = vkQueueSubmit(queue, 1, &submit_info, nullptr); res != VK_SUCCESS) {
std::cerr << "failed to submit command buffer to queue, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
if (VkResult res = vkQueueWaitIdle(queue); res != VK_SUCCESS) {
std::cerr << "failed to wait idle for graphics queue, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
vkFreeCommandBuffers(device, cmd_pool, 1, &cmd_buf);
}
static void copy_buf_to_buf(VkCommandBuffer cmd_buf, VkBuffer src, VkBuffer dst, VkDeviceSize size) {
VkBufferCopy buf_copy {
.srcOffset = 0,
.dstOffset = 0,
.size = size,
};
vkCmdCopyBuffer(cmd_buf, src, dst, 1, &buf_copy);
}
static void copy_buf_to_img(VkCommandBuffer cmd_buf, VkBuffer src, VkImage dst, uint32_t width, uint32_t height) {
VkBufferImageCopy buf_img_copy {
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = { // VkImageSubresourceLayers
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = { .x = 0, .y = 0, .z = 0 },
.imageExtent = { .width = width, .height = height, .depth = 1 },
};
vkCmdCopyBufferToImage(cmd_buf, src, dst, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buf_img_copy);
}
static std::tuple<VkImage, VkDeviceMemory>
create_img(VkPhysicalDevice physical_device, VkDevice device, uint32_t width, uint32_t height, VkFormat format,
VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags mem_flags) {
auto texture_img = [&] {
VkImageCreateInfo img_ci {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = nullptr,
.flags = {},
.imageType = VK_IMAGE_TYPE_2D,
// TODO: check if this format is supported
.format = format,
.extent = { .width = width, .height = height, .depth = 1 },
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = tiling,
.usage = usage,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = {},
.pQueueFamilyIndices = {},
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
VkImage texture_img;
if (VkResult res = vkCreateImage(device, &img_ci, nullptr, &texture_img); res != VK_SUCCESS) {
std::cerr << "failed to create image, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return texture_img;
}();
auto texture_img_device_mem = [&] {
VkMemoryRequirements mem_requirements;
vkGetImageMemoryRequirements(device, texture_img, &mem_requirements);
VkMemoryAllocateInfo mem_ai {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = nullptr,
.allocationSize = mem_requirements.size,
.memoryTypeIndex = find_mem_type(physical_device, mem_requirements.memoryTypeBits, mem_flags),
};
VkDeviceMemory texture_img_device_mem;
if (VkResult res = vkAllocateMemory(device, &mem_ai, nullptr, &texture_img_device_mem); res != VK_SUCCESS) {
std::cerr << "failed to allocate texture image memory, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return texture_img_device_mem;
}();
if (VkResult res = vkBindImageMemory(device, texture_img, texture_img_device_mem, 0); res != VK_SUCCESS) {
std::cerr << "failed to bind texture image to memory, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return std::tuple { texture_img, texture_img_device_mem };
}
static std::tuple<VkImage, VkDeviceMemory, VkImageView>
create_depth_resources(VkPhysicalDevice physical_device, VkDevice device, VkExtent2D swapchain_extent, VkFormat depth_format) {
auto [depth_img, depth_img_device_mem] = create_img(physical_device, device, swapchain_extent.width, swapchain_extent.height, depth_format,
VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
auto depth_img_view = [&] {
VkImageViewCreateInfo img_view_ci {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = {},
.flags = {},
.image = depth_img,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = depth_format,
.components = {},
.subresourceRange = { // VkImageSubresourceRange
.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
VkImageView depth_img_view;
if (VkResult res = vkCreateImageView(device, &img_view_ci, nullptr, &depth_img_view); res != VK_SUCCESS) {
std::cerr << "failed to create depth image view, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return depth_img_view;
}();
return std::tuple { depth_img, depth_img_device_mem, depth_img_view };
}
static void destroy_depth_resources(VkDevice device, VkImage depth_img, VkDeviceMemory depth_img_device_mem, VkImageView depth_img_view) {
vkDestroyImageView(device, depth_img_view, nullptr);
vkFreeMemory(device, depth_img_device_mem, nullptr);
vkDestroyImage(device, depth_img, nullptr);
}
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(Scene& scene) {
// init window
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
if (transparent_window) {
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, GLFW_TRUE);
}
bool fb_resized = false;
GLFWwindow* window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Engine", nullptr, nullptr);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// TODO: might have to improve, because if in the future we need more values in a glfw callback,
// this approch wouldn't work
glfwSetWindowUserPointer(window, &fb_resized);
glfwSetFramebufferSizeCallback(window, [](GLFWwindow* window, int /* width */, int /* height */) {
*reinterpret_cast<bool*>(glfwGetWindowUserPointer(window)) = true;
});
// TODO: improve this. This is an ugly workaround for vulkan, see comment in o3d/mesh.hpp in
// linearize_indices() declaration
std::vector<std::vector<engine::vk::Vertex>> meshes_vertices;
std::vector<std::vector<uint16_t>> meshes_indices;
for (const auto& obj : scene.objs) {
const auto [vertices, indices] = obj.mesh.linearize_indices();
meshes_vertices.push_back(std::move(vertices));
meshes_indices.push_back(std::move(indices));
}
// init Vulkan
std::cout << "Vulkan loader version: " << engine::vk::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;
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,
};
auto instance_exts = [&] {
std::vector<const char*> instance_exts;
{
uint32_t glfw_extension_count;
const char** glfw_extensions = glfwGetRequiredInstanceExtensions(&glfw_extension_count);
instance_exts.insert(instance_exts.end(), glfw_extensions, glfw_extensions + glfw_extension_count);
}
if (enable_validation_layers)
instance_exts.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
return instance_exts;
}();
auto avail_instance_exts = [&] {
uint32_t avail_instance_exts_count;
if (VkResult res = vkEnumerateInstanceExtensionProperties(nullptr, &avail_instance_exts_count, nullptr); res != VK_SUCCESS) {
std::cerr << "failed to enumerate instance extension properties, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
std::vector<VkExtensionProperties> avail_instance_exts(avail_instance_exts_count);
if (VkResult res = vkEnumerateInstanceExtensionProperties(nullptr, &avail_instance_exts_count, avail_instance_exts.data()); res != VK_SUCCESS) {
std::cerr << "failed to enumerate instance extension properties, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return avail_instance_exts;
}();
std::cout << "required instance extensions:\n";
for (const auto& extension_name : instance_exts) {
std::cout << (std::ranges::find_if(avail_instance_exts, [&](const auto& avail_ext) {
return strcmp(avail_ext.extensionName, extension_name) == 0;
}) == avail_instance_exts.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>(instance_exts.size()),
.ppEnabledExtensionNames = instance_exts.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;
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;
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;
exit(EXIT_FAILURE);
}
return surface;
}();
// select physical device and queues
auto [physical_device, graphics_queue_family_index, present_queue_family_index, physical_device_props, physical_device_features, depth_format] = [&] {
std::multimap<unsigned, PhysicalDeviceEntry> physical_devices;
auto avail_physical_devices = [&] {
uint32_t avail_physical_devices_count;
if (VkResult res = vkEnumeratePhysicalDevices(instance, &avail_physical_devices_count, nullptr); res != VK_SUCCESS) {
std::cerr << "failed to enumerate physical devices, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
std::vector<VkPhysicalDevice> avail_physical_devices(avail_physical_devices_count);
if (VkResult res = vkEnumeratePhysicalDevices(instance, &avail_physical_devices_count, avail_physical_devices.data()); res != VK_SUCCESS) {
std::cerr << "failed to enumerate physical devices, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return avail_physical_devices;
}();
if (avail_physical_devices.empty()) {
std::cerr << "failed to find physical devices with Vulkan support" << std::endl;
exit(EXIT_FAILURE);
}
std::cout << "devices:" << std::endl;
for (uint32_t i = 0; i < avail_physical_devices.size(); i++) {
const auto& avail_physical_device = avail_physical_devices[i];
auto physical_device_props = [&] {
VkPhysicalDeviceProperties2 physical_device_props{};
physical_device_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
vkGetPhysicalDeviceProperties2(avail_physical_device, &physical_device_props);
return physical_device_props;
}();
std::cout << " " << (i + 1) << ". " << physical_device_props.properties.deviceName << ":" << std::endl;
std::cout << " apiVersion: " << engine::vk::api { physical_device_props.properties.apiVersion } << std::endl;
auto physical_device_features = [&] {
VkPhysicalDeviceFeatures2 physical_device_features{};
physical_device_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
vkGetPhysicalDeviceFeatures2(avail_physical_device, &physical_device_features);
return physical_device_features;
}();
auto physical_device_ext_props = [&] {
uint32_t physical_device_ext_props_count;
if (VkResult res = vkEnumerateDeviceExtensionProperties(avail_physical_device, nullptr,
&physical_device_ext_props_count, nullptr); res != VK_SUCCESS) {
std::cerr << "failed to enumerate physical device extension properties, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
std::vector<VkExtensionProperties> physical_device_ext_props(physical_device_ext_props_count);
if (VkResult res = vkEnumerateDeviceExtensionProperties(avail_physical_device, nullptr,
&physical_device_ext_props_count, physical_device_ext_props.data()); res != VK_SUCCESS) {
std::cerr << "failed to enumerate physical device extension properties, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return physical_device_ext_props;
}();
std::cout << " required physical device extensions:" << std::endl;
for (const auto& ext : physical_device_ext_names) {
std::cout << " " << (std::ranges::find_if(physical_device_ext_props, [&](const auto& avail_ext) {
return strcmp(avail_ext.extensionName, ext) == 0;
}) == physical_device_ext_props.end() ? "!" : " ");
std::cout << " " << ext << std::endl;
}
auto queue_family_properties = [&] {
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());
return queue_family_properties;
}();
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;
auto depth_format = find_format(avail_physical_device,
{ VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT },
VK_IMAGE_TILING_OPTIMAL, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
std::cout << " depth format: ";
if (depth_format)
std::cout << string_VkFormat(*depth_format);
else
std::cout << "none";
std::cout << std::endl;
auto score = [&] {
if (VK_API_VERSION_VARIANT(physical_device_props.properties.apiVersion) != 0
|| physical_device_props.properties.apiVersion < VK_API_VERSION_1_4)
return std::optional<unsigned> {};
if (!graphics_queue_family_index || !present_queue_family_index)
return std::optional<unsigned> {};
if (std::ranges::find_if_not(physical_device_ext_names, [&](const auto& device_ext) {
return std::ranges::find_if(physical_device_ext_props,
[&](const auto& ext_prop) { return strcmp(ext_prop.extensionName, device_ext) == 0; })
!= physical_device_ext_props.end();
}) != physical_device_ext_names.end())
return std::optional<unsigned> {};
if (!physical_device_features.features.samplerAnisotropy)
return std::optional<unsigned> {};
if (!depth_format)
return std::optional<unsigned> {};
// TODO: lots of checks are probably missing, like checking if the swapchain is
// supported (I'm not sure if it's needed)
unsigned score = 0;
if (*graphics_queue_family_index == *present_queue_family_index)
score += 5;
score += [&](VkPhysicalDeviceType device_type) {
switch (device_type) {
case VK_PHYSICAL_DEVICE_TYPE_OTHER: return 0;
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return 2;
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return 10;
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return 5;
case VK_PHYSICAL_DEVICE_TYPE_CPU: return 1;
default:
{
std::cerr << "device type not supported: " << string_VkPhysicalDeviceType(device_type) << std::endl;
exit(EXIT_FAILURE);
}
}
}(physical_device_props.properties.deviceType);
return std::optional<unsigned> { score };
}();
std::cout << " score: ";
if (score)
std::cout << *score;
else
std::cout << "not suitable";
std::cout << std::endl;
if (score)
physical_devices.insert({ *score,
{
.idx = i,
.physical_device = avail_physical_device,
.graphics_queue_family_index = *graphics_queue_family_index,
.present_queue_family_index = *present_queue_family_index,
.props = physical_device_props,
.features = physical_device_features,
.depth_format = *depth_format,
}
});
}
std::cout << std::endl;
if (physical_devices.empty()) {
std::cerr << "no suitable physical device found" << std::endl;
exit(EXIT_FAILURE);
}
auto best = physical_devices.crbegin();
std::cout << "picking: " << (best->second.idx + 1) << ". " << best->second.props.properties.deviceName << " (score: " << best->first << ")" << std::endl;
return std::tuple { best->second.physical_device, best->second.graphics_queue_family_index,
best->second.present_queue_family_index, best->second.props, best->second.features, best->second.depth_format };
}();
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 = {},
};
// TODO: name is confusing. We can't call it physical_device_features because the name is
// already taken by features queried while selecting the physical device. But calling it
// device_features makes a bit of sense, because theses are features requested for (logical)
// device creation
VkPhysicalDeviceFeatures2 device_features {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,
.pNext = &device_vk13_features,
.features = {}, // default to VK_FALSE for everything
};
device_features.features.samplerAnisotropy = VK_TRUE;
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>(physical_device_ext_names.size()),
.ppEnabledExtensionNames = physical_device_ext_names.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;
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: when we recreate the swapchain, I don't know if the number of images in it can change
// between the old and new swapchain. Right now we assume that it doesn't, which might cause
// problem (but I'm not sure)
// TODO: pass the old swapchain to VkSwapchainCreateInfoKHR so the new swapchain can be created
// while the old one is in-flight
// TODO: with the same intention of recreating the swapchain in-flight, we should also do
// something about the depth image. If we recreate the swapchain in-flight without worrying
// about the depth image, we might destroy it while it's being used. But I'm not sure, we have
// to test it
VkExtent2D swapchain_extent;
VkSurfaceFormatKHR surface_format;
VkSwapchainKHR swapchain = nullptr;
std::vector<VkImage> swapchain_imgs;
std::vector<VkImageView> swapchain_img_views;
VkImage depth_img;
VkDeviceMemory depth_img_device_mem;
VkImageView depth_img_view;
const auto destroy_swapchain = [&] {
for (auto it_img_view = swapchain_img_views.rbegin(); it_img_view != swapchain_img_views.rend(); ++it_img_view)
vkDestroyImageView(device, *it_img_view, nullptr);
vkDestroySwapchainKHR(device, swapchain, nullptr);
};
const auto recreate_swapchain = [&] {
bool is_first_swapchain = (swapchain == nullptr);
if (!is_first_swapchain) {
if (VkResult res = vkDeviceWaitIdle(device); res != VK_SUCCESS) {
std::cerr << "failed to wait idle for device, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
destroy_depth_resources(device, depth_img, depth_img_device_mem, depth_img_view);
destroy_swapchain();
}
// 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;
exit(EXIT_FAILURE);
}
return surface_capabilities;
}();
{
// VK_IMAGE_USAGE_TRANSFER_DST_BIT is for the software renderer
VkImageUsageFlags required_surface_usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
if ((surface_capabilities.supportedUsageFlags & required_surface_usage) != required_surface_usage) {
std::cerr << "required surface usage flags not present" << std::endl;
exit(EXIT_FAILURE);
}
}
{
VkCompositeAlphaFlagsKHR required_composite_alpha =
(transparent_window ? VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR : VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR);
if ((surface_capabilities.supportedCompositeAlpha & required_composite_alpha) != required_composite_alpha) {
std::cerr << "required composite alpha flags not present" << std::endl;
exit(EXIT_FAILURE);
}
}
swapchain_extent = [&] {
if (surface_capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max())
return surface_capabilities.currentExtent;
int width, height;
glfwGetFramebufferSize(window, &width, &height);
// TODO: improve minimization handling. I'm on wayland so it's impossible to know if a
// window is minimized, therefore I can't really test it properly right now
while (width == 0 || height == 0) {
glfwGetFramebufferSize(window, &width, &height);
glfwWaitEvents();
}
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),
};
}();
surface_format = [&] {
auto surface_formats = [&] {
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;
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;
exit(EXIT_FAILURE);
}
return surface_formats;
}();
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;
exit(EXIT_FAILURE);
}();
[&] {
auto present_mode = [&] {
auto present_modes = [&] {
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;
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;
exit(EXIT_FAILURE);
}
return present_modes;
}();
for (const auto& present_mode : present_modes)
if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR)
return present_mode;
return VK_PRESENT_MODE_FIFO_KHR;
}();
// 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,
// VK_IMAGE_USAGE_TRANSFER_DST_BIT is for the software renderer
.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
.imageSharingMode = {},
.queueFamilyIndexCount = {},
.pQueueFamilyIndices = {},
.preTransform = surface_capabilities.currentTransform,
.compositeAlpha = (transparent_window ? VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR : 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 {
// TODO: should use VK_SHARING_MODE_EXCLUSIVE too, and handle queue family ownership
// while transitionning swapchain image layout
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();
}
if (VkResult res = vkCreateSwapchainKHR(device, &swapchain_ci, nullptr, &swapchain); res != VK_SUCCESS) {
std::cerr << "failed create swapchain, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}();
[&] {
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;
exit(EXIT_FAILURE);
}
swapchain_imgs.resize(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;
exit(EXIT_FAILURE);
}
}();
[&] {
swapchain_img_views.resize(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;
exit(EXIT_FAILURE);
}
}
}();
if (!is_first_swapchain)
std::tie(depth_img, depth_img_device_mem, depth_img_view) = create_depth_resources(physical_device, device, swapchain_extent, depth_format);
};
recreate_swapchain();
auto renderer_mode = GraphicalRendererMode::hardware;
// create descriptor set layout
auto descriptor_set_layout = [&] {
std::array descriptor_set_layout_bindings {
VkDescriptorSetLayoutBinding {
.binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
.pImmutableSamplers = {},
},
VkDescriptorSetLayoutBinding {
.binding = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
.pImmutableSamplers = {},
},
};
VkDescriptorSetLayoutCreateInfo descriptor_set_layout_ci {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.pNext = nullptr,
.flags = {},
.bindingCount = descriptor_set_layout_bindings.size(),
.pBindings = descriptor_set_layout_bindings.data(),
};
VkDescriptorSetLayout descriptor_set_layout;
if (VkResult res = vkCreateDescriptorSetLayout(device, &descriptor_set_layout_ci, nullptr, &descriptor_set_layout); res != VK_SUCCESS) {
std::cerr << "failed to create descriptor set layout, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return descriptor_set_layout;
}();
// create pipeline
auto [pl_layout, graphics_pl] = [&] {
// reading shader file
auto shader_module = [&] {
auto 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
exit(EXIT_SUCCESS);
}
// shader code has to be 32-bits aligned, which is the case with the default allocator
std::vector<char> shader_code(shader_file.tellg());
shader_file.seekg(0, std::ios::beg);
shader_file.read(shader_code.data(), static_cast<std::streamsize>(shader_code.size()));
return shader_code;
}();
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;
exit(EXIT_FAILURE);
}
return shader_module;
}();
auto [pl_layout, graphics_pl] = [&] {
std::array pl_shader_stage_cis {
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(),
};
const auto vertex_binding_desc = engine::vk::Vertex::get_binding_desc();
const auto vertex_attr_descs = engine::vk::Vertex::get_attr_descs();
VkPipelineVertexInputStateCreateInfo pl_vert_in_state_ci {
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.pNext = nullptr,
.flags = {},
.vertexBindingDescriptionCount = 1,
.pVertexBindingDescriptions = &vertex_binding_desc,
.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertex_attr_descs.size()),
.pVertexAttributeDescriptions = vertex_attr_descs.data(),
};
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_COUNTER_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,
};
VkPipelineDepthStencilStateCreateInfo pl_depth_stencil_state_ci {
.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
.pNext = nullptr,
.flags = {},
.depthTestEnable = VK_TRUE,
.depthWriteEnable = VK_TRUE,
.depthCompareOp = VK_COMPARE_OP_LESS,
.depthBoundsTestEnable = VK_FALSE,
.stencilTestEnable = VK_FALSE,
.front = {},
.back = {},
.minDepthBounds = {},
.maxDepthBounds = {},
};
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 = 1,
.pSetLayouts = &descriptor_set_layout,
.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;
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 = depth_format,
.stencilAttachmentFormat = {},
};
VkGraphicsPipelineCreateInfo graphics_pl_ci {
.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
.pNext = &pl_render_ci,
.flags = {},
.stageCount = static_cast<uint32_t>(pl_shader_stage_cis.size()),
.pStages = pl_shader_stage_cis.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 = &pl_depth_stencil_state_ci,
.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;
exit(EXIT_FAILURE);
}
return std::tuple { pl_layout, graphics_pl };
}();
vkDestroyShaderModule(device, shader_module, nullptr);
return std::tuple { pl_layout, graphics_pl };
}();
// create command pool
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;
exit(EXIT_FAILURE);
}
return cmd_pool;
}();
// create depth resources
// TODO: check why we only need one image. From the looks of it, we need max_frames_in_flight
// depth images, because there is at most max_frames_in_flight rendering at the same time
std::tie(depth_img, depth_img_device_mem, depth_img_view) = create_depth_resources(physical_device, device, swapchain_extent, depth_format);
// create texture image
auto [texture_img, texture_img_device_mem] = [&] {
int w, h, channels;
stbi_uc* pixels = stbi_load(DATADIR "/assets/textures/viking_room.png", &w, &h, &channels, STBI_rgb_alpha);
// TODO: we're also using this size as the host pixels buffer size, I don't know if mixing
// the two will cause problems later. Right now they are the same, so it doesn't
VkDeviceSize img_size = w * h * 4;
if (!pixels) {
std::cerr << "failed to load texture image, reason: " << stbi_failure_reason() << std::endl;
exit(EXIT_FAILURE);
}
auto [staging_buf, staging_buf_device_mem] = create_buf(physical_device, device, img_size,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
{
void* staging_buf_mem;
if (VkResult res = vkMapMemory(device, staging_buf_device_mem, 0, img_size, 0, &staging_buf_mem); res != VK_SUCCESS) {
std::cerr << "failed to map staging buffer memory, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
memcpy(staging_buf_mem, pixels, img_size);
vkUnmapMemory(device, staging_buf_device_mem);
}
stbi_image_free(pixels);
auto [texture_img, texture_img_device_mem] = create_img(physical_device, device, static_cast<uint32_t>(w), static_cast<uint32_t>(h), VK_FORMAT_R8G8B8A8_SRGB,
VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
{
auto cmd_buf = begin_single_time_cmds(device, cmd_pool);
transition_image_layout(cmd_buf, texture_img,
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
{}, VK_ACCESS_2_TRANSFER_WRITE_BIT,
VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_2_TRANSFER_BIT);
copy_buf_to_img(cmd_buf, staging_buf, texture_img, static_cast<uint32_t>(w), static_cast<uint32_t>(h));
transition_image_layout(cmd_buf, texture_img,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_ACCESS_2_SHADER_READ_BIT,
VK_PIPELINE_STAGE_2_TRANSFER_BIT, VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT);
end_single_time_cmds(graphics_queue, device, cmd_pool, cmd_buf);
}
vkFreeMemory(device, staging_buf_device_mem, nullptr);
vkDestroyBuffer(device, staging_buf, nullptr);
return std::tuple { texture_img, texture_img_device_mem };
}();
// create texture image view
// TODO: this is the same code, with minor differences, than the one that create swapchain image
// views, so maybe we should create a function. The thing is, this code only call a single
// function with a single create-info, so I'm not sure if it would make sense
auto texture_img_view = [&] {
VkImageViewCreateInfo img_view_ci {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = {},
.flags = {},
.image = texture_img,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = VK_FORMAT_R8G8B8A8_SRGB,
.components = {},
.subresourceRange = { // VkImageSubresourceRange
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
VkImageView texture_img_view;
if (VkResult res = vkCreateImageView(device, &img_view_ci, nullptr, &texture_img_view); res != VK_SUCCESS) {
std::cerr << "failed to create texture image view, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return texture_img_view;
}();
// create texture sampler
auto sampler = [&] {
VkSamplerCreateInfo sampler_ci {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.pNext = nullptr,
.flags = {},
.magFilter = VK_FILTER_LINEAR,
.minFilter = VK_FILTER_LINEAR,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.mipLodBias = 0.f,
.anisotropyEnable = VK_TRUE,
.maxAnisotropy = physical_device_props.properties.limits.maxSamplerAnisotropy,
.compareEnable = VK_FALSE,
// TODO: check if it has to be VK_COMPARE_OP_ALWAYS instead of VK_COMPARE_OP_NEVER
.compareOp = VK_COMPARE_OP_NEVER,
.minLod = 0.f,
.maxLod = 0.f,
.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK,
.unnormalizedCoordinates = VK_FALSE,
};
VkSampler sampler;
if (VkResult res = vkCreateSampler(device, &sampler_ci, nullptr, &sampler); res != VK_SUCCESS) {
std::cerr << "failed to create sampler, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return sampler;
}();
// create vertex buffers
auto [vertex_bufs, vertex_buf_device_mems] = [&] {
std::vector<VkBuffer> vertex_bufs;
std::vector<VkDeviceMemory> vertex_buf_device_mems;
for (const auto& vertices : meshes_vertices) {
VkDeviceSize vertex_buf_size = sizeof(engine::vk::Vertex) * vertices.size();
auto [staging_buf, staging_buf_device_mem] = create_buf(physical_device, device, vertex_buf_size,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
{
void* staging_buf_mem;
if (VkResult res = vkMapMemory(device, staging_buf_device_mem, 0, vertex_buf_size, 0, &staging_buf_mem); res != VK_SUCCESS) {
std::cerr << "failed to map staging buffer memory, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
memcpy(staging_buf_mem, vertices.data(), static_cast<size_t>(vertex_buf_size));
vkUnmapMemory(device, staging_buf_device_mem);
}
auto [vertex_buf, vertex_buf_device_mem] = create_buf(physical_device, device, vertex_buf_size,
VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
// TODO: consider using different command pool for short-lived command buffers, with the flag
// VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, for optimization. For now we will stick to the one
// which does the rendering
// TODO: don't wait individually for every copy operations, use a fence or something similar
// TODO: should use a single command buffer instead of one for each copy
{
auto cmd_buf = begin_single_time_cmds(device, cmd_pool);
copy_buf_to_buf(cmd_buf, staging_buf, vertex_buf, vertex_buf_size);
end_single_time_cmds(graphics_queue, device, cmd_pool, cmd_buf);
}
vkFreeMemory(device, staging_buf_device_mem, nullptr);
vkDestroyBuffer(device, staging_buf, nullptr);
vertex_bufs.push_back(vertex_buf);
vertex_buf_device_mems.push_back(vertex_buf_device_mem);
}
return std::tuple { vertex_bufs, vertex_buf_device_mems };
}();
// create index buffers
// TODO: this code is pretty much a duplicate with minor differences of the vertex_bufs one. We
// should probably factor it out in a function. Also, every TODOs were remove for this one, but
// they still hold
auto [index_bufs, index_buf_device_mems] = [&] {
std::vector<VkBuffer> index_bufs;
std::vector<VkDeviceMemory> index_buf_device_mems;
for (const auto& indices : meshes_indices) {
VkDeviceSize index_buf_size = sizeof(uint16_t) * indices.size();
auto [staging_buf, staging_buf_device_mem] = create_buf(physical_device, device, index_buf_size,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
{
void* staging_buf_mem;
if (VkResult res = vkMapMemory(device, staging_buf_device_mem, 0, index_buf_size, 0, &staging_buf_mem); res != VK_SUCCESS) {
std::cerr << "failed to map staging buffer memory, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
memcpy(staging_buf_mem, indices.data(), static_cast<size_t>(index_buf_size));
vkUnmapMemory(device, staging_buf_device_mem);
}
auto [index_buf, index_buf_device_mem] = create_buf(physical_device, device, index_buf_size,
VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
{
auto cmd_buf = begin_single_time_cmds(device, cmd_pool);
copy_buf_to_buf(cmd_buf, staging_buf, index_buf, index_buf_size);
end_single_time_cmds(graphics_queue, device, cmd_pool, cmd_buf);
}
vkFreeMemory(device, staging_buf_device_mem, nullptr);
vkDestroyBuffer(device, staging_buf, nullptr);
index_bufs.push_back(index_buf);
index_buf_device_mems.push_back(index_buf_device_mem);
}
return std::tuple { index_bufs, index_buf_device_mems };
}();
// create uniform buffers
auto [uniform_bufs, uniform_buf_device_mems, uniform_buf_mems] = [&] {
constexpr VkDeviceSize uniform_buf_size = sizeof(engine::vk::UniformBufferObject);
std::vector<VkBuffer> uniform_bufs(max_frames_in_flight * scene.objs.size(), nullptr);
std::vector<VkDeviceMemory> uniform_buf_device_mems(max_frames_in_flight * scene.objs.size(), nullptr);
std::vector<void*> uniform_buf_mems(max_frames_in_flight * scene.objs.size(), nullptr);
for (size_t i = 0; i < max_frames_in_flight * scene.objs.size(); i++) {
std::tie(uniform_bufs[i], uniform_buf_device_mems[i]) = create_buf(physical_device, device, uniform_buf_size,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
if (VkResult res = vkMapMemory(device, uniform_buf_device_mems[i], 0, uniform_buf_size, 0, &uniform_buf_mems[i]); res != VK_SUCCESS) {
std::cerr << "failed to map uniform buffer #" << i << " memory, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
return std::tuple { uniform_bufs, uniform_buf_device_mems, uniform_buf_mems };
}();
// create descriptor pool
auto descriptor_pool = [&] {
std::array descriptor_pool_sizes {
VkDescriptorPoolSize {
.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = static_cast<uint32_t>(max_frames_in_flight * scene.objs.size()),
},
VkDescriptorPoolSize {
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = static_cast<uint32_t>(max_frames_in_flight * scene.objs.size()),
},
};
VkDescriptorPoolCreateInfo descriptor_pool_ci {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.pNext = nullptr,
// TODO: right now we do not touch descriptor sets after they've been created, so
// setting VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT is useless
.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
.maxSets = static_cast<uint32_t>(max_frames_in_flight * scene.objs.size()),
.poolSizeCount = descriptor_pool_sizes.size(),
.pPoolSizes = descriptor_pool_sizes.data(),
};
VkDescriptorPool descriptor_pool;
if (VkResult res = vkCreateDescriptorPool(device, &descriptor_pool_ci, nullptr, &descriptor_pool); res != VK_SUCCESS) {
std::cerr << "failed to create descriptor pool, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return descriptor_pool;
}();
// create descriptor sets
// TODO: right now, we just send every descriptors every frame and for every object, without
// taking into account update frequencies. For example we should have only one set for the
// camera, shared between every objects, etc
auto descriptor_sets = [&] {
std::vector<VkDescriptorSetLayout> layouts(max_frames_in_flight * scene.objs.size(), descriptor_set_layout);
VkDescriptorSetAllocateInfo descriptor_set_ai {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.pNext = nullptr,
.descriptorPool = descriptor_pool,
.descriptorSetCount = static_cast<uint32_t>(layouts.size()),
.pSetLayouts = layouts.data(),
};
std::vector<VkDescriptorSet> descriptor_sets(max_frames_in_flight * scene.objs.size());
if (VkResult res = vkAllocateDescriptorSets(device, &descriptor_set_ai, descriptor_sets.data()); res != VK_SUCCESS) {
std::cerr << "failed to allocate descriptor sets, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
std::vector<VkDescriptorBufferInfo> descriptor_buffer_infos(max_frames_in_flight * scene.objs.size());
std::vector<VkDescriptorImageInfo> descriptor_image_infos(max_frames_in_flight * scene.objs.size());
std::vector<VkWriteDescriptorSet> write_descriptor_sets;
for (size_t i = 0; i < max_frames_in_flight * scene.objs.size(); i++) {
// uniform buffer object
descriptor_buffer_infos[i] = { // VkDescriptorBufferInfo
.buffer = uniform_bufs[i],
.offset = 0,
.range = sizeof(engine::vk::UniformBufferObject),
};
write_descriptor_sets.push_back({ // VkWriteDescriptorSet
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.pNext = nullptr,
.dstSet = descriptor_sets[i],
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.pImageInfo = {},
.pBufferInfo = &descriptor_buffer_infos[i],
.pTexelBufferView = {},
});
// combined image sampler
descriptor_image_infos[i] = { // VkDescriptorImageInfo
.sampler = sampler,
.imageView = texture_img_view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
write_descriptor_sets.push_back({ // VkWriteDescriptorSet
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.pNext = nullptr,
.dstSet = descriptor_sets[i],
.dstBinding = 1,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &descriptor_image_infos[i],
.pBufferInfo = {},
.pTexelBufferView = {},
});
}
// TODO: maybe we should call this function for each descriptor sets, which I would find
// weird by the fact that it takes an array as an argument, but IDK
vkUpdateDescriptorSets(device, static_cast<uint32_t>(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr);
return descriptor_sets;
}();
// create command buffers
auto cmd_bufs = [&] {
VkCommandBufferAllocateInfo cmd_buf_ai {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.pNext = nullptr,
.commandPool = cmd_pool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = max_frames_in_flight,
};
std::array<VkCommandBuffer, max_frames_in_flight> cmd_bufs;
if (VkResult res = vkAllocateCommandBuffers(device, &cmd_buf_ai, cmd_bufs.data()); res != VK_SUCCESS) {
std::cerr << "failed to allocate command buffers, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
return cmd_bufs;
}();
// create sync objects
auto [sems_present_complete, sems_render_finished] = [&] {
// TODO: remove duplicate code
auto sems_present_complete = [&] {
std::array<VkSemaphore, max_frames_in_flight> sems_present_complete;
size_t num = 0;
for (auto& sem : sems_present_complete) {
VkSemaphoreCreateInfo sem_ci {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
.pNext = nullptr,
.flags = {},
};
if (VkResult res = vkCreateSemaphore(device, &sem_ci, nullptr, &sem); res != VK_SUCCESS) {
std::cerr << "failed to create present complete semaphore #" << (++num) << ", error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
return sems_present_complete;
}();
auto sems_render_finished = [&] {
std::vector<VkSemaphore> sems_render_finished(swapchain_imgs.size());
size_t num = 0;
for (auto& sem : sems_render_finished) {
VkSemaphoreCreateInfo sem_ci {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
.pNext = nullptr,
.flags = {},
};
if (VkResult res = vkCreateSemaphore(device, &sem_ci, nullptr, &sem); res != VK_SUCCESS) {
std::cerr << "failed to create render finished semaphore #" << (++num) << ", error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
return sems_render_finished;
}();
return std::tuple {
sems_present_complete,
sems_render_finished,
};
}();
std::cout << "sems_present_complete: [ ";
for (auto it_sem = sems_present_complete.begin(); it_sem != sems_present_complete.end(); ++it_sem) {
if (it_sem != sems_present_complete.begin())
std::cout << ", ";
std::cout << *it_sem;
}
std::cout << " ]" << std::endl;
std::cout << "sems_render_finished: [ ";
for (auto it_sem = sems_render_finished.begin(); it_sem != sems_render_finished.end(); ++it_sem) {
if (it_sem != sems_render_finished.begin())
std::cout << ", ";
std::cout << *it_sem;
}
std::cout << " ]" << std::endl;
auto fences_in_flight = [&] {
std::array<VkFence, max_frames_in_flight> fences_in_flight;
size_t num = 0;
for (auto& fence_in_flight : fences_in_flight) {
VkFenceCreateInfo fence_in_flight_ci {
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
.pNext = nullptr,
.flags = VK_FENCE_CREATE_SIGNALED_BIT,
};
if (VkResult res = vkCreateFence(device, &fence_in_flight_ci, nullptr, &fence_in_flight); res != VK_SUCCESS) {
std::cerr << "failed to create draw fence #" << (++num) << ", error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
return fences_in_flight;
}();
std::cout << "fences_in_flight: [ ";
for (auto it_fence = fences_in_flight.begin(); it_fence != fences_in_flight.end(); ++it_fence) {
if (it_fence != fences_in_flight.begin())
std::cout << ", ";
std::cout << *it_fence;
}
std::cout << " ]" << std::endl;
// init software renderer
// TODO: resize buffer when surface extent change
Renderer<PixelFrameBuffer> software_renderer { PixelFrameBuffer {
static_cast<unsigned int>(swapchain_extent.width),
static_cast<unsigned int>(swapchain_extent.height),
} };
bool first_software_renderer_buf_creation = true;
std::array<VkBuffer, max_frames_in_flight> software_renderer_bufs;
std::array<VkDeviceMemory, max_frames_in_flight> software_renderer_buf_device_mems;
std::array<void*, max_frames_in_flight> software_renderer_buf_mems;
auto destroy_software_renderer_bufs = [&] {
for (size_t i = max_frames_in_flight; i > 0; i--) {
vkUnmapMemory(device, software_renderer_buf_device_mems[i - 1]);
vkFreeMemory(device, software_renderer_buf_device_mems[i - 1], nullptr);
vkDestroyBuffer(device, software_renderer_bufs[i - 1], nullptr);
}
};
auto recreate_software_renderer_bufs = [&] {
if (!first_software_renderer_buf_creation) {
destroy_software_renderer_bufs();
if (software_renderer.width() != swapchain_extent.width || software_renderer.height() != swapchain_extent.height)
software_renderer.resize(swapchain_extent.width, swapchain_extent.height);
} else {
first_software_renderer_buf_creation = false;
}
const VkDeviceSize software_renderer_buf_size = swapchain_extent.width * swapchain_extent.height * 4;
for (size_t i = 0; i < max_frames_in_flight; i++) {
std::tie(software_renderer_bufs[i], software_renderer_buf_device_mems[i]) = create_buf(physical_device, device, software_renderer_buf_size,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
if (VkResult res = vkMapMemory(device, software_renderer_buf_device_mems[i], 0, software_renderer_buf_size,
0, &software_renderer_buf_mems[i]); res != VK_SUCCESS) {
std::cerr << "failed to create software renderer's buffer #" << i << ", error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
return std::tuple { software_renderer_bufs, software_renderer_buf_device_mems, software_renderer_buf_mems };
};
recreate_software_renderer_bufs();
uint32_t frame_idx = 0;
double mouse_x, mouse_y;
glfwGetCursorPos(window, &mouse_x, &mouse_y);
scene_main(Matrix4::idty(), scene,
// update_surface_size
[&] {
return std::tuple { swapchain_extent.width, swapchain_extent.height };
},
// poll_events
[&](auto& kb, auto& mouse) {
if (glfwWindowShouldClose(window))
return false;
glfwPollEvents();
// TODO: improve
switch (glfwGetKey(window, GLFW_KEY_W)) {
case GLFW_PRESS:
kb.key_down_event(KeyboardKey::fw);
break;
case GLFW_RELEASE:
kb.key_up_event(KeyboardKey::fw);
break;
}
switch (glfwGetKey(window, GLFW_KEY_A)) {
case GLFW_PRESS:
kb.key_down_event(KeyboardKey::key_left);
break;
case GLFW_RELEASE:
kb.key_up_event(KeyboardKey::key_left);
break;
}
switch (glfwGetKey(window, GLFW_KEY_S)) {
case GLFW_PRESS:
kb.key_down_event(KeyboardKey::bw);
break;
case GLFW_RELEASE:
kb.key_up_event(KeyboardKey::bw);
break;
}
switch (glfwGetKey(window, GLFW_KEY_D)) {
case GLFW_PRESS:
kb.key_down_event(KeyboardKey::key_right);
break;
case GLFW_RELEASE:
kb.key_up_event(KeyboardKey::key_right);
break;
}
switch (glfwGetKey(window, GLFW_KEY_ESCAPE)) {
case GLFW_PRESS:
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
}
// TODO: very ugly, improve
static bool last_frame_toggle_renderer_mode = false;
switch (glfwGetKey(window, GLFW_KEY_O)) {
case GLFW_PRESS:
{
if (!last_frame_toggle_renderer_mode) {
last_frame_toggle_renderer_mode = true;
switch (renderer_mode) {
case GraphicalRendererMode::hardware:
{
renderer_mode = GraphicalRendererMode::software;
}
break;
case GraphicalRendererMode::software:
{
renderer_mode = GraphicalRendererMode::hardware;
}
break;
}
}
}
break;
default:
{
last_frame_toggle_renderer_mode = false;
}
}
double new_mouse_x, new_mouse_y;
glfwGetCursorPos(window, &new_mouse_x, &new_mouse_y);
if (new_mouse_x != mouse_x || new_mouse_y != mouse_y) {
// TODO: find a better name
float mouse_fac = 5.f / static_cast<float>(swapchain_extent.height);
mouse.mouse_motion_event({
mouse_fac * static_cast<float>(new_mouse_x - mouse_x),
mouse_fac * static_cast<float>(new_mouse_y - mouse_y),
});
mouse_x = new_mouse_x;
mouse_y = new_mouse_y;
}
return true;
},
// render_and_present_frame
[&](const Matrix4& view_mat, const Matrix4& proj_mat, const Matrix4& inv_view_mat, float /* time */, float ellapsed_time) {
if (show_fps)
std::cout << "\rfps: " << (1.f / ellapsed_time) << " ";
if (VkResult res = vkWaitForFences(device, 1, &fences_in_flight[frame_idx], 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;
exit(EXIT_FAILURE);
}
uint32_t img_idx;
{
VkResult res = vkAcquireNextImageKHR(device, swapchain,
std::numeric_limits<uint64_t>::max(), sems_present_complete[frame_idx], nullptr, &img_idx);
switch (res) {
case VK_SUBOPTIMAL_KHR:
case VK_SUCCESS:
break;
case VK_ERROR_OUT_OF_DATE_KHR:
recreate_swapchain();
recreate_software_renderer_bufs();
return;
default:
std::cerr << "failed to acquire next image, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
switch (renderer_mode) {
case GraphicalRendererMode::hardware:
{
// update uniform buffers
for (size_t i = 0; i < scene.objs.size(); i++) {
// TODO: should use push constants
engine::vk::UniformBufferObject ubo {
.model = scene.objs[i].transform.to_mat4(),
.view = view_mat,
.proj = proj_mat,
.inv_view = inv_view_mat,
};
memcpy(uniform_buf_mems[frame_idx * scene.objs.size() + i], &ubo, sizeof(engine::vk::UniformBufferObject));
}
}
break;
case GraphicalRendererMode::software:
break;
}
switch (renderer_mode) {
case GraphicalRendererMode::hardware:
break;
case GraphicalRendererMode::software:
{
auto proj_view_mat = proj_mat * view_mat;
software_renderer.clear();
for (const auto& obj : scene.objs) {
auto model_mat = obj.transform.to_mat4();
auto final_mat = proj_view_mat * model_mat;
const auto& mesh = obj.mesh;
std::vector<Vector4> vertices;
std::vector<Vector3> normals;
std::vector<VertexData> vertices_data;
for (const auto& vertex : mesh.vertices) {
Vector4 vertex4 { vertex, 1.f };
vertices.push_back(final_mat * vertex4);
vertices_data.push_back(VertexData((model_mat * vertex4).xyz()));
}
for (const auto& normal : mesh.normals)
normals.push_back((model_mat * Vector4 { normal, 0.f }).xyz());
for (const auto& triangle_indices : mesh.indices) {
software_renderer.draw_triangle([&]<size_t... j>(std::index_sequence<j...>) constexpr -> engine::o3d::Triangle {
return {
{
vertices[triangle_indices[j][0]],
normals [triangle_indices[j][1]],
mesh.uvs[triangle_indices[j][2]],
vertices_data[triangle_indices[j][0]]
}
...
};
}(std::make_index_sequence<3>()));
}
}
memcpy(software_renderer_buf_mems[frame_idx], software_renderer.fb.pixels(), swapchain_extent.width * swapchain_extent.height * 4);
}
break;
}
// implicit command buffer reset
// record command buffer
{
VkCommandBufferBeginInfo cmd_buf_bi {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = nullptr,
// TODO: I don't understand why here we shouldn't also set
// VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, because we always submit this
// command buffer once before resetting it, like when we copy the staging buffer to
// the vertex buffer (where we set this flag). The only difference is that we wait
// for the queue to idle for the latter, where here we only fence for the end of
// vkQueueSubmit
.flags = {},
.pInheritanceInfo = {},
};
if (VkResult res = vkBeginCommandBuffer(cmd_bufs[frame_idx], &cmd_buf_bi); res != VK_SUCCESS) {
std::cerr << "failed to begin command buffer, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
// transition layouts
switch (renderer_mode) {
case GraphicalRendererMode::hardware:
{
{
std::array img_mem_barriers {
VkImageMemoryBarrier2 {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
.srcAccessMask = {},
.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_imgs[img_idx],
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
VkImageMemoryBarrier2 {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT,
.srcAccessMask = VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT,
.dstAccessMask = VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout =
(has_stencil(depth_format) ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL),
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = depth_img,
.subresourceRange = {
.aspectMask =
static_cast<VkImageAspectFlags>(VK_IMAGE_ASPECT_DEPTH_BIT | (has_stencil(depth_format) ? VK_IMAGE_ASPECT_STENCIL_BIT : 0)),
.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 = img_mem_barriers.size(),
.pImageMemoryBarriers = img_mem_barriers.data(),
};
vkCmdPipelineBarrier2(cmd_bufs[frame_idx], &dependency_info);
}
{
VkClearValue clear_color_val { .color { .float32 = { 0.f, 0.f, 0.f, (transparent_window ? 0.f : 1.f) } } };
VkClearValue clear_depth_val { .depthStencil { .depth = 1.f, .stencil = 0 } };
VkRenderingAttachmentInfo rendering_color_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_color_val,
};
VkRenderingAttachmentInfo rendering_depth_info {
.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
.pNext = nullptr,
.imageView = depth_img_view,
.imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
.resolveMode = {},
.resolveImageView = {},
.resolveImageLayout = {},
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.clearValue = clear_depth_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 = &rendering_color_info,
.pDepthAttachment = &rendering_depth_info,
.pStencilAttachment = {},
};
vkCmdBeginRendering(cmd_bufs[frame_idx], &render_info);
}
vkCmdBindPipeline(cmd_bufs[frame_idx], 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_bufs[frame_idx], 0, 1, &viewport);
}
{
VkRect2D scissor {
.offset = { 0, 0 },
.extent = swapchain_extent,
};
vkCmdSetScissor(cmd_bufs[frame_idx], 0, 1, &scissor);
}
// TODO: not sure if we can just loop through every objects without worrying about it
for (size_t i = 0; i < scene.objs.size(); i++) {
const auto& vertex_buf = vertex_bufs[i];
const auto& index_buf = index_bufs[i];
const auto& indices = meshes_indices[i];
VkDeviceSize vertex_buf_offset = 0;
vkCmdBindVertexBuffers(cmd_bufs[frame_idx], 0, 1, &vertex_buf, &vertex_buf_offset);
vkCmdBindIndexBuffer(cmd_bufs[frame_idx], index_buf, 0, VK_INDEX_TYPE_UINT16);
vkCmdBindDescriptorSets(cmd_bufs[frame_idx], VK_PIPELINE_BIND_POINT_GRAPHICS, pl_layout, 0, 1,
&descriptor_sets[frame_idx * scene.objs.size() + i], 0, nullptr);
vkCmdDrawIndexed(cmd_bufs[frame_idx], static_cast<uint32_t>(indices.size()), 1, 0, 0, 0);
}
vkCmdEndRendering(cmd_bufs[frame_idx]);
transition_image_layout(cmd_bufs[frame_idx], 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);
}
break;
case GraphicalRendererMode::software:
{
{
VkImageMemoryBarrier2 img_mem_barrier {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
.srcAccessMask = {},
.dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = swapchain_imgs[img_idx],
.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_bufs[frame_idx], &dependency_info);
}
copy_buf_to_img(cmd_bufs[frame_idx], software_renderer_bufs[frame_idx], swapchain_imgs[img_idx], swapchain_extent.width, swapchain_extent.height);
{
VkImageMemoryBarrier2 img_mem_barrier {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT,
.dstAccessMask = {},
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = swapchain_imgs[img_idx],
.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_bufs[frame_idx], &dependency_info);
}
}
break;
}
if (VkResult res = vkEndCommandBuffer(cmd_bufs[frame_idx]); res != VK_SUCCESS) {
std::cerr << "failed to end command buffer, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
if (VkResult res = vkResetFences(device, 1, &fences_in_flight[frame_idx]); res != VK_SUCCESS) {
std::cerr << "failed to reset draw fence, error code: " << string_VkResult(res) << std::endl;
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 = &sems_present_complete[frame_idx],
.pWaitDstStageMask = &pl_stage_flags,
.commandBufferCount = 1,
.pCommandBuffers = &cmd_bufs[frame_idx],
.signalSemaphoreCount = 1,
.pSignalSemaphores = &sems_render_finished[img_idx],
};
if (VkResult res = vkQueueSubmit(graphics_queue, 1, &submit_info, fences_in_flight[frame_idx]); res != VK_SUCCESS) {
std::cerr << "failed to submit command buffer queue, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
{
VkPresentInfoKHR present_info {
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
.pNext = nullptr,
.waitSemaphoreCount = 1,
.pWaitSemaphores = &sems_render_finished[img_idx],
.swapchainCount = 1,
.pSwapchains = &swapchain,
.pImageIndices = &img_idx,
.pResults = nullptr,
};
VkResult res = vkQueuePresentKHR(present_queue, &present_info);
if (res == VK_SUBOPTIMAL_KHR || res == VK_ERROR_OUT_OF_DATE_KHR || fb_resized) {
fb_resized = false;
recreate_swapchain();
recreate_software_renderer_bufs();
} else if (res != VK_SUCCESS) {
std::cerr << "failed to present, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
}
frame_idx = (frame_idx + 1) % max_frames_in_flight;
}
);
if (show_fps)
std::cout << std::endl;
if (VkResult res = vkDeviceWaitIdle(device); res != VK_SUCCESS) {
std::cerr << "failed to wait idle for device, error code: " << string_VkResult(res) << std::endl;
exit(EXIT_FAILURE);
}
// cleanup
destroy_software_renderer_bufs();
for (auto it_fence = fences_in_flight.rbegin(); it_fence != fences_in_flight.rend(); ++it_fence)
vkDestroyFence(device, *it_fence, nullptr);
for (auto it_sem = sems_render_finished.rbegin(); it_sem != sems_render_finished.rend(); ++it_sem)
vkDestroySemaphore(device, *it_sem, nullptr);
for (auto it_sem = sems_present_complete.rbegin(); it_sem != sems_present_complete.rend(); ++it_sem)
vkDestroySemaphore(device, *it_sem, nullptr);
vkDestroyDescriptorPool(device, descriptor_pool, nullptr);
for (size_t i = max_frames_in_flight * scene.objs.size(); i > 0; i--) {
vkUnmapMemory(device, uniform_buf_device_mems[i - 1]);
vkFreeMemory(device, uniform_buf_device_mems[i - 1], nullptr);
vkDestroyBuffer(device, uniform_bufs[i - 1], nullptr);
}
for (size_t i = scene.objs.size(); i > 0; i--) {
vkFreeMemory(device, index_buf_device_mems[i - 1], nullptr);
vkDestroyBuffer(device, index_bufs[i - 1], nullptr);
}
for (size_t i = scene.objs.size(); i > 0; i--) {
vkFreeMemory(device, vertex_buf_device_mems[i - 1], nullptr);
vkDestroyBuffer(device, vertex_bufs[i - 1], nullptr);
}
vkDestroySampler(device, sampler, nullptr);
vkDestroyImageView(device, texture_img_view, nullptr);
vkFreeMemory(device, texture_img_device_mem, nullptr);
vkDestroyImage(device, texture_img, nullptr);
destroy_depth_resources(device, depth_img, depth_img_device_mem, depth_img_view);
// no need to free cmd_buf because destroying the command pool will
vkDestroyCommandPool(device, cmd_pool, nullptr);
// no need to free descriptor_sets because destroying the descriptor pool will
vkDestroyDescriptorSetLayout(device, descriptor_set_layout, nullptr);
vkDestroyPipelineLayout(device, pl_layout, nullptr);
vkDestroyPipeline(device, graphics_pl, nullptr);
destroy_swapchain();
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;
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, Mode& 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[]) {
Mode mode = Mode::graphical;
parse_args(convert_args(argc, argv), mode);
Scene scene {
{ 90.f * PI / 180.f, { { 0.f, 1.8f, 7.f }, Quaternion::one(), { 1.f, 1.f, 1.f } } },
[&] constexpr -> std::vector<Object3D> {
switch (game_type) {
case GameType::plane:
return {
{
Mesh::plane(2.f, 2.f),
{
Vector3(0.f, 0.f, 0.f),
Quaternion::one(),
Vector3(1.f, 1.f, 1.f),
}
},
};
case GameType::suzanne:
return {
{
engine::parse_object(DATADIR "/assets/suzanne.obj"),
{
Vector3(0.f, 0.f, 0.f),
Quaternion::one(),
Vector3(1.f, 1.f, 1.f),
}
},
};
case GameType::plane_and_suzanne:
return {
{
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),
}
},
};
case GameType::test:
return {
{
engine::parse_object(DATADIR "/assets/viking_room.obj"),
{
Vector3(0.f, .5f, 0.f),
Quaternion::look_towards({ -1.f, 0.f, 0.f }, { 0.f, 0.f, 1.f }).conjugate(),
Vector3(1.f, 1.f, 1.f),
}
},
};
}
std::unreachable();
}()
};
switch (mode) {
case Mode::help:
print_usage(std::cout);
return EXIT_SUCCESS;
case Mode::term:
#ifdef HAVE_NCURSES
return main_term(scene);
#else
std::cerr << "Error: ncurses was not enabled during compilation." << std::endl;
return EXIT_FAILURE;
#endif
case Mode::graphical:
return main_graphical(scene);
default:
std::unreachable();
}
}
|