-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvkutils.h
More file actions
1468 lines (1282 loc) · 53.8 KB
/
vkutils.h
File metadata and controls
1468 lines (1282 loc) · 53.8 KB
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
#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
#ifndef VKUTILS_H
#define VKUTILS_H
// This is just to put the verbose vulkan stuff in its own place
#include "readback_frame.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <fstream>
#include <ios>
#include <spdlog/spdlog.h>
#include <stdexcept>
#include <string>
#include <sys/types.h>
#include <vector>
#include <volk.h>
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <array>
#include <glm/glm.hpp>
#include <spdlog/fmt/fmt.h>
#define VK_CHECK(x) \
do { \
VkResult err = x; \
if (err) { \
spdlog::error("Vulkan error: {} (0x{:x})", \
static_cast<int>(err), \
static_cast<uint32_t>(err)); \
throw std::logic_error("Got a runtime_error"); \
} \
} while (0);
inline constexpr size_t MAX_FRAME_SLOTS = 10;
namespace vkutils {
struct PushConstants {
float iTime;
uint32_t iFrame;
glm::vec2 iResolution;
glm::vec2 iMouse;
};
/* Helper structs so that we can pass around swapchain images
* or image views on the stack without having to go to the heap
* unnesicarily. I want to sometimes avoid vector
*/
struct SwapchainImages {
std::array<VkImage, MAX_FRAME_SLOTS> images{};
uint32_t count = 0;
};
struct SwapchainImageViews {
std::array<VkImageView, MAX_FRAME_SLOTS> imageViews{};
uint32_t count = 0;
};
struct CommandBuffers {
std::array<VkCommandBuffer, MAX_FRAME_SLOTS> commandBuffers{};
uint32_t count = 0;
};
struct Fences {
std::array<VkFence, MAX_FRAME_SLOTS> fences{};
uint32_t count = 0;
};
struct Semaphores {
std::array<VkSemaphore, MAX_FRAME_SLOTS> semaphores{};
uint32_t count = 0;
};
struct FrameBuffers {
std::array<VkFramebuffer, MAX_FRAME_SLOTS> framebuffers{};
uint32_t count = 0;
};
/*
* Used to readback a buffer from GPU -> CPU.
* eg. to dump a frame as part of testing
* or to encode frames in CPU with ffmpeg
*/
struct ReadbackBuffer {
VkBuffer buffer = VK_NULL_HANDLE;
VkDeviceMemory memory = VK_NULL_HANDLE;
VkDeviceSize size = 0;
};
struct ReadbackFormatInfo {
uint32_t bytesPerPixel = 0;
bool swapRB = false;
};
[[nodiscard]] static std::vector<uint32_t>
loadSpvFile(const std::string &filename) {
std::ifstream file(filename, std::ios::ate | std::ios::binary);
if (!file.is_open())
throw std::runtime_error("Failed to open file: " + filename);
std::streamoff fileSize = file.tellg();
if (fileSize % static_cast<std::streamoff>(sizeof(uint32_t)) != 0)
throw std::runtime_error("SPIR-V file size is not a multiple of 4: " +
filename);
std::size_t byteSize = static_cast<std::size_t>(fileSize);
std::vector<uint32_t> buffer(byteSize / sizeof(uint32_t));
file.seekg(0);
file.read(reinterpret_cast<char *>(buffer.data()),
static_cast<std::streamsize>(byteSize));
if (file.gcount() != static_cast<std::streamsize>(byteSize))
throw std::runtime_error("Failed to read the complete file: " +
filename);
return buffer;
};
[[nodiscard]] inline ReadbackFormatInfo getReadbackFormatInfo(VkFormat format) {
switch (format) {
case VK_FORMAT_B8G8R8A8_UNORM:
case VK_FORMAT_B8G8R8A8_SRGB:
return {4, true};
default:
throw std::runtime_error(
"Unsupported format for readback; expected BGRA8");
}
}
/**
* Initializes volk meta-loader to find Vulkan dynamically.
* Must be called once before creating VkInstance.
* Throws runtime_error if Vulkan loader not found.
*/
static void initVolk() {
VkResult result = volkInitialize();
if (result != VK_SUCCESS) {
spdlog::error("Failed to initialize volk: Vulkan loader not found");
spdlog::error("Please install Vulkan runtime:");
spdlog::error(" macOS: brew install molten-vk");
spdlog::error(" Linux: apt install libvulkan1");
throw std::runtime_error("Failed to initialize Vulkan loader (volk)");
}
spdlog::debug("volk initialized successfully");
}
[[nodiscard]] static VkInstance setupVulkanInstance(bool offline = false) {
// Initialize volk first (only runs once, thread-safe via static guard)
initVolk();
const VkApplicationInfo appInfo = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pNext = nullptr,
.pApplicationName = "Emerald",
.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
.pEngineName = "Emerald Engine",
.engineVersion = VK_MAKE_VERSION(1, 0, 0),
.apiVersion = VK_API_VERSION_1_2,
};
spdlog::info("Size of push constants {}", sizeof(PushConstants));
std::vector<const char *> extensions;
if (!offline) {
// Offline renders on GPU to an offscreen image for readback (future
// ffmpeg encoding), so it has no GLFW surface and doesn't need
// GLFW-provided instance extensions.
uint32_t extensionCount = 0;
const char **glfwExtensions =
glfwGetRequiredInstanceExtensions(&extensionCount);
extensions.assign(glfwExtensions, glfwExtensions + extensionCount);
}
#ifdef __APPLE__
extensions.push_back("VK_KHR_portability_enumeration");
#endif
spdlog::debug("Using the following extensions: ");
for (const auto &extension : extensions) {
spdlog::debug("- {}", extension);
}
spdlog::debug("Creating vk instance...");
// Query available validation layers
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
spdlog::debug("Available validation layers:");
for (const auto &layer : availableLayers) {
spdlog::debug("- {}", layer.layerName);
}
const std::vector<const char *> desiredLayers = {
"VK_LAYER_KHRONOS_validation",
};
std::vector<const char *> enabledLayers;
for (const char *layerName : desiredLayers) {
bool layerFound = false;
for (const auto &layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (layerFound) {
enabledLayers.push_back(layerName);
} else {
spdlog::warn("Validation layer not found: {}", layerName);
}
}
spdlog::debug("Enabling validation layers:");
for (const auto &layer : enabledLayers) {
spdlog::debug("- {}", layer);
}
VkInstanceCreateInfo createInfo = {
.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
.pNext = nullptr,
#ifdef __APPLE__
.flags = VkInstanceCreateFlagBits::
VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR,
#else
.flags = 0,
#endif
.pApplicationInfo = &appInfo,
.enabledLayerCount = static_cast<uint32_t>(enabledLayers.size()),
.ppEnabledLayerNames = enabledLayers.data(),
.enabledExtensionCount = static_cast<uint32_t>(extensions.size()),
.ppEnabledExtensionNames = extensions.data(),
};
VkInstance instance;
VK_CHECK(vkCreateInstance(&createInfo, nullptr, &instance));
// Load instance-specific Vulkan functions
volkLoadInstance(instance);
return instance;
}
[[nodiscard]] static VkPhysicalDeviceProperties
getDeviceProperties(VkPhysicalDevice physicalDevice) {
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
return deviceProperties;
}
[[nodiscard]] static VkPhysicalDevice findGPU(VkInstance instance) {
uint32_t deviceCount = 0;
spdlog::debug("Enumerating devices...");
VK_CHECK(vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr));
if (deviceCount == 0) {
spdlog::error("No devices found!");
throw std::runtime_error("No devices found!");
}
spdlog::info("Found {} devices", deviceCount);
std::vector<VkPhysicalDevice> devices(deviceCount);
VK_CHECK(
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data()));
for (uint32_t i = 0; i < deviceCount; i++) {
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(devices[i], &deviceProperties);
spdlog::debug("Device {} has Vulkan version {}", i,
deviceProperties.apiVersion);
spdlog::debug("Device {} has driver version {}", i,
deviceProperties.driverVersion);
spdlog::debug("Device {} has vendor ID {}", i,
deviceProperties.vendorID);
spdlog::debug("Device {} has device ID {}", i,
deviceProperties.deviceID);
spdlog::debug("Device {} has device type {}", i,
static_cast<uint32_t>(deviceProperties.deviceType));
spdlog::debug("Device {} has device name {}", i,
deviceProperties.deviceName);
// Example of selecting a discrete GPU
if (deviceProperties.deviceType ==
VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
spdlog::info("Selecting discrete GPU: {}",
deviceProperties.deviceName);
return devices[i];
}
}
// If no discrete GPU is found, fallback to the first device
spdlog::debug("No discrete GPU found. Fallback to the first device.");
return devices[0];
}
[[nodiscard]] static VkSurfaceKHR createVulkanSurface(VkInstance instance,
GLFWwindow *window) {
spdlog::debug("Creating Vulkan surface...");
VkSurfaceKHR surface;
VkResult result =
glfwCreateWindowSurface(instance, window, nullptr, &surface);
if (result != VK_SUCCESS) {
spdlog::error("Failed to create Vulkan surface");
spdlog::error("Result: 0x{:x}", static_cast<int>(result));
vkDestroyInstance(instance, nullptr);
glfwTerminate();
throw std::runtime_error("Failed to create Vulkan surface");
}
spdlog::debug("Created vulkan surface");
return surface;
}
[[nodiscard]] static uint32_t
getVulkanGraphicsQueueIndexImpl(VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface, bool requirePresent) {
uint32_t queueFamilyCount;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount,
nullptr);
if (queueFamilyCount == 0)
throw std::runtime_error("No queue families found");
spdlog::debug("Found {} queue families", queueFamilyCount);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount,
queueFamilies.data());
// Print debug info for all queue families
for (uint32_t i = 0; i < queueFamilyCount; i++) {
spdlog::debug("Queue family {} has {} queues", i,
queueFamilies[i].queueCount);
spdlog::debug("Queue family {} supports graphics: {} ", i,
queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT);
spdlog::debug("Queue family {} supports compute: {} ", i,
queueFamilies[i].queueFlags & VK_QUEUE_COMPUTE_BIT);
spdlog::debug("Queue family {} supports transfer: {} ", i,
queueFamilies[i].queueFlags & VK_QUEUE_TRANSFER_BIT);
spdlog::debug("Queue family {} supports sparse binding: {} ", i,
queueFamilies[i].queueFlags &
VK_QUEUE_SPARSE_BINDING_BIT);
spdlog::debug("Queue family {} supports protected: {} ", i,
queueFamilies[i].queueFlags & VK_QUEUE_PROTECTED_BIT);
if (requirePresent) {
VkBool32 supportsPresent;
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface,
&supportsPresent);
spdlog::debug("Queue family {} supports present: {} ", i,
supportsPresent);
if (queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT &&
supportsPresent)
return i;
} else if (queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
return i;
}
}
throw std::runtime_error("Failed to find graphics queue");
}
[[nodiscard]] static uint32_t
getVulkanGraphicsQueueIndex(VkPhysicalDevice physicalDevice) {
// For when present is not needed eg. for offline rendering of SDF
// to encode with FFMPEG
return getVulkanGraphicsQueueIndexImpl(physicalDevice, VK_NULL_HANDLE,
false);
}
[[nodiscard]] static uint32_t
getVulkanGraphicsQueueIndex(VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface) {
return getVulkanGraphicsQueueIndexImpl(physicalDevice, surface, true);
}
[[nodiscard]] static VkDevice
createVulkanLogicalDevice(VkPhysicalDevice physicalDevice,
uint32_t graphicsQueueIndex, bool offline = false) {
float queuePriority = 1.0f;
spdlog::debug("Create a queue...");
VkDeviceQueueCreateInfo queueInfo = {
.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
.queueFamilyIndex = graphicsQueueIndex,
.queueCount = 1,
.pQueuePriorities = &queuePriority,
};
std::vector<const char *> requiredExtensions;
if (!offline) {
requiredExtensions.push_back("VK_KHR_swapchain");
}
#ifdef __APPLE__
requiredExtensions.push_back("VK_KHR_portability_subset");
#endif
spdlog::debug("Create a logical device...");
VkDevice device;
VkPhysicalDeviceDynamicRenderingFeaturesKHR dynamicRenderingFeatures{
.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR,
.dynamicRendering = VK_TRUE,
};
VkDeviceCreateInfo deviceCreateInfo = {
.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
.pNext = &dynamicRenderingFeatures,
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &queueInfo,
.enabledExtensionCount =
static_cast<uint32_t>(requiredExtensions.size()),
.ppEnabledExtensionNames =
requiredExtensions.empty() ? nullptr : requiredExtensions.data(),
};
VK_CHECK(
vkCreateDevice(physicalDevice, &deviceCreateInfo, nullptr, &device));
// Load device-specific Vulkan functions
volkLoadDevice(device);
spdlog::debug("Created logical device (offline = {})", offline);
return device;
}
[[nodiscard]] static VkSurfaceCapabilitiesKHR
getSurfaceCapabilities(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface) {
// Surface Capabilities
spdlog::debug("Get surface capabilities");
VkSurfaceCapabilitiesKHR surfaceCapabilities;
VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface,
&surfaceCapabilities));
return surfaceCapabilities;
}
[[nodiscard]] consteval auto getPreferredFormats() {
return std::to_array({
VK_FORMAT_B8G8R8A8_SRGB,
VK_FORMAT_B8G8R8A8_UNORM,
});
}
[[nodiscard]] static VkSurfaceFormatKHR
selectSwapchainFormat(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface) {
// Get surface formats
uint32_t surfaceFormatCount;
VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(
physicalDevice, surface, &surfaceFormatCount, nullptr));
spdlog::debug("Surface format count: {}", surfaceFormatCount);
if (surfaceFormatCount == 0) {
throw std::runtime_error("Failed to find any surface formats.");
}
// NOTE: Would like to move to array but not sure of a good max
std::vector<VkSurfaceFormatKHR> surfaceFormats(surfaceFormatCount);
VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(
physicalDevice, surface, &surfaceFormatCount, surfaceFormats.data()));
// Handle the special case where the surface format is undefined.
if (surfaceFormatCount == 1 &&
surfaceFormats[0].format == VK_FORMAT_UNDEFINED) {
spdlog::info("Surface format is undefined, selecting "
"VK_FORMAT_B8G8R8A8_SRGB as default.");
return {VK_FORMAT_B8G8R8A8_SRGB, surfaceFormats[0].colorSpace};
}
static constexpr auto preferredFormatArray = getPreferredFormats();
for (const auto &candidate : surfaceFormats) {
if (std::find(preferredFormatArray.begin(), preferredFormatArray.end(),
candidate.format) != preferredFormatArray.end()) {
return candidate;
}
}
// Fallback: if no preferred formats are found, use first available format.
spdlog::debug(
"No preferred format found, using the first available format.");
return surfaceFormats[0];
}
[[nodiscard]] static VkExtent2D
getSwapchainSize(GLFWwindow *window,
const VkSurfaceCapabilitiesKHR &surfaceCapabilities) {
VkExtent2D swapchainSize;
if (surfaceCapabilities.currentExtent.width == 0xFFFFFFFF) {
int width, height;
glfwGetFramebufferSize(window, &width, &height);
swapchainSize = {static_cast<uint32_t>(width),
static_cast<uint32_t>(height)};
} else {
swapchainSize = surfaceCapabilities.currentExtent;
}
spdlog::debug("Swapchain size: {}x{}", swapchainSize.width,
swapchainSize.height);
return swapchainSize;
}
struct SwapchainConfig {
VkSurfaceKHR surface = VK_NULL_HANDLE;
VkSurfaceCapabilitiesKHR surfaceCapabilities{};
VkExtent2D extent{};
VkSurfaceFormatKHR surfaceFormat{};
VkSwapchainKHR oldSwapchain = VK_NULL_HANDLE;
bool enableReadback = false;
};
[[nodiscard]] static VkSwapchainKHR
createSwapchain(VkPhysicalDevice physicalDevice, VkDevice device,
const SwapchainConfig &config) {
// Determine the number of VkImage's to use in the swapchain.
// Ideally, we desire to own 1 image at a time, the rest of the images can
// either be rendered to and/or being queued up for display.
uint32_t desiredSwapchainImages =
config.surfaceCapabilities.minImageCount + 1;
if ((config.surfaceCapabilities.maxImageCount > 0) &&
(desiredSwapchainImages > config.surfaceCapabilities.maxImageCount)) {
// Application must settle for fewer images than desired.
desiredSwapchainImages = config.surfaceCapabilities.maxImageCount;
}
spdlog::debug("Desired swapchain images: {}", desiredSwapchainImages);
// Just set identity bit transform
VkSurfaceTransformFlagBitsKHR preTransform =
VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
// Query available present modes
uint32_t presentModeCount = 0;
vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, config.surface,
&presentModeCount, nullptr);
static constexpr uint32_t presentModeCountMax = 30; // Safe upper bound
std::array<VkPresentModeKHR, presentModeCountMax> presentModes;
// Fill only the first presentModeCount elements
vkGetPhysicalDeviceSurfacePresentModesKHR(
physicalDevice, config.surface, &presentModeCount, presentModes.data());
// Log only the valid entries
spdlog::info("Available present modes:");
for (uint32_t i = 0; i < presentModeCount; i++) {
spdlog::info("- {}", (int)presentModes[i]);
}
VkPresentModeKHR swapchainPresentMode =
VK_PRESENT_MODE_FIFO_KHR; // safe default
// Select mode (MAILBOX → IMMEDIATE → FIFO)
for (uint32_t i = 0; i < presentModeCount; i++) {
VkPresentModeKHR mode = presentModes[i];
if (mode == VK_PRESENT_MODE_MAILBOX_KHR) {
swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR;
break;
}
if (mode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
}
}
VkCompositeAlphaFlagBitsKHR composite = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
if (config.surfaceCapabilities.supportedCompositeAlpha &
VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) {
composite = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
} else if (config.surfaceCapabilities.supportedCompositeAlpha &
VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) {
composite = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
} else if (config.surfaceCapabilities.supportedCompositeAlpha &
VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR) {
composite = VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
} else if (config.surfaceCapabilities.supportedCompositeAlpha &
VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR) {
composite = VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR;
}
spdlog::debug("Composite alpha: {}", static_cast<int>(composite));
spdlog::debug("Selected surface format");
spdlog::info("Surface format: {}",
static_cast<int>(config.surfaceFormat.format));
spdlog::info("Color space: {}",
static_cast<int>(config.surfaceFormat.colorSpace));
// Create a swapchain
spdlog::debug("Create a swapchain");
VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
if (config.enableReadback) {
imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
}
VkSwapchainCreateInfoKHR swapchainCreateInfo{
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
.pNext = nullptr,
.surface = config.surface,
.minImageCount = desiredSwapchainImages,
.imageFormat = config.surfaceFormat.format,
.imageColorSpace = config.surfaceFormat.colorSpace,
.imageExtent =
{
.width = config.extent.width,
.height = config.extent.height,
},
.imageArrayLayers = 1,
.imageUsage = imageUsage,
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
.preTransform = preTransform,
.compositeAlpha = composite,
.presentMode = swapchainPresentMode,
.clipped = VK_TRUE,
.oldSwapchain = config.oldSwapchain,
};
VkSwapchainKHR swapchain;
VK_CHECK(vkCreateSwapchainKHR(device, &swapchainCreateInfo, nullptr,
&swapchain));
return swapchain;
}
[[nodiscard]] static SwapchainImages
getSwapchainImages(VkDevice device, VkSwapchainKHR swapchain) {
SwapchainImages swapchainImages;
uint32_t swapchainImageCount;
VK_CHECK(vkGetSwapchainImagesKHR(device, swapchain, &swapchainImageCount,
nullptr));
spdlog::debug("Swapchain image count: {}", swapchainImageCount);
swapchainImages.count = swapchainImageCount;
if (swapchainImageCount > MAX_FRAME_SLOTS) {
throw std::runtime_error(fmt::format("Swapchain image count {} exceeds "
"maximum images {}",
swapchainImageCount,
MAX_FRAME_SLOTS));
}
VK_CHECK(vkGetSwapchainImagesKHR(device, swapchain, &swapchainImageCount,
swapchainImages.images.data()));
for (uint32_t i = 0; i < swapchainImageCount; i++) {
spdlog::debug("Swapchain image {}", i);
}
return swapchainImages;
}
[[nodiscard]] static SwapchainImageViews
createSwapchainImageViews(VkDevice device, VkSurfaceFormatKHR surfaceFormat,
const SwapchainImages &swapchainImages) {
// Create image views
SwapchainImageViews swapchainImageViews;
swapchainImageViews.count = swapchainImages.count;
for (uint32_t i = 0; i < swapchainImages.count; i++) {
VkImageViewCreateInfo imageViewCreateInfo{
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.flags = 0,
.image = swapchainImages.images[i],
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = surfaceFormat.format,
.components =
{
.r = VK_COMPONENT_SWIZZLE_IDENTITY,
.g = VK_COMPONENT_SWIZZLE_IDENTITY,
.b = VK_COMPONENT_SWIZZLE_IDENTITY,
.a = VK_COMPONENT_SWIZZLE_IDENTITY,
},
.subresourceRange =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
imageViewCreateInfo.pNext = nullptr;
VK_CHECK(vkCreateImageView(device, &imageViewCreateInfo, nullptr,
&swapchainImageViews.imageViews[i]));
}
return swapchainImageViews;
}
[[nodiscard]] static VkCommandPool
createCommandPool(VkDevice device, uint32_t graphicsQueueIndex) {
spdlog::debug("Create command pool");
VkCommandPoolCreateInfo commandPoolCreateInfo{
.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
.queueFamilyIndex = graphicsQueueIndex,
};
VkCommandPool commandPool = VK_NULL_HANDLE;
VK_CHECK(vkCreateCommandPool(device, &commandPoolCreateInfo, nullptr,
&commandPool));
return commandPool;
}
[[nodiscard]] static uint32_t
findMemoryTypeIndex(VkPhysicalDevice physicalDevice, uint32_t typeFilter,
VkMemoryPropertyFlags properties) {
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
if ((typeFilter & (1 << i)) &&
(memProperties.memoryTypes[i].propertyFlags & properties) ==
properties) {
return i;
}
}
throw std::runtime_error("Failed to find suitable memory type");
}
[[nodiscard]] static ReadbackBuffer
createReadbackBuffer(VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage,
VkMemoryPropertyFlags properties) {
ReadbackBuffer buffer{
.size = size,
};
VkBufferCreateInfo bufferInfo{
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.size = size,
.usage = usage,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
};
VK_CHECK(vkCreateBuffer(device, &bufferInfo, nullptr, &buffer.buffer));
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, buffer.buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.allocationSize = memRequirements.size,
.memoryTypeIndex = findMemoryTypeIndex(
physicalDevice, memRequirements.memoryTypeBits, properties),
};
VK_CHECK(vkAllocateMemory(device, &allocInfo, nullptr, &buffer.memory));
VK_CHECK(vkBindBufferMemory(device, buffer.buffer, buffer.memory, 0));
return buffer;
}
static void destroyReadbackBuffer(VkDevice device, ReadbackBuffer &buffer) {
if (buffer.buffer != VK_NULL_HANDLE) {
vkDestroyBuffer(device, buffer.buffer, nullptr);
}
if (buffer.memory != VK_NULL_HANDLE) {
vkFreeMemory(device, buffer.memory, nullptr);
}
buffer.buffer = VK_NULL_HANDLE;
buffer.memory = VK_NULL_HANDLE;
buffer.size = 0;
}
[[nodiscard]] static VkDescriptorSetLayout
createDescriptorSetLayout(VkDevice device) {
VkDescriptorSetLayoutBinding layoutBinding{
.binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
};
VkDescriptorSetLayoutCreateInfo layoutInfo{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.bindingCount = 1,
.pBindings = &layoutBinding,
};
VkDescriptorSetLayout descriptorSetLayout;
VK_CHECK(vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr,
&descriptorSetLayout));
return descriptorSetLayout;
}
[[nodiscard]] static VkDescriptorPool createDescriptorPool(VkDevice &device) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = 1;
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = 1;
poolInfo.pPoolSizes = &poolSize;
poolInfo.maxSets = 1;
VkDescriptorPool descriptorPool;
VK_CHECK(
vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool));
return descriptorPool;
}
[[nodiscard]] static VkDescriptorSet
allocateDescriptorSet(VkDescriptorPool &descriptorPool, VkDevice &device,
VkDescriptorSetLayout &descriptorSetLayout) {
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
VkDescriptorSet descriptorSet;
VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet));
return descriptorSet;
}
[[nodiscard]] static CommandBuffers
createCommandBuffers(VkDevice device, VkCommandPool commandPool,
uint32_t commandBufferCount) {
CommandBuffers commandBuffers;
commandBuffers.count = commandBufferCount;
spdlog::info("Create command buffers");
VkCommandBufferAllocateInfo commandBufferAllocateInfo{
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.pNext = nullptr,
.commandPool = commandPool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = commandBufferCount,
};
VK_CHECK(vkAllocateCommandBuffers(device, &commandBufferAllocateInfo,
commandBuffers.commandBuffers.data()));
return commandBuffers;
}
static void transitionImageLayout(VkDevice logicalDevice,
VkCommandPool commandPool, VkQueue queue,
VkImage image, VkImageLayout oldLayout,
VkImageLayout newLayout) {
VkCommandBufferAllocateInfo allocInfo{
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.commandPool = commandPool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = 1,
};
VkCommandBuffer commandBuffer;
VK_CHECK(
vkAllocateCommandBuffers(logicalDevice, &allocInfo, &commandBuffer));
VkCommandBufferBeginInfo beginInfo{
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
};
VK_CHECK(vkBeginCommandBuffer(commandBuffer, &beginInfo));
VkImageMemoryBarrier barrier{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = oldLayout,
.newLayout = newLayout,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = image,
.subresourceRange =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
VkPipelineStageFlags srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
VkPipelineStageFlags dstStage =
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED &&
newLayout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
// No need to wait on prior writes; we don't care about old contents.
barrier.srcAccessMask = 0;
// Make color-attachment writes visible for subsequent render pass use.
barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
} else {
throw std::runtime_error("Unsupported image layout transition");
}
vkCmdPipelineBarrier(commandBuffer, srcStage, dstStage, 0, 0, nullptr, 0,
nullptr, 1, &barrier);
VK_CHECK(vkEndCommandBuffer(commandBuffer));
VkSubmitInfo submitInfo{
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.commandBufferCount = 1,
.pCommandBuffers = &commandBuffer,
};
// Submit and wait so the image is ready before further use.
VK_CHECK(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VK_CHECK(vkQueueWaitIdle(queue));
vkFreeCommandBuffers(logicalDevice, commandPool, 1, &commandBuffer);
}
[[nodiscard]] static Fences createFences(VkDevice device, uint32_t count) {
spdlog::info("Create fences");
Fences fences;
fences.count = count;
for (uint32_t i = 0; i < count; i++) {
VkFenceCreateInfo fenceCreateInfo{
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
.flags = VK_FENCE_CREATE_SIGNALED_BIT,
};
VK_CHECK(vkCreateFence(device, &fenceCreateInfo, nullptr,
&fences.fences[i]));
}
return fences;
}
[[nodiscard]] static VkSemaphore createSemaphore(VkDevice device) {
VkSemaphoreCreateInfo semaphoreCreateInfo{
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
};
VkSemaphore semaphore;
VK_CHECK(
vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &semaphore));
return semaphore;
}
[[nodiscard]] static Semaphores createSemaphores(VkDevice device,
uint32_t count) {
Semaphores semaphores;
semaphores.count = count;
for (uint32_t i = 0; i < count; i++) {
semaphores.semaphores[i] = createSemaphore(device);
}
return semaphores;
}
[[nodiscard]] static VkRenderPass
createRenderPass(VkDevice device, VkFormat format, bool offline = false) {
spdlog::debug("Create render pass");
VkAttachmentDescription colorAttachment{
.format = format,
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
// Offline keeps the image in COLOR_ATTACHMENT_OPTIMAL between passes,
// transitioning to TRANSFER_SRC_OPTIMAL only for readback.
// Swapchain rendering discards old contents and transitions to PRESENT.
.initialLayout = offline ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
: VK_IMAGE_LAYOUT_UNDEFINED,
.finalLayout = offline ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL
: VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
};
VkAttachmentReference colorAttachmentRef{
.attachment = 0,
.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
};
VkSubpassDescription subpass{
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.colorAttachmentCount = 1,
.pColorAttachments = &colorAttachmentRef,
};
VkRenderPassCreateInfo renderPassInfo{
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
.attachmentCount = 1,
.pAttachments = &colorAttachment,
.subpassCount = 1,
.pSubpasses = &subpass,
};
VkRenderPass renderPass;
VK_CHECK(vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass));
return renderPass;
}
[[nodiscard]] static FrameBuffers
createFrameBuffers(VkDevice device, VkRenderPass renderPass, VkExtent2D extent,
const SwapchainImageViews &swapchainImageViews) {
spdlog::info("Create framebuffers");
FrameBuffers frameBuffers;
frameBuffers.count = swapchainImageViews.count;
for (uint32_t i = 0; i < swapchainImageViews.count; i++) {
VkFramebufferCreateInfo framebufferInfo{
.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
.renderPass = renderPass,
.attachmentCount = 1,
.pAttachments = &swapchainImageViews.imageViews[i],
.width = extent.width,
.height = extent.height,
.layers = 1,
};
VK_CHECK(vkCreateFramebuffer(device, &framebufferInfo, nullptr,
&frameBuffers.framebuffers[i]));
}
return frameBuffers;
}
[[nodiscard]] static VkPipelineLayout createPipelineLayout(VkDevice device) {